forked from tskit-dev/tskit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtables.py
More file actions
4279 lines (3817 loc) · 173 KB
/
tables.py
File metadata and controls
4279 lines (3817 loc) · 173 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
#
# MIT License
#
# Copyright (c) 2018-2024 Tskit Developers
# Copyright (c) 2017 University of Oxford
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""
Tree sequence IO via the tables API.
"""
import collections.abc
import dataclasses
import datetime
import json
import numbers
import warnings
from collections.abc import Mapping
from dataclasses import dataclass
from functools import reduce
from typing import Dict
from typing import Optional
from typing import Union
import numpy as np
import _tskit
import tskit
import tskit.metadata as metadata
import tskit.provenance as provenance
import tskit.util as util
from tskit import UNKNOWN_TIME
dataclass_options = {"frozen": True}
# Needed for cases where `None` can be an appropriate kwarg value,
# we override the meta so that it looks good in the docs.
class NotSetMeta(type):
def __repr__(cls):
return "Not set"
class NOTSET(metaclass=NotSetMeta):
pass
@metadata.lazy_decode()
@dataclass(**dataclass_options)
class IndividualTableRow(util.Dataclass):
"""
A row in an :class:`IndividualTable`.
"""
__slots__ = ["flags", "location", "parents", "metadata"]
flags: int
"""
See :attr:`Individual.flags`
"""
location: np.ndarray
"""
See :attr:`Individual.location`
"""
parents: np.ndarray
"""
See :attr:`Individual.parents`
"""
metadata: Optional[Union[bytes, dict]]
"""
See :attr:`Individual.metadata`
"""
# We need a custom eq for the numpy arrays
def __eq__(self, other):
return (
isinstance(other, IndividualTableRow)
and self.flags == other.flags
and np.array_equal(self.location, other.location)
and np.array_equal(self.parents, other.parents)
and self.metadata == other.metadata
)
@metadata.lazy_decode()
@dataclass(**dataclass_options)
class NodeTableRow(util.Dataclass):
"""
A row in a :class:`NodeTable`.
"""
__slots__ = ["flags", "time", "population", "individual", "metadata"]
flags: int
"""
See :attr:`Node.flags`
"""
time: float
"""
See :attr:`Node.time`
"""
population: int
"""
See :attr:`Node.population`
"""
individual: int
"""
See :attr:`Node.individual`
"""
metadata: Optional[Union[bytes, dict]]
"""
See :attr:`Node.metadata`
"""
@metadata.lazy_decode()
@dataclass(**dataclass_options)
class EdgeTableRow(util.Dataclass):
"""
A row in an :class:`EdgeTable`.
"""
__slots__ = ["left", "right", "parent", "child", "metadata"]
left: float
"""
See :attr:`Edge.left`
"""
right: float
"""
See :attr:`Edge.right`
"""
parent: int
"""
See :attr:`Edge.parent`
"""
child: int
"""
See :attr:`Edge.child`
"""
metadata: Optional[Union[bytes, dict]]
"""
See :attr:`Edge.metadata`
"""
@metadata.lazy_decode()
@dataclass(**dataclass_options)
class MigrationTableRow(util.Dataclass):
"""
A row in a :class:`MigrationTable`.
"""
__slots__ = ["left", "right", "node", "source", "dest", "time", "metadata"]
left: float
"""
See :attr:`Migration.left`
"""
right: float
"""
See :attr:`Migration.right`
"""
node: int
"""
See :attr:`Migration.node`
"""
source: int
"""
See :attr:`Migration.source`
"""
dest: int
"""
See :attr:`Migration.dest`
"""
time: float
"""
See :attr:`Migration.time`
"""
metadata: Optional[Union[bytes, dict]]
"""
See :attr:`Migration.metadata`
"""
@metadata.lazy_decode()
@dataclass(**dataclass_options)
class SiteTableRow(util.Dataclass):
"""
A row in a :class:`SiteTable`.
"""
__slots__ = ["position", "ancestral_state", "metadata"]
position: float
"""
See :attr:`Site.position`
"""
ancestral_state: str
"""
See :attr:`Site.ancestral_state`
"""
metadata: Optional[Union[bytes, dict]]
"""
See :attr:`Site.metadata`
"""
@metadata.lazy_decode()
@dataclass(**dataclass_options)
class MutationTableRow(util.Dataclass):
"""
A row in a :class:`MutationTable`.
"""
__slots__ = ["site", "node", "derived_state", "parent", "metadata", "time"]
site: int
"""
See :attr:`Mutation.site`
"""
node: int
"""
See :attr:`Mutation.node`
"""
derived_state: str
"""
See :attr:`Mutation.derived_state`
"""
parent: int
"""
See :attr:`Mutation.parent`
"""
metadata: Optional[Union[bytes, dict]]
"""
See :attr:`Mutation.metadata`
"""
time: float
"""
See :attr:`Mutation.time`
"""
# We need a custom eq here as we have unknown times (nans) to check
def __eq__(self, other):
return (
isinstance(other, MutationTableRow)
and self.site == other.site
and self.node == other.node
and self.derived_state == other.derived_state
and self.parent == other.parent
and self.metadata == other.metadata
and (
self.time == other.time
or (
util.is_unknown_time(self.time) and util.is_unknown_time(other.time)
)
)
)
@metadata.lazy_decode()
@dataclass(**dataclass_options)
class PopulationTableRow(util.Dataclass):
"""
A row in a :class:`PopulationTable`.
"""
__slots__ = ["metadata"]
metadata: Optional[Union[bytes, dict]]
"""
See :attr:`Population.metadata`
"""
@dataclass(**dataclass_options)
class ProvenanceTableRow(util.Dataclass):
"""
A row in a :class:`ProvenanceTable`.
"""
__slots__ = ["timestamp", "record"]
timestamp: str
"""
See :attr:`Provenance.timestamp`
"""
record: str
"""
See :attr:`Provenance.record`
"""
@dataclass(**dataclass_options)
class TableCollectionIndexes(util.Dataclass):
"""
A class encapsulating the indexes of a :class:`TableCollection`
"""
edge_insertion_order: np.ndarray = None
edge_removal_order: np.ndarray = None
def asdict(self):
return {k: v for k, v in dataclasses.asdict(self).items() if v is not None}
@property
def nbytes(self) -> int:
"""
The number of bytes taken by the indexes
"""
total = 0
if self.edge_removal_order is not None:
total += self.edge_removal_order.nbytes
if self.edge_insertion_order is not None:
total += self.edge_insertion_order.nbytes
return total
def keep_with_offset(keep, data, offset):
"""
Used when filtering _offset columns in tables
"""
# We need the astype here for 32 bit machines
lens = np.diff(offset).astype(np.int32)
return (
data[np.repeat(keep, lens)],
np.concatenate(
[
np.array([0], dtype=offset.dtype),
np.cumsum(lens[keep], dtype=offset.dtype),
]
),
)
class BaseTable:
"""
Superclass of high-level tables. Not intended for direct instantiation.
"""
# The list of columns in the table. Must be set by subclasses.
column_names = []
def __init__(self, ll_table, row_class):
self.ll_table = ll_table
self.row_class = row_class
def _check_required_args(self, **kwargs):
for k, v in kwargs.items():
if v is None:
raise TypeError(f"{k} is required")
@property
def num_rows(self) -> int:
return self.ll_table.num_rows
@property
def max_rows(self) -> int:
return self.ll_table.max_rows
@property
def max_rows_increment(self) -> int:
return self.ll_table.max_rows_increment
@property
def nbytes(self) -> int:
"""
Returns the total number of bytes required to store the data
in this table. Note that this may not be equal to
the actual memory footprint.
"""
# It's not ideal that we run asdict() here to do this as we're
# currently creating copies of the column arrays, so it would
# be more efficient to have dedicated low-level methods. However,
# if we do have read-only views on the underlying memory for the
# column arrays then this will be a perfectly good way of
# computing the nbytes values and the overhead minimal.
d = self.asdict()
nbytes = 0
# Some tables don't have a metadata_schema
metadata_schema = d.pop("metadata_schema", None)
if metadata_schema is not None:
nbytes += len(metadata_schema.encode())
nbytes += sum(col.nbytes for col in d.values())
return nbytes
def equals(self, other, ignore_metadata=False):
"""
Returns True if `self` and `other` are equal. By default, two tables
are considered equal if their columns and metadata schemas are
byte-for-byte identical.
:param other: Another table instance
:param bool ignore_metadata: If True exclude metadata and metadata schemas
from the comparison.
:return: True if other is equal to this table; False otherwise.
:rtype: bool
"""
# Note: most tables support ignore_metadata, we can override for those that don't
ret = False
if type(other) is type(self):
ret = bool(
self.ll_table.equals(other.ll_table, ignore_metadata=ignore_metadata)
)
return ret
def assert_equals(self, other, *, ignore_metadata=False):
"""
Raise an AssertionError for the first found difference between
this and another table of the same type.
:param other: Another table instance
:param bool ignore_metadata: If True exclude metadata and metadata schemas
from the comparison.
"""
if type(other) is not type(self):
raise AssertionError(f"Types differ: self={type(self)} other={type(other)}")
# Check using the low-level method to avoid slowly going through everything
if self.equals(other, ignore_metadata=ignore_metadata):
return
if not ignore_metadata and self.metadata_schema != other.metadata_schema:
raise AssertionError(
f"{type(self).__name__} metadata schemas differ: "
f"self={self.metadata_schema} "
f"other={other.metadata_schema}"
)
for n, (row_self, row_other) in enumerate(zip(self, other)):
if ignore_metadata:
row_self = dataclasses.replace(row_self, metadata=None)
row_other = dataclasses.replace(row_other, metadata=None)
if row_self != row_other:
self_dict = dataclasses.asdict(self[n])
other_dict = dataclasses.asdict(other[n])
diff_string = []
for col in self_dict.keys():
if isinstance(self_dict[col], np.ndarray):
equal = np.array_equal(self_dict[col], other_dict[col])
else:
equal = self_dict[col] == other_dict[col]
if not equal:
diff_string.append(
f"self.{col}={self_dict[col]} other.{col}={other_dict[col]}"
)
diff_string = "\n".join(diff_string)
raise AssertionError(
f"{type(self).__name__} row {n} differs:\n{diff_string}"
)
if self.num_rows != other.num_rows:
raise AssertionError(
f"{type(self).__name__} number of rows differ: self={self.num_rows} "
f"other={other.num_rows}"
)
raise AssertionError(
"Tables differ in an undetected way - "
"this is a bug, please report an issue on gitub"
) # pragma: no cover
def __eq__(self, other):
return self.equals(other)
def __len__(self):
return self.num_rows
def __getattr__(self, name):
if name in self.column_names:
return getattr(self.ll_table, name)
else:
raise AttributeError(
f"{self.__class__.__name__} object has no attribute {name}"
)
def __setattr__(self, name, value):
if name in self.column_names:
d = self.asdict()
d[name] = value
self.set_columns(**d)
else:
object.__setattr__(self, name, value)
def _make_row(self, *args):
return self.row_class(*args)
def __getitem__(self, index):
"""
If passed an integer, return the specified row of this table, decoding metadata
if it is present. Supports negative indexing, e.g. ``table[-5]``.
If passed a slice, iterable or array return a new table containing the specified
rows. Similar to numpy fancy indexing, if the array or iterables contains
booleans then the index acts as a mask, returning those rows for which the mask
is True. Note that as the result is a new table, the row ids will change as tskit
row ids are row indexes.
:param index: the index of a desired row, a slice of the desired rows, an
iterable or array of the desired row numbers, or a boolean array to use as
a mask.
"""
if isinstance(index, numbers.Integral):
# Single row by integer
if index < 0:
index += len(self)
if index < 0 or index >= len(self):
raise IndexError("Index out of bounds")
return self._make_row(*self.ll_table.get_row(index))
elif isinstance(index, numbers.Number):
raise TypeError("Index must be integer, slice or iterable")
elif isinstance(index, slice):
index = range(*index.indices(len(self)))
else:
index = np.asarray(index)
if index.dtype == np.bool_:
if len(index) != len(self):
raise IndexError("Boolean index must be same length as table")
index = np.flatnonzero(index)
index = util.safe_np_int_cast(index, np.int32)
ret = self.__class__()
ret.metadata_schema = self.metadata_schema
ret.ll_table.extend(self.ll_table, row_indexes=index)
return ret
def __setitem__(self, index, new_row):
"""
Replaces a row of this table at the specified index with information from a
row-like object. Metadata, will be validated and encoded according to the table's
:attr:`metadata_schema<tskit.IndividualTable.metadata_schema>`.
:param index: the index of the row to change
:param row-like new_row: An object that has attributes corresponding to the
properties of the new row. Both the objects returned from ``table[i]`` and
e.g. ``ts.individual(i)`` work for this purpose, along with any other
object with the correct attributes.
"""
if isinstance(index, numbers.Integral):
# Single row by integer
if index < 0:
index += len(self)
if index < 0 or index >= len(self):
raise IndexError("Index out of bounds")
else:
raise TypeError("Index must be integer")
row_data = {
column: getattr(new_row, column)
for column in self.column_names
if "_offset" not in column
}
# Encode the metadata - note that if this becomes a perf bottleneck it is
# possible to use the cached, encoded metadata in the row object, rather than
# decode and reencode
if "metadata" in row_data:
row_data["metadata"] = self.metadata_schema.validate_and_encode_row(
row_data["metadata"]
)
self.ll_table.update_row(row_index=index, **row_data)
def append(self, row):
"""
Adds a new row to this table and returns the ID of the new row. Metadata, if
specified, will be validated and encoded according to the table's
:attr:`metadata_schema<tskit.IndividualTable.metadata_schema>`.
:param row-like row: An object that has attributes corresponding to the
properties of the new row. Both the objects returned from ``table[i]`` and
e.g. ``ts.individual(i)`` work for this purpose, along with any other
object with the correct attributes.
:return: The index of the newly added row.
:rtype: int
"""
return self.add_row(
**{
column: getattr(row, column)
for column in self.column_names
if "_offset" not in column
}
)
def replace_with(self, other):
# Overwrite the contents of this table with a copy of the other table
self.set_columns(**other.asdict())
def clear(self):
"""
Deletes all rows in this table.
"""
self.ll_table.clear()
def reset(self):
# Deprecated alias for clear
self.clear()
def truncate(self, num_rows):
"""
Truncates this table so that the only the first ``num_rows`` are retained.
:param int num_rows: The number of rows to retain in this table.
"""
return self.ll_table.truncate(num_rows)
def keep_rows(self, keep):
"""
.. include:: substitutions/table_keep_rows_main.rst
:param array-like keep: The rows to keep as a boolean array. Must
be the same length as the table, and convertible to a numpy
array of dtype bool.
:return: The mapping between old and new row IDs as a numpy
array (dtype int32).
:rtype: numpy.ndarray (dtype=np.int32)
"""
# We do this check here rather than in the C code because calling
# len() on the input will cause a more readable exception to be
# raised than the inscrutable errors we get from numpy when
# converting arguments of the wrong type.
if len(keep) != len(self):
msg = (
"Argument for keep_rows must be a boolean array of "
"the same length as the table. "
f"(need:{len(self)}, got:{len(keep)})"
)
raise ValueError(msg)
return self.ll_table.keep_rows(keep)
# Pickle support
def __getstate__(self):
return self.asdict()
# Unpickle support
def __setstate__(self, state):
self.__init__()
self.set_columns(**state)
def copy(self):
"""
Returns a deep copy of this table
"""
copy = self.__class__()
copy.set_columns(**self.asdict())
return copy
def asdict(self):
"""
Returns a dictionary mapping the names of the columns in this table
to the corresponding numpy arrays.
"""
ret = {col: getattr(self, col) for col in self.column_names}
# Not all tables have metadata
try:
ret["metadata_schema"] = repr(self.metadata_schema)
except AttributeError:
pass
return ret
def set_columns(self, **kwargs):
"""
Sets the values for each column in this :class:`Table` using values
provided in numpy arrays. Overwrites existing data in all the table columns.
"""
raise NotImplementedError()
def __str__(self):
headers, rows = self._text_header_and_rows(
limit=tskit._print_options["max_lines"]
)
return util.unicode_table(rows, header=headers, row_separator=False)
def _repr_html_(self):
"""
Called e.g. by jupyter notebooks to render tables
"""
headers, rows = self._text_header_and_rows(
limit=tskit._print_options["max_lines"]
)
return util.html_table(rows, header=headers)
def _columns_all_integer(self, *colnames):
# For displaying floating point values without loads of decimal places
return all(
np.all(getattr(self, col) == np.floor(getattr(self, col)))
for col in colnames
)
class MetadataTable(BaseTable):
"""
Base class for tables that have a metadata column.
"""
# TODO this class has some overlap with the MetadataProvider base class
# and also the TreeSequence class. These all have methods to deal with
# schemas and essentially do the same thing (provide a facade for the
# low-level get/set metadata schemas functionality). We should refactor
# this so we're only doing it in one place.
# https://github.com/tskit-dev/tskit/issues/1957
def __init__(self, ll_table, row_class):
super().__init__(ll_table, row_class)
def _make_row(self, *args):
return self.row_class(*args, metadata_decoder=self.metadata_schema.decode_row)
def packset_metadata(self, metadatas):
"""
Packs the specified list of metadata values and updates the ``metadata``
and ``metadata_offset`` columns. The length of the metadatas array
must be equal to the number of rows in the table.
:param list metadatas: A list of metadata bytes values.
"""
packed, offset = util.pack_bytes(metadatas)
d = self.asdict()
d["metadata"] = packed
d["metadata_offset"] = offset
self.set_columns(**d)
@property
def metadata_schema(self) -> metadata.MetadataSchema:
"""
The :class:`tskit.MetadataSchema` for this table.
"""
# This isn't as inefficient as it looks because we're using an LRU cache on
# the parse_metadata_schema function. Thus, we're really only incurring the
# cost of creating the unicode string from the low-level schema and looking
# up the functools cache.
return metadata.parse_metadata_schema(self.ll_table.metadata_schema)
@metadata_schema.setter
def metadata_schema(self, schema: metadata.MetadataSchema) -> None:
if not isinstance(schema, metadata.MetadataSchema):
raise TypeError(
"Only instances of tskit.MetadataSchema can be assigned to "
f"metadata_schema, not {type(schema)}"
)
self.ll_table.metadata_schema = repr(schema)
def metadata_vector(self, key, *, dtype=None, default_value=NOTSET):
"""
Returns a numpy array of metadata values obtained by extracting ``key``
from each metadata entry, and using ``default_value`` if the key is
not present. ``key`` may be a list, in which case nested values are returned.
For instance, ``key = ["a", "x"]`` will return an array of
``row.metadata["a"]["x"]`` values, iterated over rows in this table.
:param str key: The name, or a list of names, of metadata entries.
:param str dtype: The dtype of the result (can usually be omitted).
:param object default_value: The value to be inserted if the metadata key
is not present. Note that for numeric columns, a default value of None
will result in a non-numeric array. The default behaviour is to raise
``KeyError`` on missing entries.
"""
if default_value == NOTSET:
def getter(d, k):
return d[k]
else:
def getter(d, k):
return (
d.get(k, default_value) if isinstance(d, Mapping) else default_value
)
if isinstance(key, list):
out = np.array(
[
reduce(
getter,
key,
row.metadata,
)
for row in self
],
dtype=dtype,
)
else:
out = np.array(
[getter(row.metadata, key) for row in self],
dtype=dtype,
)
return out
def drop_metadata(self, *, keep_schema=False):
"""
Drops all metadata in this table. By default, the schema is also cleared,
except if ``keep_schema`` is True.
:param bool keep_schema: True if the current schema should be kept intact.
"""
data = self.asdict()
data["metadata"] = []
data["metadata_offset"][:] = 0
self.set_columns(**data)
if not keep_schema:
self.metadata_schema = metadata.MetadataSchema.null()
class IndividualTable(MetadataTable):
"""
A table defining the individuals in a tree sequence. Note that although
each Individual has associated nodes, reference to these is not stored in
the individual table, but rather reference to the individual is stored for
each node in the :class:`NodeTable`. This is similar to the way in which
the relationship between sites and mutations is modelled.
.. include:: substitutions/table_edit_warning.rst
:ivar flags: The array of flags values.
:vartype flags: numpy.ndarray, dtype=np.uint32
:ivar location: The flattened array of floating point location values. See
:ref:`sec_encoding_ragged_columns` for more details.
:vartype location: numpy.ndarray, dtype=np.float64
:ivar location_offset: The array of offsets into the location column. See
:ref:`sec_encoding_ragged_columns` for more details.
:vartype location_offset: numpy.ndarray, dtype=np.uint32
:ivar parents: The flattened array of parent individual ids. See
:ref:`sec_encoding_ragged_columns` for more details.
:vartype parents: numpy.ndarray, dtype=np.int32
:ivar parents_offset: The array of offsets into the parents column. See
:ref:`sec_encoding_ragged_columns` for more details.
:vartype parents_offset: numpy.ndarray, dtype=np.uint32
:ivar metadata: The flattened array of binary metadata values. See
:ref:`sec_tables_api_binary_columns` for more details.
:vartype metadata: numpy.ndarray, dtype=np.int8
:ivar metadata_offset: The array of offsets into the metadata column. See
:ref:`sec_tables_api_binary_columns` for more details.
:vartype metadata_offset: numpy.ndarray, dtype=np.uint32
:ivar metadata_schema: The metadata schema for this table's metadata column
:vartype metadata_schema: tskit.MetadataSchema
"""
column_names = [
"flags",
"location",
"location_offset",
"parents",
"parents_offset",
"metadata",
"metadata_offset",
]
def __init__(self, max_rows_increment=0, ll_table=None):
if ll_table is None:
ll_table = _tskit.IndividualTable(max_rows_increment=max_rows_increment)
super().__init__(ll_table, IndividualTableRow)
def _text_header_and_rows(self, limit=None):
headers = ("id", "flags", "location", "parents", "metadata")
rows = []
row_indexes = util.truncate_rows(self.num_rows, limit)
for j in row_indexes:
if j == -1:
rows.append(f"__skipped__{self.num_rows - limit}")
else:
row = self[j]
location_str = ", ".join(map(str, row.location))
parents_str = ", ".join([f"{p:,}" for p in row.parents])
rows.append(
"{:,}\t{}\t{}\t{}\t{}".format(
j,
row.flags,
location_str,
parents_str,
util.render_metadata(row.metadata),
).split("\t")
)
return headers, rows
def add_row(self, flags=0, location=None, parents=None, metadata=None):
"""
Adds a new row to this :class:`IndividualTable` and returns the ID of the
corresponding individual. Metadata, if specified, will be validated and encoded
according to the table's
:attr:`metadata_schema<tskit.IndividualTable.metadata_schema>`.
:param int flags: The bitwise flags for the new node.
:param array-like location: A list of numeric values or one-dimensional numpy
array describing the location of this individual. If not specified
or None, a zero-dimensional location is stored.
:param array-like parents: A list or array of ids of parent individuals. If not
specified an empty array is stored.
:param object metadata: Any object that is valid metadata for the table's schema.
Defaults to the default metadata value for the table's schema. This is
typically ``{}``. For no schema, ``None``.
:return: The ID of the newly added individual.
:rtype: int
"""
if metadata is None:
metadata = self.metadata_schema.empty_value
metadata = self.metadata_schema.validate_and_encode_row(metadata)
return self.ll_table.add_row(
flags=flags, location=location, parents=parents, metadata=metadata
)
def set_columns(
self,
flags=None,
location=None,
location_offset=None,
parents=None,
parents_offset=None,
metadata=None,
metadata_offset=None,
metadata_schema=None,
):
"""
Sets the values for each column in this :class:`IndividualTable` using the
values in the specified arrays. Overwrites existing data in all the table
columns.
The ``flags`` array is mandatory and defines the number of individuals
the table will contain.
The ``location`` and ``location_offset`` parameters must be supplied
together, and meet the requirements for :ref:`sec_encoding_ragged_columns`.
The ``parents`` and ``parents_offset`` parameters must be supplied
together, and meet the requirements for :ref:`sec_encoding_ragged_columns`.
The ``metadata`` and ``metadata_offset`` parameters must be supplied
together, and meet the requirements for :ref:`sec_encoding_ragged_columns`.
See :ref:`sec_tables_api_binary_columns` for more information and
:ref:`sec_tutorial_metadata_bulk` for an example of how to prepare metadata.
:param flags: The bitwise flags for each individual. Required.
:type flags: numpy.ndarray, dtype=np.uint32
:param location: The flattened location array. Must be specified along
with ``location_offset``. If not specified or None, an empty location
value is stored for each individual.
:type location: numpy.ndarray, dtype=np.float64
:param location_offset: The offsets into the ``location`` array.
:type location_offset: numpy.ndarray, dtype=np.uint32.
:param parents: The flattened parents array. Must be specified along
with ``parents_offset``. If not specified or None, an empty parents array
is stored for each individual.
:type parents: numpy.ndarray, dtype=np.int32
:param parents_offset: The offsets into the ``parents`` array.
:type parents_offset: numpy.ndarray, dtype=np.uint32.
:param metadata: The flattened metadata array. Must be specified along
with ``metadata_offset``. If not specified or None, an empty metadata
value is stored for each individual.
:type metadata: numpy.ndarray, dtype=np.int8
:param metadata_offset: The offsets into the ``metadata`` array.
:type metadata_offset: numpy.ndarray, dtype=np.uint32.
:param metadata_schema: The encoded metadata schema. If None (default)
do not overwrite the exising schema. Note that a schema will need to be
encoded as a string, e.g. via ``repr(new_metadata_schema)``.
:type metadata_schema: str
"""
self._check_required_args(flags=flags)
self.ll_table.set_columns(
dict(
flags=flags,
location=location,
location_offset=location_offset,
parents=parents,
parents_offset=parents_offset,
metadata=metadata,
metadata_offset=metadata_offset,
metadata_schema=metadata_schema,
)
)
def append_columns(
self,
flags=None,
location=None,
location_offset=None,
parents=None,
parents_offset=None,
metadata=None,
metadata_offset=None,
):
"""
Appends the specified arrays to the end of the columns in this
:class:`IndividualTable`. This allows many new rows to be added at once.
The ``flags`` array is mandatory and defines the number of
extra individuals to add to the table.
The ``parents`` and ``parents_offset`` parameters must be supplied
together, and meet the requirements for :ref:`sec_encoding_ragged_columns`.
The ``location`` and ``location_offset`` parameters must be supplied
together, and meet the requirements for :ref:`sec_encoding_ragged_columns`.
The ``metadata`` and ``metadata_offset`` parameters must be supplied
together, and meet the requirements for :ref:`sec_encoding_ragged_columns`.
See :ref:`sec_tables_api_binary_columns` for more information and
:ref:`sec_tutorial_metadata_bulk` for an example of how to prepare metadata.