tskit 1.0.1__cp314-cp314-macosx_10_15_universal2.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
tskit/text_formats.py ADDED
@@ -0,0 +1,456 @@
1
+ # MIT License
2
+ #
3
+ # Copyright (c) 2021-2024 Tskit Developers
4
+ #
5
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ # of this software and associated documentation files (the "Software"), to deal
7
+ # in the Software without restriction, including without limitation the rights
8
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ # copies of the Software, and to permit persons to whom the Software is
10
+ # furnished to do so, subject to the following conditions:
11
+ #
12
+ # The above copyright notice and this permission notice shall be included in all
13
+ # copies or substantial portions of the Software.
14
+ #
15
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ # SOFTWARE.
22
+ """
23
+ Module responsible for working with text format data.
24
+ """
25
+ import base64
26
+
27
+ import numpy as np
28
+
29
+ import tskit
30
+ from tskit import util
31
+
32
+
33
+ def parse_fam(fam_file):
34
+ """
35
+ Parse PLINK .fam file and convert to tskit IndividualTable.
36
+
37
+ Assumes fam file contains five columns: FID, IID, PAT, MAT, SEX
38
+
39
+ :param fam_file: PLINK .fam file object
40
+ :param tskit.TableCollection tc: TableCollection with IndividualTable to
41
+ which the individuals will be added
42
+ """
43
+ individuals = np.loadtxt(
44
+ fname=fam_file,
45
+ dtype=str,
46
+ ndmin=2, # read file as 2-D table
47
+ usecols=(0, 1, 2, 3, 4), # only keep FID, IID, PAT, MAT, SEX columns
48
+ ) # requires same number of columns in each row, i.e. not ragged
49
+
50
+ id_map = {} # dict for translating PLINK ID to tskit IndividualTable ID
51
+ for tskit_id, (plink_fid, plink_iid, _pat, _mat, _sex) in enumerate(individuals):
52
+ # include space between strings to ensure uniqueness
53
+ plink_id = f"{plink_fid} {plink_iid}"
54
+ if plink_id in id_map:
55
+ raise ValueError("Duplicate PLINK ID: {plink_id}")
56
+ id_map[plink_id] = tskit_id
57
+ id_map["0"] = -1 # -1 is used in tskit to denote "missing"
58
+
59
+ tc = tskit.TableCollection(1)
60
+ tb = tc.individuals
61
+ tb.metadata_schema = tskit.MetadataSchema(
62
+ {
63
+ "codec": "json",
64
+ "type": "object",
65
+ "properties": {
66
+ "plink_fid": {"type": "string"},
67
+ "plink_iid": {"type": "string"},
68
+ "sex": {"type": "integer"},
69
+ },
70
+ "required": ["plink_fid", "plink_iid", "sex"],
71
+ "additionalProperties": True,
72
+ }
73
+ )
74
+ for plink_fid, plink_iid, pat, mat, sex in individuals:
75
+ sex = int(sex)
76
+ if not (sex in range(3)):
77
+ raise ValueError(
78
+ "Sex must be one of the following: 0 (unknown), 1 (male), 2 (female)"
79
+ )
80
+ metadata_dict = {"plink_fid": plink_fid, "plink_iid": plink_iid, "sex": sex}
81
+ pat_id = f"{plink_fid} {pat}" if pat != "0" else pat
82
+ mat_id = f"{plink_fid} {mat}" if mat != "0" else mat
83
+ tb.add_row(
84
+ parents=[
85
+ id_map[pat_id],
86
+ id_map[mat_id],
87
+ ],
88
+ metadata=metadata_dict,
89
+ )
90
+ tc.sort()
91
+
92
+ return tb
93
+
94
+
95
+ def flexible_file_output(ts_export_func):
96
+ """
97
+ Decorator to support writing to either an open file-like object
98
+ or to a path. Assumes the second argument is the output.
99
+ """
100
+
101
+ def f(ts, file_or_path, **kwargs):
102
+ file, local_file = util.convert_file_like_to_open_file(file_or_path, "w")
103
+ try:
104
+ ts_export_func(ts, file, **kwargs)
105
+ finally:
106
+ if local_file:
107
+ file.close()
108
+
109
+ return f
110
+
111
+
112
+ @flexible_file_output
113
+ def write_nexus(
114
+ ts,
115
+ out,
116
+ *,
117
+ precision,
118
+ include_trees,
119
+ include_alignments,
120
+ reference_sequence,
121
+ missing_data_character,
122
+ isolated_as_missing=None,
123
+ ):
124
+ # See TreeSequence.write_nexus for documentation on parameters.
125
+ if precision is None:
126
+ pos_precision = 0 if ts.discrete_genome else 17
127
+ time_precision = None
128
+ else:
129
+ pos_precision = precision
130
+ time_precision = precision
131
+
132
+ indent = " "
133
+ print("#NEXUS", file=out)
134
+ print("BEGIN TAXA;", file=out)
135
+ print("", f"DIMENSIONS NTAX={ts.num_samples};", sep=indent, file=out)
136
+ taxlabels = " ".join(f"n{u}" for u in ts.samples())
137
+ print("", f"TAXLABELS {taxlabels};", sep=indent, file=out)
138
+ print("END;", file=out)
139
+
140
+ if include_alignments is None:
141
+ include_alignments = ts.discrete_genome and ts.num_sites > 0
142
+ if include_alignments:
143
+ missing_data_character = (
144
+ "?" if missing_data_character is None else missing_data_character
145
+ )
146
+ print("BEGIN DATA;", file=out)
147
+ print("", f"DIMENSIONS NCHAR={int(ts.sequence_length)};", sep=indent, file=out)
148
+ print(
149
+ "",
150
+ f"FORMAT DATATYPE=DNA MISSING={missing_data_character};",
151
+ sep=indent,
152
+ file=out,
153
+ )
154
+ print("", "MATRIX", file=out, sep=indent)
155
+ alignments = ts.alignments(
156
+ reference_sequence=reference_sequence,
157
+ missing_data_character=missing_data_character,
158
+ isolated_as_missing=isolated_as_missing,
159
+ )
160
+ for u, alignment in zip(ts.samples(), alignments):
161
+ print(2 * indent, f"n{u}", " ", alignment, sep="", file=out)
162
+ print("", ";", sep=indent, file=out)
163
+ print("END;", file=out)
164
+
165
+ include_trees = True if include_trees is None else include_trees
166
+ if include_trees:
167
+ print("BEGIN TREES;", file=out)
168
+ for tree in ts.trees():
169
+ start_interval = "{0:.{1}f}".format(tree.interval.left, pos_precision)
170
+ end_interval = "{0:.{1}f}".format(tree.interval.right, pos_precision)
171
+ tree_label = f"t{start_interval}^{end_interval}"
172
+ newick = tree.as_newick(precision=time_precision)
173
+ print("", f"TREE {tree_label} = [&R] {newick}", sep=indent, file=out)
174
+ print("END;", file=out)
175
+
176
+
177
+ def wrap_text(text, width):
178
+ """
179
+ Return an iterator over the lines in the specified string of at most the
180
+ specified width. (We could use textwrap.wrap for this, but it uses a
181
+ more complicated algorithm appropriate for blocks of words.)
182
+ """
183
+ width = len(text) if width == 0 else width
184
+ N = len(text) // width
185
+ offset = 0
186
+ for _ in range(N):
187
+ yield text[offset : offset + width]
188
+ offset += width
189
+ if offset != len(text):
190
+ yield text[offset:]
191
+
192
+
193
+ @flexible_file_output
194
+ def write_fasta(
195
+ ts,
196
+ output,
197
+ *,
198
+ wrap_width,
199
+ reference_sequence,
200
+ missing_data_character,
201
+ isolated_as_missing=None,
202
+ ):
203
+ # See TreeSequence.write_fasta for documentation
204
+ if wrap_width < 0 or int(wrap_width) != wrap_width:
205
+ raise ValueError(
206
+ "wrap_width must be a non-negative integer. "
207
+ "You may specify `wrap_width=0` "
208
+ "if you do not want any wrapping."
209
+ )
210
+ wrap_width = int(wrap_width)
211
+ alignments = ts.alignments(
212
+ reference_sequence=reference_sequence,
213
+ missing_data_character=missing_data_character,
214
+ isolated_as_missing=isolated_as_missing,
215
+ )
216
+ for u, alignment in zip(ts.samples(), alignments):
217
+ print(">", f"n{u}", sep="", file=output)
218
+ for line in wrap_text(alignment, wrap_width):
219
+ print(line, file=output)
220
+
221
+
222
+ def _build_newick(tree, *, node, precision, node_labels, include_branch_lengths):
223
+ label = node_labels.get(node, "")
224
+ if tree.is_leaf(node):
225
+ s = f"{label}"
226
+ else:
227
+ s = "("
228
+ for child in tree.children(node):
229
+ branch_length = tree.branch_length(child)
230
+ subtree = _build_newick(
231
+ tree,
232
+ node=child,
233
+ precision=precision,
234
+ node_labels=node_labels,
235
+ include_branch_lengths=include_branch_lengths,
236
+ )
237
+ if include_branch_lengths:
238
+ subtree += ":{0:.{1}f}".format(branch_length, precision)
239
+ s += subtree + ","
240
+ s = s[:-1] + f"){label}"
241
+ return s
242
+
243
+
244
+ def build_newick(tree, *, root, precision, node_labels, include_branch_lengths):
245
+ """
246
+ Simple recursive version of the newick generator used when non-default
247
+ node labels are needed, or when branch lengths are omitted
248
+ """
249
+ s = _build_newick(
250
+ tree,
251
+ node=root,
252
+ precision=precision,
253
+ node_labels=node_labels,
254
+ include_branch_lengths=include_branch_lengths,
255
+ )
256
+ return s + ";"
257
+
258
+
259
+ def dump_text(
260
+ ts,
261
+ *,
262
+ nodes,
263
+ edges,
264
+ sites,
265
+ mutations,
266
+ individuals,
267
+ populations,
268
+ migrations,
269
+ provenances,
270
+ precision,
271
+ encoding,
272
+ base64_metadata,
273
+ ):
274
+ if nodes is not None:
275
+ print(
276
+ "id",
277
+ "is_sample",
278
+ "time",
279
+ "population",
280
+ "individual",
281
+ "metadata",
282
+ sep="\t",
283
+ file=nodes,
284
+ )
285
+ for node in ts.nodes():
286
+ metadata = text_metadata(base64_metadata, encoding, node)
287
+ row = (
288
+ "{id:d}\t"
289
+ "{is_sample:d}\t"
290
+ "{time:.{precision}f}\t"
291
+ "{population:d}\t"
292
+ "{individual:d}\t"
293
+ "{metadata}"
294
+ ).format(
295
+ precision=precision,
296
+ id=node.id,
297
+ is_sample=node.is_sample(),
298
+ time=node.time,
299
+ population=node.population,
300
+ individual=node.individual,
301
+ metadata=metadata,
302
+ )
303
+ print(row, file=nodes)
304
+
305
+ if edges is not None:
306
+ print("left", "right", "parent", "child", "metadata", sep="\t", file=edges)
307
+ for edge in ts.edges():
308
+ metadata = text_metadata(base64_metadata, encoding, edge)
309
+ row = (
310
+ "{left:.{precision}f}\t"
311
+ "{right:.{precision}f}\t"
312
+ "{parent:d}\t"
313
+ "{child:d}\t"
314
+ "{metadata}"
315
+ ).format(
316
+ precision=precision,
317
+ left=edge.left,
318
+ right=edge.right,
319
+ parent=edge.parent,
320
+ child=edge.child,
321
+ metadata=metadata,
322
+ )
323
+ print(row, file=edges)
324
+
325
+ if sites is not None:
326
+ print("position", "ancestral_state", "metadata", sep="\t", file=sites)
327
+ for site in ts.sites():
328
+ metadata = text_metadata(base64_metadata, encoding, site)
329
+ row = (
330
+ "{position:.{precision}f}\t" "{ancestral_state}\t" "{metadata}"
331
+ ).format(
332
+ precision=precision,
333
+ position=site.position,
334
+ ancestral_state=site.ancestral_state,
335
+ metadata=metadata,
336
+ )
337
+ print(row, file=sites)
338
+
339
+ if mutations is not None:
340
+ print(
341
+ "site",
342
+ "node",
343
+ "time",
344
+ "derived_state",
345
+ "parent",
346
+ "metadata",
347
+ sep="\t",
348
+ file=mutations,
349
+ )
350
+ for site in ts.sites():
351
+ for mutation in site.mutations:
352
+ metadata = text_metadata(base64_metadata, encoding, mutation)
353
+ row = (
354
+ "{site}\t"
355
+ "{node}\t"
356
+ "{time}\t"
357
+ "{derived_state}\t"
358
+ "{parent}\t"
359
+ "{metadata}"
360
+ ).format(
361
+ site=mutation.site,
362
+ node=mutation.node,
363
+ time=(
364
+ "unknown"
365
+ if util.is_unknown_time(mutation.time)
366
+ else mutation.time
367
+ ),
368
+ derived_state=mutation.derived_state,
369
+ parent=mutation.parent,
370
+ metadata=metadata,
371
+ )
372
+ print(row, file=mutations)
373
+
374
+ if individuals is not None:
375
+ print(
376
+ "id",
377
+ "flags",
378
+ "location",
379
+ "parents",
380
+ "metadata",
381
+ sep="\t",
382
+ file=individuals,
383
+ )
384
+ for individual in ts.individuals():
385
+ metadata = text_metadata(base64_metadata, encoding, individual)
386
+ location = ",".join(map(str, individual.location))
387
+ parents = ",".join(map(str, individual.parents))
388
+ row = (
389
+ "{id}\t" "{flags}\t" "{location}\t" "{parents}\t" "{metadata}"
390
+ ).format(
391
+ id=individual.id,
392
+ flags=individual.flags,
393
+ location=location,
394
+ parents=parents,
395
+ metadata=metadata,
396
+ )
397
+ print(row, file=individuals)
398
+
399
+ if populations is not None:
400
+ print("id", "metadata", sep="\t", file=populations)
401
+ for population in ts.populations():
402
+ metadata = text_metadata(base64_metadata, encoding, population)
403
+ row = ("{id}\t" "{metadata}").format(id=population.id, metadata=metadata)
404
+ print(row, file=populations)
405
+
406
+ if migrations is not None:
407
+ print(
408
+ "left",
409
+ "right",
410
+ "node",
411
+ "source",
412
+ "dest",
413
+ "time",
414
+ "metadata",
415
+ sep="\t",
416
+ file=migrations,
417
+ )
418
+ for migration in ts.migrations():
419
+ metadata = text_metadata(base64_metadata, encoding, migration)
420
+ row = (
421
+ "{left}\t"
422
+ "{right}\t"
423
+ "{node}\t"
424
+ "{source}\t"
425
+ "{dest}\t"
426
+ "{time}\t"
427
+ "{metadata}\t"
428
+ ).format(
429
+ left=migration.left,
430
+ right=migration.right,
431
+ node=migration.node,
432
+ source=migration.source,
433
+ dest=migration.dest,
434
+ time=migration.time,
435
+ metadata=metadata,
436
+ )
437
+ print(row, file=migrations)
438
+
439
+ if provenances is not None:
440
+ print("id", "timestamp", "record", sep="\t", file=provenances)
441
+ for provenance in ts.provenances():
442
+ row = ("{id}\t" "{timestamp}\t" "{record}\t").format(
443
+ id=provenance.id,
444
+ timestamp=provenance.timestamp,
445
+ record=provenance.record,
446
+ )
447
+ print(row, file=provenances)
448
+
449
+
450
+ def text_metadata(base64_metadata, encoding, node):
451
+ metadata = node.metadata
452
+ if isinstance(metadata, bytes) and base64_metadata:
453
+ metadata = base64.b64encode(metadata).decode(encoding)
454
+ else:
455
+ metadata = repr(metadata)
456
+ return metadata