Debian Codegraph @

weblogo/_ext/nexus/__init__.py

raw
1 # Nexus.py - a NEXUS parser
2 #
3 # Copyright 2005-2008 by Frank Kauff & Cymon J. Cox. All rights reserved.
4 # This code is part of the Biopython distribution and governed by its
5 # license. Please see the LICENSE file that should have been included
6 # as part of this package.
7 #
8 # Bug reports welcome: [email protected] or the Biopython issue tracker
9 # at http://github.com/biopython/biopython.
10
11 """Parse the contents of a NEXUS file.
12
13 Based upon 'NEXUS: An extensible file format for systematic information'
14 Maddison, Swofford, Maddison. 1997. Syst. Biol. 46(4):590-621
15
16 Authors: Frank Kauff and Cymon J. Cox
17 """
18
19 # type: ignore
20
21 import contextlib
22 import copy
23 import math
24 import random
25 import sys
26 from collections import namedtuple
27 from functools import reduce
28
29 from ... import data
30 from ...seq import Alphabet, Seq, protein_alphabet
31
32 # --- Changes from Bio.Nexus ---
33 # Renamed Nexus.py to __init__.py. Helps with api documentation.
34
35 # from Bio import File
36 # from Bio.Alphabet import IUPAC
37 # from Bio.Data import IUPACData
38 # from Bio.Seq import Seq
39
40
41 _IUPACData = dict(
42 ambiguous_dna_letters=data.dna_extended_letters,
43 ambiguous_rna_letters=data.rna_extended_letters,
44 ambiguous_dna_values=data.dna_ambiguity,
45 ambiguous_rna_values=data.rna_ambiguity,
46 protein_letters=data.amino_acid_letters,
47 unambiguous_dna_letters=data.dna_letters,
48 unambiguous_rna_letters=data.rna_letters,
49 )
50
51 IUPACData = namedtuple("IUPACDataTuple", _IUPACData.keys())(**_IUPACData)
52
53
54 _IUPAC = dict(
55 ambiguous_dna=Alphabet(data.dna_extended_letters + "-?"),
56 ambiguous_rna=Alphabet(data.rna_extended_letters + "-?"),
57 protein=protein_alphabet, # Alphabet(IUPACData.protein_letters+'-?')
58 )
59
60 IUPAC = namedtuple("IUPATuple", _IUPAC.keys())(**_IUPAC)
61
62
63 @contextlib.contextmanager
64 def as_handle(handleish, mode="r"):
65 """Treat a filename or file-like object as an open file handle."""
66 if isinstance(handleish, str):
67 with open(handleish, mode) as fp:
68 yield fp
69 else:
70 yield handleish
71
72
73 # Not bundling cnexus
74 def _get_command_lines(file_contents):
75 lines = _kill_comments_and_break_lines(file_contents)
76 commandlines = _adjust_lines(lines)
77 return commandlines
78
79
80 # --- End Changes ---
81
82 from .Trees import Tree
83
84 INTERLEAVE = 70
85 SPECIAL_COMMANDS = [
86 "charstatelabels",
87 "charlabels",
88 "taxlabels",
89 "taxset",
90 "charset",
91 "charpartition",
92 "taxpartition",
93 "matrix",
94 "tree",
95 "utree",
96 "translate",
97 "codonposset",
98 "title",
99 ]
100 KNOWN_NEXUS_BLOCKS = ["trees", "data", "characters", "taxa", "sets", "codons"]
101 PUNCTUATION = "()[]{}/\\,;:=*'\"`+-<>"
102 MRBAYESSAFE = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_"
103 WHITESPACE = " \t\n"
104 # SPECIALCOMMENTS = ['!', '&', '%', '/', '\\', '@'] # original list of special comments
105 SPECIALCOMMENTS = [
106 "&"
107 ] # supported special comment ('tree' command), all others are ignored
108 CHARSET = "chars"
109 TAXSET = "taxa"
110 CODONPOSITIONS = "codonpositions"
111 DEFAULTNEXUS = (
112 "#NEXUS\nbegin data; dimensions ntax=0 nchar=0; format datatype=dna; end; "
113 )
114
115
116 class NexusError(Exception):
117 pass
118
119
120 class CharBuffer(object):
121 """Helps reading NEXUS-words and characters from a buffer (semi-PRIVATE).
122
123 This class is not intended for public use (any more).
124 """
125
126 def __init__(self, string):
127 if string:
128 self.buffer = list(string)
129 else:
130 self.buffer = []
131
132 def peek(self):
133 if self.buffer:
134 return self.buffer[0]
135 else:
136 return None
137
138 def peek_nonwhitespace(self):
139 b = "".join(self.buffer).strip()
140 if b:
141 return b[0]
142 else:
143 return None
144
145 def __next__(self):
146 if self.buffer:
147 return self.buffer.pop(0)
148 else:
149 return None
150
151 if sys.version_info[0] < 3:
152
153 def next(self):
154 """Deprecated Python 2 style alias for Python 3 style __next__ method."""
155 return self.__next__()
156
157 def next_nonwhitespace(self):
158 while True:
159 p = next(self)
160 if p is None:
161 break
162 if p not in WHITESPACE:
163 return p
164 return None
165
166 def skip_whitespace(self):
167 while self.buffer[0] in WHITESPACE:
168 self.buffer = self.buffer[1:]
169
170 def next_until(self, target):
171 for t in target:
172 try:
173 pos = self.buffer.index(t)
174 except ValueError:
175 pass
176 else:
177 found = "".join(self.buffer[:pos])
178 self.buffer = self.buffer[pos:]
179 return found
180 else:
181 return None
182
183 def peek_word(self, word):
184 return "".join(self.buffer[: len(word)]) == word
185
186 def next_word(self):
187 """Return the next NEXUS word from a string.
188
189 This deals with single and double quotes, whitespace and punctuation.
190 """
191
192 word = []
193 quoted = False
194 first = self.next_nonwhitespace() # get first character
195 if not first: # return empty if only whitespace left
196 return None
197 word.append(first)
198 if first == "'": # word starts with a quote
199 quoted = "'"
200 elif first == '"':
201 quoted = '"'
202 elif first in PUNCTUATION: # if it's punctuation, return immediately
203 return first
204 while True:
205 c = self.peek()
206 if c == quoted: # a quote?
207 word.append(next(self)) # store quote
208 if self.peek() == quoted: # double quote
209 skip = next(self) # skip second quote
210 elif quoted: # second single quote ends word
211 break
212 elif quoted:
213 word.append(next(self)) # if quoted, then add anything
214 elif not c or c in PUNCTUATION or c in WHITESPACE:
215 # if not quoted and special character, stop
216 break
217 else:
218 word.append(next(self)) # standard character
219 return "".join(word)
220
221 def rest(self):
222 """Return the rest of the string without parsing."""
223 return "".join(self.buffer)
224
225
226 class StepMatrix(object):
227 """Calculate a stepmatrix for weighted parsimony.
228
229 See Wheeler (1990), Cladistics 6:269-275.
230 """
231
232 def __init__(self, symbols, gap):
233 self.data = {}
234 self.symbols = sorted(symbols)
235 if gap:
236 self.symbols.append(gap)
237 for x in self.symbols:
238 for y in [s for s in self.symbols if s != x]:
239 self.set(x, y, 0)
240
241 def set(self, x, y, value):
242 if x > y:
243 x, y = y, x
244 self.data[x + y] = value
245
246 def add(self, x, y, value):
247 if x > y:
248 x, y = y, x
249 self.data[x + y] += value
250
251 def sum(self):
252 return reduce(lambda x, y: x + y, self.data.values())
253
254 def transformation(self):
255 total = self.sum()
256 if total != 0:
257 for k in self.data:
258 self.data[k] = self.data[k] / float(total)
259 return self
260
261 def weighting(self):
262 for k in self.data:
263 if self.data[k] != 0:
264 self.data[k] = -math.log(self.data[k])
265 return self
266
267 def smprint(self, name="your_name_here"):
268 matrix = "usertype %s stepmatrix=%d\n" % (name, len(self.symbols))
269 matrix += " %s\n" % " ".join(self.symbols)
270 for x in self.symbols:
271 matrix += "[%s]".ljust(8) % x
272 for y in self.symbols:
273 if x == y:
274 matrix += " . "
275 else:
276 if x > y:
277 x1, y1 = y, x
278 else:
279 x1, y1 = x, y
280 if self.data[x1 + y1] == 0:
281 matrix += "inf. "
282 else:
283 matrix += "%2.2f".ljust(10) % (self.data[x1 + y1])
284 matrix += "\n"
285 matrix += ";\n"
286 return matrix
287
288
289 def safename(name, mrbayes=False):
290 """Return a taxon identifier according to NEXUS standard.
291
292 Wrap quotes around names with punctuation or whitespace, and double
293 single quotes.
294
295 mrbayes=True: write names without quotes, whitespace or punctuation
296 for the mrbayes software package.
297 """
298 if mrbayes:
299 safe = name.replace(" ", "_")
300 safe = "".join(c for c in safe if c in MRBAYESSAFE)
301 else:
302 safe = name.replace("'", "''")
303 if set(safe).intersection(set(WHITESPACE + PUNCTUATION)):
304 safe = "'" + safe + "'"
305 return safe
306
307
308 def quotestrip(word):
309 """Remove quotes and/or double quotes around identifiers."""
310 if not word:
311 return None
312 while (word.startswith("'") and word.endswith("'")) or (
313 word.startswith('"') and word.endswith('"')
314 ):
315 word = word[1:-1]
316 return word
317
318
319 def get_start_end(sequence, skiplist=["-", "?"]):
320 """Return position of first and last character which is not in skiplist.
321
322 Skiplist defaults to ['-','?'])."""
323
324 length = len(sequence)
325 if length == 0:
326 return None, None
327 end = length - 1
328 while end >= 0 and (sequence[end] in skiplist):
329 end -= 1
330 start = 0
331 while start < length and (sequence[start] in skiplist):
332 start += 1
333 if start == length and end == -1: # empty sequence
334 return -1, -1
335 else:
336 return start, end
337
338
339 def _sort_keys_by_values(p):
340 """Returns a sorted list of keys of p sorted by values of p."""
341 return sorted((pn for pn in p if p[pn]), key=lambda pn: p[pn])
342
343
344 def _make_unique(l):
345 """Check that all values in list are unique and return a pruned and sorted list."""
346 return sorted(set(l))
347
348
349 def _unique_label(previous_labels, label):
350 """Returns a unique name if label is already in previous_labels."""
351 while label in previous_labels:
352 if label.split(".")[-1].startswith("copy"):
353 label = (
354 ".".join(label.split(".")[:-1])
355 + ".copy"
356 + str(eval("0" + label.split(".")[-1][4:]) + 1)
357 )
358 else:
359 label += ".copy"
360 return label
361
362
363 def _seqmatrix2strmatrix(matrix):
364 """Converts a Seq-object matrix to a plain sequence-string matrix."""
365 return dict((t, str(matrix[t])) for t in matrix)
366
367
368 def _compact4nexus(orig_list):
369 """Transform [1 2 3 5 6 7 8 12 15 18 20] (baseindex 0, used in the Nexus class)
370 into '2-4 6-9 13-19\\3 21' (baseindex 1, used in programs like Paup or MrBayes.).
371 """
372
373 if not orig_list:
374 return ""
375 orig_list = sorted(set(orig_list))
376 shortlist = []
377 clist = orig_list[:]
378 clist.append(clist[-1] + 0.5) # dummy value makes it easier
379 while len(clist) > 1:
380 step = 1
381 for i, x in enumerate(clist):
382 if x == clist[0] + i * step: # are we still in the right step?
383 continue
384 elif i == 1 and len(clist) > 3 and clist[i + 1] - x == x - clist[0]:
385 # second element, and possibly at least 3 elements to link,
386 # and the next one is in the right step
387 step = x - clist[0]
388 else: # pattern broke, add all values before current position to new list
389 sub = clist[:i]
390 if len(sub) == 1:
391 shortlist.append(str(sub[0] + 1))
392 else:
393 if step == 1:
394 shortlist.append("%d-%d" % (sub[0] + 1, sub[-1] + 1))
395 else:
396 shortlist.append("%d-%d\\%d" % (sub[0] + 1, sub[-1] + 1, step))
397 clist = clist[i:]
398 break
399 return " ".join(shortlist)
400
401
402 def combine(matrices):
403 """Combine matrices in [(name,nexus-instance),...] and return new nexus instance.
404
405 combined_matrix=combine([(name1,nexus_instance1),(name2,nexus_instance2),...]
406 Character sets, character partitions and taxon sets are prefixed, readjusted
407 and present in the combined matrix.
408 """
409
410 if not matrices:
411 return None
412 name = matrices[0][0]
413 combined = copy.deepcopy(matrices[0][1]) # initiate with copy of first matrix
414 mixed_datatypes = len(set(n[1].datatype for n in matrices)) > 1
415 if mixed_datatypes:
416 # dealing with mixed matrices is application specific.
417 # You take care of that yourself!
418 combined.datatype = "None"
419 # raise NexusError('Matrices must be of same datatype')
420 combined.charlabels = None
421 combined.statelabels = None
422 combined.interleave = False
423 combined.translate = None
424
425 # rename taxon sets and character sets and name them with prefix
426 for cn, cs in combined.charsets.items():
427 combined.charsets["%s.%s" % (name, cn)] = cs
428 del combined.charsets[cn]
429 for tn, ts in combined.taxsets.items():
430 combined.taxsets["%s.%s" % (name, tn)] = ts
431 del combined.taxsets[tn]
432 # previous partitions usually don't make much sense in combined matrix
433 # just initiate one new partition parted by single matrices
434 combined.charpartitions = {"combined": {name: list(range(combined.nchar))}}
435 for n, m in matrices[1:]: # add all other matrices
436 both = [t for t in combined.taxlabels if t in m.taxlabels]
437 combined_only = [t for t in combined.taxlabels if t not in both]
438 m_only = [t for t in m.taxlabels if t not in both]
439 for t in both:
440 # concatenate sequences and unify gap and missing character symbols
441 combined.matrix[t] += Seq(
442 str(m.matrix[t])
443 .replace(m.gap, combined.gap)
444 .replace(m.missing, combined.missing),
445 combined.alphabet,
446 )
447 # replace date of missing taxa with symbol for missing data
448 for t in combined_only:
449 combined.matrix[t] += Seq(combined.missing * m.nchar, combined.alphabet)
450 for t in m_only:
451 combined.matrix[t] = Seq(
452 combined.missing * combined.nchar, combined.alphabet
453 ) + Seq(
454 str(m.matrix[t])
455 .replace(m.gap, combined.gap)
456 .replace(m.missing, combined.missing),
457 combined.alphabet,
458 )
459 combined.taxlabels.extend(m_only) # new taxon list
460 for cn, cs in m.charsets.items(): # adjust character sets for new matrix
461 combined.charsets["%s.%s" % (n, cn)] = [x + combined.nchar for x in cs]
462 if m.taxsets:
463 if not combined.taxsets:
464 combined.taxsets = {}
465 # update taxon sets
466 combined.taxsets.update(
467 dict(("%s.%s" % (n, tn), ts) for tn, ts in m.taxsets.items())
468 )
469 # update new charpartition
470 combined.charpartitions["combined"][n] = list(
471 range(combined.nchar, combined.nchar + m.nchar)
472 )
473 # update charlabels
474 if m.charlabels:
475 if not combined.charlabels:
476 combined.charlabels = {}
477 combined.charlabels.update(
478 dict((combined.nchar + i, label) for (i, label) in m.charlabels.items())
479 )
480 combined.nchar += m.nchar # update nchar and ntax
481 combined.ntax += len(m_only)
482
483 # some prefer partitions, some charsets:
484 # make separate charset for ecah initial dataset
485 for c in combined.charpartitions["combined"]:
486 combined.charsets[c] = combined.charpartitions["combined"][c]
487
488 return combined
489
490
491 def _kill_comments_and_break_lines(text):
492 r"""Delete []-delimited comments out of a file and break into lines separated by ';'.
493
494 stripped_text=_kill_comments_and_break_lines(text):
495 Nested and multiline comments are allowed. [ and ] symbols within single
496 or double quotes are ignored, newline ends a quote, all symbols with quotes are
497 treated the same (thus not quoting inside comments like [this character ']' ends a comment])
498 Special [&...] and [\...] comments remain untouched, if not inside standard comment.
499 Quotes inside special [& and [\ are treated as normal characters,
500 but no nesting inside these special comments allowed (like [& [\ ]]).
501 ';' ist deleted from end of line.
502
503 NOTE: this function is very slow for large files, and obsolete when using C extension cnexus
504 """
505 if not text:
506 # Empty file/stream
507 return []
508
509 contents = iter(text)
510 newtext = []
511 newline = []
512 quotelevel = ""
513 speciallevel = False
514 commlevel = 0
515 # Parse with one character look ahead (for special comments)
516 t2 = next(contents)
517 while True:
518 t = t2
519 try:
520 t2 = next(contents)
521 except StopIteration:
522 t2 = None
523 if t is None:
524 break
525 if t == quotelevel and not (commlevel or speciallevel):
526 # matching quote ends quotation
527 quotelevel = ""
528 elif (
529 not quotelevel
530 and not (commlevel or speciallevel)
531 and (t == '"' or t == "'")
532 ):
533 # single or double quote starts quotation
534 quotelevel = t
535 elif not quotelevel and t == "[":
536 # opening bracket outside a quote
537 if t2 in SPECIALCOMMENTS and commlevel == 0 and not speciallevel:
538 speciallevel = True
539 else:
540 commlevel += 1
541 elif not quotelevel and t == "]":
542 # closing bracket ioutside a quote
543 if speciallevel:
544 speciallevel = False
545 else:
546 commlevel -= 1
547 if commlevel < 0:
548 raise NexusError("Nexus formatting error: unmatched ]")
549 continue
550 if commlevel == 0:
551 # copy if we're not in comment
552 if t == ";" and not quotelevel:
553 newtext.append("".join(newline))
554 newline = []
555 else:
556 newline.append(t)
557 # level of comments should be 0 at the end of the file
558 if newline:
559 newtext.append("\n".join(newline))
560 if commlevel > 0:
561 raise NexusError("Nexus formatting error: unmatched [")
562 return newtext
563
564
565 def _adjust_lines(lines):
566 """Adjust linebreaks to match ';', strip leading/trailing whitespace.
567
568 list_of_commandlines=_adjust_lines(input_text)
569 Lines are adjusted so that no linebreaks occur within a commandline
570 (except matrix command line)
571 """
572 formatted_lines = []
573 for l in lines:
574 # Convert line endings
575 l = l.replace("\r\n", "\n").replace("\r", "\n").strip()
576 if l.lower().startswith("matrix"):
577 formatted_lines.append(l)
578 else:
579 l = l.replace("\n", " ")
580 if l:
581 formatted_lines.append(l)
582 return formatted_lines
583
584
585 def _replace_parenthesized_ambigs(seq, rev_ambig_values):
586 """Replaces ambigs in xxx(ACG)xxx format by IUPAC ambiguity code."""
587
588 opening = seq.find("(")
589 while opening > -1:
590 closing = seq.find(")")
591 if closing < 0:
592 raise NexusError("Missing closing parenthesis in: " + seq)
593 elif closing < opening:
594 raise NexusError("Missing opening parenthesis in: " + seq)
595 ambig = "".join(sorted(seq[opening + 1 : closing]))
596 ambig_code = rev_ambig_values[ambig.upper()]
597 if ambig != ambig.upper():
598 ambig_code = ambig_code.lower()
599 seq = seq[:opening] + ambig_code + seq[closing + 1 :]
600 opening = seq.find("(")
601 return seq
602
603
604 class Commandline(object):
605 """Represent a commandline as command and options."""
606
607 def __init__(self, line, title):
608 self.options = {}
609 options = []
610 self.command = None
611 try:
612 # Assume matrix (all other command lines have been stripped of \n)
613 self.command, options = line.strip().split("\n", 1)
614 except ValueError: # Not matrix
615 # self.command,options=line.split(' ',1) # no: could be tab or spaces (translate...)
616 self.command = line.split()[0]
617 options = " ".join(line.split()[1:])
618 self.command = self.command.strip().lower()
619 if self.command in SPECIAL_COMMANDS:
620 # special command that need newlines and order of options preserved
621 self.options = options.strip()
622 else:
623 if len(options) > 0:
624 try:
625 options = options.replace("=", " = ").split()
626 valued_indices = [
627 (n - 1, n, n + 1)
628 for n in range(len(options))
629 if options[n] == "=" and n != 0 and n != len((options))
630 ]
631 indices = []
632 for sl in valued_indices:
633 indices.extend(sl)
634 token_indices = [n for n in range(len(options)) if n not in indices]
635 for opt in valued_indices:
636 # self.options[options[opt[0]].lower()] = options[opt[2]].lower()
637 self.options[options[opt[0]].lower()] = options[opt[2]]
638 for token in token_indices:
639 self.options[options[token].lower()] = None
640 except ValueError:
641 raise NexusError("Incorrect formatting in line: %s" % line)
642
643
644 class Block(object):
645 """Represent a NEXUS block with block name and list of commandlines."""
646
647 def __init__(self, title=None):
648 self.title = title
649 self.commandlines = []
650
651
652 class Nexus(object):
653 def __init__(self, input=None):
654 self.ntax = 0 # number of taxa
655 self.nchar = 0 # number of characters
656 self.unaltered_taxlabels = (
657 []
658 ) # taxlabels as the appear in the input file (incl. duplicates, etc.)
659 self.taxlabels = [] # labels for taxa, ordered by their id
660 self.charlabels = None # ... and for characters
661 self.statelabels = None # ... and for states
662 self.datatype = "dna" # (standard), dna, rna, nucleotide, protein
663 self.respectcase = False # case sensitivity
664 self.missing = "?" # symbol for missing characters
665 self.gap = "-" # symbol for gap
666 self.symbols = None # set of symbols
667 self.equate = None # set of symbol synonyms
668 self.matchchar = None # matching char for matrix representation
669 self.labels = None # left, right, no
670 self.transpose = False # whether matrix is transposed
671 self.interleave = False # whether matrix is interleaved
672 self.tokens = False # unsupported
673 self.eliminate = None # unsupported
674 self.matrix = None # ...
675 self.unknown_blocks = [] # blocks we don't care about
676 self.taxsets = {}
677 self.charsets = {}
678 self.charpartitions = {}
679 self.taxpartitions = {}
680 self.trees = [] # list of Trees (instances of Tree class)
681 self.translate = None # Dict to translate taxon <-> taxon numbers
682 self.structured = [] # structured input representation
683 self.set = {} # dict of the set command to set various options
684 self.options = {} # dict of the options command in the data block
685 self.codonposset = (
686 None # name of the charpartition that defines codon positions
687 )
688
689 # some defaults
690 self.options["gapmode"] = "missing"
691
692 if input:
693 self.read(input)
694 else:
695 self.read(DEFAULTNEXUS)
696
697 def get_original_taxon_order(self):
698 """Included for backwards compatibility (DEPRECATED)."""
699 return self.taxlabels
700
701 def set_original_taxon_order(self, value):
702 """Included for backwards compatibility (DEPRECATED)."""
703 self.taxlabels = value
704
705 original_taxon_order = property(get_original_taxon_order, set_original_taxon_order)
706
707 def read(self, input):
708 """Read and parse NEXUS input (a filename, file-handle, or string)."""
709
710 # 1. Assume we have the name of a file in the execution dir or a
711 # file-like object.
712 # Note we need to add parsing of the path to dir/filename
713 try:
714 with as_handle(input) as fp:
715 file_contents = fp.read()
716 self.filename = getattr(fp, "name", "Unknown_nexus_file")
717 except (TypeError, IOError, AttributeError):
718 # 2 Assume we have a string from a fh.read()
719 if isinstance(input, str):
720 file_contents = input
721 self.filename = "input_string"
722 else:
723 print(input.strip()[:50])
724 raise NexusError("Unrecognized input: %s ..." % input[:100])
725 file_contents = file_contents.strip()
726 if file_contents.startswith("#NEXUS"):
727 file_contents = file_contents[6:]
728 commandlines = _get_command_lines(file_contents)
729 # get rid of stupid 'NEXUS token - in merged treefiles, this might appear multiple times'
730 for i, cl in enumerate(commandlines):
731 try:
732 if cl[:6].upper() == "#NEXUS":
733 commandlines[i] = cl[6:].strip()
734 except:
735 pass
736 # now loop through blocks (we parse only data in known blocks, thus ignoring non-block commands
737 nexus_block_gen = self._get_nexus_block(commandlines)
738 while True:
739 try:
740 title, contents = next(nexus_block_gen)
741 except StopIteration:
742 break
743 if title in KNOWN_NEXUS_BLOCKS:
744 self._parse_nexus_block(title, contents)
745 else:
746 self._unknown_nexus_block(title, contents)
747
748 def _get_nexus_block(self, file_contents):
749 """Generator for looping through Nexus blocks."""
750 inblock = False
751 blocklines = []
752 while file_contents:
753 cl = file_contents.pop(0)
754 if cl.lower().startswith("begin"):
755 if not inblock:
756 inblock = True
757 title = cl.split()[1].lower()
758 else:
759 raise NexusError("Illegal block nesting in block %s" % title)
760 elif cl.lower().startswith("end"):
761 if inblock:
762 inblock = False
763 yield title, blocklines
764 blocklines = []
765 else:
766 raise NexusError("Unmatched 'end'.")
767 elif inblock:
768 blocklines.append(cl)
769
770 def _unknown_nexus_block(self, title, contents):
771 block = Block()
772 block.commandlines.append(contents)
773 block.title = title
774 self.unknown_blocks.append(block)
775
776 def _parse_nexus_block(self, title, contents):
777 """Parse a known Nexus Block (PRIVATE)."""
778 # attached the structered block representation
779 self._apply_block_structure(title, contents)
780 # now check for taxa,characters,data blocks. If this stuff is defined more than once
781 # the later occurences will override the previous ones.
782 block = self.structured[-1]
783 for line in block.commandlines:
784 try:
785 getattr(self, "_" + line.command)(line.options)
786 except AttributeError:
787 raise NexusError("Unknown command: %s " % line.command)
788
789 def _title(self, options):
790 pass
791
792 def _link(self, options):
793 pass
794
795 def _dimensions(self, options):
796 if "ntax" in options:
797 self.ntax = eval(options["ntax"])
798 if "nchar" in options:
799 self.nchar = eval(options["nchar"])
800
801 def _format(self, options):
802 # print options
803 # we first need to test respectcase, then symbols (which depends on respectcase)
804 # then datatype (which, if standard, depends on symbols and respectcase in order to generate
805 # dicts for ambiguous values and alphabet
806 if "respectcase" in options:
807 self.respectcase = True
808 # adjust symbols to for respectcase
809 if "symbols" in options:
810 self.symbols = options["symbols"]
811 if (self.symbols.startswith('"') and self.symbols.endswith('"')) or (
812 self.symbols.startswith("'") and self.symbols.endswith("'")
813 ):
814 self.symbols = self.symbols[1:-1].replace(" ", "")
815 if not self.respectcase:
816 self.symbols = self.symbols.lower() + self.symbols.upper()
817 self.symbols = list(set(self.symbols))
818 if "datatype" in options:
819 self.datatype = options["datatype"].lower()
820 # TODO: Create a fresh instance of each object for self.alphabet
821 if self.datatype == "dna" or self.datatype == "nucleotide":
822 self.alphabet = IUPAC.ambiguous_dna
823 self.ambiguous_values = IUPACData.ambiguous_dna_values.copy()
824 self.unambiguous_letters = IUPACData.unambiguous_dna_letters
825 elif self.datatype == "rna":
826 self.alphabet = IUPAC.ambiguous_rna
827 self.ambiguous_values = IUPACData.ambiguous_rna_values.copy()
828 self.unambiguous_letters = IUPACData.unambiguous_rna_letters
829 elif self.datatype == "protein":
830 # TODO - Should this not be ExtendedIUPACProtein?
831 self.alphabet = IUPAC.protein
832 self.ambiguous_values = {
833 "B": "DN",
834 "Z": "EQ",
835 "X": IUPACData.protein_letters,
836 }
837 # that's how PAUP handles it
838 self.unambiguous_letters = IUPACData.protein_letters + "*" # stop-codon
839 elif self.datatype == "standard":
840 raise NexusError("Datatype standard is not yet supported.")
841 # self.alphabet = None
842 # self.ambiguous_values = {}
843 # if not self.symbols:
844 # self.symbols = '01' # if nothing else defined, then 0 and 1 are the default states
845 # self.unambiguous_letters = self.symbols
846 else:
847 raise NexusError("Unsupported datatype: " + self.datatype)
848 self.valid_characters = (
849 "".join(self.ambiguous_values) + self.unambiguous_letters
850 )
851 if not self.respectcase:
852 self.valid_characters = (
853 self.valid_characters.lower() + self.valid_characters.upper()
854 )
855 # we have to sort the reverse ambig coding dict key characters:
856 # to be sure that it's 'ACGT':'N' and not 'GTCA':'N'
857 rev = dict(
858 (i[1], i[0]) for i in self.ambiguous_values.items() if i[0] != "X"
859 )
860 self.rev_ambiguous_values = {}
861 for k, v in rev.items():
862 key = sorted(c for c in k)
863 self.rev_ambiguous_values["".join(key)] = v
864 # overwrite symbols for datype rna,dna,nucleotide
865 if self.datatype in ["dna", "rna", "nucleotide"]:
866 self.symbols = self.alphabet.letters
867 if self.missing not in self.ambiguous_values:
868 self.ambiguous_values[self.missing] = (
869 self.unambiguous_letters + self.gap
870 )
871 self.ambiguous_values[self.gap] = self.gap
872 elif self.datatype == "standard":
873 if not self.symbols:
874 self.symbols = ["1", "0"]
875 if "missing" in options:
876 self.missing = options["missing"][0]
877 if "gap" in options:
878 self.gap = options["gap"][0]
879 if "equate" in options:
880 self.equate = options["equate"]
881 if "matchchar" in options:
882 self.matchchar = options["matchchar"][0]
883 if "labels" in options:
884 self.labels = options["labels"]
885 if "transpose" in options:
886 raise NexusError("TRANSPOSE is not supported!")
887 self.transpose = True
888 if "interleave" in options:
889 if options["interleave"] is None or options["interleave"].lower() == "yes":
890 self.interleave = True
891 if "tokens" in options:
892 self.tokens = True
893 if "notokens" in options:
894 self.tokens = False
895
896 def _set(self, options):
897 self.set = options
898
899 def _options(self, options):
900 self.options = options
901
902 def _eliminate(self, options):
903 self.eliminate = options
904
905 def _taxlabels(self, options):
906 """Get taxon labels (PRIVATE).
907
908 As the taxon names are already in the matrix, this is superfluous
909 except for transpose matrices, which are currently unsupported anyway.
910 Thus, we ignore the taxlabels command to make handling of duplicate
911 taxon names easier.
912 """
913 pass
914 # self.taxlabels = []
915 # opts = CharBuffer(options)
916 # while True:
917 # taxon = quotestrip(opts.next_word())
918 # if not taxon:
919 # break
920 # self.taxlabels.append(taxon)
921
922 def _check_taxlabels(self, taxon):
923 """Check for presence of taxon in self.taxlabels."""
924 # According to NEXUS standard, underscores shall be treated as spaces...,
925 # so checking for identity is more difficult
926 nextaxa = dict((t.replace(" ", "_"), t) for t in self.taxlabels)
927 nexid = taxon.replace(" ", "_")
928 return nextaxa.get(nexid)
929
930 def _charlabels(self, options):
931 self.charlabels = {}
932 opts = CharBuffer(options)
933 while True:
934 # get id and state
935 w = opts.next_word()
936 if (
937 w is None
938 ): # McClade saves and reads charlabel-lists with terminal comma?!
939 break
940 identifier = self._resolve(w, set_type=CHARSET)
941 state = quotestrip(opts.next_word())
942 self.charlabels[identifier] = state
943 # check for comma or end of command
944 c = opts.next_nonwhitespace()
945 if c is None:
946 break
947 elif c != ",":
948 raise NexusError("Missing ',' in line %s." % options)
949
950 def _charstatelabels(self, options):
951 # warning: charstatelabels supports only charlabels-syntax!
952 self._charlabels(options)
953
954 def _statelabels(self, options):
955 # self.charlabels = options
956 # print 'Command statelabels is not supported and will be ignored.'
957 pass
958
959 def _matrix(self, options):
960 if not self.ntax or not self.nchar:
961 raise NexusError("Dimensions must be specified before matrix!")
962 self.matrix = {}
963 taxcount = 0
964 first_matrix_block = True
965
966 # eliminate empty lines and leading/trailing whitespace
967 lines = [l.strip() for l in options.split("\n") if l.strip() != ""]
968 lineiter = iter(lines)
969 while True:
970 try:
971 l = next(lineiter)
972 except StopIteration:
973 if taxcount < self.ntax:
974 raise NexusError("Not enough taxa in matrix.")
975 elif taxcount > self.ntax:
976 raise NexusError("Too many taxa in matrix.")
977 else:
978 break
979 # count the taxa and check for interleaved matrix
980 taxcount += 1
981 ##print taxcount
982 if taxcount > self.ntax:
983 if not self.interleave:
984 raise NexusError(
985 "Too many taxa in matrix - should matrix be interleaved?"
986 )
987 else:
988 taxcount = 1
989 first_matrix_block = False
990 # get taxon name and sequence
991 linechars = CharBuffer(l)
992 id = quotestrip(linechars.next_word())
993 l = linechars.rest().strip()
994 chars = ""
995 if self.interleave:
996 # interleaved matrix
997 # print 'In interleave'
998 if l:
999 chars = "".join(l.split())
1000 else:
1001 chars = "".join(next(lineiter).split())
1002 else:
1003 # non-interleaved matrix
1004 chars = "".join(l.split())
1005 while len(chars) < self.nchar:
1006 l = next(lineiter)
1007 chars += "".join(l.split())
1008 iupac_seq = Seq(
1009 _replace_parenthesized_ambigs(chars, self.rev_ambiguous_values),
1010 self.alphabet,
1011 )
1012 # first taxon has the reference sequence if matchhar is used
1013 if taxcount == 1:
1014 refseq = iupac_seq
1015 else:
1016 if self.matchchar:
1017 while True:
1018 p = str(iupac_seq).find(self.matchchar)
1019 if p == -1:
1020 break
1021 iupac_seq = Seq(
1022 str(iupac_seq)[:p] + refseq[p] + str(iupac_seq)[p + 1 :],
1023 self.alphabet,
1024 )
1025 # check for invalid characters
1026 for i, c in enumerate(str(iupac_seq)):
1027 if (
1028 c not in self.valid_characters
1029 and c != self.gap
1030 and c != self.missing
1031 ):
1032 raise NexusError(
1033 "Taxon %s: Illegal character %s in sequence %s "
1034 "(check dimensions/interleaving)" % (id, c, iupac_seq)
1035 )
1036 # add sequence to matrix
1037 if first_matrix_block:
1038 self.unaltered_taxlabels.append(id)
1039 id = _unique_label(list(self.matrix.keys()), id)
1040 self.matrix[id] = iupac_seq
1041 self.taxlabels.append(id)
1042 else:
1043 # taxon names need to be in the same order in each interleaved block
1044 id = _unique_label(self.taxlabels[: taxcount - 1], id)
1045 taxon_present = self._check_taxlabels(id)
1046 if taxon_present:
1047 self.matrix[taxon_present] += iupac_seq
1048 else:
1049 raise NexusError(
1050 "Taxon %s not in first block of interleaved "
1051 "matrix. Check matrix dimensions and interleave." % id
1052 )
1053 # check all sequences for length according to nchar
1054 for taxon in self.matrix:
1055 if len(self.matrix[taxon]) != self.nchar:
1056 raise NexusError(
1057 "Matrix Nchar %d does not match data length (%d) for taxon %s"
1058 % (self.nchar, len(self.matrix[taxon]), taxon)
1059 )
1060 # check that taxlabels is identical with matrix.keys. If not, it's a problem
1061 matrixkeys = sorted(self.matrix)
1062 taxlabelssort = sorted(self.taxlabels[:])
1063 assert matrixkeys == taxlabelssort, (
1064 "ERROR: TAXLABELS must be identical with MATRIX. "
1065 + "Please Report this as a bug, and send in data file."
1066 )
1067
1068 def _translate(self, options):
1069 self.translate = {}
1070 opts = CharBuffer(options)
1071 while True:
1072 try:
1073 # get id and state
1074 identifier = int(opts.next_word())
1075 label = quotestrip(opts.next_word())
1076 self.translate[identifier] = label
1077 # check for comma or end of command
1078 c = opts.next_nonwhitespace()
1079 if c is None:
1080 break
1081 elif c != ",":
1082 raise NexusError("Missing ',' in line %s." % options)
1083 except NexusError:
1084 raise
1085 except:
1086 raise NexusError("Format error in line %s." % options)
1087
1088 def _utree(self, options):
1089 """Some software (clustalx) uses 'utree' to denote an unrooted tree."""
1090 self._tree(options)
1091
1092 def _tree(self, options):
1093 opts = CharBuffer(options)
1094 if opts.peek_nonwhitespace() == "*":
1095 # a star can be used to make it the default tree in some software packages
1096 dummy = opts.next_nonwhitespace()
1097 name = opts.next_word()
1098 if opts.next_nonwhitespace() != "=":
1099 raise NexusError("Syntax error in tree description: %s" % options[:50])
1100 rooted = False
1101 weight = 1.0
1102 while opts.peek_nonwhitespace() == "[":
1103 open = opts.next_nonwhitespace()
1104 symbol = next(opts)
1105 if symbol != "&":
1106 raise NexusError(
1107 "Illegal special comment [%s...] in tree description: %s"
1108 % (symbol, options[:50])
1109 )
1110 special = next(opts)
1111 value = opts.next_until("]")
1112 closing = next(opts)
1113 if special == "R":
1114 rooted = True
1115 elif special == "U":
1116 rooted = False
1117 elif special == "W":
1118 weight = float(value)
1119 tree = Tree(name=name, weight=weight, rooted=rooted, tree=opts.rest().strip())
1120 # if there's an active translation table, translate
1121 if self.translate:
1122 for n in tree.get_terminals():
1123 try:
1124 tree.node(n).data.taxon = safename(
1125 self.translate[int(tree.node(n).data.taxon)]
1126 )
1127 except (ValueError, KeyError):
1128 raise NexusError(
1129 "Unable to substitute %s using 'translate' data."
1130 % tree.node(n).data.taxon
1131 )
1132 self.trees.append(tree)
1133
1134 def _apply_block_structure(self, title, lines):
1135 block = Block("")
1136 block.title = title
1137 for line in lines:
1138 block.commandlines.append(Commandline(line, title))
1139 self.structured.append(block)
1140
1141 def _taxset(self, options):
1142 name, taxa = self._get_indices(options, set_type=TAXSET)
1143 self.taxsets[name] = _make_unique(taxa)
1144
1145 def _charset(self, options):
1146 name, sites = self._get_indices(options, set_type=CHARSET)
1147 self.charsets[name] = _make_unique(sites)
1148
1149 def _taxpartition(self, options):
1150 taxpartition = {}
1151 quotelevel = False
1152 opts = CharBuffer(options)
1153 name = self._name_n_vector(opts)
1154 if not name:
1155 raise NexusError("Formatting error in taxpartition: %s " % options)
1156 # now collect thesubbpartitions and parse them
1157 # subpartitons separated by commas - which unfortunately could be part of a quoted identifier...
1158 # this is rather unelegant, but we have to avoid double-parsing and potential change of special nexus-words
1159 sub = ""
1160 while True:
1161 w = next(opts)
1162 if w is None or (w == "," and not quotelevel):
1163 subname, subindices = self._get_indices(
1164 sub, set_type=TAXSET, separator=":"
1165 )
1166 taxpartition[subname] = _make_unique(subindices)
1167 sub = ""
1168 if w is None:
1169 break
1170 else:
1171 if w == "'":
1172 quotelevel = not quotelevel
1173 sub += w
1174 self.taxpartitions[name] = taxpartition
1175
1176 def _codonposset(self, options):
1177 """Read codon positions from a codons block as written from McClade.
1178
1179 Here codonposset is just a fancy name for a character partition with
1180 the name CodonPositions and the partitions N,1,2,3
1181 """
1182
1183 prev_partitions = list(self.charpartitions.keys())
1184 self._charpartition(options)
1185 # mcclade calls it CodonPositions, but you never know...
1186 codonname = [n for n in self.charpartitions if n not in prev_partitions]
1187 if codonname == [] or len(codonname) > 1:
1188 raise NexusError("Formatting Error in codonposset: %s " % options)
1189 else:
1190 self.codonposset = codonname[0]
1191
1192 def _codeset(self, options):
1193 pass
1194
1195 def _charpartition(self, options):
1196 charpartition = {}
1197 quotelevel = False
1198 opts = CharBuffer(options)
1199 name = self._name_n_vector(opts)
1200 if not name:
1201 raise NexusError("Formatting error in charpartition: %s " % options)
1202 # now collect thesubbpartitions and parse them
1203 # subpartitons separated by commas - which unfortunately could be part of a quoted identifier...
1204 sub = ""
1205 while True:
1206 w = next(opts)
1207 if w is None or (w == "," and not quotelevel):
1208 subname, subindices = self._get_indices(
1209 sub, set_type=CHARSET, separator=":"
1210 )
1211 charpartition[subname] = _make_unique(subindices)
1212 sub = ""
1213 if w is None:
1214 break
1215 else:
1216 if w == "'":
1217 quotelevel = not quotelevel
1218 sub += w
1219 self.charpartitions[name] = charpartition
1220
1221 def _get_indices(self, options, set_type=CHARSET, separator="="):
1222 """Parse the taxset/charset specification (PRIVATE).
1223
1224 e.g. '1 2 3 - 5 dog cat 10 - 20 \\ 3'
1225 --> [0,1,2,3,4,'dog','cat',9,12,15,18]
1226 """
1227 opts = CharBuffer(options)
1228 name = self._name_n_vector(opts, separator=separator)
1229 indices = self._parse_list(opts, set_type=set_type)
1230 if indices is None:
1231 raise NexusError("Formatting error in line: %s " % options)
1232 return name, indices
1233
1234 def _name_n_vector(self, opts, separator="="):
1235 """Extract name and check that it's not in vector format."""
1236 rest = opts.rest()
1237 name = opts.next_word()
1238 # we ignore * before names
1239 if name == "*":
1240 name = opts.next_word()
1241 if not name:
1242 raise NexusError("Formatting error in line: %s " % rest)
1243 name = quotestrip(name)
1244 if opts.peek_nonwhitespace == "(":
1245 open = opts.next_nonwhitespace()
1246 qualifier = open.next_word()
1247 close = opts.next_nonwhitespace()
1248 if qualifier.lower() == "vector":
1249 raise NexusError("Unsupported VECTOR format in line %s" % (opts))
1250 elif qualifier.lower() != "standard":
1251 raise NexusError("Unknown qualifier %s in line %s" % (qualifier, opts))
1252 if opts.next_nonwhitespace() != separator:
1253 raise NexusError("Formatting error in line: %s " % rest)
1254 return name
1255
1256 def _parse_list(self, options_buffer, set_type):
1257 """Parse a NEXUS list (PRIVATE).
1258
1259 e.g. [1, 2, 4-8\\2, dog, cat] --> [1,2,4,6,8,17,21],
1260 (assuming dog is taxon no. 17 and cat is taxon no. 21).
1261 """
1262 plain_list = []
1263 if options_buffer.peek_nonwhitespace():
1264 try:
1265 # capture all possible exceptions and treat them as formatting
1266 # errors, if they are not NexusError
1267 while True:
1268 identifier = options_buffer.next_word() # next list element
1269 if not identifier: # end of list?
1270 break
1271 start = self._resolve(identifier, set_type=set_type)
1272 if options_buffer.peek_nonwhitespace() == "-": # followd by -
1273 end = start
1274 step = 1
1275 # get hyphen and end of range
1276 hyphen = options_buffer.next_nonwhitespace()
1277 end = self._resolve(
1278 options_buffer.next_word(), set_type=set_type
1279 )
1280 if set_type == CHARSET:
1281 if (
1282 options_buffer.peek_nonwhitespace() == "\\"
1283 ): # followd by \
1284 backslash = options_buffer.next_nonwhitespace()
1285 step = int(
1286 options_buffer.next_word()
1287 ) # get backslash and step
1288 plain_list.extend(range(start, end + 1, step))
1289 else:
1290 if isinstance(start, list) or isinstance(end, list):
1291 raise NexusError(
1292 "Name if character sets not allowed in range definition: %s"
1293 % identifier
1294 )
1295 start = self.taxlabels.index(start)
1296 end = self.taxlabels.index(end)
1297 taxrange = self.taxlabels[start : end + 1]
1298 plain_list.extend(taxrange)
1299 else:
1300 if isinstance(
1301 start, list
1302 ): # start was the name of charset or taxset
1303 plain_list.extend(start)
1304 else: # start was an ordinary identifier
1305 plain_list.append(start)
1306 except NexusError:
1307 raise
1308 except:
1309 return None
1310 return plain_list
1311
1312 def _resolve(self, identifier, set_type=None):
1313 """Translate identifier in list into character/taxon index.
1314
1315 Characters (which are referred to by their index in Nexus.py):
1316 Plain numbers are returned minus 1 (Nexus indices to python indices)
1317 Text identifiers are translated into their indices (if plain character identifiers),
1318 the first hit in charlabels is returned (charlabels don't need to be unique)
1319 or the range of indices is returned (if names of character sets).
1320 Taxa (which are referred to by their unique name in Nexus.py):
1321 Plain numbers are translated in their taxon name, underscores and spaces are considered equal.
1322 Names are returned unchanged (if plain taxon identifiers), or the names in
1323 the corresponding taxon set is returned.
1324 """
1325 identifier = quotestrip(identifier)
1326 if not set_type:
1327 raise NexusError("INTERNAL ERROR: Need type to resolve identifier.")
1328 if set_type == CHARSET:
1329 try:
1330 n = int(identifier)
1331 except ValueError:
1332 if self.charlabels and identifier in self.charlabels.values():
1333 for k in self.charlabels:
1334 if self.charlabels[k] == identifier:
1335 return k
1336 elif self.charsets and identifier in self.charsets:
1337 return self.charsets[identifier]
1338 else:
1339 raise NexusError("Unknown character identifier: %s" % identifier)
1340 else:
1341 if n <= self.nchar:
1342 return n - 1
1343 else:
1344 raise NexusError(
1345 "Illegal character identifier: %d>nchar (=%d)."
1346 % (identifier, self.nchar)
1347 )
1348 elif set_type == TAXSET:
1349 try:
1350 n = int(identifier)
1351 except ValueError:
1352 taxlabels_id = self._check_taxlabels(identifier)
1353 if taxlabels_id:
1354 return taxlabels_id
1355 elif self.taxsets and identifier in self.taxsets:
1356 return self.taxsets[identifier]
1357 else:
1358 raise NexusError("Unknown taxon identifier: %s" % identifier)
1359 else:
1360 if n > 0 and n <= self.ntax:
1361 return self.taxlabels[n - 1]
1362 else:
1363 raise NexusError(
1364 "Illegal taxon identifier: %d>ntax (=%d)."
1365 % (identifier, self.ntax)
1366 )
1367 else:
1368 raise NexusError("Unknown set specification: %s." % set_type)
1369
1370 def _stateset(self, options):
1371 # Not implemented
1372 pass
1373
1374 def _changeset(self, options):
1375 # Not implemented
1376 pass
1377
1378 def _treeset(self, options):
1379 # Not implemented
1380 pass
1381
1382 def _treepartition(self, options):
1383 # Not implemented
1384 pass
1385
1386 def write_nexus_data_partitions(
1387 self,
1388 matrix=None,
1389 filename=None,
1390 blocksize=None,
1391 interleave=False,
1392 exclude=[],
1393 delete=[],
1394 charpartition=None,
1395 comment="",
1396 mrbayes=False,
1397 ):
1398 """Writes a nexus file for each partition in charpartition.
1399
1400 Only non-excluded characters and non-deleted taxa are included,
1401 just the data block is written.
1402 """
1403
1404 if not matrix:
1405 matrix = self.matrix
1406 if not matrix:
1407 return
1408 if not filename:
1409 filename = self.filename
1410 if charpartition:
1411 pfilenames = {}
1412 for p in charpartition:
1413 total_exclude = [] + exclude
1414 total_exclude.extend(
1415 c for c in range(self.nchar) if c not in charpartition[p]
1416 )
1417 total_exclude = _make_unique(total_exclude)
1418 pcomment = comment + "\nPartition: " + p + "\n"
1419 dot = filename.rfind(".")
1420 if dot > 0:
1421 pfilename = filename[:dot] + "_" + p + ".data"
1422 else:
1423 pfilename = filename + "_" + p
1424 pfilenames[p] = pfilename
1425 self.write_nexus_data(
1426 filename=pfilename,
1427 matrix=matrix,
1428 blocksize=blocksize,
1429 interleave=interleave,
1430 exclude=total_exclude,
1431 delete=delete,
1432 comment=pcomment,
1433 append_sets=False,
1434 mrbayes=mrbayes,
1435 )
1436 return pfilenames
1437 else:
1438 fn = self.filename + ".data"
1439 self.write_nexus_data(
1440 filename=fn,
1441 matrix=matrix,
1442 blocksize=blocksize,
1443 interleave=interleave,
1444 exclude=exclude,
1445 delete=delete,
1446 comment=comment,
1447 append_sets=False,
1448 mrbayes=mrbayes,
1449 )
1450 return fn
1451
1452 def write_nexus_data(
1453 self,
1454 filename=None,
1455 matrix=None,
1456 exclude=[],
1457 delete=[],
1458 blocksize=None,
1459 interleave=False,
1460 interleave_by_partition=False,
1461 comment=None,
1462 omit_NEXUS=False,
1463 append_sets=True,
1464 mrbayes=False,
1465 codons_block=True,
1466 ):
1467 """Writes a nexus file with data and sets block to a file or handle.
1468
1469 Character sets and partitions are appended by default, and are
1470 adjusted according to excluded characters (i.e. character sets
1471 still point to the same sites (not necessarily same positions),
1472 without including the deleted characters.
1473
1474 filename - Either a filename as a string (which will be opened,
1475 written to and closed), or a handle object (which will
1476 be written to but NOT closed).
1477 interleave_by_partition - Optional name of partition (string)
1478 omit_NEXUS - Boolean. If true, the '#NEXUS' line normally at the
1479 start of the file is omitted.
1480
1481 Returns the filename/handle used to write the data.
1482 """
1483 if not matrix:
1484 matrix = self.matrix
1485 if not matrix:
1486 return
1487 if not filename:
1488 filename = self.filename
1489 if [t for t in delete if not self._check_taxlabels(t)]:
1490 raise NexusError(
1491 "Unknown taxa: %s"
1492 % ", ".join(set(delete).difference(set(self.taxlabels)))
1493 )
1494 if interleave_by_partition:
1495 if not interleave_by_partition in self.charpartitions:
1496 raise NexusError("Unknown partition: %r" % interleave_by_partition)
1497 else:
1498 partition = self.charpartitions[interleave_by_partition]
1499 # we need to sort the partition names by starting position before we exclude characters
1500 names = _sort_keys_by_values(partition)
1501 newpartition = {}
1502 for p in partition:
1503 newpartition[p] = [c for c in partition[p] if c not in exclude]
1504 # how many taxa and how many characters are left?
1505 undelete = [
1506 taxon for taxon in self.taxlabels if taxon in matrix and taxon not in delete
1507 ]
1508 cropped_matrix = _seqmatrix2strmatrix(
1509 self.crop_matrix(matrix, exclude=exclude, delete=delete)
1510 )
1511 ntax_adjusted = len(undelete)
1512 nchar_adjusted = len(cropped_matrix[undelete[0]])
1513 if not undelete or (undelete and undelete[0] == ""):
1514 return
1515
1516 with as_handle(filename, mode="w") as fh:
1517 if not omit_NEXUS:
1518 fh.write("#NEXUS\n")
1519 if comment:
1520 fh.write("[" + comment + "]\n")
1521 fh.write("begin data;\n")
1522 fh.write(
1523 "\tdimensions ntax=%d nchar=%d;\n" % (ntax_adjusted, nchar_adjusted)
1524 )
1525 fh.write("\tformat datatype=" + self.datatype)
1526 if self.respectcase:
1527 fh.write(" respectcase")
1528 if self.missing:
1529 fh.write(" missing=" + self.missing)
1530 if self.gap:
1531 fh.write(" gap=" + self.gap)
1532 if self.matchchar:
1533 fh.write(" matchchar=" + self.matchchar)
1534 if self.labels:
1535 fh.write(" labels=" + self.labels)
1536 if self.equate:
1537 fh.write(" equate=" + self.equate)
1538 if interleave or interleave_by_partition:
1539 fh.write(" interleave")
1540 fh.write(";\n")
1541 # if self.taxlabels:
1542 # fh.write('taxlabels '+' '.join(self.taxlabels)+';\n')
1543 if self.charlabels:
1544 newcharlabels = self._adjust_charlabels(exclude=exclude)
1545 clkeys = sorted(newcharlabels)
1546 fh.write(
1547 "charlabels "
1548 + ", ".join(
1549 "%s %s" % (k + 1, safename(newcharlabels[k])) for k in clkeys
1550 )
1551 + ";\n"
1552 )
1553 fh.write("matrix\n")
1554 if not blocksize:
1555 if interleave:
1556 blocksize = 70
1557 else:
1558 blocksize = self.nchar
1559 # delete deleted taxa and ecxclude excluded characters...
1560 namelength = max(len(safename(t, mrbayes=mrbayes)) for t in undelete)
1561 if interleave_by_partition:
1562 # interleave by partitions, but adjust partitions with regard to excluded characters
1563 seek = 0
1564 for p in names:
1565 fh.write("[%s: %s]\n" % (interleave_by_partition, p))
1566 if len(newpartition[p]) > 0:
1567 for taxon in undelete:
1568 fh.write(
1569 safename(taxon, mrbayes=mrbayes).ljust(namelength + 1)
1570 )
1571 fh.write(
1572 cropped_matrix[taxon][
1573 seek : seek + len(newpartition[p])
1574 ]
1575 + "\n"
1576 )
1577 fh.write("\n")
1578 else:
1579 fh.write("[empty]\n\n")
1580 seek += len(newpartition[p])
1581 elif interleave:
1582 for seek in range(0, nchar_adjusted, blocksize):
1583 for taxon in undelete:
1584 fh.write(safename(taxon, mrbayes=mrbayes).ljust(namelength + 1))
1585 fh.write(cropped_matrix[taxon][seek : seek + blocksize] + "\n")
1586 fh.write("\n")
1587 else:
1588 for taxon in undelete:
1589 if blocksize < nchar_adjusted:
1590 fh.write(safename(taxon, mrbayes=mrbayes) + "\n")
1591 else:
1592 fh.write(safename(taxon, mrbayes=mrbayes).ljust(namelength + 1))
1593 taxon_seq = cropped_matrix[taxon]
1594 for seek in range(0, nchar_adjusted, blocksize):
1595 fh.write(taxon_seq[seek : seek + blocksize] + "\n")
1596 del taxon_seq
1597 fh.write(";\nend;\n")
1598 if append_sets:
1599 if codons_block:
1600 fh.write(
1601 self.append_sets(
1602 exclude=exclude,
1603 delete=delete,
1604 mrbayes=mrbayes,
1605 include_codons=False,
1606 )
1607 )
1608 fh.write(
1609 self.append_sets(
1610 exclude=exclude,
1611 delete=delete,
1612 mrbayes=mrbayes,
1613 codons_only=True,
1614 )
1615 )
1616 else:
1617 fh.write(
1618 self.append_sets(
1619 exclude=exclude, delete=delete, mrbayes=mrbayes
1620 )
1621 )
1622 return filename
1623
1624 def append_sets(
1625 self,
1626 exclude=[],
1627 delete=[],
1628 mrbayes=False,
1629 include_codons=True,
1630 codons_only=False,
1631 ):
1632 """Returns a sets block."""
1633 if not self.charsets and not self.taxsets and not self.charpartitions:
1634 return ""
1635 if codons_only:
1636 setsb = ["\nbegin codons"]
1637 else:
1638 setsb = ["\nbegin sets"]
1639 # - now if characters have been excluded, the character sets need to be adjusted,
1640 # so that they still point to the right character positions
1641 # calculate a list of offsets: for each deleted character, the following character position
1642 # in the new file will have an additional offset of -1
1643 offset = 0
1644 offlist = []
1645 for c in range(self.nchar):
1646 if c in exclude:
1647 offset += 1
1648 offlist.append(
1649 -1
1650 ) # dummy value as these character positions are excluded
1651 else:
1652 offlist.append(c - offset)
1653 # now adjust each of the character sets
1654 if not codons_only:
1655 for n, ns in self.charsets.items():
1656 cset = [offlist[c] for c in ns if c not in exclude]
1657 if cset:
1658 setsb.append(
1659 "charset %s = %s" % (safename(n), _compact4nexus(cset))
1660 )
1661 for n, s in self.taxsets.items():
1662 tset = [safename(t, mrbayes=mrbayes) for t in s if t not in delete]
1663 if tset:
1664 setsb.append("taxset %s = %s" % (safename(n), " ".join(tset)))
1665 for n, p in self.charpartitions.items():
1666 if not include_codons and n == CODONPOSITIONS:
1667 continue
1668 elif codons_only and n != CODONPOSITIONS:
1669 continue
1670 # as characters have been excluded, the partitions must be adjusted
1671 # if a partition is empty, it will be omitted from the charpartition command
1672 # (although paup allows charpartition part=t1:,t2:,t3:1-100)
1673 names = _sort_keys_by_values(p)
1674 newpartition = {}
1675 for sn in names:
1676 nsp = [offlist[c] for c in p[sn] if c not in exclude]
1677 if nsp:
1678 newpartition[sn] = nsp
1679 if newpartition:
1680 if include_codons and n == CODONPOSITIONS:
1681 command = "codonposset"
1682 else:
1683 command = "charpartition"
1684 setsb.append(
1685 "%s %s = %s"
1686 % (
1687 command,
1688 safename(n),
1689 ", ".join(
1690 "%s: %s" % (sn, _compact4nexus(newpartition[sn]))
1691 for sn in names
1692 if sn in newpartition
1693 ),
1694 )
1695 )
1696 # now write charpartititions, much easier than charpartitions
1697 for n, p in self.taxpartitions.items():
1698 names = _sort_keys_by_values(p)
1699 newpartition = {}
1700 for sn in names:
1701 nsp = [t for t in p[sn] if t not in delete]
1702 if nsp:
1703 newpartition[sn] = nsp
1704 if newpartition:
1705 setsb.append(
1706 "taxpartition %s = %s"
1707 % (
1708 safename(n),
1709 ", ".join(
1710 "%s: %s"
1711 % (
1712 safename(sn),
1713 " ".join(safename(x) for x in newpartition[sn]),
1714 )
1715 for sn in names
1716 if sn in newpartition
1717 ),
1718 )
1719 )
1720 # add 'end' and return everything
1721 setsb.append("end;\n")
1722 if len(setsb) == 2: # begin and end only
1723 return ""
1724 else:
1725 return ";\n".join(setsb)
1726
1727 def export_fasta(self, filename=None, width=70):
1728 """Writes matrix into a fasta file."""
1729 if not filename:
1730 if "." in self.filename and self.filename.split(".")[-1].lower() in [
1731 "paup",
1732 "nexus",
1733 "nex",
1734 "dat",
1735 ]:
1736 filename = ".".join(self.filename.split(".")[:-1]) + ".fas"
1737 else:
1738 filename = self.filename + ".fas"
1739 with open(filename, "w") as fh:
1740 for taxon in self.taxlabels:
1741 fh.write(">" + safename(taxon) + "\n")
1742 for i in range(0, len(str(self.matrix[taxon])), width):
1743 fh.write(str(self.matrix[taxon])[i : i + width] + "\n")
1744 return filename
1745
1746 def export_phylip(self, filename=None):
1747 """Writes matrix into a PHYLIP file.
1748
1749 Note that this writes a relaxed PHYLIP format file, where the names
1750 are not truncated, nor checked for invalid characters."""
1751 if not filename:
1752 if "." in self.filename and self.filename.split(".")[-1].lower() in [
1753 "paup",
1754 "nexus",
1755 "nex",
1756 "dat",
1757 ]:
1758 filename = ".".join(self.filename.split(".")[:-1]) + ".phy"
1759 else:
1760 filename = self.filename + ".phy"
1761 with open(filename, "w") as fh:
1762 fh.write("%d %d\n" % (self.ntax, self.nchar))
1763 for taxon in self.taxlabels:
1764 fh.write("%s %s\n" % (safename(taxon), str(self.matrix[taxon])))
1765 return filename
1766
1767 def constant(self, matrix=None, delete=[], exclude=[]):
1768 """Return a list with all constant characters."""
1769 if not matrix:
1770 matrix = self.matrix
1771 undelete = [t for t in self.taxlabels if t in matrix and t not in delete]
1772 if not undelete:
1773 return None
1774 elif len(undelete) == 1:
1775 return [x for x in range(len(matrix[undelete[0]])) if x not in exclude]
1776 # get the first sequence and expand all ambiguous values
1777 constant = [
1778 (x, self.ambiguous_values.get(n.upper(), n.upper()))
1779 for x, n in enumerate(str(matrix[undelete[0]]))
1780 if x not in exclude
1781 ]
1782
1783 for taxon in undelete[1:]:
1784 newconstant = []
1785 for site in constant:
1786 # print '%d (paup=%d)' % (site[0],site[0]+1),
1787 seqsite = matrix[taxon][site[0]].upper()
1788 # print seqsite,'checked against',site[1],'\t',
1789 if (
1790 seqsite == self.missing
1791 or (
1792 seqsite == self.gap
1793 and self.options["gapmode"].lower() == "missing"
1794 )
1795 or seqsite == site[1]
1796 ):
1797 # missing or same as before -> ok
1798 newconstant.append(site)
1799 elif (
1800 seqsite in site[1]
1801 or site[1] == self.missing
1802 or (
1803 self.options["gapmode"].lower() == "missing"
1804 and site[1] == self.gap
1805 )
1806 ):
1807 # subset of an ambig or only missing in previous -> take subset
1808 newconstant.append(
1809 (site[0], self.ambiguous_values.get(seqsite, seqsite))
1810 )
1811 elif seqsite in self.ambiguous_values:
1812 # is it an ambig: check the intersection with prev. values
1813 intersect = set(self.ambiguous_values[seqsite]).intersection(
1814 set(site[1])
1815 )
1816 if intersect:
1817 newconstant.append((site[0], "".join(intersect)))
1818 # print 'ok'
1819 # else:
1820 # print 'failed'
1821 # else:
1822 # print 'failed'
1823 constant = newconstant
1824 cpos = [s[0] for s in constant]
1825 return cpos
1826
1827 def cstatus(self, site, delete=[], narrow=True):
1828 """Summarize character.
1829
1830 narrow=True: paup-mode (a c ? --> ac; ? ? ? --> ?)
1831 narrow=false: (a c ? --> a c g t -; ? ? ? --> a c g t -)
1832 """
1833 undelete = [t for t in self.taxlabels if t not in delete]
1834 if not undelete:
1835 return None
1836 cstatus = []
1837 for t in undelete:
1838 c = self.matrix[t][site].upper()
1839 if self.options.get("gapmode") == "missing" and c == self.gap:
1840 c = self.missing
1841 if narrow and c == self.missing:
1842 if c not in cstatus:
1843 cstatus.append(c)
1844 else:
1845 cstatus.extend(b for b in self.ambiguous_values[c] if b not in cstatus)
1846 if self.missing in cstatus and narrow and len(cstatus) > 1:
1847 cstatus = [c for c in cstatus if c != self.missing]
1848 cstatus.sort()
1849 return cstatus
1850
1851 def weighted_stepmatrix(self, name="your_name_here", exclude=[], delete=[]):
1852 """Calculates a stepmatrix for weighted parsimony.
1853
1854 See Wheeler (1990), Cladistics 6:269-275 and
1855 Felsenstein (1981), Biol. J. Linn. Soc. 16:183-196
1856 """
1857 m = StepMatrix(self.unambiguous_letters, self.gap)
1858 for site in [s for s in range(self.nchar) if s not in exclude]:
1859 cstatus = self.cstatus(site, delete)
1860 for i, b1 in enumerate(cstatus[:-1]):
1861 for b2 in cstatus[i + 1 :]:
1862 m.add(b1.upper(), b2.upper(), 1)
1863 return m.transformation().weighting().smprint(name=name)
1864
1865 def crop_matrix(self, matrix=None, delete=[], exclude=[]):
1866 """Return a matrix without deleted taxa and excluded characters."""
1867 if not matrix:
1868 matrix = self.matrix
1869 if [t for t in delete if not self._check_taxlabels(t)]:
1870 raise NexusError(
1871 "Unknown taxa: %s" % ", ".join(set(delete).difference(self.taxlabels))
1872 )
1873 if exclude != []:
1874 undelete = [t for t in self.taxlabels if t in matrix and t not in delete]
1875 if not undelete:
1876 return {}
1877 m = [str(matrix[k]) for k in undelete]
1878 sitesm = [s for i, s in enumerate(zip(*m)) if i not in exclude]
1879 if sitesm == []:
1880 return dict((t, Seq("", self.alphabet)) for t in undelete)
1881 else:
1882 m = [Seq(s, self.alphabet) for s in ("".join(x) for x in zip(*sitesm))]
1883 return dict(zip(undelete, m))
1884 else:
1885 return dict(
1886 (t, matrix[t])
1887 for t in self.taxlabels
1888 if t in matrix and t not in delete
1889 )
1890
1891 def bootstrap(self, matrix=None, delete=[], exclude=[]):
1892 """Return a bootstrapped matrix."""
1893 if not matrix:
1894 matrix = self.matrix
1895 seqobjects = isinstance(
1896 matrix[list(matrix.keys())[0]], Seq
1897 ) # remember if Seq objects
1898 cm = self.crop_matrix(delete=delete, exclude=exclude) # crop data out
1899 if not cm: # everything deleted?
1900 return {}
1901 elif not cm[list(cm.keys())[0]]: # everything excluded?
1902 return cm
1903 undelete = [t for t in self.taxlabels if t in cm]
1904 if seqobjects:
1905 sitesm = list(zip(*[str(cm[t]) for t in undelete]))
1906 alphabet = matrix[list(matrix.keys())[0]].alphabet
1907 else:
1908 sitesm = list(zip(*[cm[t] for t in undelete]))
1909 bootstrapsitesm = [
1910 sitesm[random.randint(0, len(sitesm) - 1)] for i in range(len(sitesm))
1911 ]
1912 bootstrapseqs = ["".join(x) for x in zip(*bootstrapsitesm)]
1913 if seqobjects:
1914 bootstrapseqs = [Seq(s, alphabet) for s in bootstrapseqs]
1915 return dict(zip(undelete, bootstrapseqs))
1916
1917 def add_sequence(self, name, sequence):
1918 """Adds a sequence (string) to the matrix."""
1919
1920 if not name:
1921 raise NexusError("New sequence must have a name")
1922
1923 diff = self.nchar - len(sequence)
1924 if diff < 0:
1925 self.insert_gap(self.nchar, -diff)
1926 elif diff > 0:
1927 sequence += self.missing * diff
1928
1929 if name in self.taxlabels:
1930 unique_name = _unique_label(self.taxlabels, name)
1931 # print "WARNING: Sequence name %s is already present. Sequence was added as %s." % (name,unique_name)
1932 else:
1933 unique_name = name
1934
1935 assert (
1936 unique_name not in self.matrix
1937 ), "ERROR. There is a discrepancy between taxlabels and matrix keys. Report this as a bug."
1938
1939 self.matrix[unique_name] = Seq(sequence, self.alphabet)
1940 self.ntax += 1
1941 self.taxlabels.append(unique_name)
1942 self.unaltered_taxlabels.append(name)
1943
1944 def insert_gap(self, pos, n=1, leftgreedy=False):
1945 """Add a gap into the matrix and adjust charsets and partitions.
1946
1947 pos=0: first position
1948 pos=nchar: last position
1949 """
1950
1951 def _adjust(set, x, d, leftgreedy=False):
1952 """Adjusts character sets if gaps are inserted, taking care of
1953 new gaps within a coherent character set."""
1954 # if 3 gaps are inserted at pos. 9 in a set that looks like 1 2 3 8 9 10 11 13 14 15
1955 # then the adjusted set will be 1 2 3 8 9 10 11 12 13 14 15 16 17 18
1956 # but inserting into position 8 it will stay like 1 2 3 11 12 13 14 15 16 17 18
1957 set.sort()
1958 addpos = 0
1959 for i, c in enumerate(set):
1960 if c >= x:
1961 set[i] = c + d
1962 # if we add gaps within a group of characters, we want the gap position included in this group
1963 if c == x:
1964 if leftgreedy or (i > 0 and set[i - 1] == c - 1):
1965 addpos = i
1966 if addpos > 0:
1967 set[addpos:addpos] = list(range(x, x + d))
1968 return set
1969
1970 if pos < 0 or pos > self.nchar:
1971 raise NexusError("Illegal gap position: %d" % pos)
1972 if n == 0:
1973 return
1974 sitesm = list(zip(*[str(self.matrix[t]) for t in self.taxlabels]))
1975 sitesm[pos:pos] = [["-"] * len(self.taxlabels)] * n
1976 mapped = ["".join(x) for x in zip(*sitesm)]
1977 listed = [
1978 (taxon, Seq(mapped[i], self.alphabet))
1979 for i, taxon in enumerate(self.taxlabels)
1980 ]
1981 self.matrix = dict(listed)
1982 self.nchar += n
1983 # now adjust character sets
1984 for i, s in self.charsets.items():
1985 self.charsets[i] = _adjust(s, pos, n, leftgreedy=leftgreedy)
1986 for p in self.charpartitions:
1987 for sp, s in self.charpartitions[p].items():
1988 self.charpartitions[p][sp] = _adjust(s, pos, n, leftgreedy=leftgreedy)
1989 # now adjust character state labels
1990 self.charlabels = self._adjust_charlabels(insert=[pos] * n)
1991 return self.charlabels
1992
1993 def _adjust_charlabels(self, exclude=None, insert=None):
1994 """Return adjusted indices of self.charlabels if characters are excluded or inserted."""
1995 if exclude and insert:
1996 raise NexusError("Can't exclude and insert at the same time")
1997 if not self.charlabels:
1998 return None
1999 labels = sorted(self.charlabels)
2000 newcharlabels = {}
2001 if exclude:
2002 exclude.sort()
2003 exclude.append(sys.maxsize)
2004 excount = 0
2005 for c in labels:
2006 if not c in exclude:
2007 while c > exclude[excount]:
2008 excount += 1
2009 newcharlabels[c - excount] = self.charlabels[c]
2010 elif insert:
2011 insert.sort()
2012 insert.append(sys.maxsize)
2013 icount = 0
2014 for c in labels:
2015 while c >= insert[icount]:
2016 icount += 1
2017 newcharlabels[c + icount] = self.charlabels[c]
2018 else:
2019 return self.charlabels
2020 return newcharlabels
2021
2022 def invert(self, charlist):
2023 """Returns all character indices that are not in charlist."""
2024 return [c for c in range(self.nchar) if c not in charlist]
2025
2026 def gaponly(self, include_missing=False):
2027 """Return gap-only sites."""
2028 gap = set(self.gap)
2029 if include_missing:
2030 gap.add(self.missing)
2031 sitesm = zip(*[str(self.matrix[t]) for t in self.taxlabels])
2032 return [i for i, site in enumerate(sitesm) if set(site).issubset(gap)]
2033
2034 def terminal_gap_to_missing(self, missing=None, skip_n=True):
2035 """Replaces all terminal gaps with missing character.
2036
2037 Mixtures like ???------??------- are properly resolved."""
2038
2039 if not missing:
2040 missing = self.missing
2041 replace = [self.missing, self.gap]
2042 if not skip_n:
2043 replace.extend(["n", "N"])
2044 for taxon in self.taxlabels:
2045 sequence = str(self.matrix[taxon])
2046 length = len(sequence)
2047 start, end = get_start_end(sequence, skiplist=replace)
2048 if start == -1 and end == -1:
2049 sequence = missing * length
2050 else:
2051 sequence = sequence[: end + 1] + missing * (length - end - 1)
2052 sequence = start * missing + sequence[start:]
2053 assert length == len(sequence), (
2054 "Illegal sequence manipulation in Nexus.terminal_gap_to_missing in taxon %s"
2055 % taxon
2056 )
2057 self.matrix[taxon] = Seq(sequence, self.alphabet)