Repository navigation
Expand file tree
/
Copy pathseqalign.py
More file actions
208 lines (154 loc) · 5.4 KB
/
Copy pathseqalign.py
File metadata and controls
208 lines (154 loc) · 5.4 KB
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
'''
Sequence alignment stuff.
Based on psico.seqalign
(c) 2018 Schrodinger, Inc.
(c) 2011 Thomas Holder, MPI for Developmental Biology
License: BSD-2-Clause
'''
from pymol import cmd, CmdException
import functools
from typing import TYPE_CHECKING
if TYPE_CHECKING:
import Bio.Align
@functools.cache
def _get_aligner_BLOSUM62() -> "Bio.Align.PairwiseAligner":
from Bio.Align import PairwiseAligner, substitution_matrices
blosum62 = substitution_matrices.load("BLOSUM62")
missing_codes = ''.join(set('JUO-.?').difference(blosum62.alphabet))
blosum62 = blosum62.select(blosum62.alphabet + missing_codes)
aligner = PairwiseAligner(internal_open_gap_score=-10,
extend_gap_score=-.5,
substitution_matrix=blosum62)
assert aligner.mode == "global"
return aligner
def needle_alignment(s1, s2):
'''
DESCRIPTION
Does a Needleman-Wunsch Alignment of sequence s1 and s2 and
returns a Bio.Align.MultipleSeqAlignment object.
'''
from Bio.Align import MultipleSeqAlignment
from Bio.SeqRecord import SeqRecord
from Bio.Seq import Seq
aligner = _get_aligner_BLOSUM62()
alns = aligner.align(s1, s2)
a = MultipleSeqAlignment([])
s1 = SeqRecord(Seq(alns[0][0]), id="s1")
s2 = SeqRecord(Seq(alns[0][1]), id="s2")
a.extend([s1, s2])
return a
def alignment_mapping(seq1, seq2):
'''
DESCRIPTION
Returns an iterator with seq1 indices mapped to seq2 indices
>>> mapping = dict(alignment_mapping(s1, s2))
'''
i, j = -1, -1
for a, b in zip(seq1, seq2):
if a != '-': i += 1
if b != '-': j += 1
if a != '-' and b != '-': yield i, j
def aln_magic_format(infile):
'''
DESCRIPTION
Guess alignment file format.
'''
with open(infile) as handle:
for line in handle:
if len(line.rstrip()) > 0:
break
if line.startswith('CLUSTAL') or line.startswith('MUSCLE'):
informat = 'clustal'
elif line.startswith('>P1;'):
informat = 'pir'
elif line.startswith('>'):
informat = 'fasta'
elif line.startswith('# STOCKHOLM'):
informat = 'stockholm'
elif line.startswith('Align '):
informat = 'fatcat'
elif line.startswith('# ProSMART Alignment File'):
informat = 'prosmart'
else:
informat = 'emboss'
return informat
def aln_magic_read(infile, format=None):
'''
DESCRIPTION
Wrapper for Bio.AlignIO.read that guesses alignment file format.
'''
from Bio import AlignIO
if not format:
format = aln_magic_format(infile)
with open(infile) as handle:
return AlignIO.read(handle, format)
def load_aln_multi(filename, object=None, mapping='', alignioformat='', guide='',
quiet=1, _self=cmd):
'''
DESCRIPTION
Load a multiple sequence alignment from file and apply it to already
loaded structures.
Requires Biopython (conda install biopython)
USAGE
load_aln_multi filename [, object [, mapping [, alignioformat [, guide ]]]]
ARGUMENTS
filename = str: alignment file
object = str: name of the new alignment object {default: filename prefix}
mapping = str: space separated list of sequence-id to object-name
mappings {default: assume sequence-id = object-name}
alignioformat = str: file format, see http://biopython.org/wiki/AlignIO
{default: guess from first line in file}
guide = str: object name of "guide" object (PyMOL only knows many-to-one
alignment, not true multiple alignments) {default: random object}
SEE ALSO
psico.importing.load_aln
'''
import os
quiet = int(quiet)
if object is None:
object = os.path.basename(filename).rsplit('.', 1)[0]
# load alignment file
alignment = aln_magic_read(cmd.exp_path(filename), alignioformat)
# object name mapping
if isinstance(mapping, str):
mapping = mapping.split()
mapping = dict(zip(mapping[0::2], mapping[1::2]))
i2index = [None] * len(alignment)
onames = [None] * len(alignment)
indices = [-1] * len(alignment)
# get structure models and sequences
for r, record in enumerate(alignment):
oname = mapping.get(record.id, record.id)
if not oname:
continue
atoms = []
n = _self.iterate('?{} & guide'.format(oname), 'atoms.append((oneletter or "?", index))',
space=locals())
if n == 0:
print(" Warning: no atoms for object '{}'".format(oname))
continue
# align sequences from file to structures
aln = needle_alignment(str(record.seq), ''.join(a[0] for a in atoms))
# get index mappings
i2index[r] = dict((i, atoms[j][1])
for (i, j) in alignment_mapping(*aln))
onames[r] = oname
if len(onames) < 2:
raise CmdException('Failed to map alignment to objects')
# build alignment list
raw = []
for c in range(len(alignment[0])):
rawcol = []
for r, aa in enumerate(alignment[:, c]):
if onames[r] is None:
continue
if aa != '-':
indices[r] += 1
index = i2index[r].get(indices[r], -1)
if index >= 0:
rawcol.append((onames[r], index))
if len(rawcol) > 1:
raw.append(rawcol)
_self.set_raw_alignment(object, raw, guide=guide)
return raw
# vi:expandtab:smarttab