-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathdemes.py
More file actions
2881 lines (2570 loc) · 111 KB
/
demes.py
File metadata and controls
2881 lines (2570 loc) · 111 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
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
from __future__ import annotations
import copy
import collections
import itertools
import math
import numbers
import operator
from typing import List, Union, Optional, Dict, MutableMapping, Mapping, Any, Set, Tuple
import warnings
import attr
from .load_dump import dumps as demes_dumps
Number = Union[int, float]
Name = str
Time = Number
Size = Number
Rate = float
Proportion = float
_ISCLOSE_REL_TOL = 1e-9
_ISCLOSE_ABS_TOL = 1e-12
# Validator functions.
def int_or_float(self, attribute, value):
if (
not isinstance(value, numbers.Real) and not hasattr(value, "__float__")
) or value != value: # type-agnostic test for NaN
raise TypeError(f"{attribute.name} must be a number")
def positive(self, attribute, value):
if value <= 0:
raise ValueError(f"{attribute.name} must be greater than zero")
def non_negative(self, attribute, value):
if value < 0:
raise ValueError(f"{attribute.name} must be non-negative")
def finite(self, attribute, value):
if math.isinf(value):
raise ValueError(f"{attribute.name} must be finite")
def unit_interval(self, attribute, value):
if not (0 <= value <= 1):
raise ValueError(f"must have 0 <= {attribute.name} <= 1")
def unit_interval_exclusive_lo(self, attribute, value):
if not (0 < value <= 1):
raise ValueError(f"must have 0 < {attribute.name} <= 1")
def sum_less_than_one(self, attribute, value):
if sum(value) > 1:
raise ValueError(f"{attribute.name} must sum to less than one")
def nonzero_len(self, attribute, value):
if len(value) == 0:
if isinstance(value, str):
raise ValueError(f"{attribute.name} must be a non-empty string")
else:
raise ValueError(f"{attribute.name} must have non-zero length")
def valid_deme_name(self, attribute, value):
if not value.isidentifier():
raise ValueError(
f"Invalid deme name '{value}'. Names must be valid python identifiers. "
"We recommend choosing a name that starts with a letter or "
"underscore, and is followed by one or more letters, numbers, "
"or underscores."
)
def isclose_deme_proportions(
a_names: List[Name],
a_proportions: List[Proportion],
b_names: List[Name],
b_proportions: List[Proportion],
*,
rel_tol=_ISCLOSE_REL_TOL,
abs_tol=_ISCLOSE_ABS_TOL,
) -> bool:
"""
Returns true if (a_names, a_proportions) and (b_names, b_proportions)
are semantically equivalent. The order of names is ignored, and proportions
are checked for numerical closeness.
"""
if len(a_names) != len(b_names) or len(a_proportions) != len(b_proportions):
return False
a = sorted(zip(a_names, a_proportions), key=operator.itemgetter(0))
b = sorted(zip(b_names, b_proportions), key=operator.itemgetter(0))
for (a_id, a_proportion), (b_id, b_proportion) in zip(a, b):
if a_id != b_id or not math.isclose(
a_proportion, b_proportion, rel_tol=rel_tol, abs_tol=abs_tol
):
return False
return True
_DummyAttribute = collections.namedtuple("_DummyAttribute", ["name"])
def validate_item(name, value, required_type, scope, validator=None):
if not isinstance(value, required_type):
raise TypeError(
f"{scope}: field '{name}' must be a {required_type}; "
f"current type is {type(value)}."
)
if validator is not None:
if not isinstance(validator, (list, tuple)):
validator = [validator]
dummy_attribute = _DummyAttribute(f"{scope}: {name}")
for v in validator:
v(None, dummy_attribute, value)
# We need to use this trick because None is a meaningful input value for these
# pop_x functions.
NO_DEFAULT = object()
def pop_item(data, name, *, required_type, default=NO_DEFAULT, scope=""):
if name in data:
value = data.pop(name)
validate_item(name, value, required_type, scope=scope)
else:
if default is NO_DEFAULT:
raise KeyError(f"{scope}: required field '{name}' not found")
value = default
return value
def pop_list(data, name, default=NO_DEFAULT, required_type=None, scope=""):
value = pop_item(data, name, default=default, required_type=list)
if required_type is not None and default is not None:
for item in value:
validate_item(name, item, required_type, scope)
return value
def pop_object(data, name, default=NO_DEFAULT, scope=""):
return pop_item(
data, name, default=default, required_type=MutableMapping, scope=scope
)
def check_allowed(data, allowed_fields, scope):
for key in data.keys():
if key not in allowed_fields:
raise KeyError(
f"{scope}: unexpected field: '{key}'. "
f"Allowed fields are: {allowed_fields}"
)
def check_defaults(defaults, allowed_fields, scope):
for key, value in defaults.items():
if key not in allowed_fields:
raise KeyError(
f"{scope}: unexpected field: '{key}'. "
f"Allowed fields are: {list(allowed_fields)}"
)
required_type, validator = allowed_fields[key]
validate_item(key, value, required_type, scope, validator=validator)
def insert_defaults(data, defaults):
for key, value in defaults.items():
if key not in data:
data[key] = value
@attr.s(auto_attribs=True, kw_only=True, slots=True)
class Epoch:
"""
Population parameters for a deme in a specified time interval.
An epoch spans the open-closed time interval ``(start_time, end_time]``,
where ``start_time`` is the more ancient time,
and ``end_time`` is more recent.
Time values increase from the present towards the past,
and ``start_time`` is strictly greater than ``end_time``.
Epoch objects are not intended to be constructed directly.
:ivar float start_time:
The start time of the epoch.
This value is greater than zero and may be infinity.
:ivar float end_time:
The end time of the epoch.
This value is greater than or equal to zero and finite.
:ivar float start_size:
Population size at ``start_time``.
:ivar float end_size:
Population size at ``end_time``.
If ``start_size != end_size``, the population size changes
between the start and end times according to the
``size_function``.
:ivar str size_function: The size change function. This is either
``constant``, ``exponential`` or ``linear``, though it is possible
that additional values will be added in the future.
* ``constant``: the deme's size does not change over the epoch.
* ``exponential``: the deme's size changes exponentially from
``start_size`` to ``end_size`` over the epoch.
If :math:`t` is a time within the span of the epoch,
the deme size :math:`N` at :math:`t` can be calculated as:
.. code::
dt = (epoch.start_time - t) / epoch.time_span
r = math.log(epoch.end_size / epoch.start_size)
N = epoch.start_size * math.exp(r * dt)
* ``linear``: the deme's size changes linearly from
``start_size`` to ``end_size`` over the epoch.
If :math:`t` is a time within the span of the epoch,
the deme size :math:`N` at :math:`t` can be calculated as:
.. code::
dt = (epoch.start_time - t) / epoch.time_span
N = epoch.start_size + (epoch.end_size - epoch.start_size) * dt
:ivar float selfing_rate: The selfing rate for this epoch.
:ivar float cloning_rate: The cloning rate for this epoch.
"""
start_time: Time = attr.ib(validator=[int_or_float, non_negative])
end_time: Time = attr.ib(validator=[int_or_float, non_negative, finite])
start_size: Size = attr.ib(validator=[int_or_float, positive, finite])
end_size: Size = attr.ib(validator=[int_or_float, positive, finite])
size_function: str = attr.ib(
validator=attr.validators.in_(["constant", "exponential", "linear"])
)
selfing_rate: Proportion = attr.ib(
default=0, validator=[int_or_float, unit_interval]
)
cloning_rate: Proportion = attr.ib(
default=0, validator=[int_or_float, unit_interval]
)
def __attrs_post_init__(self):
if self.start_time <= self.end_time:
raise ValueError("must have start_time > end_time")
if math.isinf(self.start_time) and self.start_size != self.end_size:
raise ValueError("if start time is inf, must be a constant size epoch")
if self.size_function == "constant" and self.start_size != self.end_size:
raise ValueError("start_size != end_size, but size_function is constant")
@property
def time_span(self):
"""
The time span of the epoch.
:rtype: float
"""
return self.start_time - self.end_time
def assert_close(
self,
other,
*,
rel_tol=_ISCLOSE_REL_TOL,
abs_tol=_ISCLOSE_ABS_TOL,
):
"""
Raises AssertionError if the object is not equal to ``other``,
up to a numerical tolerance.
Compares values of the following attributes:
``start_time``, ``end_time``, ``start_size``, ``end_size``,
``size_function``, ``selfing_rate``, ``cloning_rate``.
:param other: The epoch to compare against.
:type other: :class:`.Epoch`
:param rel_tol: The relative tolerance permitted for numerical
comparisons. See documentation for :func:`math.isclose`
:type rel_tol: float
:param abs_tol: The absolute tolerance permitted for numerical
comparisons. See documentation for :func:`math.isclose`.
:type abs_tol: float
"""
assert (
self.__class__ is other.__class__
), f"Failed as other epoch is not instance of {self.__class__} type."
assert math.isclose(
self.start_time, other.start_time, rel_tol=rel_tol, abs_tol=abs_tol
), f"Failed for start_time {self.start_time} != {other.start_time} (other)."
assert math.isclose(
self.end_time, other.end_time, rel_tol=rel_tol, abs_tol=abs_tol
), f"Failed for end_time {self.end_time} != {other.end_time} (other)."
assert math.isclose(
self.start_size, other.start_size, rel_tol=rel_tol, abs_tol=abs_tol
), (
f"Failed for start_size "
f"{self.start_size} != {other.start_size} (other)."
)
assert math.isclose(
self.end_size, other.end_size, rel_tol=rel_tol, abs_tol=abs_tol
), f"Failed for end_size {self.end_size} != {other.end_size} (other)."
assert self.size_function == other.size_function
assert math.isclose(
self.selfing_rate, other.selfing_rate, rel_tol=rel_tol, abs_tol=abs_tol
), (
f"Failed for selfing_rate "
f"{self.selfing_rate} != {other.selfing_rate} (other)."
)
assert math.isclose(
self.cloning_rate, other.cloning_rate, rel_tol=rel_tol, abs_tol=abs_tol
), (
f"Failed for cloning_rate "
f"{self.cloning_rate} != {other.cloning_rate} (other)."
)
def isclose(
self,
other,
*,
rel_tol=_ISCLOSE_REL_TOL,
abs_tol=_ISCLOSE_ABS_TOL,
) -> bool:
"""
Returns true if the epoch and ``other`` epoch implement essentially
the same epoch. For more information see :meth:`assert_close`.
:param other: The epoch to compare against.
:type other: :class:`.Epoch`
:param rel_tol: The relative tolerance permitted for numerical
comparisons. See documentation for :func:`math.isclose`
:type rel_tol: float
:param abs_tol: The absolute tolerance permitted for numerical
comparisons. See documentation for :func:`math.isclose`.
:type abs_tol: float
:return: True if the two epochs are equivalent, False otherwise.
:rtype: bool
"""
try:
self.assert_close(other, rel_tol=rel_tol, abs_tol=abs_tol)
return True
except AssertionError:
return False
@attr.s(auto_attribs=True, kw_only=True, slots=True)
class AsymmetricMigration:
"""
Continuous asymmetric migration.
The source and destination demes follow the forwards-in-time convention,
where migrants are born in the source deme and (potentially) have children
in the dest deme.
AsymmetricMigration objects are not intended to be constructed directly.
:ivar str source: The source deme for asymmetric migration.
:ivar str dest: The destination deme for asymmetric migration.
:ivar float start_time: The time at which the migration rate is activated.
:ivar float end_time: The time at which the migration rate is deactivated.
:ivar float rate: The rate of migration per generation.
"""
source: Name = attr.ib(
validator=[attr.validators.instance_of(str), valid_deme_name]
)
dest: Name = attr.ib(validator=[attr.validators.instance_of(str), valid_deme_name])
start_time: Time = attr.ib(validator=[int_or_float, non_negative])
end_time: Time = attr.ib(validator=[int_or_float, non_negative, finite])
rate: Rate = attr.ib(validator=[int_or_float, unit_interval])
def __attrs_post_init__(self):
if self.source == self.dest:
raise ValueError("source and dest cannot be the same deme")
if not (self.start_time > self.end_time):
raise ValueError("must have start_time > end_time")
def assert_close(
self,
other,
*,
rel_tol=_ISCLOSE_REL_TOL,
abs_tol=_ISCLOSE_ABS_TOL,
):
"""
Raises AssertionError if the object is not equal to ``other``,
up to a numerical tolerance.
Compares values of the following attributes:
``source``, ``dest``, ``start_time``, ``end_time``, ``rate``.
:param AsymmetricMigration other: The migration to compare against.
:param rel_tol: The relative tolerance permitted for numerical
comparisons. See documentation for :func:`math.isclose`
:type rel_tol: float
:param abs_tol: The absolute tolerance permitted for numerical
comparisons. See documentation for :func:`math.isclose`.
:type abs_tol: float
"""
assert (
self.__class__ is other.__class__
), f"Failed as other migration is not instance of {self.__class__} type."
assert self.source == other.source
assert self.dest == other.dest
assert math.isclose(
self.start_time, other.start_time, rel_tol=rel_tol, abs_tol=abs_tol
), f"Failed for start_time {self.start_time} != {other.start_time} (other)."
assert math.isclose(
self.end_time, other.end_time, rel_tol=rel_tol, abs_tol=abs_tol
), f"Failed for end_time {self.end_time} != {other.end_time} (other)."
assert math.isclose(
self.rate, other.rate, rel_tol=rel_tol, abs_tol=abs_tol
), f"Failed for rate {self.rate} != {other.rate} (other)."
def isclose(
self,
other,
*,
rel_tol=_ISCLOSE_REL_TOL,
abs_tol=_ISCLOSE_ABS_TOL,
) -> bool:
"""
Returns true if the migration is equal to the ``other`` migration.
For more information see :meth:`assert_close`.
:param AsymmetricMigration other: The migration to compare against.
:param rel_tol: The relative tolerance permitted for numerical
comparisons. See documentation for :func:`math.isclose`
:type rel_tol: float
:param abs_tol: The absolute tolerance permitted for numerical
comparisons. See documentation for :func:`math.isclose`.
:type abs_tol: float
:return: True if the two epochs are equivalent, False otherwise.
:rtype: bool
"""
try:
self.assert_close(other, rel_tol=rel_tol, abs_tol=abs_tol)
return True
except AssertionError:
return False
@attr.s(auto_attribs=True, kw_only=True, slots=True)
class Pulse:
"""
An instantaneous pulse of migration from one deme to another.
Source and destination demes follow the forwards-in-time convention,
where migrants are born in a source deme and (potentially) have children
in the dest deme.
If more than one source is given, migration is concurrent,
and the sum of the migrant proportions sums to less than or equal to one.
Pulse objects are not intended to be constructed directly.
:ivar list(str) sources: The source deme(s).
:ivar str dest: The destination deme.
:ivar float time: The time of migration.
:ivar list(float) proportions: Immediately following migration, the proportion(s)
of individuals in the destination deme made up of migrant individuals or
having parents from the source deme(s).
"""
sources: List[Name] = attr.ib(
validator=attr.validators.and_(
attr.validators.deep_iterable(
member_validator=attr.validators.and_(
attr.validators.instance_of(str), valid_deme_name
),
iterable_validator=attr.validators.instance_of(list),
),
nonzero_len,
)
)
dest: Name = attr.ib(validator=[attr.validators.instance_of(str), valid_deme_name])
time: Time = attr.ib(validator=[int_or_float, positive, finite])
proportions: List[Proportion] = attr.ib(
validator=attr.validators.deep_iterable(
member_validator=attr.validators.and_(
int_or_float, unit_interval_exclusive_lo
),
iterable_validator=attr.validators.instance_of(list),
)
)
def __attrs_post_init__(self):
for source in self.sources:
if source == self.dest:
raise ValueError(f"source ({source}) cannot be the same as dest")
if self.sources.count(source) != 1:
raise ValueError(f"source ({source}) cannot be repeated in sources")
if len(self.sources) != len(self.proportions):
raise ValueError("sources and proportions must have the same length")
if sum(self.proportions) > 1:
raise ValueError("proportions must sum to less than one")
def assert_close(
self,
other,
*,
rel_tol=_ISCLOSE_REL_TOL,
abs_tol=_ISCLOSE_ABS_TOL,
):
"""
Raises AssertionError if the object is not equal to ``other``,
up to a numerical tolerance.
Compares values of the following attributes:
``source``, ``dest``, ``time``, ``proportion``.
:param other: The pulse to compare against.
:type other: :class:`.Pulse`
:param rel_tol: The relative tolerance permitted for numerical
comparisons. See documentation for :func:`math.isclose`
:type rel_tol: float
:param abs_tol: The absolute tolerance permitted for numerical
comparisons. See documentation for :func:`math.isclose`.
:type abs_tol: float
"""
assert (
self.__class__ is other.__class__
), f"Failed as other pulse is not instance of {self.__class__} type."
assert len(self.sources) == len(other.sources)
for s in self.sources:
assert s in other.sources
for s in other.sources:
assert s in self.sources
assert self.dest == other.dest
assert math.isclose(
self.time, other.time, rel_tol=rel_tol, abs_tol=abs_tol
), f"Failed for time {self.time} != {other.time} (other)."
assert len(self.proportions) == len(other.proportions)
assert math.isclose(
sum(self.proportions),
sum(other.proportions),
rel_tol=rel_tol,
abs_tol=abs_tol,
), (
f"Failed for unequal proportions sums: "
f"sum({self.proportions}) != sum({other.proportions}) (other)."
)
assert isclose_deme_proportions(
self.sources, self.proportions, other.sources, other.proportions
)
def isclose(
self,
other,
*,
rel_tol=_ISCLOSE_REL_TOL,
abs_tol=_ISCLOSE_ABS_TOL,
) -> bool:
"""
Returns true if the pulse is equal to the ``other`` pulse.
For more information see :meth:`assert_close`.
:param other: The pulse to compare against.
:type other: :class:`.Pulse`
:param rel_tol: The relative tolerance permitted for numerical
comparisons. See documentation for :func:`math.isclose`
:type rel_tol: float
:param abs_tol: The absolute tolerance permitted for numerical
comparisons. See documentation for :func:`math.isclose`.
:type abs_tol: float
:return: True if the two pulses are equivalent, False otherwise.
:rtype: bool
"""
try:
self.assert_close(other, rel_tol=rel_tol, abs_tol=abs_tol)
return True
except AssertionError:
return False
@attr.s(auto_attribs=True, kw_only=True, slots=True)
class Split:
"""
A split event, in which a deme ends at a given time and
contributes ancestry to an arbitrary number of descendant demes. Note
that there could be just a single descendant deme, in which case ``split``
is a bit of a misnomer.
Split objects are not intended to be constructed directly.
:ivar str parent: The parental deme.
:ivar list[str] children: A list of descendant demes.
:ivar float time: The split time.
"""
parent: Name = attr.ib(
validator=[attr.validators.instance_of(str), valid_deme_name]
)
children: List[Name] = attr.ib(
validator=attr.validators.and_(
attr.validators.deep_iterable(
member_validator=attr.validators.and_(
attr.validators.instance_of(str), valid_deme_name
),
iterable_validator=attr.validators.instance_of(list),
),
nonzero_len,
)
)
time: Time = attr.ib(validator=[int_or_float, non_negative, finite])
def __attrs_post_init__(self):
if self.parent in self.children:
raise ValueError("child and parent cannot be the same deme")
if len(set(self.children)) != len(self.children):
raise ValueError("cannot repeat children in split")
def assert_close(
self,
other,
*,
rel_tol=_ISCLOSE_REL_TOL,
abs_tol=_ISCLOSE_ABS_TOL,
) -> bool:
"""
Raises AssertionError if the object is not equal to ``other``,
up to a numerical tolerance.
Compares values of the following attributes:
``parent``, ``children``, ``time``.
:param other: The split to compare against.
:type other: :class:`.Split`
:param rel_tol: The relative tolerance permitted for numerical
comparisons. See documentation for :func:`math.isclose`
:type rel_tol: float
:param abs_tol: The absolute tolerance permitted for numerical
comparisons. See documentation for :func:`math.isclose`.
:type abs_tol: float
"""
assert (
self.__class__ is other.__class__
), f"Failed as other split is not instance of {self.__class__} type."
assert self.parent == other.parent
assert sorted(self.children) == sorted(other.children)
assert math.isclose(
self.time, other.time, rel_tol=rel_tol, abs_tol=abs_tol
), f"Failed for time {self.time} != {other.time} (other)."
return True
def isclose(
self,
other,
*,
rel_tol=_ISCLOSE_REL_TOL,
abs_tol=_ISCLOSE_ABS_TOL,
) -> bool:
"""
Returns true if the split is equal to the ``other`` split.
Compares values of the following attributes:
``parent``, ``children``, ``time``.
:param other: The split to compare against.
:type other: :class:`.Split`
:param rel_tol: The relative tolerance permitted for numerical
comparisons. See documentation for :func:`math.isclose`
:type rel_tol: float
:param abs_tol: The absolute tolerance permitted for numerical
comparisons. See documentation for :func:`math.isclose`.
:type abs_tol: float
:return: True if the two splits are equivalent, False otherwise.
:rtype: bool
"""
try:
self.assert_close(other, rel_tol=rel_tol, abs_tol=abs_tol)
return True
except AssertionError:
return False
@attr.s(auto_attribs=True, kw_only=True, slots=True)
class Branch:
"""
A branch event, where a new deme branches off from a parental
deme. The parental deme need not end at that time.
Branch objects are not intended to be constructed directly.
:ivar str parent: The parental deme.
:ivar str child: The descendant deme.
:ivar float time: The branch time.
"""
parent: Name = attr.ib(
validator=[attr.validators.instance_of(str), valid_deme_name]
)
child: Name = attr.ib(validator=[attr.validators.instance_of(str), valid_deme_name])
time: Time = attr.ib(validator=[int_or_float, non_negative, finite])
def __attrs_post_init__(self):
if self.child == self.parent:
raise ValueError("child and parent cannot be the same deme")
def assert_close(
self,
other,
*,
rel_tol=_ISCLOSE_REL_TOL,
abs_tol=_ISCLOSE_ABS_TOL,
):
"""
Raises AssertionError if the object is not equal to ``other``,
up to a numerical tolerance.
Compares values of the following attributes:
``parent``, ``child``, ``time``.
:param other: The branch to compare against.
:type other: :class:`.Branch`
:param rel_tol: The relative tolerance permitted for numerical
comparisons. See documentation for :func:`math.isclose`
:type rel_tol: float
:param abs_tol: The absolute tolerance permitted for numerical
comparisons. See documentation for :func:`math.isclose`.
:type abs_tol: float
"""
assert (
self.__class__ is other.__class__
), f"failed as other branch is not instance of {self.__class__} type."
assert self.parent == other.parent
assert self.child == other.child
assert math.isclose(
self.time, other.time, rel_tol=rel_tol, abs_tol=abs_tol
), f"Failed for time {self.time} != {other.time} (other)."
def isclose(
self,
other,
*,
rel_tol=_ISCLOSE_REL_TOL,
abs_tol=_ISCLOSE_ABS_TOL,
) -> bool:
"""
Returns true if the branch is equal to the ``other`` branch.
For more information see :meth:`assert_close`.
:param other: The branch to compare against.
:type other: :class:`.Branch`
:param rel_tol: The relative tolerance permitted for numerical
comparisons. See documentation for :func:`math.isclose`
:type rel_tol: float
:param abs_tol: The absolute tolerance permitted for numerical
comparisons. See documentation for :func:`math.isclose`.
:type abs_tol: float
:return: True if the two branches are equivalent, False otherwise.
:rtype: bool
"""
try:
self.assert_close(other, rel_tol=rel_tol, abs_tol=abs_tol)
return True
except AssertionError:
return False
@attr.s(auto_attribs=True, kw_only=True, slots=True)
class Merge:
"""
A merge event, in which two or more demes end at some time and
contribute to a descendant deme.
Merge objects are not intended to be constructed directly.
:ivar list[str] parents: A list of parental demes.
:ivar list[float] proportions: A list of ancestry proportions,
in order of ``parents``.
:ivar str child: The descendant deme.
:ivar float time: The merge time.
"""
parents: List[Name] = attr.ib(
validator=attr.validators.deep_iterable(
member_validator=attr.validators.and_(
attr.validators.instance_of(str), valid_deme_name
),
iterable_validator=attr.validators.instance_of(list),
)
)
proportions: List[Proportion] = attr.ib(
validator=attr.validators.deep_iterable(
member_validator=int_or_float,
iterable_validator=attr.validators.instance_of(list),
)
)
child: Name = attr.ib(validator=[attr.validators.instance_of(str), valid_deme_name])
time: Time = attr.ib(validator=[int_or_float, non_negative, finite])
@proportions.validator
def _check_proportions(self, attribute, _value):
if len(self.proportions) > 0 and not math.isclose(sum(self.proportions), 1.0):
raise ValueError("proportions must sum to 1.0")
for proportion in self.proportions:
unit_interval(self, attribute, proportion)
positive(self, attribute, proportion)
def __attrs_post_init__(self):
if len(self.parents) < 2:
raise ValueError("merge must involve at least two ancestors")
if len(self.parents) != len(self.proportions):
raise ValueError("parents and proportions must have same length")
if self.child in self.parents:
raise ValueError("merged deme cannot be its own ancestor")
if len(set(self.parents)) != len(self.parents):
raise ValueError("cannot repeat parents in merge")
def assert_close(
self,
other,
*,
rel_tol=_ISCLOSE_REL_TOL,
abs_tol=_ISCLOSE_ABS_TOL,
):
"""
Raises AssertionError if the object is not equal to ``other``,
up to a numerical tolerance.
Compares values of the following attributes:
``parents``, ``proportions``, ``child``, ``time``.
:param other: The merge to compare against.
:type other: :class:`.Merge`
:param rel_tol: The relative tolerance permitted for numerical
comparisons. See documentation for :func:`math.isclose`
:type rel_tol: float
:param abs_tol: The absolute tolerance permitted for numerical
comparisons. See documentation for :func:`math.isclose`.
:type abs_tol: float
"""
assert (
self.__class__ is other.__class__
), f"Failed as other merge is not instance of {self.__class__} type."
assert isclose_deme_proportions(
self.parents,
self.proportions,
other.parents,
other.proportions,
rel_tol=rel_tol,
abs_tol=abs_tol,
), (
f"Parents or corresponding proportions are different: "
f"parents: {self.parents}, {other.parents} (other), "
f"proportions: {self.proportions}, {other.proportions} (other)."
)
assert self.child == other.child
assert math.isclose(
self.time, other.time, rel_tol=rel_tol, abs_tol=abs_tol
), f"Failed for time {self.time} != {other.time} (other)."
def isclose(
self,
other,
*,
rel_tol=_ISCLOSE_REL_TOL,
abs_tol=_ISCLOSE_ABS_TOL,
) -> bool:
"""
Returns true if the merge is equal to the ``other`` merge.
For more information see :meth:`assert_close`.
:param other: The merge to compare against.
:type other: :class:`.Merge`
:param rel_tol: The relative tolerance permitted for numerical
comparisons. See documentation for :func:`math.isclose`
:type rel_tol: float
:param abs_tol: The absolute tolerance permitted for numerical
comparisons. See documentation for :func:`math.isclose`.
:type abs_tol: float
:return: True if the two merges are equivalent, False otherwise.
:rtype: bool
"""
try:
self.assert_close(other, rel_tol=rel_tol, abs_tol=abs_tol)
return True
except AssertionError:
return False
@attr.s(auto_attribs=True, kw_only=True, slots=True)
class Admix:
"""
An admixture event, where two or more demes contribute ancestry
to a new deme.
Admix objects are not intended to be constructed directly.
:ivar list[str] parents: A list of source demes.
:ivar list[float] proportions: A list of ancestry proportions,
in order of ``parents``.
:ivar str child: The admixed deme.
:ivar float time: The admixture time.
"""
parents: List[Name] = attr.ib(
validator=attr.validators.deep_iterable(
member_validator=attr.validators.and_(
attr.validators.instance_of(str), valid_deme_name
),
iterable_validator=attr.validators.instance_of(list),
)
)
proportions: List[Proportion] = attr.ib(
validator=attr.validators.deep_iterable(
member_validator=int_or_float,
iterable_validator=attr.validators.instance_of(list),
)
)
child: Name = attr.ib(validator=[attr.validators.instance_of(str), valid_deme_name])
time: Time = attr.ib(validator=[int_or_float, non_negative, finite])
@proportions.validator
def _check_proportions(self, attribute, _value):
if len(self.proportions) > 0 and not math.isclose(sum(self.proportions), 1.0):
raise ValueError("proportions must sum to 1.0")
for proportion in self.proportions:
unit_interval(self, attribute, proportion)
positive(self, attribute, proportion)
def __attrs_post_init__(self):
if len(self.parents) < 2:
raise ValueError("admixture must involve at least two ancestors")
if len(self.parents) != len(self.proportions):
raise ValueError("parents and proportions must have same length")
if self.child in self.parents:
raise ValueError("admixed deme cannot be its own ancestor")
if len(set(self.parents)) != len(self.parents):
raise ValueError("cannot repeat parents in admixure")
def assert_close(
self,
other,
*,
rel_tol=_ISCLOSE_REL_TOL,
abs_tol=_ISCLOSE_ABS_TOL,
):
"""
Raises AssertionError if the object is not equal to ``other``,
up to a numerical tolerance.
Compares values of the following attributes:
``parents``, ``proportions``, ``child``, ``time``.
:param other: The admixture to compare against.
:type other: :class:`.Admix`
:param rel_tol: The relative tolerance permitted for numerical
comparisons. See documentation for :func:`math.isclose`
:type rel_tol: float
:param abs_tol: The absolute tolerance permitted for numerical
comparisons. See documentation for :func:`math.isclose`.
:type abs_tol: float
"""
assert (
self.__class__ is other.__class__
), f"Failed as other admixture is not instance of {self.__class__} type."
assert isclose_deme_proportions(
self.parents,
self.proportions,
other.parents,
other.proportions,
rel_tol=rel_tol,
abs_tol=abs_tol,
), (
f"Parents or corresponding proportions are different: "
f"parents: {self.parents}, {other.parents} (other), "
f"proportions: {self.proportions}, {other.proportions} (other)."
)
assert self.child == other.child
assert math.isclose(
self.time,
other.time,
rel_tol=rel_tol,
abs_tol=abs_tol,
), f"Failed for time {self.time} != {other.time} (other)."
def isclose(
self,
other,
*,
rel_tol=_ISCLOSE_REL_TOL,
abs_tol=_ISCLOSE_ABS_TOL,
) -> bool:
"""
Returns true if the admixture is equal to the ``other`` admixture.
For more information see :meth:`assert_close`.
:param other: The admixture to compare against.
:type other: :class:`.Admix`