forked from biopython/biopython
/
Nexus.py
2157 lines (1966 loc) · 82.6 KB
/
Nexus.py
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
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2005-2008 by Frank Kauff & Cymon J. Cox. All rights reserved.
# Revisions copyright 2014-2015 by Joe Cora (standard data)
#
# This file is part of the Biopython distribution and governed by your
# choice of the "Biopython License Agreement" or the "BSD 3-Clause License".
# Please see the LICENSE file that should have been included as part of this
# package.
"""Nexus class. Parse the contents of a NEXUS file.
Based upon 'NEXUS: An extensible file format for systematic information'
Maddison, Swofford, Maddison. 1997. Syst. Biol. 46(4):590-621
"""
from functools import reduce
import copy
import math
import random
import sys
from Bio import File
from Bio.Data import IUPACData
from Bio.Seq import Seq
from Bio.Nexus.StandardData import StandardData
from Bio.Nexus.Trees import Tree
INTERLEAVE = 70
SPECIAL_COMMANDS = [
"charstatelabels",
"charlabels",
"taxlabels",
"taxset",
"charset",
"charpartition",
"taxpartition",
"matrix",
"tree",
"utree",
"translate",
"codonposset",
"title",
]
KNOWN_NEXUS_BLOCKS = ["trees", "data", "characters", "taxa", "sets", "codons"]
PUNCTUATION = "()[]{}\\,;:=*\\'\"`+-<>"
MRBAYESSAFE = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_"
WHITESPACE = " \t\n"
# SPECIALCOMMENTS = ['!','&','%','/','\\','@'] # original list of special comments
SPECIALCOMMENTS = [
"&"
] # supported special comment ('tree' command), all others are ignored
CHARSET = "chars"
TAXSET = "taxa"
CODONPOSITIONS = "codonpositions"
DEFAULTNEXUS = (
"#NEXUS\nbegin data; dimensions ntax=0 nchar=0; format datatype=dna; end; "
)
class NexusError(Exception):
"""Provision for the management of Nexus exceptions."""
pass
class CharBuffer:
"""Helps reading NEXUS-words and characters from a buffer (semi-PRIVATE).
This class is not intended for public use (any more).
"""
def __init__(self, string):
"""Initialize the class."""
if string:
self.buffer = list(string)
else:
self.buffer = []
def peek(self):
"""Return the first character from the buffer."""
if self.buffer:
return self.buffer[0]
else:
return None
def peek_nonwhitespace(self):
"""Return the first character from the buffer, do not include spaces."""
b = "".join(self.buffer).strip()
if b:
return b[0]
else:
return None
def __next__(self):
"""Iterate over NEXUS characters in the file."""
if self.buffer:
return self.buffer.pop(0)
else:
return None
def next_nonwhitespace(self):
"""Check for next non whitespace character in NEXUS file."""
while True:
p = next(self)
if p is None:
break
if p not in WHITESPACE:
return p
return None
def skip_whitespace(self):
"""Skip whitespace characters in NEXUS file."""
while self.buffer[0] in WHITESPACE:
self.buffer = self.buffer[1:]
def next_until(self, target):
"""Iterate over the NEXUS file until a target character is reached."""
for t in target:
try:
pos = self.buffer.index(t)
except ValueError:
pass
else:
found = "".join(self.buffer[:pos])
self.buffer = self.buffer[pos:]
return found
else:
return None
def peek_word(self, word):
"""Return a word stored in the buffer."""
return "".join(self.buffer[: len(word)]) == word
def next_word(self):
"""Return the next NEXUS word from a string.
This deals with single and double quotes, whitespace and punctuation.
"""
word = []
quoted = False
# get first character
first = self.next_nonwhitespace()
if not first:
# return empty if only whitespace left
return None
word.append(first)
if first == "'":
quoted = "'"
elif first == '"':
quoted = '"'
elif first in PUNCTUATION:
# if it's non-quote punctuation, return immediately
return first
while True:
c = self.peek()
if c == quoted: # a quote?
word.append(next(self)) # store quote
if self.peek() == quoted: # double quote
next(self) # skip second quote
elif quoted: # second single quote ends word
break
elif quoted:
# if quoted, then add anything
word.append(next(self))
elif not c or c in PUNCTUATION or c in WHITESPACE:
# if not quoted and special character, stop
break
else:
word.append(next(self)) # standard character
return "".join(word)
def rest(self):
"""Return the rest of the string without parsing."""
return "".join(self.buffer)
class StepMatrix:
"""Calculate a stepmatrix for weighted parsimony.
See :
COMBINATORIAL WEIGHTS IN PHYLOGENETIC ANALYSIS - A STATISTICAL PARSIMONY PROCEDURE
Wheeler (1990), Cladistics 6:269-275.
"""
def __init__(self, symbols, gap):
"""Initialize the class."""
self.data = {}
self.symbols = sorted(symbols)
if gap:
self.symbols.append(gap)
for x in self.symbols:
for y in [s for s in self.symbols if s != x]:
self.set(x, y, 0)
def set(self, x, y, value):
"""Set a given value in the matrix's position."""
if x > y:
x, y = y, x
self.data[x + y] = value
def add(self, x, y, value):
"""Add the given value to existing, in matrix's position."""
if x > y:
x, y = y, x
self.data[x + y] += value
def sum(self):
"""Calculate the associations, makes matrix of associations."""
return reduce(lambda x, y: x + y, self.data.values())
def transformation(self):
"""Calculate the transformation matrix.
Normalizes the columns of the matrix of associations.
"""
total = self.sum()
if total != 0:
for k in self.data:
self.data[k] = self.data[k] / float(total)
return self
def weighting(self):
"""Calculate the Phylogenetic weight matrix.
Constructed from the logarithmic transformation of the
transformation matrix.
"""
for k in self.data:
if self.data[k] != 0:
self.data[k] = -math.log(self.data[k])
return self
def smprint(self, name="your_name_here"):
"""Print a stepmatrix."""
matrix = "usertype %s stepmatrix=%d\n" % (name, len(self.symbols))
matrix += " %s\n" % " ".join(self.symbols)
for x in self.symbols:
matrix += "[%s]".ljust(8) % x
for y in self.symbols:
if x == y:
matrix += " . "
else:
if x > y:
x1, y1 = y, x
else:
x1, y1 = x, y
if self.data[x1 + y1] == 0:
matrix += "inf. "
else:
matrix += "%2.2f".ljust(10) % (self.data[x1 + y1])
matrix += "\n"
matrix += ";\n"
return matrix
def safename(name, mrbayes=False):
"""Return a taxon identifier according to NEXUS standard.
Wrap quotes around names with punctuation or whitespace, and double
single quotes.
mrbayes=True: write names without quotes, whitespace or punctuation
for the mrbayes software package.
"""
if mrbayes:
safe = name.replace(" ", "_")
safe = "".join(c for c in safe if c in MRBAYESSAFE)
else:
safe = name.replace("'", "''")
if set(safe).intersection(set(WHITESPACE + PUNCTUATION)):
safe = "'" + safe + "'"
return safe
def quotestrip(word):
"""Remove quotes and/or double quotes around identifiers."""
if not word:
return None
while (word.startswith("'") and word.endswith("'")) or (
word.startswith('"') and word.endswith('"')
):
word = word[1:-1]
return word
def get_start_end(sequence, skiplist=("-", "?")):
"""Return position of first and last character which is not in skiplist.
Skiplist defaults to ['-','?'].
"""
length = len(sequence)
if length == 0:
return None, None
end = length - 1
while end >= 0 and (sequence[end] in skiplist):
end -= 1
start = 0
while start < length and (sequence[start] in skiplist):
start += 1
if start == length and end == -1: # empty sequence
return -1, -1
else:
return start, end
def _sort_keys_by_values(p):
"""Return a sorted list of keys of p sorted by values of p (PRIVATE)."""
return sorted((pn for pn in p if p[pn]), key=lambda pn: p[pn])
def _make_unique(l):
"""Check all values in list are unique and return a pruned and sorted list (PRIVATE)."""
return sorted(set(l))
def _unique_label(previous_labels, label):
"""Return a unique name if label is already in previous_labels (PRIVATE)."""
while label in previous_labels:
label_split = label.split(".")
if label_split[-1].startswith("copy"):
copy_num = 1
if label_split[-1] != "copy":
copy_num = int(label_split[-1][4:]) + 1
new_label = "%s.copy%s" % (".".join(label_split[:-1]), copy_num)
label = new_label
else:
label += ".copy"
return label
def _seqmatrix2strmatrix(matrix):
"""Convert a Seq-object matrix to a plain sequence-string matrix (PRIVATE)."""
return {t: str(matrix[t]) for t in matrix}
def _compact4nexus(orig_list):
r"""Compact lists for Nexus output (PRIVATE).
Example
-------
>>> _compact4nexus([1, 2, 3, 5, 6, 7, 8, 12, 15, 18, 20])
'2-4 6-9 13-19\\3 21'
Transform [1 2 3 5 6 7 8 12 15 18 20] (baseindex 0, used in the Nexus class)
into '2-4 6-9 13-19\\3 21' (baseindex 1, used in programs like Paup or MrBayes.).
"""
if not orig_list:
return ""
orig_list = sorted(set(orig_list))
shortlist = []
clist = orig_list[:]
clist.append(clist[-1] + 0.5) # dummy value makes it easier
while len(clist) > 1:
step = 1
for i, x in enumerate(clist):
if x == clist[0] + i * step: # are we still in the right step?
continue
elif i == 1 and len(clist) > 3 and clist[i + 1] - x == x - clist[0]:
# second element, and possibly at least 3 elements to link,
# and the next one is in the right step
step = x - clist[0]
else: # pattern broke, add all values before current position to new list
sub = clist[:i]
if len(sub) == 1:
shortlist.append(str(sub[0] + 1))
else:
if step == 1:
shortlist.append("%d-%d" % (sub[0] + 1, sub[-1] + 1))
else:
shortlist.append("%d-%d\\%d" % (sub[0] + 1, sub[-1] + 1, step))
clist = clist[i:]
break
return " ".join(shortlist)
def combine(matrices):
"""Combine matrices in [(name,nexus-instance),...] and return new nexus instance.
combined_matrix=combine([(name1,nexus_instance1),(name2,nexus_instance2),...]
Character sets, character partitions and taxon sets are prefixed, readjusted
and present in the combined matrix.
"""
if not matrices:
return None
name = matrices[0][0]
combined = copy.deepcopy(matrices[0][1]) # initiate with copy of first matrix
mixed_datatypes = len({n[1].datatype for n in matrices}) > 1
if mixed_datatypes:
# dealing with mixed matrices is application specific.
# You take care of that yourself!
combined.datatype = "None"
# raise NexusError('Matrices must be of same datatype')
combined.charlabels = None
combined.statelabels = None
combined.interleave = False
combined.translate = None
# rename taxon sets and character sets and name them with prefix
for cn, cs in combined.charsets.items():
combined.charsets["%s.%s" % (name, cn)] = cs
del combined.charsets[cn]
for tn, ts in combined.taxsets.items():
combined.taxsets["%s.%s" % (name, tn)] = ts
del combined.taxsets[tn]
# previous partitions usually don't make much sense in combined matrix
# just initiate one new partition parted by single matrices
combined.charpartitions = {"combined": {name: list(range(combined.nchar))}}
for n, m in matrices[1:]: # add all other matrices
both = [t for t in combined.taxlabels if t in m.taxlabels]
combined_only = [t for t in combined.taxlabels if t not in both]
m_only = [t for t in m.taxlabels if t not in both]
for t in both:
# concatenate sequences and unify gap and missing character symbols
combined.matrix[t] += Seq(
str(m.matrix[t])
.replace(m.gap, combined.gap)
.replace(m.missing, combined.missing)
)
# replace date of missing taxa with symbol for missing data
for t in combined_only:
combined.matrix[t] += Seq(combined.missing * m.nchar)
for t in m_only:
combined.matrix[t] = Seq(combined.missing * combined.nchar) + Seq(
str(m.matrix[t])
.replace(m.gap, combined.gap)
.replace(m.missing, combined.missing)
)
combined.taxlabels.extend(m_only) # new taxon list
for cn, cs in m.charsets.items(): # adjust character sets for new matrix
combined.charsets["%s.%s" % (n, cn)] = [x + combined.nchar for x in cs]
if m.taxsets:
if not combined.taxsets:
combined.taxsets = {}
# update taxon sets
combined.taxsets.update(
{"%s.%s" % (n, tn): ts for tn, ts in m.taxsets.items()}
)
# update new charpartition
combined.charpartitions["combined"][n] = list(
range(combined.nchar, combined.nchar + m.nchar)
)
# update charlabels
if m.charlabels:
if not combined.charlabels:
combined.charlabels = {}
combined.charlabels.update(
{combined.nchar + i: label for i, label in m.charlabels.items()}
)
combined.nchar += m.nchar # update nchar and ntax
combined.ntax += len(m_only)
# some prefer partitions, some charsets:
# make separate charset for ecah initial dataset
for c in combined.charpartitions["combined"]:
combined.charsets[c] = combined.charpartitions["combined"][c]
return combined
def _kill_comments_and_break_lines(text):
r"""Delete []-delimited comments out of a file and break into lines separated by ';' (PRIVATE).
stripped_text=_kill_comments_and_break_lines(text):
Nested and multiline comments are allowed. [ and ] symbols within single
or double quotes are ignored, newline ends a quote, all symbols with quotes are
treated the same (thus not quoting inside comments like [this character ']' ends a comment])
Special [&...] and [\...] comments remain untouched, if not inside standard comment.
Quotes inside special [& and [\ are treated as normal characters,
but no nesting inside these special comments allowed (like [& [\ ]]).
';' ist deleted from end of line.
NOTE: this function is very slow for large files, and obsolete when using C extension cnexus
"""
if not text:
return ""
contents = iter(text)
newtext = []
newline = []
quotelevel = ""
speciallevel = False
commlevel = 0
# Parse with one character look ahead (for special comments)
t2 = next(contents)
while True:
t = t2
try:
t2 = next(contents)
except StopIteration:
t2 = None
if t is None:
break
if t == quotelevel and not (commlevel or speciallevel):
# matching quote ends quotation
quotelevel = ""
elif (
not quotelevel
and not (commlevel or speciallevel)
and (t == '"' or t == "'")
):
# single or double quote starts quotation
quotelevel = t
elif not quotelevel and t == "[":
# opening bracket outside a quote
if t2 in SPECIALCOMMENTS and commlevel == 0 and not speciallevel:
speciallevel = True
else:
commlevel += 1
elif not quotelevel and t == "]":
# closing bracket ioutside a quote
if speciallevel:
speciallevel = False
else:
commlevel -= 1
if commlevel < 0:
raise NexusError("Nexus formatting error: unmatched ]")
continue
if commlevel == 0:
# copy if we're not in comment
if t == ";" and not quotelevel:
newtext.append("".join(newline))
newline = []
else:
newline.append(t)
# level of comments should be 0 at the end of the file
if newline:
newtext.append("\n".join(newline))
if commlevel > 0:
raise NexusError("Nexus formatting error: unmatched [")
return newtext
def _adjust_lines(lines):
"""Adjust linebreaks to match ';', strip leading/trailing whitespace (PRIVATE).
list_of_commandlines=_adjust_lines(input_text)
Lines are adjusted so that no linebreaks occur within a commandline
(except matrix command line)
"""
formatted_lines = []
for line in lines:
# Convert line endings
line = line.replace("\r\n", "\n").replace("\r", "\n").strip()
if line.lower().startswith("matrix"):
formatted_lines.append(line)
else:
line = line.replace("\n", " ")
if line:
formatted_lines.append(line)
return formatted_lines
def _replace_parenthesized_ambigs(seq, rev_ambig_values):
"""Replace ambigs in xxx(ACG)xxx format by IUPAC ambiguity code (PRIVATE)."""
opening = seq.find("(")
while opening > -1:
closing = seq.find(")")
if closing < 0:
raise NexusError("Missing closing parenthesis in: " + seq)
elif closing < opening:
raise NexusError("Missing opening parenthesis in: " + seq)
ambig = "".join(sorted(seq[opening + 1 : closing]))
ambig_code = rev_ambig_values[ambig.upper()]
if ambig != ambig.upper():
ambig_code = ambig_code.lower()
seq = seq[:opening] + ambig_code + seq[closing + 1 :]
opening = seq.find("(")
return seq
class Commandline:
"""Represent a commandline as command and options."""
def __init__(self, line, title):
"""Initialize the class."""
self.options = {}
options = []
self.command = None
try:
# Assume matrix (all other command lines have been stripped of \n)
self.command, options = line.strip().split("\n", 1)
except ValueError: # Not matrix
# self.command,options=line.split(' ',1) # no: could be tab or spaces (translate...)
self.command = line.split()[0]
options = " ".join(line.split()[1:])
self.command = self.command.strip().lower()
if self.command in SPECIAL_COMMANDS:
# special command that need newlines and order of options preserved
self.options = options.strip()
else:
if len(options) > 0:
try:
options = options.replace("=", " = ").split()
valued_indices = [
(n - 1, n, n + 1)
for n in range(len(options))
if options[n] == "=" and n != 0 and n != len(options)
]
indices = []
for sl in valued_indices:
indices.extend(sl)
token_indices = [n for n in range(len(options)) if n not in indices]
for opt in valued_indices:
# self.options[options[opt[0]].lower()] = options[opt[2]].lower()
self.options[options[opt[0]].lower()] = options[opt[2]]
for token in token_indices:
self.options[options[token].lower()] = None
except ValueError:
raise NexusError(
"Incorrect formatting in line: %s" % line
) from None
class Block:
"""Represent a NEXUS block with block name and list of commandlines."""
def __init__(self, title=None):
"""Initialize the class."""
self.title = title
self.commandlines = []
class Nexus:
"""Create the Nexus class, main class for the management of Nexus files."""
def __init__(self, input=None):
"""Initialize the class."""
self.ntax = 0 # number of taxa
self.nchar = 0 # number of characters
self.unaltered_taxlabels = (
[]
) # taxlabels as the appear in the input file (incl. duplicates, etc.)
self.taxlabels = [] # labels for taxa, ordered by their id
self.charlabels = None # ... and for characters
self.statelabels = None # ... and for states
self.datatype = "dna" # (standard), dna, rna, nucleotide, protein
self.respectcase = False # case sensitivity
self.missing = "?" # symbol for missing characters
self.gap = "-" # symbol for gap
self.symbols = None # set of symbols
self.equate = None # set of symbol synonyms
self.matchchar = None # matching char for matrix representation
self.labels = None # left, right, no
self.transpose = False # whether matrix is transposed
self.interleave = False # whether matrix is interleaved
self.tokens = False # unsupported
self.eliminate = None # unsupported
self.matrix = None # ...
self.unknown_blocks = [] # blocks we don't care about
self.taxsets = {}
self.charsets = {}
self.charpartitions = {}
self.taxpartitions = {}
self.trees = [] # list of Trees (instances of Tree class)
self.translate = None # Dict to translate taxon <-> taxon numbers
self.structured = [] # structured input representation
self.set = {} # dict of the set command to set various options
self.options = {} # dict of the options command in the data block
self.codonposset = (
None # name of the charpartition that defines codon positions
)
# some defaults
self.options["gapmode"] = "missing"
if input:
self.read(input)
else:
self.read(DEFAULTNEXUS)
def get_original_taxon_order(self):
"""Included for backwards compatibility (DEPRECATED)."""
return self.taxlabels
def set_original_taxon_order(self, value):
"""Included for backwards compatibility (DEPRECATED)."""
self.taxlabels = value
original_taxon_order = property(get_original_taxon_order, set_original_taxon_order)
def read(self, input):
"""Read and parse NEXUS input (a filename, file-handle, or string)."""
# 1. Assume we have the name of a file in the execution dir or a
# file-like object.
# Note we need to add parsing of the path to dir/filename
try:
with File.as_handle(input) as fp:
file_contents = fp.read()
self.filename = getattr(fp, "name", "Unknown_nexus_file")
except (TypeError, OSError, AttributeError):
# 2. Assume we have a string from a fh.read()
if isinstance(input, str):
file_contents = input
self.filename = "input_string"
else:
print(input.strip()[:50])
raise NexusError("Unrecognized input: %s ..." % input[:100]) from None
file_contents = file_contents.strip()
if file_contents.startswith("#NEXUS"):
file_contents = file_contents[6:]
commandlines = _get_command_lines(file_contents)
# get rid of stupid 'NEXUS token - in merged treefiles, this might appear multiple times'
for i, cl in enumerate(commandlines):
try:
if cl[:6].upper() == "#NEXUS":
commandlines[i] = cl[6:].strip()
except IndexError:
pass
# now loop through blocks (we parse only data in known blocks, thus ignoring non-block commands
nexus_block_gen = self._get_nexus_block(commandlines)
while True:
try:
title, contents = next(nexus_block_gen)
except StopIteration:
break
if title in KNOWN_NEXUS_BLOCKS:
self._parse_nexus_block(title, contents)
else:
self._unknown_nexus_block(title, contents)
def _get_nexus_block(self, file_contents):
"""Return a generator for looping through Nexus blocks (PRIVATE)."""
inblock = False
blocklines = []
while file_contents:
cl = file_contents.pop(0)
if cl.lower().startswith("begin"):
if not inblock:
inblock = True
title = cl.split()[1].lower()
else:
raise NexusError("Illegal block nesting in block %s" % title)
elif cl.lower().startswith("end"):
if inblock:
inblock = False
yield title, blocklines
blocklines = []
else:
raise NexusError("Unmatched 'end'.")
elif inblock:
blocklines.append(cl)
def _unknown_nexus_block(self, title, contents):
block = Block()
block.commandlines.append(contents)
block.title = title
self.unknown_blocks.append(block)
def _parse_nexus_block(self, title, contents):
"""Parse a known Nexus Block (PRIVATE)."""
# attached the structured block representation
self._apply_block_structure(title, contents)
# now check for taxa,characters,data blocks. If this stuff is defined more than once
# the later occurrences will override the previous ones.
block = self.structured[-1]
for line in block.commandlines:
try:
getattr(self, "_" + line.command)(line.options)
except AttributeError:
raise NexusError("Unknown command: %s " % line.command) from None
def _title(self, options):
pass
def _link(self, options):
pass
def _dimensions(self, options):
if "ntax" in options:
self.ntax = eval(options["ntax"])
if "nchar" in options:
self.nchar = eval(options["nchar"])
def _format(self, options):
# print options
# we first need to test respectcase, then symbols (which depends on respectcase)
# then datatype (which, if standard, depends on symbols and respectcase in order to generate
# dicts for ambiguous values
if "respectcase" in options:
self.respectcase = True
# adjust symbols to for respectcase
if "symbols" in options:
self.symbols = "".join(options["symbols"].split())
if (self.symbols.startswith('"') and self.symbols.endswith('"')) or (
self.symbols.startswith("'") and self.symbols.endswith("'")
):
self.symbols = self.symbols[1:-1]
if not self.respectcase:
self.symbols = list(self.symbols.upper())
# self.symbols = self.symbols.lower() + self.symbols.upper()
# self.symbols = list(set(self.symbols))
if "datatype" in options:
self.datatype = options["datatype"].lower()
if self.datatype == "dna" or self.datatype == "nucleotide":
self.ambiguous_values = IUPACData.ambiguous_dna_values.copy()
self.unambiguous_letters = IUPACData.unambiguous_dna_letters
elif self.datatype == "rna":
self.ambiguous_values = IUPACData.ambiguous_rna_values.copy()
self.unambiguous_letters = IUPACData.unambiguous_rna_letters
elif self.datatype == "protein":
self.ambiguous_values = {
"B": "DN",
"Z": "EQ",
"X": IUPACData.protein_letters,
}
# that's how PAUP handles it
self.unambiguous_letters = IUPACData.protein_letters + "*" # stop-codon
elif self.datatype == "standard":
self.ambiguous_values = {}
if not self.symbols:
# PARSER BUG ##
# This error arises when symbols are absent or when
# whitespace is located within the SYMBOLS command values.
# The Nexus parser quits reading the SYMBOLS line upon
# finding a whitespace character.
raise NexusError(
"Symbols must be defined when using standard datatype. "
"Please remove any whitespace (spaces, tabs, etc.) "
"between values for symbols as this confuses the Nexus parser."
)
self.unambiguous_letters = "".join(self.symbols)
if not self.respectcase:
self.unambiguous_letters += self.unambiguous_letters.lower()
else:
raise NexusError("Unsupported datatype: " + self.datatype)
self.valid_characters = (
"".join(self.ambiguous_values) + self.unambiguous_letters
)
if not self.respectcase:
self.valid_characters = (
self.valid_characters.lower() + self.valid_characters.upper()
)
# we have to sort the reverse ambig coding dict key characters:
# to be sure that it's 'ACGT':'N' and not 'GTCA':'N'
rev = {v: k for k, v in self.ambiguous_values.items() if k != "X"}
self.rev_ambiguous_values = {}
for k, v in rev.items():
key = sorted(c for c in k)
self.rev_ambiguous_values["".join(key)] = v
# overwrite symbols for datatype rna,dna,nucleotide
if self.datatype in ["dna", "nucleotide"]:
self.symbols = IUPACData.ambiguous_dna_letters
if self.missing not in self.ambiguous_values:
self.ambiguous_values[self.missing] = (
self.unambiguous_letters + self.gap
)
self.ambiguous_values[self.gap] = self.gap
elif self.datatype == "rna":
self.symbols = IUPACData.ambiguous_rna_letters
if self.missing not in self.ambiguous_values:
self.ambiguous_values[self.missing] = (
self.unambiguous_letters + self.gap
)
self.ambiguous_values[self.gap] = self.gap
# elif self.datatype == 'standard':
# if not self.symbols:
# self.symbols = ['0', '1']
if "missing" in options:
self.missing = options["missing"][0]
if "gap" in options:
self.gap = options["gap"][0]
if "equate" in options:
self.equate = options["equate"]
if "matchchar" in options:
self.matchchar = options["matchchar"][0]
if "labels" in options:
self.labels = options["labels"]
if "transpose" in options:
# self.transpose = True
raise NexusError("TRANSPOSE is not supported!")
if "interleave" in options:
if options["interleave"] is None or options["interleave"].lower() == "yes":
self.interleave = True
if "tokens" in options:
self.tokens = True
if "notokens" in options:
self.tokens = False
def _set(self, options):
self.set = options
def _options(self, options):
self.options = options
def _eliminate(self, options):
self.eliminate = options
def _taxlabels(self, options):
"""Get taxon labels (PRIVATE).
As the taxon names are already in the matrix, this is superfluous
except for transpose matrices, which are currently unsupported anyway.
Thus, we ignore the taxlabels command to make handling of duplicate
taxon names easier.
"""
pass
# self.taxlabels = []
# opts = CharBuffer(options)
# while True:
# taxon = quotestrip(opts.next_word())
# if not taxon:
# break
# self.taxlabels.append(taxon)
def _check_taxlabels(self, taxon):
"""Check for presence of taxon in self.taxlabels (PRIVATE)."""
# According to NEXUS standard, underscores shall be treated as spaces...,
# so checking for identity is more difficult
nextaxa = {t.replace(" ", "_"): t for t in self.taxlabels}
nexid = taxon.replace(" ", "_")
return nextaxa.get(nexid)
def _charlabels(self, options):
"""Get labels for characters (PRIVATE)."""
self.charlabels = {}
opts = CharBuffer(options)
while True:
# get id and state
w = opts.next_word()
if (
w is None
): # McClade saves and reads charlabel-lists with terminal comma?!
break
identifier = self._resolve(w, set_type=CHARSET)
state = quotestrip(opts.next_word())
self.charlabels[identifier] = state
# check for comma or end of command
c = opts.next_nonwhitespace()
if c is None:
break
elif c != ",":
raise NexusError("Missing ',' in line %s." % options)
def _charstatelabels(self, options):
self.charlabels = {}
self.statelabels = {}
opts = CharBuffer(options)
# Make sure symbols are defined
if not self.symbols:
raise NexusError("Symbols must be defined when using character states")
while True:
# get id and character name
w = opts.next_word()
# McClade saves and reads charlabel-lists with terminal comma?!
if w is None:
break
identifier = self._resolve(w, set_type=CHARSET)
character = quotestrip(opts.next_word())
self.charlabels[identifier] = character
self.statelabels[identifier] = []
# check for comma, slash or end of command
c = opts.next_nonwhitespace()
if c is None:
break
elif c != ",":
# Check if states are defined, otherwise report error
if c != "/":
raise NexusError("Missing ',' in line %s." % options)
# Get the first state
state = quotestrip(opts.next_word())
if state is None:
raise NexusError("Missing character state in line %s." % options)
while True:
# Make sure current state does not exceed number of
# available symbols
if len(self.statelabels[identifier]) > len(self.symbols):
raise NexusError(
"Character states exceed number of available symbols in line %s."
% options
)
# Add the character state to the statelabels
self.statelabels[identifier].append(state)
# Check for another state or comma to end states (last
# character should not have comma at end of states - but
# we'll ignore)
state = quotestrip(opts.next_word())
if state is None:
return
elif state == ",":
break
def _statelabels(self, options):
# self.charlabels = options
# print("Command statelabels is not supported and will be ignored.")