-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsumtimes.py
executable file
·1807 lines (1567 loc) · 64.4 KB
/
sumtimes.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
#! /usr/bin/env python
"""
CLI program for estimating the posterior probability of divergence-time
scenarios from posterior samples of trees.
"""
import sys
import os
import re
import io
import time
import collections
import gzip
import traceback
import tempfile
import argparse
import logging
import unittest
import math
import itertools
import random
try:
import queue
except ImportError:
import Queue as queue
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
import multiprocessing
logging.basicConfig(level=logging.INFO)
_LOG = logging.getLogger(os.path.basename(__file__))
_LOCK = multiprocessing.Lock()
_RNG = random.Random()
_program_info = {
'name': os.path.basename(__file__),
'author': 'Jamie Oaks',
'version': '0.1.0',
'description': __doc__,
'copyright': 'Copyright (C) 2015 Jamie Oaks',
'license': 'GNU GPL version 3 or later',}
try:
import yaml
except ImportError:
raise ImportError("""No module named yaml.
The package 'pyyaml' is required for {0}. Please try to install on the command
line using:
sudo pip install pyyaml
If you do not have admin privileges you can install via:
pip install --user pyyaml
""".format(_program_info['name']))
try:
import dendropy
except ImportError:
raise ImportError("""No module named dendropy.
The package 'dendropy' is required for {0}. Please try to install on the
command line using:
sudo pip install dendropy
If you do not have admin privileges you can install via:
pip install --user dendropy
""".format(_program_info['name']))
def list_splitter(l, n, by_size=False):
"""
Returns generator that yields list `l` as `n` sublists, or as `n`-sized
sublists if `by_size` is True.
>>> import types
>>> ret = list_splitter([1,2,3,4,5,6,7], 2)
>>> isinstance(ret, types.GeneratorType)
True
>>> ret = list(ret)
>>> len(ret) == 2
True
>>> isinstance(ret[0], list)
True
>>> isinstance(ret[1], list)
True
>>> ret[0] == [1,2,3]
True
When ``by_size = False`` and length of input list is not multiple of ``n``,
extra elements are in the last list.
>>> ret[1] == [4,5,6,7]
True
>>> ret = list_splitter([1,2,3,4,5,6,7], 2, by_size = True)
>>> isinstance(ret, types.GeneratorType)
True
>>> ret = list(ret)
>>> len(ret) == 4
True
>>> isinstance(ret[0], list)
True
>>> ret[0] == [1,2]
True
>>> ret[1] == [3,4]
True
>>> ret[3] == [7]
True
"""
if n < 1:
raise StopIteration
elif by_size:
for i in range(0, len(l), n):
yield l[i:i+n]
else:
if n > len(l):
n = len(l)
step_size = len(l)//int(n)
if step_size < 1:
step_size = 1
i = -step_size
for i in range(0, ((n-1)*step_size), step_size):
yield l[i:i+step_size]
yield l[i+step_size:]
def get_new_path(path, max_attempts = 1000):
path = os.path.abspath(os.path.expandvars(os.path.expanduser(path)))
if not os.path.exists(path):
return path
attempt = 0
while True:
p = '-'.join([path, str(attempt)])
if not os.path.exists(p):
return p
if attempt >= max_attempts:
raise Exception('failed to get unique path')
attempt += 1
def expand_path(path):
"""
Returns a full path
>>> expected_path = os.path.expanduser('~/testing')
>>> expected_path == expand_path('~/testing')
True
"""
return os.path.abspath(os.path.expandvars(os.path.expanduser(path)))
def is_file(path):
"""
Returns boolean of whether or not argument is a path
Returns False if path does not exist:
>>> is_file("/this/path/probably/is/not/on/anyones/system")
False
Returns False if the path is a directory:
>>> is_file(os.path.dirname(__file__))
False
Returns True if the path is a file:
>>> is_file(__file__)
True
"""
if not path:
return False
if not os.path.isfile(path):
return False
return True
def is_gzipped(file_path):
"""
Returns True if argument is a path to a gzipped file; False otherwise.
Returns False if path does not exist:
>>> is_gzipped('')
False
Returns False if regular file is empty:
>>> fd, temp_path = tempfile.mkstemp()
>>> os.close(fd)
>>> is_gzipped(temp_path)
False
Returns False for regular file with content:
>>> f = io.open(temp_path, mode = 'w', encoding='utf-8')
>>> f.write(u'testing...') #doctest: +ELLIPSIS
10...
>>> f.close()
>>> is_gzipped(temp_path)
False
>>> os.remove(temp_path)
Returns False if gzipped file is empty:
>>> fd, temp_path = tempfile.mkstemp()
>>> f = gzip.open(temp_path, mode = "wt", compresslevel = 9)
>>> f.write("")
0
>>> f.close()
>>> is_gzipped(temp_path)
False
Returns True if file has gzipped content:
>>> f = gzip.open(temp_path, mode = "wt", compresslevel = 9)
>>> f.write("testing...")
10
>>> f.close()
>>> is_gzipped(temp_path)
True
>>> os.remove(temp_path)
"""
try:
fs = gzip.open(file_path)
d = next(fs)
fs.close()
except:
return False
return True
class ReadFile(object):
"""
Obtain a text stream in read mode from a regular or gzipped file.
Behaves like ``open`` for regular files:
>>> test_path = os.path.join(os.path.dirname(__file__), os.path.pardir,
... 'test-data', 'config.yml')
>>> if os.path.exists(test_path):
... with ReadFile(test_path) as f:
... l = f.next().strip()
... l == "---"
... else:
... True
...
...
True
Behaves like ``open`` for gzipped files:
>>> test_path = os.path.join(os.path.dirname(__file__), os.path.pardir,
... 'test-data', 'trees', 'crocs-1.trees.gz')
>>> if os.path.exists(test_path):
... with ReadFile(test_path) as f:
... l = f.next().strip()
... l == "#NEXUS"
... else:
... True
...
...
True
"""
open_files = set()
def __init__(self, path):
self.path = path
self.gzipped = is_gzipped(self.path)
self.encoding = 'utf-8'
if self.gzipped:
try:
self.file_stream = gzip.open(filename = self.path, mode = 'rt',
encoding = self.encoding)
except (TypeError, ValueError):
self.file_stream = gzip.open(filename = self.path, mode = 'r')
else:
self.file_stream = io.open(self.path, mode = 'r',
encoding = self.encoding)
self.__class__.open_files.add(self.path)
def close(self):
self.file_stream.close()
self.__class__.open_files.remove(self.path)
def __enter__(self):
return self.file_stream
def __exit__(self, type, value, traceback):
self.close()
def __iter__(self):
return self.file_stream.__iter__()
def next(self):
return next(self.file_stream)
def read(self):
return self.file_stream.read()
def readline(self):
return self.file_stream.readline()
def readlines(self):
return self.file_stream.readlines()
def _get_closed(self):
return self.file_stream.closed
closed = property(_get_closed)
def seek(self, i):
self.file_stream.seek(i)
def flush(self):
self.file_stream.flush()
def fileno(self):
return self.file_stream.fileno()
class ConditionEvaluator(object):
"""
>>> ce = ConditionEvaluator(expression_str = "{x} < {y} < {z}")
>>> str(ce)
'{x} < {y} < {z}'
>>> ce.evaluate({'x': 1.0, 'y': 2.0, 'z': 3.0})
True
>>> ce.num_evals
1
>>> ce.num_true
1
Extra keys are okay:
>>> ce.evaluate({'x': 1.0, 'y': 2.0, 'z': 3.0, 'xx': 4.0})
True
>>> ce.num_evals
2
>>> ce.num_true
2
>>> ce.evaluate({'x': 5.0, 'y': 2.0, 'z': 3.0, 'xx': 4.0})
False
>>> ce.num_evals
3
>>> ce.num_true
2
But, all variables in the expression must be keys:
>>> ce.evaluate({'xx': 1.0, 'y': 2.0, 'z': 3.0})
Traceback (most recent call last):
...
KeyError: 'x'
>>> ce = ConditionEvaluator("{x} < {y} = {z}")
Traceback (most recent call last):
...
SyntaxError: Expression contains invalid syntax '='
>>> ce = ConditionEvaluator("{x} < ({y} == {z}")
>>> ce.evaluate({'x': 1.0, 'y': 3.0, 'z': 3.0}) #doctest: +ELLIPSIS
Traceback (most recent call last):
...
SyntaxError: ...
>>> ce = ConditionEvaluator("abs({x} - {y}) < 1.0")
>>> ce.evaluate({'x': 1.1, 'y': 1.3})
True
"""
INVALID_PATTERNS = {
'=': re.compile(r'[^=]=[^=]'),
}
def __init__(self, expression_str):
for k, p in self.INVALID_PATTERNS.items():
if p.search(expression_str):
raise SyntaxError('Expression contains invalid syntax '
'{0!r}'.format(k))
self.expression = expression_str
self.num_evals = 0
self.num_true = 0
def __str__(self):
return self.expression
def evaluate(self, d):
ret = eval(self.expression.format(**d))
self.num_evals += 1
if ret:
self.num_true += 1
return ret
class SumTimesError(Exception):
def __init__(self, *args, **kwargs):
Exception.__init__(self, *args, **kwargs)
class TipSubsetDataError(SumTimesError):
def __init__(self, *args, **kwargs):
SumTimesError.__init__(self, *args, **kwargs)
class PosteriorSampleDataError(SumTimesError):
def __init__(self, *args, **kwargs):
SumTimesError.__init__(self, *args, **kwargs)
class YamlConfigFormattingError(SumTimesError):
def __init__(self, *args, **kwargs):
SumTimesError.__init__(self, *args, **kwargs)
class AnalysisManager(object):
"""
Container for all posterior samples found in the YAML config file.
An instance is initiated with a list of ``posterior``s parsed from
the YAML config file.
"""
number_pattern_string = r'[\d\.Ee\-\+]+'
nodes_pattern_string = r'[\w\s\,\.\-\{\}]+'
node_name_pattern_string = r'(?P<format_key>\{\s*(?P<name>[\w\.\-]+)\s*\})'
codiverged_pattern_string = (
'(?P<block>codiverged\s*\(\s*'
'nodes\s*=\s*\[\s*(?P<nodes>{0})\s*\]'
'\s*,\s*'
'window\s*=\s*(?P<window>[\s\d\.Ee\-\+]+)\s*\))'.format(
nodes_pattern_string))
node_name_pattern = re.compile(node_name_pattern_string)
codiverged_pattern = re.compile(codiverged_pattern_string)
window_pattern_string = '(?P<min>{0})\s*-\s*(?P<max>{0})'.format(number_pattern_string)
window_pattern = re.compile(window_pattern_string)
def __init__(self, config_path, num_processors):
posterior_samples = []
self.config_path = config_path
with ReadFile(self.config_path) as yaml_stream:
config = yaml.load(yaml_stream)
expression_strings = []
for setting_dict in config:
if len(setting_dict) > 1:
raise YamlConfigFormattingError(
"Top level keys must be either 'posterior' or "
"'expression'; found: {0} ".format(", ".join(
setting_dict.keys())))
key = list(setting_dict.keys())[0]
if key.lower() == 'posterior':
posterior_samples.append(PosteriorSample(
config_path = config_path,
**setting_dict[key]))
elif key.lower() == 'expression':
expression_strings.append(setting_dict[key].strip())
else:
raise YamlConfigFormattingError(
"Top level keys must be either 'posterior' or "
"'expression'; found: {0} ".format(key))
self.posterior_sample_map = collections.OrderedDict(zip(
[ps.name for ps in posterior_samples],
posterior_samples))
self.num_processors = int(num_processors)
self.shared_nodes = []
tip_subset_names = []
for ps in self.posterior_samples:
for path in ps.paths:
if not is_file(path):
raise SumTimesError(
"Cannot find path {0!r}".format(path))
for posterior_sample in self.posterior_sample_map.values():
for tip_subset in posterior_sample.tip_subset_map.values():
tip_subset_names.append(tip_subset.name)
self.tip_subset_names = set(tip_subset_names)
self.expression_names = set(
"{{{0}}}".format(n) for n in self.tip_subset_names)
self.expressions = []
for expression_str in expression_strings:
self.expressions.append((
expression_str,
self._parse_expression(expression_str)))
self.min_sample_size = None
def _get_posterior_samples(self):
return self.posterior_sample_map.values()
posterior_samples = property(_get_posterior_samples)
def _parse_expression(self, expression):
new_expression = expression
match_idx = -1
for match_idx, name_match in enumerate(
self.node_name_pattern.finditer(expression)):
name_str = name_match.group('name').strip()
if not name_str in self.tip_subset_names:
raise YamlConfigFormattingError(
"undefined tip subset name {0!r} used in "
"expression:\n{1}".format(name_str, expression))
format_key = name_match.group('format_key')
new_expression = new_expression.replace(format_key, '{{{0}}}'.format(
name_str))
if match_idx < 0:
raise YamlConfigFormattingError(
"no defined tip subset names found in expression:\n"
"{0}".format(expression))
match_idx = -1
for match_idx, codiv_match in enumerate(
self.codiverged_pattern.finditer(new_expression)):
nodes_str = codiv_match.group('nodes')
node_list = [n.strip() for n in nodes_str.split(',')]
nodes = set(node_list)
if len(nodes) != len(node_list):
raise YamlConfigFormattingError(
"duplicated tip subset names in codiverged "
"expression:\n{0}".format(
codiv_match.group('block')))
if not nodes.issubset(self.expression_names):
raise YamlConfigFormattingError(
"undefined tip subset names in codiverged "
"expression:\n{0}".format(
codiv_match.group('block')))
window_str = codiv_match.group('window')
window_width = None
window_min = None
window_max = None
try:
window_width = float(window_str)
except:
window_match = self.window_pattern.match(window_str)
try:
window_min = float(window_match.group('min'))
window_max = float(window_match.group('max'))
except:
raise YamlConfigFormattingError("could not parse codiverged"
" 'window' argument in:\n{0}".format(
codiv_match.group('block')))
conditions = []
if window_width is not None:
for node1, node2 in itertools.combinations(nodes, 2):
conditions.append("(math.fabs({0} - {1}) < {2})".format(
node1, node2, window_width))
else:
for node in nodes:
conditions.append("({0} < {1} < {2})".format(window_min,
node, window_max))
replacement = " & ".join(conditions)
new_expression = new_expression.replace(codiv_match.group('block'),
replacement)
if (match_idx < 0) and (expression.find('codiverged') >= 0):
raise YamlConfigFormattingError(
"could not parse 'codiverged' statement in "
"expression:\n{0}".format(expression))
return ConditionEvaluator(new_expression)
def _get_node_age_extractors(self):
workers = []
for ps in self.posterior_samples:
workers.extend(ps.get_workers())
return workers
def _extract_node_ages(self):
workers = self._get_node_age_extractors()
np = min((self.num_processors, len(workers)))
workers = JobManager.run_workers(workers, np)
# sort workers by order of tree paths in config
worker_dict = {}
for w in workers:
worker_dict[w.path] = w
sorted_workers = []
for ps in self.posterior_samples:
sorted_workers.extend(worker_dict[path] for path in ps.paths)
for worker in sorted_workers:
for tip_subset_name, node_ages in worker.node_ages.items():
self.posterior_sample_map[worker.label].tip_subset_map[
tip_subset_name].node_ages.extend(node_ages)
self.shared_nodes.extend(worker.shared_nodes)
for ps in self.posterior_samples:
for ts in ps.tip_subsets:
if ps.sample_size < 1:
ps.sample_size = len(ts.node_ages)
else:
assert ps.sample_size == len(ts.node_ages)
self.min_sample_size = min((
ps.sample_size for ps in self.posterior_samples))
def _sample_iter(self):
sample_dict_iters = []
for ps in self.posterior_samples:
if ps.sample_size > self.min_sample_size:
sample_dict_iters.append(ps.sample_iter(self.min_sample_size))
else:
sample_dict_iters.append(ps.sample_iter())
for idx in range(self.min_sample_size):
d = {}
for dict_iter in sample_dict_iters:
d.update(next(dict_iter))
yield d
def _write_results(self):
for expression_str, evaluator in self.expressions:
results = {}
results['exp_str'] = expression_str
results['num_samples'] = evaluator.num_evals
results['num_true'] = evaluator.num_true
results['prob'] = float(evaluator.num_true) / float(evaluator.num_evals)
sys.stdout.write("- expression: >\n")
sys.stdout.write(" {exp_str}\n".format(**results))
sys.stdout.write(" number_of_samples: {num_samples}\n".format(**results))
sys.stdout.write(" number_of_samples_passing: {num_true}\n".format(**results))
sys.stdout.write(" estimated_posterior_probability: {prob}\n".format(**results))
def run_analysis(self):
self._extract_node_ages()
self._write_shared_node_age_warning()
for d in self._sample_iter():
for expression_str, evaluator in self.expressions:
evaluator.evaluate(d)
self._write_results()
def _write_shared_node_age_warning(self):
if self.shared_nodes:
out_stream = StringIO()
sys.stderr.write("""\
WARNING: Some of the tip subsets you defined map to the same node in some of
the trees. All of the information about the shared nodes is listed
below. For each case in which multiple tip subsets mapped to the same
node, the tree file, index, and label is given, along with the tip
subsets that shared a node.\n""")
out_stream.write("tree_file\ttree_index\ttree_label\ttip_subsets\n")
for shared_node in self.shared_nodes:
out_stream.write("{0.tree_path}\t{0.tree_index}\t"
"{0.tree_label}\t{1}\n".format(
shared_node,
", ".join(shared_node.tip_subset_names)))
sys.stderr.write(out_stream.getvalue())
class PosteriorSample(object):
"""
This is the main container for the samples of node ages from a
posterior of phylogenies.
An instance of this class should be initiated with parameters parsed from a
``posterior`` within the YAML config file. One positional argument is also
required:
- config_path : A string of the path to the YAML config file.
The parameters must include the following key-value pairs:
- paths : A list of strings that specify paths to tree files (relative to
the config path).
- tip_subsets : A list of sets of key-value pairs that will each initiate
a ``TipSubset`` instance.
and optionally:
- burnin : An integer.
- schema : A string specifying the format of the tree files (default:
'nexus').
An example of initiating an instance:
>>> d = {'paths': ['trees/test.trees.gz'],
... 'tip_subsets': [{
... 'name': 'bufo',
... 'tips': ['Bnebulifer', 'Bamericanus']}]}
>>> ps = PosteriorSample('test-data/config.yml', **d)
>>> len(ps.paths) == 1
True
>>> ps.paths == (os.path.abspath('test-data/trees/test.trees.gz'),)
True
>>> len(ps.tip_subsets) == 1
True
>>> list(ps.tip_subsets)[0].name == 'bufo'
True
"""
count = 0
def __init__(self, config_path, **kwargs):
self.__class__.count += 1
self.config_path = config_path
self.name = self.__class__.__name__ + '-' + str(self.count)
paths = kwargs.pop('paths', None)
if not paths:
raise PosteriorSampleDataError("A posterior sample must contain a "
"list of 'paths'")
self.paths = tuple(expand_path(os.path.join(os.path.dirname(
config_path), p)) for p in paths)
tip_subsets = kwargs.pop('tip_subsets', None)
if not tip_subsets:
raise PosteriorSampleDataError("A posterior sample must contain a "
"list of 'tip_subsets'")
tip_subset_list = [TipSubset(**d) for d in tip_subsets]
self.tip_subset_map = collections.OrderedDict(zip(
[ts.name for ts in tip_subset_list],
tip_subset_list))
self.schema = kwargs.pop('schema', 'nexus')
self.burnin = int(kwargs.pop('burnin', 0))
if len(kwargs) > 0:
_LOG.warning("Unexpected attributes in posterior sample {0!r}: "
"{1}".format(self.name, ", ".join(kwargs.keys())))
self.sample_size = 0
def _get_tip_subsets(self):
return self.tip_subset_map.values()
tip_subsets = property(_get_tip_subsets)
def get_workers(self):
workers = []
for path in self.paths:
w = PosteriorWorker(path = path,
schema = self.schema,
burnin = self.burnin,
tip_subsets = list(self.tip_subsets),
label = self.name)
workers.append(w)
return workers
def sample_iter(self, sample_size = None, rng = None):
index_iter = range(self.sample_size)
if sample_size and (sample_size != self.sample_size):
if not rng:
rng = _RNG
if sample_size > self.sample_size:
# index_iter = (rng.choice(range(self.sample_size)) for i in range(
# sample_size))
raise SumTimesError(
"Requesting a sample of size {0} from a "
"PosteriorSample with {1} samples".format(
sample_size,
self.sample_size))
else:
index_iter = sorted(rng.sample(range(self.sample_size), sample_size))
for idx in index_iter:
d = {}
for ts in self.tip_subsets:
d[ts.name] = ts.node_ages[idx]
yield d
class PosteriorWorker(object):
"""
These instances are assigned a single posterior tree file from which to
extract node ages.
Instances should be created via the ``get_workers`` method of the
``PosteriorSample`` class
>>> d = {'paths': ['trees/test.trees.gz'],
... 'tip_subsets': [{
... 'name': 'toads',
... 'tips': ['Bnebulifer', 'Bamericanus']}]}
>>> ps = PosteriorSample('test-data/config.yml', **d)
>>> workers = ps.get_workers()
>>> len(workers) == 1
True
>>> w = workers[0]
>>> w.path == os.path.abspath('test-data/trees/test.trees.gz')
True
>>> w.burnin == 0
True
>>> w.schema == 'nexus'
True
>>> w.label == ps.name
True
>>> w.finished == False
True
>>> w.node_ages == {'toads': []}
True
>>> w.tip_subsets == [('toads', ('Bnebulifer', 'Bamericanus'), False)]
True
"""
count = 0
def __init__(self, path, schema, burnin, tip_subsets, label = None):
self.__class__.count += 1
self.name = self.__class__.__name__ + '-' + str(self.count)
self.path = path
self.schema = schema
self.burnin = burnin
self.label = label
self.finished = False
self.node_ages = dict((ts.name, []) for ts in tip_subsets)
self.tip_subsets = [(ts.name, ts.tips, ts.stem_based) for ts in tip_subsets]
self.shared_nodes = []
self.error = None
self.trace_back = None
def start(self):
try:
return self._extract_node_ages()
except Exception as e:
self.error = e
f = StringIO()
traceback.print_exc(file=f)
self.trace_back = f.getvalue()
def _extract_node_ages(self):
with ReadFile(self.path) as tree_stream:
tree_iter = dendropy.Tree.yield_from_files(
files = [tree_stream],
schema = self.schema,
preserve_underscores = True)
for tree_idx, tree in enumerate(tree_iter):
if tree_idx < self.burnin:
continue
if not tree.is_rooted:
raise Exception('Tree {0} in {1!r} is not rooted'.format(
tree_idx + 1,
self.path))
tree.calc_node_ages()
nodes_visited = {}
shared_nodes = set()
for name, tips, stem_based in self.tip_subsets:
mrca_node = tree.mrca(taxon_labels = tips)
target_node = mrca_node
if target_node.parent_node and stem_based:
target_node = mrca_node.parent_node
self.node_ages[name].append(target_node.age)
if id(target_node) in nodes_visited:
nodes_visited[id(target_node)].append(name)
shared_nodes.add(id(target_node))
else:
nodes_visited[id(target_node)] = [name]
for node_id in shared_nodes:
self.shared_nodes.append(SharedNode(
tree_path = self.path,
tree_index = tree_idx,
tree_label = tree.label,
node_id = node_id,
tip_subset_names = nodes_visited[node_id]))
self.finished = True
class SharedNode(object):
def __init__(self,
tree_path,
tree_index,
tree_label,
node_id,
tip_subset_names):
self.tree_path = tree_path
self.tree_index = tree_index
self.tree_label = tree_label
self.node_id = node_id
self.tip_subset_names = tuple(tip_subset_names)
class JobManager(multiprocessing.Process):
count = 0
def __init__(self,
work_queue = None,
result_queue = None,
get_timeout = 0.4,
put_timeout = 0.2,
log = None,
lock = None):
multiprocessing.Process.__init__(self)
self.__class__.count += 1
self.name = self.__class__.__name__ + '-' + str(self.count)
if not work_queue:
work_queue = multiprocessing.Queue()
if not result_queue:
result_queue = multiprocessing.Queue()
self.work_queue = work_queue
self.result_queue = result_queue
self.get_timeout = get_timeout
self.put_timeout = put_timeout
if not log:
log = _LOG
self.log = log
if not lock:
lock = _LOCK
self.lock = lock
self.killed = False
def compose_msg(self, msg):
return '{0} ({1}): {2}'.format(self.name, self.pid, msg)
def send_msg(self, msg, method_str='info'):
self.lock.acquire()
try:
getattr(self.log, method_str)(self.compose_msg(msg))
finally:
self.lock.release()
def send_debug(self, msg):
self.send_msg(msg, method_str='debug')
def send_info(self, msg):
self.send_msg(msg, method_str='info')
def send_warning(self, msg):
self.send_msg(msg, method_str='warning')
def send_error(self, msg):
self.send_msg(msg, method_str='error')
def _get_worker(self):
worker = None
try:
self.send_debug('getting worker')
worker = self.work_queue.get(block=True, timeout=self.get_timeout)
self.send_debug('received worker {0}'.format(
getattr(worker, 'name', 'nameless')))
# without blocking processes were stopping when the queue
# was not empty, and without timeout, the processes would
# hang waiting for jobs.
except queue.Empty:
time.sleep(0.2)
if not self.work_queue.empty():
self.send_warning('raised queue.Empty, but queue is '
'not empty... trying again')
return self._get_worker()
else:
self.send_info('work queue is empty')
return worker
def _put_worker(self, worker):
try:
self.send_debug('returning worker {0}'.format(
getattr(worker, 'name', 'nameless')))
self.result_queue.put(worker, block=True, timeout=self.put_timeout)
self.send_debug('worker {0} returned'.format(
getattr(worker, 'name', 'nameless')))
except queue.Full as e:
time.sleep(0.2)
if not self.result_queue.full():
self.send_warning('raised queue.Full, but queue is '
'not full... trying again')
self._put_worker(worker)
else:
self.send_error('result queue is full... aborting')
self.killed = True
raise e
def run(self):
self.send_debug('starting run')
while not self.killed:
worker = self._get_worker()
if worker is None:
break
self.send_info('starting worker {0}'.format(
getattr(worker, 'name', 'nameless')))
worker.start()
self.send_info('worker {0} finished'.format(
getattr(worker, 'name', 'nameless')))
self._put_worker(worker)
if self.killed:
self.send_error('job manager was killed!')
self.send_debug('end run')
@classmethod
def run_workers(cls,
workers,
num_processors,
get_timeout = 0.4,
put_timeout = 0.2,
queue_max = 500):
work_queue = multiprocessing.Queue()
result_queue = multiprocessing.Queue()
finished = []
for w_list in list_splitter(workers, queue_max, by_size = True):
assert work_queue.empty()
assert result_queue.empty()
for w in w_list:
work_queue.put(w)
managers = []
for i in range(num_processors):
m = cls(work_queue = work_queue,
result_queue = result_queue,
get_timeout = get_timeout,
put_timeout = put_timeout)
managers.append(m)
for i in range(len(managers)):
managers[i].start()
for i in range(len(w_list)):
_LOG.debug('JobManager.run_workers: getting result...')
w_list[i] = result_queue.get()
_LOG.debug('JobManager.run_workers: got result {0}'.format(
getattr(w_list[i], 'name', 'nameless')))
for i in range(len(managers)):
managers[i].join()
for w in w_list:
if getattr(w, "error", None):
_LOG.error('Worker {0} returned with an error:\n{1}'.format(
getattr(w, 'name', 'nameless'),
w.trace_back))
raise w.error
assert work_queue.empty()
assert result_queue.empty()
finished.extend(w_list)