protein.py 24.4 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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
443
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
503
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
687
688
689
690
691
692
693
694
695
696
697
698
699
700
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
# coding=utf-8
"""
                            Secondary structure list
"""

from __future__ import absolute_import, division, print_function, \
    unicode_literals

# from ..core import legacy.SequenceList as SequenceList
from ..core.legacy import SequenceList as SequenceList
import logging
import os
import pkg_resources as pkgr
import re
import sys
from six import iteritems, text_type
from copy import copy
from ..core.legacy import AminoAcid as AmnAcd
from .common import (reg_load, ppdict, Capturing)

# import skbio.Protein as skprot
# TODO: interface skbio ??


LOG = logging.getLogger(__name__)


# TODO: implement psipred format 3.5
class SsList(object):
    """Reader for secondary prediction structure files"""
    types = {
        'psipred': re.compile(r'^(?P<up_index>\d+)'
                              r'\s+(?P<up_residue>[AC-IK-NP-TVWYZ])'
                              r'\s+(?P<ss_pred>[HEC])'
                              r'\s+(?P<ss_conf>\d?)'),
        'psipred2': re.compile(r'^(?P<up_index>\d+)'
                               r'\s+(?P<up_residue>[AC-IK-NP-TVWYZ])'
                               r'\s+(?P<ss_pred>[HEC])'
                               r'\s+(?P<ss_conf>\d?)'),
        'psipred3': re.compile(r'^(?P<up_index>\d+)'
                               r'\s+(?P<up_residue>[AC-IK-NP-TVWYZ])'
                               r'\s+(?P<ss_pred>[HEC])'
                               r'\s+(?P<ss_conf>\d?)'),
        'indextableplus': re.compile(r'^(?P<up_index>\d+)'
                                     r'\s+(?P<up_residue>[AC-IK-NP-TVWYZ])'
                                     r'\s+(?P<ss_pred>[HEC])'
                                     r'\s+(?P<ss_conf>\d?)'),
        'ss2': re.compile(r'^\s*(?P<up_index>\d+)'
                          r'\s+(?P<up_residue>[AC-IK-NP-TVWYZ])'
                          r'\s+(?P<ss_pred>[HECBTG])'
                          r'\s+(?P<h_conf>\d?\.?\d*)'
                          r'\s+(?P<e_conf>\d?\.?\d*)'
                          r'\s+(?P<c_conf>\d?\.?\d*)'),
    }
    # psipred_reg = re.compile(r'^(?P<up_index>\d+)'
    #                          r'\s+(?P<up_residue>[AC-IK-NP-TVWYZ])'
    #                          r'\s+(?P<ss_pred>[HEC])'
    #                          r'\s+(?P<ss_conf>\d?)')
    # psipred2_reg = re.compile(r'^(?P<ss_pred>[HEC]+)')
    # psipred3_reg = re.compile(r'^\s*(?P<up_index>\d+)'
    #                           r'\s+(?P<up_residue>[AC-IK-NP-TVWYZ])'
    #                           r'\s+(?P<ss_pred>[HEC])'
    #                           r'\s+(?P<h_conf>\d?\.?\d*)'
    #                           r'\s+(?P<e_conf>\d?\.?\d*)'
    #                           r'\s+(?P<c_conf>\d?\.?\d*)')
    # indxplus_reg = re.compile(
    #     r'^(?P<up_index>\d+)\s+(?P<up_residue>[AC-IK-NP-TVWYZ])\s+'
    #     r'(?P<ss_pred>[CEH])\s+(?P<ss_conf>\d)\s+(?P<msa_index>[\d\-]+)\s+'
    #     r'(?P<msa_consper>[\d\-]+)\s+(?P<msa_cons>[*~\-])\s+'
    #     r'(?P<in_const>[*~\-])\s+(?P<pdb_atom>[\d\-]+)\s+'
    #     r'(?P<pdb_chain>[\-\w])\s+(?P<pdb_index>[\d\-]+\w?)\s+'
    #     r'(?P<pdb_residue>[AC-IK-NP-TVWYZ\-])\s+(?P<pdb_x_pos>[\d.\-]+)\s+'
    #     r'(?P<pdb_y_pos>[\d.\-]+)\s+(?P<pdb_z_pos>[\d\-.]+)')
    ss_dist_reg = re.compile(r"\s+(\d+\.\d+) \( (\d+\.\d+)\)")

    def __init__(self, sett):
        """

        :param sett:
        :return:
        """
        self.settings = sett
        self.ss_matrix = []
        self.ssdict = {}
        self.ssdist = {}
        self.filetype = ''

    def __bool__(self):
        return True if self.ss_matrix else False

    def __nonzero__(self):
        return self.__bool__()

    @property
    def index(self):
        """:return:"""
        if self.ss_matrix:
            # Assuming human idx (1 ...) correspond to ss_matrix first column !!!
            return [int(_) for _ in zip(*self.ss_matrix)[0]]
        else:
            return []

    @property
    def sequence(self):
        """
        
        Returns
        -------

        """
        if self.ss_matrix:
            return [_ for _ in zip(*self.ss_matrix)[2]]
        else:
            return []

    def check_filetype(self, filename):
        """
        

        Parameters
        ----------
        filename :
            return:

        Returns
        -------


        """
        filetype = os.path.splitext(filename)[1][1:]
        filetype = filetype if 'txt' not in filetype else \
            os.path.splitext(os.path.splitext(filename)[0])[1][1:]
        LOG.info("Checking if file %s correspond to %s format", filename,
                 filetype)
        # Check if given type is supported
        # TODO: make only one file type checking (cf reader.MapFile)
        # TODO: report this check into commands section
        if os.stat(filename).st_size == 0:
            LOG.warning("File %s is empty !", filename)
            return [None] * 2
        with open(filename) as infile:
            # Check first and second line of file
            for index, line in enumerate(infile):
                if filetype in self.types:
                    match = self.types[filetype].match(line)
                else:
                    LOG.error("Format %s not supported !", filetype)
                    match = None
                if match:
                    LOG.info("Format type correct (%s)", filetype)
                    return filetype, self.types[filetype]
                if index > 3:
                    LOG.warning("Given type do not correspond, checking if "
                                "the file corresponds to default format for "
                                "contact lists...")
                    for subformat in self.types:
                        if self.types.get(subformat).match(line):
                            LOG.info("Default format type found") \
                                if subformat != "empty" else \
                                LOG.warning("The file seems to be empty ...")
                            return subformat, self.types[subformat]
                    # Stop checking after second line
                    LOG.error("Can't read %s file.", filetype)
                    break
        LOG.error("Wrong format type given ...")
        return [None] * 2

    def read(self, filename):
        """
        

        Parameters
        ----------
        filename :
            return:

        Returns
        -------

        
        """
        sstype, ssregex = self.check_filetype(filename)
        LOG.info("Reading secondary structure file %s [%s]",
                 filename, sstype)

        self.ssdict = reg_load(ssregex, filename)
        ss_index_dict = {'H': 1, 'C': 1, 'E': 1}
        for line_id in sorted(self.ssdict.keys()):
            # Modif champ ss_pred
            # Si line_id
            if line_id != min(self.ssdict.keys()) and \
                    self.ssdict[line_id]['ss_pred'] not in \
                    self.ssdict[line_id - 1]['ss_pred']:
                # If next ss isn't the same, increment relative struct in
                # ss_index_dict
                ss_index_dict[self.ssdict[line_id - 1]['ss_pred'][0]] += 1

            ss_pred = "".join((
                self.ssdict[line_id]['ss_pred'],
                str(ss_index_dict[self.ssdict[line_id]['ss_pred']])))
            # TODO: change ssmatrix in order to accept h, e and c conf scores
            score = self.ssdict[line_id].get('ss_conf') if \
                self.ssdict[line_id].get('ss_conf') else \
                self.ssdict[line_id].get(
                    self.ssdict[line_id].get('ss_pred', "").lower() +
                    '_conf', "")
            self.ss_matrix.append([
                self.ssdict[line_id].get('up_index', ""),
                self.ssdict[line_id].get('up_residue', ""),
                ss_pred,
                score])

        LOG.debug("Secondary structure list:\n%s\n"
                  "Secondary structure dict:\n%s", self.ss_matrix,
                  self.ssdict)

    # TODO: remove in future updates
    def read_psipred(self, filename, ss2=False):
        """
        

        Parameters
        ----------
        filename :
            

        Returns
        -------

        
        """
        if ss2:
            self.ssdict = reg_load(self.psipred3_reg, filename)
        else:
            self.ssdict = reg_load(self.psipred_reg, filename)
        # TODO: supprimer psipred_list dans les futures implementations
        ss_index_dict = {'H': 1, 'C': 1, 'E': 1}
        for line_id in sorted(self.ssdict.keys()):
            # Modif champ ss_pred
            # Si line_id
            if line_id != min(self.ssdict.keys()) and \
                    self.ssdict[line_id]['ss_pred'] not in \
                    self.ssdict[line_id - 1]['ss_pred']:
                # If next ss isn't the same, increment relative struct in
                # ss_index_dict
                ss_index_dict[self.ssdict[line_id - 1]['ss_pred'][0]] += 1

            self.ssdict[line_id]['ss_pred'] = "".join(
                (self.ssdict[line_id]['ss_pred'],
                 str(ss_index_dict[self.ssdict[line_id]['ss_pred']])))

            self.ss_matrix.append([self.ssdict[line_id]['up_index'],
                                   self.ssdict[line_id]['up_residue'],
                                   self.ssdict[line_id]['ss_pred'],
                                   self.ssdict[line_id].get('ss_conf')])

    def write_ssfasta(self, filename, desc="pdbid"):
        """
        

        Parameters
        ----------
        filename :
            param desc:
        desc :
            (Default value = "pdbid")

        Returns
        -------

        
        """
        with open(filename, str('w')) as psipred:
            psipred.write(str("> %s\n" % desc))
            psipred.write(str("".join([_[0] for _ in zip(*self.ss_matrix)[2]])))

    # TODO: remove in future updates
    def read_indextableplus(self, filename):
        """


        Parameters
        ----------
        filename :
            return:

        Returns
        -------

        
        """
        c = 0
        error_list = []
        ss_index_dict = {'H': 1, 'C': 1, 'E': 1}
        with open(filename) as f:
            for line in f:
                indxplus_match = self.indxplus_reg.search(line)
                if line.startswith("up_"):
                    continue
                elif indxplus_match:

                    # TODO: Other method to replace ss code ?
                    # => build indx_list with group_dict !
                    ss = indxplus_match.group('ss_pred')
                    ss_start = indxplus_match.start('ss_pred')
                    line = "".join([line[:ss_start], ss, str(ss_index_dict[ss]),
                                    line[ss_start + 1:-1]])
                    if self.ss_matrix and self.ss_matrix[-1][2][0] != ss:
                        # Si ss est une structure secondaire diff, on incremente
                        # la valeur de l'ancienne dans ss_index_dict
                        ss_index_dict[self.ss_matrix[-1][2][0]] += 1

                    self.ss_matrix.append(line.split())
                    c += 1
                else:
                    error_list.append(int(self.ss_matrix[-1][0]) + 1)
            try:
                assert c == int(self.ss_matrix[-1][0])
            except AssertionError:
                sys.exit('Uneven number of matching lines (%d) '
                         'vs up_index (%d) : lines %s' % (c,
                                                          int(self.ss_matrix[
                                                                  -1][0]),
                                                          str(error_list)))

    def _read_ssdist(self, infile, filename=''):
        """
        

        Parameters
        ----------
        infile :
            param filename:
        filename :
            (Default value = '')

        Returns
        -------

        
        """
        LOG.info("Reading distance file {0}".format(filename))
        c = 0
        atom_list = []
        for line in infile:
            c += 1
            line_list = line.split('\t')
            dist_sdev_list = self.ss_dist_reg.findall(line)
            if line.startswith('i'):
                atom_list = [elt.strip() for elt in line_list[1:]]
            elif re.search(r'^([HE],[HE]\+\d)', line):
                bond_type = line[0:5]
                self.ssdist[bond_type] = {}
                for i, (dist, sdev) in enumerate(dist_sdev_list):
                    dist, sdev = float(dist), float(sdev)
                    if sdev < 0.1:
                        # TODO: explain more why we choose 0.1 as treshold !
                        dist, sdev = None, None
                    self.ssdist[bond_type][atom_list[i]] = (dist, sdev)
                try:
                    assert len(dist_sdev_list) == len(atom_list)
                except AssertionError:
                    sys.exit(
                        'Error at %s, line %d : uneven number of columns '
                        'between current line and header' % (filename, c))

    def read_ssdist(self, ssdistpath=None):
        """
        Read average dist file generated using PDB

        Parameters
        ----------
        ssdistpath :
            return: (Default value = None)

        Returns
        -------

        
        """
        filename = os.path.abspath(ssdistpath) if ssdistpath else None

        LOG.info("Loading ss dist file")
        try:
            with open(filename) as f:
                self._read_ssdist(f, filename=filename)
        except Exception as message:
            LOG.error("%s", message)
            LOG.error("Can't load given ss dist file...")
            LOG.error("Loading default ss dist file")
            with pkgr.resource_stream(__name__, self.settings.SS_DIST) as f:
                self._read_ssdist(f, filename=self.settings.SS_DIST)

    def seq_sublist(self, sequence):
        """
        Check and  adjust sslist with given sequence

        Parameters
        ----------
        sequence :
            input amino acid sequence (one letter format)

        Returns
        -------

        
        """
        LOG.debug("Adjust sslist related to sequence %s", str(sequence))
        tableplus_inv = zip(*self.ss_matrix)
        # Get amino acid sequence related to secondary structure prediction
        tableplus_seq = "".join(tableplus_inv[1])

        if sequence in tableplus_seq:
            imin = tableplus_seq.find(sequence)
            imax = imin + len(sequence)
            try:
                assert tableplus_seq[imin:imax] == sequence
            except AssertionError:
                sys.exit('Missing residues in indextableplus file')

            self.ss_matrix = self.ss_matrix[imin:imax]
            LOG.debug("Secondary structure matrix relative to given "
                      "sequence:\n%s", self.ss_matrix)
            # TODO: read_dssp


class AminoAcidSequence(SequenceList.SequenceList, object):
    """Amino acid sequence"""
    startres_reg = re.compile(r"^\s*residue\s+(?P<name>[A-Za-z]{1,4})",
                              flags=re.I)
    end_reg = re.compile(r"^\s*end", flags=re.I)
    restatement_reg = {
        "atom": re.compile(r"atom\s+(?P<name>\w{1,4})\s*(?:.*?"
                           r"(?:(?:type=(?P<type>\w{1,4}))|"
                           r"(?:"
                           r"(?:charge= ?)(?P<charge>-?\d\.\d{1,3}))|"
                           r"(?:(?:mass=)(?P<mass>[- ]\d\.\d{1,3}))|"
                           r"(?:(?:excl\s*=\s*)\((?P<exclude>[^(]+)\)))){1,4}"
                           r"\s*end",
                           flags=re.I),
        "bond": re.compile(r"bond\s+(?P<atm1>\w{1,4})\s+(?P<atm2>\w{1,4})",
                           flags=re.I),
        "improper": re.compile(r"improper\s+(?P<atm1>\w{1,4})"
                               r"\s+(?P<atm2>\w{1,4})\s+(?P<atm3>\w{1,4})"
                               r"\s+(?P<atm4>\w{1,4})", flags=re.I),
        "dihedral": re.compile(r"dihedral\s+(?P<atm1>\w{1,4})"
                               r"\s+(?P<atm2>\w{1,4})\s+(?P<atm3>\w{1,4})"
                               r"\s+(?P<atm4>\w{1,4})", flags=re.I),
        "dono": re.compile(r"dono\s+(?P<hatm>\w{1,4})\s+(?:(?P<heavatm>\w{1,"
                           r"4})|(?:\"\s*\"))?", flags=re.I),
        "acce": re.compile(
            r"^\s*acce\s+(?P<accatm>\w{1,4})\s+(?:(?P<antatm>\w{1,"
            r"4})|(?:\"\s*\"))", flags=re.I)
    }

    def __init__(self, topologyfile, *args, **kwargs):
        """

        :param topologyfile:
        :param args:
        :param kwargs:
        :return:
        """
        super(AminoAcidSequence, self).__init__(*args, **kwargs)
        self._topfile = topologyfile
        self._topology = None
        self._topok = False
        self.sequence = ''

    @property
    def humanidx(self):
        """:return:"""
        return range(1, len(self.sequence) + 1)

    @property
    def topology(self):
        """
        Topology dict with 3l code as dict key
        :return:

        Parameters
        ----------

        Returns
        -------

        
        """
        if not self._topology or not self._topok:
            topo = self.readtopo()
            if self.aalist:
                self._topology = [(aa, topo[aa]) for aa in self.aalist]
                self._topok = True
            else:
                self._topology = list(iteritems(topo))
        return self._topology

    def __getitem__(self, key):
        """

        :param key:
        :return:
        """
        return self.aalist[key]

    def __repr__(self):
        """

        :return:
        """
        return "Amino Acid sequence %s (%d)" % (self.sequence,
                                                len(self.sequence))

    def readtopo(self):
        """
        Parse topology file for amino acids
        :return:

        Parameters
        ----------

        Returns
        -------

        
        """
        topo = {}
        with pkgr.resource_stream(__name__, self._topfile) as tpf:
            res_flag = False
            resname = ""
            for line in tpf:
                if not res_flag:
                    match = self.startres_reg.match(line)
                    if match:
                        res_flag = True
                        resname = match.group("name")
                        topo[resname] = {}
                else:
                    # Check if end of residue statement
                    match = self.end_reg.match(line)
                    if match:
                        res_flag = False
                        resname = ""
                        continue
                    # Walk along reg dict
                    for regid, reg in iteritems(self.restatement_reg):
                        if regid not in topo[resname]:
                            topo[resname][regid] = []
                        if regid == "bond":
                            match = re.findall(reg, line)
                            if match:
                                topo[resname][regid] += match
                                break
                        else:
                            match = reg.search(line)
                            if match:
                                if regid in ("improper", "dihedral"):
                                    # Add tuple into list since we need atm order
                                    topo[resname][regid].append(match.groups())
                                else:
                                    # Add dict
                                    topo[resname][regid].append(
                                        match.groupdict())
                                break
        LOG.debug("Topology used:\n%s", ppdict(topo))
        return topo

    def read(self, filename):
        """
        

        Parameters
        ----------
        filename :
            return:

        Returns
        -------

        
        """
        # TODO: smarter reader checking type of file (fasta, etc ...)
        # TODO: capturing has some troubles with unicode ...
        # with Capturing() as output:
        with Capturing() as output:
            if os.path.splitext(filename)[1] == '.seq':
                    self.ReadSeq(text_type(filename))
            else:
                self.ReadFasta(text_type(filename))
        LOG.info("".join(output).capitalize())
        self.sequence = "".join(
            (AmnAcd.AminoAcid(str(_))[0]
             for _ in self.aalist))
        LOG.info("Amino acid sequence:\t%s", self.sequence)


class Protein(object):
    """Protein class"""

    def __init__(self, sett):
        """

        :param sett:
        :return:
        """
        self.aa_sequence = AminoAcidSequence(sett.TOPO)
        self.sec_struct = SsList(sett)
        self.index = []  # Index starting from 1
        self.seqfile_path = u''

    @staticmethod
    def sync_index(index1, index2):
        """
        Return humanidx with upper min from existing humanidx

        Parameters
        ----------
        index1 :
            param index2:
        index2 :
            

        Returns
        -------

        
        """
        if index1 and not index2:
            return index1
        elif index2 and not index1:
            return index2
        elif not index1 and not index2:
            return []
        elif len(index1) == len(index2):
            if min(index1) < min(index2):
                return index2
            else:
                return index1
        elif len(index1) != len(index2):
            raise IndexError(
                "Please check humanidx list from input files. They "
                "are not the same length !")

    @property
    def topology(self):
        """:return:"""
        return self.aa_sequence.topology

    def set_aa_sequence(self, filename, ssidx=False):
        """
        Save the amino acid sequence

        Parameters
        ----------
        filename :
            param ssidx:
        ssidx :
            (Default value = False)

        Returns
        -------

        
        """
        self.aa_sequence.read(filename)
        self.index = range(1, len(self.aa_sequence.sequence) + 1)
        LOG.debug("Index: %s", self.index)
        if self.sec_struct.ss_matrix:
            self.sec_struct.seq_sublist(self.aa_sequence.sequence)
            if ssidx:
                LOG.info("Using secondary structure index for amino acid "
                         "sequence")
                self.index = self.sync_index(self.aa_sequence.humanidx,
                                             self.sec_struct.index)

    def set_sec_struct(self, filename, ssdist_filename='', ssidx=False):
        """
        

        Parameters
        ----------
        filename :
            param ssdist_filename:
        ssidx :
            return: (Default value = False)
        ssdist_filename :
            (Default value = '')

        Returns
        -------

        
        """
        # TODO: Add test checking if both amino acid and sec_struct sequence
        # have the same length after seq_sublist call
        # Read secondary structure prediction file
        self.sec_struct.read(filename)
        if ssdist_filename:
            # Read secondary distance matrix
            self.sec_struct.read_ssdist(ssdist_filename)
        else:
            LOG.error("No secondary structure distance file found. Please "
                      "check configuration file")
        if self.aa_sequence.sequence:
            # Synchronise sec structure sequence with aa sequence
            LOG.info("Align secondary structure sequence with protein "
                     "sequence")
            self.sec_struct.seq_sublist(self.aa_sequence.sequence)
        if ssidx:
            LOG.info("Using secondary structure index for amino acid "
                     "sequence")
            self.index = self.sync_index(self.aa_sequence.humanidx,
                                         self.sec_struct.index)

    def write_seq(self, outfile, seqrange=(1, -1)):
        """
        

        Parameters
        ----------
        outfile :
            return:

        Returns
        -------

        
        """
        # TODO: same as above, trouble with unicode calls inside capturing
        # with Capturing() as output:
        seq = copy(self.aa_sequence)
        seq.aalist = seq.aalist[seqrange[0] - 1: seqrange[1]] \
            if seqrange[1] != -1 else seq.aalist[seqrange[0] - 1:]
        seq.WriteSeq(text_type(outfile))
        self.seqfile_path = '%s' % outfile


if __name__ == "__main__":
    from .settings import AriaEcSettings

    settings = AriaEcSettings("setup")
    prot = Protein(settings)
    prot.set_aa_sequence("../examples/data/BPT1_BOVIN.fa")
    LOG.info(prot.aa_sequence)