Debian Codegraph @

weblogo/matrix.py

raw
1 # Copyright (c) 2005 Gavin E. Crooks
2 # Copyright (c) 2006 John Gilman
3
4 # This software is distributed under the MIT Open Source License.
5 # <http://www.opensource.org/licenses/mit-license.html>
6 #
7 # Permission is hereby granted, free of charge, to any person obtaining a
8 # copy of this software and associated documentation files (the "Software"),
9 # to deal in the Software without restriction, including without limitation
10 # the rights to use, copy, modify, merge, publish, distribute, sublicense,
11 # and/or sell copies of the Software, and to permit persons to whom the
12 # Software is furnished to do so, subject to the following conditions:
13 #
14 # The above copyright notice and this permission notice shall be included
15 # in all copies or substantial portions of the Software.
16 #
17 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
22 # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
23 # IN THE SOFTWARE.
24
25
26 """
27 Arrays indexed by alphabetic strings.
28 """
29
30 from array import array
31 from typing import Any, List, Optional, TextIO, Tuple, Union
32
33 import numpy as np
34 from numpy.typing import ArrayLike, DTypeLike
35
36 from .seq import (
37 Alphabet,
38 Seq,
39 unambiguous_dna_alphabet,
40 unambiguous_protein_alphabet,
41 unambiguous_rna_alphabet,
42 )
43 from .utils import ischar, isint
44
45 __all__ = "AlphabeticArray", "Motif"
46
47
48 class AlphabeticArray(object):
49 """An alphabetic array. Wraps a numpy array so that each dimension
50 can be associated with an alphabet and indexed with characters or strings.
51
52 Attributes :
53 - alphabets -- A sequence of alphabets used to index the array
54 - array -- The underlying array object that is indexed.
55
56 Examples :
57
58 >>> from weblogo.seq import *
59 >>> from weblogo.matrix import AlphabeticArray
60 >>>
61 >>> str(protein_alphabet)
62 'ACDEFGHIKLMNOPQRSTUVWYBJZX*-'
63 >>> matrix = AlphabeticArray( (protein_alphabet, protein_alphabet) )
64 >>>
65 >>> # Index by character or integer:
66 >>> matrix['A', 'C'] = 10
67 >>> matrix[0,1]
68 10
69 >>>
70 >>> # Different alphabets on each dimension:
71 >>> import numpy as na
72 >>> a234 = zeros( shape = (2,3,4) )
73 >>> alpha = ( "AB", "ABC", "ABCD")
74 >>> aa = AlphabeticArray(alpha,a234)
75 >>> aa['A', 'B', 'C'] = 22
76 >>>
77 >>> # String indices are converted to integer index arrays:
78 ...
79 >>> aa['A', 'B', 'ABCD']
80 array([ 0, 0, 22, 0])
81
82
83 Authors:
84 o GEC 2005, JXG 2006
85
86 """
87
88 # Design note: Subclassing numpy arrays is hard, so instead we
89 # build this proxy wrapper.
90
91 __slots__ = ["alphabets", "array"]
92
93 def __init__(
94 self,
95 alphabets: Union[Alphabet, Tuple[Union[Alphabet, None], ...], str],
96 values: Optional["ArrayLike"] = None,
97 dtype: Optional["DTypeLike"] = None,
98 ):
99 """
100 Args:
101 - alphabets -- a list of alphabets (as string or Alphabet objects) to
102 be used to convert strings into indices. The lengths of
103 the alphabets match the shape of the indexed array.
104 Alternatively, an integer or None in the list indicate a
105 non-alphabetic dimension. If None the dimension length is
106 taken from values argument.
107 - values -- An array of values to be indexed. If None a new
108 array is created. If this argument is not a numpy array
109 then the alphabet list must be explicit (cannot contain
110 None.)
111 - dtype -- An optional numpy type code.
112 """
113
114 # A dummy object to be used in place of None in the alphabets list
115 # so that we get meaningful error messages if we try to index a
116 # nonalphabetic dimension with a string.
117 class NullAlphabet(Alphabet):
118 def ord(self, key: str) -> int:
119 raise IndexError(
120 "This dimension does not have an alphabet"
121 ) # pragma: no cover
122
123 def ords(self, string: Union["Seq", str]) -> array:
124 raise IndexError(
125 "This dimension does not have an alphabet"
126 ) # pragma: no cover
127
128 alpha: List[Union[Alphabet, None]] = []
129 shape: List[Union[int, None]] = []
130 for a in alphabets:
131 if isinstance(a, str):
132 a = Alphabet(a)
133
134 if a is None:
135 shape.append(None)
136 alpha.append(NullAlphabet(letters=""))
137 elif isinstance(a, Alphabet):
138 shape.append(len(a))
139 alpha.append(a)
140 else:
141 shape.append(int(a)) # pragma: no cover
142 alpha.append(None) # pragma: no cover
143
144 if values is None:
145 values = np.zeros(shape=shape, dtype=dtype) # type: ignore
146 else:
147 values = np.asarray(values, dtype=dtype)
148 vshape = values.shape
149 if len(shape) != len(vshape):
150 raise ValueError(
151 "The values array is the wrong shape."
152 ) # pragma: no cover
153 for s1, s2 in zip(shape, vshape):
154 if s1 is not None and s1 != s2:
155 raise ValueError(
156 "The values array is the wrong shape."
157 ) # pragma: no cover
158 self.array = values
159 self.alphabets = tuple(alpha)
160
161 def __getitem__(self, key: Any) -> Any:
162 return self.array.__getitem__(self._ordkey(key)) # type: ignore
163
164 def __setitem__(self, key: Any, value: Any) -> None:
165 self.array.__setitem__(self._ordkey(key), value)
166
167 def _ordkey(self, key: Any) -> Union[int, np.ndarray, slice, Tuple, Alphabet]:
168 """Convert string indices into integers. Handles characters, strings
169 slices with strings, and tuples of the same. Anything else is
170 unchanged.
171 """
172
173 def norm(
174 key: Any, alpha: Alphabet
175 ) -> Union[int, np.ndarray, slice, Tuple, Alphabet, None]:
176 if key is None:
177 return None
178 elif isinstance(key, str) or isinstance(key, Alphabet):
179 assert alpha is not None
180 key = str(key)
181 if len(key) == 1:
182 return alpha.ord(key)
183 if len(key) == 0:
184 return None # pragma: no cover
185 return np.asarray(alpha.ords(key))
186 elif isinstance(key, slice):
187 start = norm(key.start, alpha) # pragma: no cover
188 stop = norm(key.stop, alpha) # pragma: no cover
189 step = key.step # pragma: no cover
190 return slice(start, stop, step) # pragma: no cover
191 else:
192 return key
193
194 if isinstance(key, tuple):
195 return tuple([norm(k, a) for k, a in zip(key, self.alphabets)]) # type: ignore
196 else:
197 return norm(key, self.alphabets[0]) # type: ignore # FIXME
198
199 def index(self, keys: Any) -> np.ndarray:
200 """Return an array of shape (len(key1), len(key2), ...) whose values
201 are indexed by keys.
202
203 a.outerindex( (I,J,K) )[i,j,k] == a.array[I[i],J[j],K[k]]
204
205 """
206 # TODO: Above docstring is not very clear.
207 # Deep voodoo using numpy indexing
208 keys = self._ordkey(keys)
209 outerkeys = []
210 for i, k in enumerate(keys):
211 if k is None:
212 k = range(0, self.array.shape[i])
213 k = np.asarray(k)
214 for j in range(len(keys) - i - 1):
215 k = k[..., np.newaxis]
216 outerkeys.append(k)
217 return self.array.__getitem__(tuple(outerkeys))
218
219 def reindex(self, new_alphabet: Alphabet) -> "AlphabeticArray":
220 """Create a new AlphabeticArray with the given alphabet. The new
221 alphabet must be a subset of the current alphabet. Useful for
222 extracting a submatrix or for permuting the alphabet.
223 """
224 new_array = self.index(new_alphabet)
225 return AlphabeticArray(new_alphabet, new_array)
226
227 # The following code is designed to proxy all attributes
228 # of the wrapped array. But I'm not entirely sure that this will work as
229 # intended.
230 def __getattr__(self, name: str) -> str:
231 try:
232 return self.array.__getattr__(self, name) # type: ignore
233 except AttributeError:
234 return getattr(self.array, name)
235
236 def __setattr__(self, name: str, value: str) -> None:
237 try:
238 return object.__setattr__(self, name, value)
239 except AttributeError: # pragma: no cover
240 return setattr(self.array, name, value) # pragma: no cover
241
242
243 # End class AlphabeticArray
244
245
246 class Motif(AlphabeticArray):
247 """A two dimensional array where the second dimension is indexed by an
248 Alphabet. Used to represent sequence motifs and similar information.
249
250
251 Attr:
252 - alphabet -- An Alphabet
253 - array -- A numpy array
254 - name -- The name of this motif (if any) as a string.
255 - description -- The description, if any.
256
257 """
258
259 _TRANSFAC_DELIM_LINES = ["XX", "//"]
260
261 def __init__(
262 self,
263 alphabet: Alphabet,
264 array: Optional["ArrayLike"] = None,
265 dtype: Optional["DTypeLike"] = None,
266 name: Optional[str] = None,
267 description: Optional[str] = None,
268 scale: Optional[float] = None,
269 ):
270 AlphabeticArray.__init__(self, (None, alphabet), array, dtype)
271 self.name = name
272 self.description = description
273 self.scale = scale
274
275 @property
276 def alphabet(self) -> Alphabet:
277 assert self.alphabets[1] is not None
278 return self.alphabets[1]
279
280 def reindex(self, alphabet: Union[Alphabet, Tuple[Alphabet, ...], str]) -> "Motif":
281 return Motif(alphabet, AlphabeticArray.reindex(self, (None, alphabet))) # type: ignore
282
283 # These methods alter self, and therefore do not return a value.
284 # (Compare to Seq objects, where the data is immutable and
285 # therefore methods return a new Seq.)
286 # TODO: Should reindex (above) also act on self?
287
288 # Deprecate?
289 def reverse(self) -> None:
290 """Reverse sequence data"""
291 self.array = self.array[::-1] # view into the original numpy array
292
293 # Deprecate?
294 def complement(self) -> None:
295 """Complement nucleic acid sequence."""
296 from weblogo.seq import Alphabet, Seq
297
298 alphabet = self.alphabet
299 complement_alphabet = Alphabet(Seq(str(alphabet), alphabet).complement())
300 self.alphabets = (None, complement_alphabet)
301
302 assert alphabet is not None
303 m = self.reindex(alphabet)
304 self.alphabets = (None, alphabet)
305 self.array = m.array
306
307 # Deprecate?
308 def reverse_complement(self) -> None:
309 """Complements and reverses nucleic acid
310 sequence (i.e. the other strand of a DNA sequence.)
311 """
312 self.reverse()
313 self.complement()
314
315 @classmethod
316 def read_transfac(
317 cls, fin: TextIO, alphabet: Optional[Union[Alphabet, str]] = None
318 ) -> "Motif":
319 """Parse a TRANSFAC-format PWM from a file.
320 Returns a Motif object, representing the provided
321 PWM along with an inferred or provided alphabet.
322 """
323
324 items = []
325
326 start = False
327 for line in fin:
328 if line.isspace() or line[0] == "#":
329 continue # pragma: no cover
330
331 stuff = line.split()
332
333 if stuff[0] == "PO" or stuff[0] == "P0":
334 start = True
335
336 # 'XX' delimiters may precede the first motif
337 if start:
338 if stuff[0] in cls._TRANSFAC_DELIM_LINES:
339 break
340 else:
341 items.append(stuff)
342
343 if len(items) < 2:
344 raise ValueError("Vacuous file.")
345
346 # Is the first line a header line?
347 header = items.pop(0)
348 hcols = len(header)
349 rows = len(items)
350 cols = len(items[0])
351 if not (
352 header[0] == "PO"
353 or header[0] == "P0"
354 or hcols == cols - 1
355 or hcols == cols - 2
356 ):
357 raise ValueError("Missing header line!") # pragma: no cover
358
359 # Do all lines (except the first) contain the same number of items?
360 cols = len(items[0])
361 for i in range(1, len(items)):
362 if cols != len(items[i]):
363 raise ValueError(
364 "Inconsistant length, row: {}".format(i)
365 ) # pragma: no cover
366
367 # Vertical or horizontal arrangement?
368 if header[0] == "PO" or header[0] == "P0":
369 header.pop(0)
370
371 position_header = True
372
373 for h in header:
374 if not ischar(h):
375 raise ValueError(
376 "Expected a single character per header "
377 'item, but got "{}" as one item'.format(h)
378 ) # pragma: no cover
379 if not isint(h):
380 position_header = False
381
382 alphabet_header = False if position_header else True
383
384 # Check row headers
385 if alphabet_header:
386 for i, r in enumerate(items):
387 if not isint(r[0]) and r[0][0] != "P":
388 raise ValueError(
389 "Expected position " "as first item on line {}".format(i)
390 ) # pragma: no cover
391 r.pop(0)
392 defacto_alphabet_str = "".join(header)
393 else:
394 a = [] # pragma: no cover
395 for i, r in enumerate(items): # pragma: no cover
396 if not ischar(r[0]) and r[0][0] != "P": # pragma: no cover
397 raise ValueError(
398 "Expected position " # pragma: no cover
399 "as first item on line {}".format(i)
400 ) # pragma: no cover
401 a.append(r.pop(0)) # pragma: no cover
402 defacto_alphabet_str = "".join(a) # pragma: no cover
403
404 # Check defacto_alphabet
405 defacto_alphabet = Alphabet(defacto_alphabet_str)
406
407 if alphabet:
408 alphabet = Alphabet(str(alphabet))
409 if not defacto_alphabet.alphabetic(str(alphabet)):
410 # Allow alphabet to be a superset of defacto_alphabet
411 alphabet = defacto_alphabet
412
413 else:
414 alphabets = (
415 unambiguous_rna_alphabet,
416 unambiguous_dna_alphabet,
417 unambiguous_protein_alphabet,
418 )
419 for aa in alphabets:
420 if defacto_alphabet.alphabetic(str(aa)):
421 alphabet = aa
422 break
423 if not alphabet:
424 alphabet = defacto_alphabet # pragma: no cover
425
426 # The last item of each row may be extra cruft. Remove
427 if len(items[0]) == len(header) + 1:
428 for r in items:
429 r.pop()
430
431 # items should now be a list of lists of numbers (as strings)
432 rows = len(items)
433 cols = len(items[0])
434 matrix = np.zeros((rows, cols), dtype=np.float64)
435 for rr in range(rows):
436 for cc in range(cols):
437 matrix[rr, cc] = float(items[rr][cc])
438
439 if position_header:
440 matrix.transpose() # pragma: no cover
441
442 return Motif(defacto_alphabet, matrix).reindex(alphabet)