econverter.py 36.2 KB
Newer Older
fabrice's avatar
fabrice committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
"""
                            Input/Output aria_ec scripts
"""
from __future__ import absolute_import, division, print_function

import logging
import math
import random
import collections
import itertools
import datetime
import os
import sys
import json
import re
16
import pkg_resources as pkgr
fabrice's avatar
fabrice committed
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
import aria.legacy.AminoAcid as AminoAcid
import aria.ConversionTable as ConversionTable
import aria.conversion
from .base import (Capturing, get_filename)
from .protein import Protein
from .reader import ProtFileListReader
from .protmap import (ResAtmMap, ResMap)

logger = logging.getLogger(__name__)


class AriaEcBbConverter(object):
    def __init__(self, settings):
        # TODO: check_type settings (AriaEcSettings)
        self.settings = settings
        self.protein = Protein(settings)
        self.reader = ProtFileListReader()
        self.outprefix = ''

    def run(self):
        # Check input
        logger.debug("Settings:\n" + json.dumps(self.settings.setup.config,
                                                indent=4))
        logger.debug("Args:\n" + json.dumps(self.settings.setup.args,
                                            indent=4))
        # Check output infrastructure
        self.settings.make_infrastructure()
        # TODO: redirect print output to logging ? (low priority)
        # ----------------------------- Input -------------------------------- #
        self.outprefix = get_filename(self.settings.bbconv.args.get("seq",
                                                                    None))
        # Load Sequence file
        self.protein.set_aa_sequence(self.settings.bbconv.args.get("seq", None))
        # Load secondary structure prediction file
        self.protein.set_sec_struct(self.settings.bbconv.args.get("sspred",
                                                                  None))
        self.reader.add_file(self.settings.bbconv.args.get("contactfile"),
                             filetypelist=[self.settings.bbconv.args.get(
                                 "contact_type")])
        self.reader.read(self.protein,
                         groupby_method=self.settings.setup.config['groupby_method'],
                         scsc=self.settings.scsc_min)
        # ---------------------------- Processing ---------------------------- #
        # Convert plmdca contacts in couplingmatrix file (CCMPred format)
        self.reader.filelist[0].mapdict["scoremap"].to_csv(
            "%s/%s.mat" % (self.settings.outdir, self.outprefix),
            index=False, header=False, sep="\t", float_format="%13.10f")

        self.settings.bbconv.config['couplingmatrix'] = "%s/%s.mat" % (
            self.settings.outdir, self.outprefix)
        # Convert psipred format (fasta-like)
        self.protein.sec_struct.write_ssfasta("%s/%s.psipred" % (
            self.settings.outdir, self.outprefix), desc=self.outprefix)
        self.settings.bbconv.config['psipredfile'] = "%s/%s.psipred" % (
            self.settings.outdir, self.outprefix)
        # Compute diversityvalue
        self.settings.bbconv.config['diversityvalue'] = \
            self.compute_diversityvalue(self.settings.bbconv.args.get("msa"),
                                        len(self.protein.aa_sequence.sequence))
        # Generate .ini file with bbconv options (input args for bbcontacts)
        # TODO: Generate with only bbconv option !
        self.settings.write_config("%s/%s.ini" % (self.settings.outdir,
                                                  self.outprefix))

    @staticmethod
    def compute_diversityvalue(msa, l):
        # Compute n value
        msa_reg = re.compile("^>[A-Za-z0-9]+_[A-Za-z0-9]+")
        n = 0

        with open(msa) as f:
            for index, line in enumerate(f):
                match = msa_reg.match(line)
                if match and "deselect" not in line:
                    n += 1

        return math.sqrt(n) / float(l)


class AriaXMLConverter(object):
    def __init__(self):
        # TODO: stock here pickle file path for cns donor/ acceptor dict
        pass

    @staticmethod
    def deff(distance_list, dpow=6):
        return math.pow(sum([math.pow(x, -int(dpow)) for x in
                             distance_list]), -1 / 6)

    @staticmethod
    def write_dist_xml(restraint_dict, outfile):
        xml_file = open(outfile, "w")
        xml_file.write('''\
<!DOCTYPE distance_restraint_list SYSTEM "distance_restraint1.0.dtd">
<distance_restraint_list>
''')
        # Pour chaque contrainte
        # Pour chaque contribution
        for restraint_id in restraint_dict:
            xml_file.write('''\
  <restraint id="{rest_id}" weight="{rest_weight:.1f}" distance="{rest_dist:.1f}" \
lower_bound="{lower_bound:.1f}" upper_bound="{upper_bound:.1f}" active="1" \
reliable="{reliable}" list_name="{list_name}">
'''.format(rest_id=restraint_id,
                rest_weight=restraint_dict[restraint_id]["meta"]["weight"],
                rest_dist=float(restraint_dict[restraint_id]["meta"]["distance"]),
                lower_bound=float(restraint_dict[restraint_id]["meta"]["lower_bound"]),
                upper_bound=float(restraint_dict[restraint_id]["meta"]["upper_bound"]),
                reliable=restraint_dict[restraint_id]["meta"]["reliable"],
                list_name=restraint_dict[restraint_id]["meta"]["list_name"]))
            for contrib_id in restraint_dict[restraint_id]["contrib"]:
                res_id = restraint_dict[restraint_id]["contrib"][contrib_id][
                    "spin_pair"].keys()
                xml_file.write('''\
    <contribution id="{id}" weight="{weight}">
      <spin_pair>
        <atom segid="{res1_segid}" residue="{res1_pos}" name="{atm1_name}"/>
        <atom segid="{res2_segid}" residue="{res2_pos}" name="{atm2_name}"/>
      </spin_pair>
    </contribution>
'''.format(id=contrib_id, res1_segid="", res2_segid="",
                    weight=restraint_dict[restraint_id]["contrib"][contrib_id]["meta"]["weight"],
                    res1_pos=res_id[0], res2_pos=res_id[1],
                    atm1_name=restraint_dict[restraint_id]["contrib"][
                        contrib_id]["spin_pair"][res_id[0]],
                    atm2_name=restraint_dict[restraint_id]["contrib"][
                        contrib_id]["spin_pair"][res_id[1]]))
            xml_file.write('''\
  </restraint>
''')
        xml_file.write('''\
</distance_restraint_list>
''')

    @staticmethod
    def _write_helix_hb_tbl(sec_struct, outfile, dminus, dplus):
        outfile.write('''\
! Short range Hbond list (Alpha helix)
''')
        for i, ss in enumerate(sec_struct):
            if (i + 4) < len(sec_struct):
                if 'H' in ss[2] and 'H' in sec_struct[i + 4][2]:
                    # Si residus dans helice
                    res1 = i + 1
                    res2 = i + 5
                    outfile.write('''\
assign (resid {res1} and name o) (resid {res2} and name n)  2.8 {dminus} {dplus}
assign (resid {res1} and name o) (resid {res2} and name hn)  1.8 {dminus} {dplus}
'''.format(res1=res1, res2=res2, dminus=dminus, dplus=dplus))

    @staticmethod
    def _write_hbmap_tbl(hbmap, outfile, dminus, dplus, n_hb=None,
                         hb_type="main", topo=None):
        """
        Build hbdond distance restraints from a res-res contact map. Tbl
        restraints generated use pseudoatoms since we assume we don't know
        which donnor/acceptor are involved.
        :param hbmap: Hbond contact map with first humanidx =  ['donor',
                      'acceptor'] => Non symetric matrix !!!
        :param outfile:
        :param dminus:
        :param dplus:
        :param n_hb:
        :param hb_type: Long range hbond type
        :return:
        """
        # TODO: test with several deviation since these restraints should
        # contain noise !!
        # Parcourt la matrice de contact
        outfile.write('''\
! Long range Hbond list (beta sheet)
''')
        contacts = hbmap["scoremap"].sortedset(human_idx=True)
        distmap = hbmap.get("distmap")
        if n_hb:
            contacts = contacts[:n_hb]
        logger.debug(contacts)
        donors = []
        acces = []
        for contact in contacts:
            # The first residu represent the hydrogen bond donor and the
            # second residu represent the hydrogen bond acceptor
            res1, res2 = contact
            if res1 not in donors + acces and res2 not in donors + acces:
                # Add only if new donor and new acces don't belong to
                # previous hbond restraints
                donors.append(res1)
                acces.append(res2)
                residx1, residx2 = int(res1) - 1, int(res2) - 1
                dist = distmap.iat[(residx1, residx2)]
                if hb_type == "all":
                    # This method is deprecated seems it should add noise ...
                    if topo:
                        print(topo)
                        print(res1, res2)
                        print(topo[residx1][1]['dono'])
                        print(topo[residx2][1]['acce'])
                        print([x[0] for x in topo])
                        # print(hbmap['contactmap'].sequence[residx1])
                        # print(hbmap['contactmap'].sequence[residx2])
                        # print(distmap.index[residx2])
                        # print(dist)
                        # print(hbmap["scoremap"])
                    # Get all donor from cns topology file and make group atom/pseudoatm
                    # Get all acceptor from cns topology file
                    # !!!! Ignore case flag !!!!!
                    raise NotImplementedError
                else:
                    if hb_type != "main":
                        logger.error("Wrong longrange hbond type given. Default "
                                     "option used (main)")
                    # First residue = donor for a backbone hydrogen bond (N-H...O=C)
                    outfile.write('''\
    assign (resid {res1} and name o) (resid {res2} and name n)  2.8 {dminus} {dplus}
    assign (resid {res1} and name o) (resid {res2} and name hn)  1.8 {dminus} {dplus}
    '''.format(res1=res1, res2=res2, dminus=dminus, dplus=dplus, dist=dist))
        logger.info("Writing %d hbonds from hbmap in %s" % (len(donors),
                                                            outfile.name))

    def write_hb_tbl(self, protein, outfile, hbmap=None, dminus=0.0,
                     dplus=0.5, n_hb=None, lr_type='main'):
        """

        :param protein:
        :param outfile:
        :type outfile: str
        :param hbmap:
        :param dminus:
        :param dplus:
        :param n_hb:
        :param lr_type:
        :return:
        """
        with open(outfile, 'w') as outfile:
            # Write short range hbond tbl restraints
            self._write_helix_hb_tbl(protein.sec_struct.ss_matrix, outfile, dminus,
                                     dplus)
            if hbmap:
                # TODO: add another flag in order to generate hbmap xml
                # ambig. Tbl pseudoatoms is probably not the best way to use
                # hbmap
                self._write_hbmap_tbl(hbmap, outfile, dminus, dplus,
                                      n_hb=n_hb, hb_type=lr_type,
                                      topo=protein.topology)

    @staticmethod
    def write_ssdist_tbl(sec_struct, ss_dist, outfile):
        # Build global secondary structure distance restraints (H-H+4, E-E+1,
        #  ...)
        with open(outfile, 'w') as outfile:
            for a in xrange(len(sec_struct) - 1):
                for b in range(a + 1, len(sec_struct)):
                    ss1 = sec_struct[a][2]
                    ss2 = sec_struct[b][2]
                    if (ss1 != ss2) or 'C' in ss1 or 'C' in ss2:
                        continue
                    else:
                        d = b - a  # ecart en nombre de residus
                        ss_dict_key = '%s,%s+%d' % (ss1[0], ss2[0], d)
                        ss_dist_subdict = ss_dist.get(ss_dict_key)
                        if ss_dist_subdict:
                            for atoms, (dist, sdev) in ss_dist_subdict.items():
                                if dist is not None and sdev is not None:
                                    atm1, atm2 = tuple(atoms.split('-'))
                                    res1 = a + 1
                                    res2 = b + 1
                                    outfile.write('''\
assign (resid {res1} and name {atm1}) (resid {res2} and name {atm2})  {dist} {sdev} {sdev} weight 5
'''.format(res1=res1, atm1=atm1, res2=res2, atm2=atm2, dist=dist, sdev=sdev))

    @staticmethod
    def write_dihedral_tbl(sec_struct, outfile, k=0.5, e=2):
        # Build dihedral angle restraints (phi, psi)
        with open(outfile, "w") as outfile:
            for i in xrange(len(sec_struct)):
                if (i + 1) != len(sec_struct):
                    if sec_struct[i][2] == sec_struct[i + 1][2]:
                        # Si ss identique
                        ss = sec_struct[i][2][0]
                        res1 = i + 1
                        res2 = i + 2

                        if ss == 'H':
                            phi = -57.0
                            psi = -47.0
                            r = 7.0
                        elif ss == 'E':
                            phi = -127.0
                            psi = 122.0
                            r = 20.0
                        else:
                            phi, psi, r = (None, None, None)

                        if phi and psi:
                            outfile.write('''\
assign (resid {res1} and name c) (resid {res2} and name n) (resid {res2} and name ca) \
(resid {res2} and name c)  {k} {phi} {r} {e}
assign (resid {res1} and name n) (resid {res1} and name ca) (resid {res1} and name c) \
(resid {res2} and name n)  {k} {psi} {r} {e}
    '''.format(res1=res1, res2=res2, k=k, phi=phi, psi=psi, r=r, e=e))

    @staticmethod
    def unambig_dist_xmltag(unambigous_dict):
        res = ""
        for unambig in unambigous_dict:
            res += '''
    <unambiguous_distance_restraints file="{file}" format="{format}" ccpn_id="" enabled="{enabled}" add_to_network="{add_to_network}" calibrate="{calibrate}" run_network_anchoring="{run_network_anchoring}" filter_contributions="{filter_contributions}"/>\
'''.format(file=unambigous_dict[unambig]['file'],
                   format=unambigous_dict[unambig]['format'],
                   enabled=unambigous_dict[unambig]['enabled'],
                   add_to_network=unambigous_dict[unambig]['add_to_network'],
                   calibrate=unambigous_dict[unambig]['calibrate'],
                   run_network_anchoring=unambigous_dict[unambig][
                       'run_network_anchoring'],
                   filter_contributions=unambigous_dict[unambig][
                       'filter_contributions'])

        return {'unambiguous_distance_restraints': res}

    @staticmethod
    def ambig_dist_xmltag(ambigous_dict):
        res = ""
        for ambig in ambigous_dict:
            res += '''
    <ambiguous_distance_restraints file="{file}" format="{format}" ccpn_id="" enabled="{enabled}" add_to_network="{add_to_network}" calibrate="{calibrate}" run_network_anchoring="{run_network_anchoring}" filter_contributions="{filter_contributions}"/>\
'''.format(file=ambigous_dict[ambig]['file'],
                   format=ambigous_dict[ambig]['format'],
                   enabled=ambigous_dict[ambig]['enabled'],
                   add_to_network=ambigous_dict[ambig]['add_to_network'],
                   calibrate=ambigous_dict[ambig]['calibrate'],
                   run_network_anchoring=ambigous_dict[ambig][
                       'run_network_anchoring'],
                   filter_contributions=ambigous_dict[ambig][
                       'filter_contributions'])

        return {'ambiguous_distance_restraints': res}


class AriaEcXMLConverter(AriaXMLConverter):
    def __init__(self, settings):
        self.restraint_list = []
        self.settings = settings
        self.outprefix = ""
        super(AriaEcXMLConverter, self).__init__()

    def targetdistmap(self, distype, sequence, distfile=None, groupby=None):
        # TODO: valeur par defaut de distfile au  fichier contenant les infos
        #  fixes
        # ! target est une ResAtmMap pour les 20 aa, sinon il s'agit d'une
        # carte de distance (native ou predite)
        # Fixed
        # -----
        #   => target contient des infos pour les 20 aa qui modifieront le champ
        #      distance de la contrainte
        #   => AaAtmMap (20 aa) OU AtmMap
        # pdbstat
        # -------
        #   => target contient des infos pour les 20 aa. Ces valeurs
        #      correspondant au mode des distribution des structures de haute
        #      resolution.
        #   => Construire Maps en fonction des modes des distribution
        #   => SsAaAtmMap (Ajout info structure secondaire) OU AaAtmMap (20
        # aa) OU AaMap (20 aa) OU AtmMap pour les 20 aa
        # distfile
        # ---------
        #   => target contient les infos de distances predites en fonction
        # des positions
        #   => ResMap (contacts pdb ou predits)
        targetmap = ResAtmMap(sequence)
        targetmap.reduce(groupby)
        if distfile:
            # Retourne resmap associe au fichier de distance
            targetmap = distfile.mapdict.get('alldistmap')[:]
        elif distype == "fixed":
            # Fixed distances with bound in aria_ec.ini
            # retourne ResAtmMap (20 aa)
            targetmap[:] = self.settings.setup.config["restraint_distance"]
        elif distype == "pdbstat":
            # TODO: pdbstats a partir d'une matrice pickle (faire une
            # fonction qui genere la matrice en dehors et la sauvegarde
            # dans le dossier conf)
            # Met a jour les valeurs de targetmap en fonction de celles dispo
            #  dans pdbstat
            # settings = self.settings.setup.config
            # pdbdict = {atmbound.replace('_upper_bound', ''): settings.get(
            #     atmbound, None) for atmbound in (bound for bound in settings
            #                                      if '_upper_bound' in bound.lower())}
            # targetmap.subfill(pdbdict, level=1)
            raise NotImplementedError
        else:
            # retourne fixed AtmMap
            raise ValueError("Unknown distance_type %s" % distype)
        return targetmap

    def write_map_restraint(self, contactmap, nb_c, targetdist, scoremap=None,
                            listname=""):
        """
        Translate contactmap in ARIA XML restraint
        :param listname:
        :param contactmap: ResAtmMap for a protein
        :param nb_c: Number of restraints selected
        :param targetdist: ResAtmMap for each atom for each amino acid
        :param scoremap: sorted list of contacts
        :return:
        """
        # Number of selected contacts
        nb_c = nb_c if nb_c < len(contactmap.contactset()) else len(
            contactmap.contactset())

        if scoremap is not None:
            # TODO: implement viterbiscore as scoremap for bbcontacts ?
            pair_list = scoremap.sortedset()[:nb_c]
        else:
            # TODO: Probleme selection des contacts utilises en l'absence de
            # poids:
            #       - aleatoire (implementation actuelle) => Tester la
            # robustesse
            #       - trouver une maniere d'attribuer des poids dans le cas
            # d'une matrice de distance d'un pdb ?
            #       - Def le max independent set dans le graphe (matrice de
            # contacts) => utiliser tout les contact de ce set ou def des
            # poids  pour selectionner l * f contacts de ce set
            pair_list = random.sample(contactmap.contactset(),
                                      nb_c)
            # Initial contact list start at 0
            # pair_list = [(int(x[0]) + 1, int(x[1]) + 1) for x in pair_list]
443
        logger.info("Selecting %d contacts:\n%s" % (nb_c, pair_list))
fabrice's avatar
fabrice committed
444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502

        if self.settings.setup.config['evfold_weight'] and scoremap is not None:
            weight_list = list(float(10.0 / (x + 1)) for x, v in enumerate(
                pair_list))
        else:
            weight_list = list(1.0 for _ in pair_list)

        neigh_flag = self.settings.setup.config['neighborhood_contact']
        adr_flag = self.settings.setup.config["ambiguous_distance_restraint"]
        adr_type = self.settings.setup.config["ambiguous_distance_type"]
        pair_flag = self.settings.setup.config["pair_list"]
        target_dist = self.settings.setup.config["restraint_distance"]

        conv_table = ConversionTable.ConversionTable().table['AMINO_ACID'][
            'iupac']

        # Dict giving all atms foreach aa
        aa_atm = dict((AminoAcid.AminoAcid(aa)[0],
                       filter(contactmap.heavy_reg.match, v.keys())) for
                      aa, v in conv_table.items())

        # Dict giving atoms product for each res-res pair
        aa_atm_pair = {(aa1, aa2): list(itertools.product(atms1, atms2))
                       for aa1, atms1 in aa_atm.items()
                       for aa2, atms2 in aa_atm.items()
                       }
        if pair_flag == "min":
            def min_atms(aa1, aa2, atms):
                # Function to minimize atom pair list between aa1 & aa2
                return [
                    atmpair for atmpair in atms if atmpair in (
                        ('CA', 'CA'),
                        ('CB', 'CB'),
                        self.settings.scsc_min[aa1][aa2])]
            aa_atm_pair = \
                {
                    (aa1, aa2): min_atms(aa1, aa2, list(itertools.product(atms1,
                                                                          atms2)))
                    for aa1, atms1 in aa_atm.items()
                    for aa2, atms2 in aa_atm.items()
                }

        def min_ind(ind):
            return ind if ind >= 0 else 0

        def max_ind(ind, max_idx):
            return ind if ind <= max_idx else max_idx

        def resname(residx):
            return AminoAcid.AminoAcid(contactmap.index.values[residx][-3:])[0]

        max_seqidx = len(contactmap.sequence)
        restraint_dict = collections.OrderedDict()
        rest_id = 0
        contrib_id = 0

        for contactidx, contact in enumerate(pair_list):
            # /!\ humanidx in contact must start at 1 !n_factor
            # Add neighbors if neigh_flag
503
            logger.debug("Contact %s" % str(contact))
fabrice's avatar
fabrice committed
504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686
            resx_idx = range(min_ind(contact[0] - 1),
                             max_ind(contact[0] + 2, max_seqidx)) if \
                neigh_flag else [contact[0]]
            resy_idx = range(min_ind(contact[1] - 1),
                             max_ind(contact[1] + 2, max_seqidx)) if \
                neigh_flag else [contact[1]]
            contactweight = weight_list[contactidx]

            dist_list = []
            if adr_flag:
                rest_id += 1
                # TODO: Autre dist_list if target != ResMap
                # dist_list containt all atm-atm dist foren_factorach res-res (+ neigh)
                #  if target is a  ResAtmMap or only one dist foreach res-res
                # !!!!! Utiliser stack pour eviter les distances en doubles ????
                if isinstance(targetdist, ResAtmMap) or len(
                        targetdist.index.levels) == 2:
                    idx_names = list(targetdist.index.get_level_values(
                        'residuex').unique()[x] for x in resx_idx)
                    idy_names = list(targetdist.index.get_level_values(
                        'residuex').unique()[y] for y in resy_idx)
                    dist_list = [
                        dist
                        for ix, x in enumerate(idx_names)
                        for yx, y in enumerate(idy_names)
                        for dist in list(targetdist.loc[x][y].values.flat)]
                elif isinstance(targetdist, ResMap):
                    # TODO: target avec pdbstats
                    raise NotImplementedError('Need implementation of target '
                                              'dist from generic table '
                                              'implementatn_factorion')
                if adr_type == "deff":
                    # Compute effective distance from distance list between
                    # all pairs in the adr
                    target_dist = "%.2f" % self.deff(dist_list,
                                                     self.settings.setup.config["deffpow"])
                elif adr_type == "min":
                    target_dist = min(dist_list)
                else:
                    target_dist = self.settings.setup.confn_factorig[
                        "restraint_distance"]

            for resx in resx_idx:
                for resy in resy_idx:
                    resxn = targetdist.index.levels[0][resx]
                    resyn = targetdist.index.levels[0][resy]
                    for atm_pair in aa_atm_pair[(resname(resx),
                                                 resname(resy))]:
                        if adr_flag:
                            contrib_id += 1
                        else:
                            if len(targetdist.index.levels) == 2:
                                target_dist = targetdist.loc[resxn,
                                                             atm_pair[0]][resyn,
                                                                          atm_pair[1]]
                            else:
                                target_dist = "%.2f" % targetdist.iat[resx,
                                                                      resy]

                            if target_dist is None:
                                # In case missing distance values
                                target_dist = self.settings.setup.config[
                                    "restraint_distance"]
                                logger.warning(
                                    "Target distance is missing for restraint "
                                    "%s-%s (%s). Using default distance (%s)"
                                    % (resx + 1, resy + 1, atm_pair, target_dist))

                            rest_id += 1
                            contrib_id = 1

                        # TODO: Impact poids contribution si neigh_flag ??
                        if restraint_dict.get(rest_id, None) is None:
                            # If restraint doesn't exist
                            # TODO: set upper and lower bound if sdv not None
                            if atm_pair == ("CA", "CA"):
                                upp_bound = self.settings.setup.config["ca_upper_bound"]
                            elif atm_pair == ("CB", "CB"):
                                upp_bound = self.settings.setup.config["cb_upper_bound"]
                            else:
                                upp_bound = self.settings.setup.config[
                                    "def_upper_bound"]
                            if target_dist >= upp_bound:
                                upp_bound = target_dist + self.settings.setup.config["lower_bound"]

                            restraint_dict[rest_id] = {
                                "meta": {
                                    "weight": contactweight,
                                    "distance": target_dist,
                                    "lower_bound": self.settings.setup.config["lower_bound"],
                                    "upper_bound": upp_bound,
                                    "active": 1,
                                    "reliable": 0,
                                    "list_name": listname
                                },
                                "contrib": {}
                            }
                        restraint_dict[rest_id]["contrib"][contrib_id] = {
                            "meta": {
                                "weight": 1.0
                            },
                            "spin_pair": {
                                resx + 1: atm_pair[0],
                                resy + 1: atm_pair[1]
                            }
                        }
        xml_file = self.settings.infra["xml"] + "/" + "_".join((
            self.outprefix, listname)) + ".xml"
        self.write_dist_xml(restraint_dict, xml_file)
        return xml_file, pair_list

    def write_maplist_restraints(self, maplist, nb_c, targetmap):
        out = ([], [])

        for maptype in maplist:
            logger.info("Writing %s ARIA XML distance restraints" % maptype)
            outfile, pairlist = self.write_map_restraint(
                maplist[maptype]['contactmap'], nb_c,
                targetmap, listname=maptype,
                scoremap=maplist[maptype].get("scoremap"))
            out[0].append(outfile)
            maplist[maptype]["filteredlist"] = pairlist
            out[1].append(pairlist)
        return out

    def write_tbl_restraints(self, protein, hbmap=None, n_hb=None):
        """
        Write tbl restraints
        :param n_hb:
        :param protein:
        :param hbmap: Extra hbond map (eg: metapsicov hbonds)
        :return:
        """
        dihed_file = os.path.join(self.settings.infra["tbl"], self.outprefix +
                                  "_dihed.tbl")
        hb_file = os.path.join(self.settings.infra["tbl"], self.outprefix +
                               "_hbond.tbl")
        ssdist_file = os.path.join(self.settings.infra["tbl"], self.outprefix +
                                   "_ssdist.tbl")
        self.write_dihedral_tbl(protein.sec_struct.ss_matrix, dihed_file)
        self.write_hb_tbl(protein, hb_file,
                          hbmap=hbmap, n_hb=n_hb,
                          lr_type=self.settings.setup.config['longrange_hbtype'],
                          dminus=self.settings.setup.config['hb_dminus'],
                          dplus=self.settings.setup.config['hb_dplus'])
        self.write_ssdist_tbl(protein.sec_struct.ss_matrix,
                              protein.sec_struct.ssdist,
                              ssdist_file)
        return {'hbond': hb_file, 'dihed': dihed_file, 'ssdist': ssdist_file}

    def write_xmlseq(self, seqpath):
        xml_file = os.path.join(self.settings.infra["xml"], self.outprefix +
                                ".xml")

        m = aria.conversion.MoleculeSettings()
        m['format'] = 'seq'
        m['input'] = seqpath
        m['output'] = xml_file
        m['type'] = 'PROTEIN'
        m['segid'] = '    '
        m['first_residue_number'] = 1
        m['naming_convention'] = ''
        m['name'] = self.outprefix

        c = aria.conversion.ConverterSettings()
        c.reset()
        c['molecule'] = m
        c['project_name'] = self.outprefix

        converter = aria.conversion.Converter()
        converter.setSettings(c)

        # TODO: generate xml in order to use convert method ??
        # converter.convert()
        with Capturing() as output:
            converter._convert_sequence()

        logger.info("\n" + "".join(output))

        return xml_file

    def write_project(self, aria_template, seqfile, dist_files, tbl_files,
                      desc=""):
687 688
        if aria_template:
            template = os.path.abspath(aria_template)
fabrice's avatar
fabrice committed
689

690 691 692 693
            try:
                t = open(template, 'r')
            except IOError:
                sys.exit("""Can't open "%s" file.""" % template)
fabrice's avatar
fabrice committed
694

695 696 697 698 699 700
            aria_project_template = t.read()
            t.close()
        else:
            logger.info("Reading default aria template file %s" % self.settings.ARIAPROJ_TEMPLATE)
            aria_project_template = pkgr.resource_string(
                __name__, self.settings.ARIAPROJ_TEMPLATE)
fabrice's avatar
fabrice committed
701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801

        aria_project_dict = {}

        # Check if ratio cool1 / cool2 is 5:4
        steps_1 = float(self.settings.setup.config['md_parameters_steps_cool1'])
        steps_2 = float(self.settings.setup.config['md_parameters_steps_cool2'])
        if steps_1 / steps_2 != float(5) / int(4):
            sys.exit('Length of first and second cooling stages must be fixed in '
                     'the ratio %.2f:%.2f' % (steps_1, steps_2))

        aria_project_dict.update(self.settings.setup.config)
        work_dir = os.path.abspath(aria_project_dict['working_directory'])
        temp_root = os.path.abspath(aria_project_dict['temp_root'])

        if not os.path.exists(work_dir) or not os.path.exists(temp_root):
            logger.warning("Working dir %s and temp directory %s doesn't exist." % (
                work_dir, temp_root))
            logger.info("Create new directory %s" % work_dir)
            os.makedirs(work_dir)
            logger.info("Create new directory %s" % temp_root)
            os.makedirs(temp_root)

        for direct in (work_dir, temp_root):

            if not os.path.exists(os.path.join(direct, self.outprefix)):
                os.makedirs(os.path.join(direct, self.outprefix))

            if not os.path.exists(os.path.join(direct, self.outprefix, desc)):
                os.makedirs(os.path.join(direct, self.outprefix, desc))

        work_dir = os.path.join(work_dir, self.outprefix, desc)
        temp_root = os.path.join(temp_root, self.outprefix, desc)

        aria_project_dict['working_directory'] = work_dir
        aria_project_dict['temp_root'] = temp_root

        project = {'project_name': self.outprefix,
                   'date': datetime.date.today().isoformat(),
                   'file_root': self.outprefix}
        aria_project_dict.update(project)

        data_molecule = {'molecule_file': seqfile}
        aria_project_dict.update(data_molecule)

        un_dict = dict()
        am_dict = dict()

        # SS dist tbl restraint
        un_dict['ss'] = {
            'file': tbl_files["ssdist"],
            'format': self.settings.setup.config['ss_dist_format'],
            'enabled': self.settings.setup.config['ss_dist_enabled'],
            'add_to_network': self.settings.setup.config['ss_dist_add_to_network'],
            'calibrate': self.settings.setup.config['ss_dist_calibrate'],
            'run_network_anchoring': self.settings.setup.config['ss_dist_run_network_anchoring'],
            'filter_contributions': self.settings.setup.config['ss_dist_filter_contributions']}

        if self.settings.setup.config["ambiguous_distance_restraint"]:
            # Ajout dist_files a am_dict
            for distfile in dist_files:
                am_dict[distfile] = {
                    'file': distfile,
                    'format': self.settings.setup.config['dist_format'],
                    'enabled': self.settings.setup.config['dist_enabled'],
                    'add_to_network': self.settings.setup.config['dist_add_to_network'],
                    'calibrate': self.settings.setup.config['dist_calibrate'],
                    'run_network_anchoring': self.settings.setup.config['dist_run_network_anchoring'],
                    'filter_contributions': self.settings.setup.config['dist_filter_contributions']}
        else:
            # Ajout dist_files a un_dict
            for distfile in dist_files:
                un_dict[distfile] = {
                    'file': distfile,
                    'format': self.settings.setup.config['dist_format'],
                    'enabled': self.settings.setup.config['dist_enabled'],
                    'add_to_network': self.settings.setup.config['dist_add_to_network'],
                    'calibrate': self.settings.setup.config['dist_calibrate'],
                    'run_network_anchoring': self.settings.setup.config['dist_run_network_anchoring'],
                    'filter_contributions': self.settings.setup.config['dist_filter_contributions']}

        data_unambig_distance_restraints = self.unambig_dist_xmltag(un_dict)
        data_ambig_distance_restraints = self.ambig_dist_xmltag(am_dict)

        aria_project_dict.update(data_ambig_distance_restraints)
        aria_project_dict.update(data_unambig_distance_restraints)

        data_hbonds = {'hbond_dist_file': tbl_files["hbond"]}
        aria_project_dict.update(data_hbonds)

        data_dihedrals = {'dihed_angle_file': tbl_files["dihed"]}
        aria_project_dict.update(data_dihedrals)

        if self.settings.setup.config['cpus']:
            aria_project_dict['n_cpus'] = self.settings.setup.config['cpus']
        else:
            aria_project_dict['n_cpus'] = '20'

        proj_file = "%s/%s_%s_aria_project.xml" % (work_dir, self.outprefix, desc)
        with open(proj_file, 'w') as proj_xml:
            logger.info("Writing ARIA project file (%s)" % proj_file)
            proj_xml.write(aria_project_template % aria_project_dict)