phykit 2.6.0__tar.gz → 2.7.0__tar.gz

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.
Files changed (159) hide show
  1. {phykit-2.6.0 → phykit-2.7.0}/PKG-INFO +1 -1
  2. {phykit-2.6.0 → phykit-2.7.0}/phykit/cli_registry.py +2 -0
  3. phykit-2.7.0/phykit/helpers/genomic_coordinates.py +175 -0
  4. phykit-2.7.0/phykit/helpers/topology_landscape.py +190 -0
  5. {phykit-2.6.0 → phykit-2.7.0}/phykit/phykit.py +76 -0
  6. {phykit-2.6.0 → phykit-2.7.0}/phykit/service_factories.py +1 -0
  7. phykit-2.7.0/phykit/services/tree/topology_landscape.py +248 -0
  8. phykit-2.7.0/phykit/version.py +1 -0
  9. {phykit-2.6.0 → phykit-2.7.0}/phykit.egg-info/PKG-INFO +1 -1
  10. {phykit-2.6.0 → phykit-2.7.0}/phykit.egg-info/SOURCES.txt +3 -0
  11. {phykit-2.6.0 → phykit-2.7.0}/phykit.egg-info/entry_points.txt +2 -0
  12. phykit-2.6.0/phykit/version.py +0 -1
  13. {phykit-2.6.0 → phykit-2.7.0}/LICENSE.md +0 -0
  14. {phykit-2.6.0 → phykit-2.7.0}/README.md +0 -0
  15. {phykit-2.6.0 → phykit-2.7.0}/phykit/__init__.py +0 -0
  16. {phykit-2.6.0 → phykit-2.7.0}/phykit/__main__.py +0 -0
  17. {phykit-2.6.0 → phykit-2.7.0}/phykit/errors.py +0 -0
  18. {phykit-2.6.0 → phykit-2.7.0}/phykit/helpers/__init__.py +0 -0
  19. {phykit-2.6.0 → phykit-2.7.0}/phykit/helpers/boolean_argument_parsing.py +0 -0
  20. {phykit-2.6.0 → phykit-2.7.0}/phykit/helpers/caching.py +0 -0
  21. {phykit-2.6.0 → phykit-2.7.0}/phykit/helpers/circular_layout.py +0 -0
  22. {phykit-2.6.0 → phykit-2.7.0}/phykit/helpers/color_annotations.py +0 -0
  23. {phykit-2.6.0 → phykit-2.7.0}/phykit/helpers/discrete_models.py +0 -0
  24. {phykit-2.6.0 → phykit-2.7.0}/phykit/helpers/files.py +0 -0
  25. {phykit-2.6.0 → phykit-2.7.0}/phykit/helpers/geological_timescale.py +0 -0
  26. {phykit-2.6.0 → phykit-2.7.0}/phykit/helpers/json_output.py +0 -0
  27. {phykit-2.6.0 → phykit-2.7.0}/phykit/helpers/parallel.py +0 -0
  28. {phykit-2.6.0 → phykit-2.7.0}/phykit/helpers/parsimony_utils.py +0 -0
  29. {phykit-2.6.0 → phykit-2.7.0}/phykit/helpers/pgls_utils.py +0 -0
  30. {phykit-2.6.0 → phykit-2.7.0}/phykit/helpers/plot_config.py +0 -0
  31. {phykit-2.6.0 → phykit-2.7.0}/phykit/helpers/quartet_utils.py +0 -0
  32. {phykit-2.6.0 → phykit-2.7.0}/phykit/helpers/stats_summary.py +0 -0
  33. {phykit-2.6.0 → phykit-2.7.0}/phykit/helpers/streaming.py +0 -0
  34. {phykit-2.6.0 → phykit-2.7.0}/phykit/helpers/trait_parsing.py +0 -0
  35. {phykit-2.6.0 → phykit-2.7.0}/phykit/helpers/tree_paths.py +0 -0
  36. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/__init__.py +0 -0
  37. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/alignment/__init__.py +0 -0
  38. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/alignment/_fasta.py +0 -0
  39. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/alignment/alignment_entropy.py +0 -0
  40. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/alignment/alignment_length.py +0 -0
  41. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/alignment/alignment_length_no_gaps.py +0 -0
  42. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/alignment/alignment_outlier_regions.py +0 -0
  43. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/alignment/alignment_outlier_taxa.py +0 -0
  44. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/alignment/alignment_recoding.py +0 -0
  45. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/alignment/alignment_subsample.py +0 -0
  46. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/alignment/base.py +0 -0
  47. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/alignment/codon_dnds.py +0 -0
  48. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/alignment/column_score.py +0 -0
  49. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/alignment/composition_per_taxon.py +0 -0
  50. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/alignment/compositional_bias_per_site.py +0 -0
  51. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/alignment/create_concatenation_matrix.py +0 -0
  52. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/alignment/dfoil.py +0 -0
  53. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/alignment/dna_threader.py +0 -0
  54. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/alignment/dstatistic.py +0 -0
  55. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/alignment/evolutionary_rate_per_site.py +0 -0
  56. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/alignment/faidx.py +0 -0
  57. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/alignment/gc_content.py +0 -0
  58. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/alignment/identity_matrix.py +0 -0
  59. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/alignment/mask_alignment.py +0 -0
  60. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/alignment/occupancy_filter.py +0 -0
  61. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/alignment/occupancy_per_taxon.py +0 -0
  62. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/alignment/pairwise_identity.py +0 -0
  63. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/alignment/parsimony_informative_sites.py +0 -0
  64. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/alignment/phylo_gwas.py +0 -0
  65. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/alignment/plot_alignment_qc.py +0 -0
  66. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/alignment/rcv.py +0 -0
  67. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/alignment/rcvt.py +0 -0
  68. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/alignment/rename_fasta_entries.py +0 -0
  69. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/alignment/sum_of_pairs_score.py +0 -0
  70. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/alignment/taxon_groups.py +0 -0
  71. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/alignment/variable_sites.py +0 -0
  72. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/base.py +0 -0
  73. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/__init__.py +0 -0
  74. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/ancestral_reconstruction.py +0 -0
  75. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/base.py +0 -0
  76. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/bipartition_support_stats.py +0 -0
  77. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/branch_length_multiplier.py +0 -0
  78. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/character_map.py +0 -0
  79. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/chronogram.py +0 -0
  80. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/collapse_branches.py +0 -0
  81. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/concordance_asr.py +0 -0
  82. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/consensus_network.py +0 -0
  83. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/consensus_tree.py +0 -0
  84. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/cont_map.py +0 -0
  85. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/cophylo.py +0 -0
  86. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/covarying_evolutionary_rates.py +0 -0
  87. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/density_map.py +0 -0
  88. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/discordance_asymmetry.py +0 -0
  89. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/dtt.py +0 -0
  90. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/dvmc.py +0 -0
  91. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/episodic_rate_covariation.py +0 -0
  92. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/evo_tempo_map.py +0 -0
  93. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/evolutionary_rate.py +0 -0
  94. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/faiths_pd.py +0 -0
  95. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/fit_continuous.py +0 -0
  96. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/fit_discrete.py +0 -0
  97. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/hidden_paralogy_check.py +0 -0
  98. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/hybridization.py +0 -0
  99. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/independent_contrasts.py +0 -0
  100. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/internal_branch_stats.py +0 -0
  101. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/internode_labeler.py +0 -0
  102. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/kf_distance.py +0 -0
  103. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/last_common_ancestor_subtree.py +0 -0
  104. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/lb_score.py +0 -0
  105. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/ltt.py +0 -0
  106. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/monophyly_check.py +0 -0
  107. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/nearest_neighbor_interchange.py +0 -0
  108. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/neighbor_net.py +0 -0
  109. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/network_signal.py +0 -0
  110. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/ou_shift_detection.py +0 -0
  111. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/ouwie.py +0 -0
  112. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/parsimony_score.py +0 -0
  113. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/patristic_distances.py +0 -0
  114. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/phenogram.py +0 -0
  115. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/phylo_anova.py +0 -0
  116. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/phylo_heatmap.py +0 -0
  117. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/phylo_impute.py +0 -0
  118. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/phylo_logistic.py +0 -0
  119. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/phylo_path.py +0 -0
  120. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/phylogenetic_glm.py +0 -0
  121. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/phylogenetic_ordination.py +0 -0
  122. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/phylogenetic_regression.py +0 -0
  123. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/phylogenetic_signal.py +0 -0
  124. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/phylomorphospace.py +0 -0
  125. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/polytomy_test.py +0 -0
  126. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/print_tree.py +0 -0
  127. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/projected_covarying_rates.py +0 -0
  128. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/prune_tree.py +0 -0
  129. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/quartet_network.py +0 -0
  130. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/quartet_pie.py +0 -0
  131. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/rate_heterogeneity.py +0 -0
  132. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/relative_rate_test.py +0 -0
  133. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/rename_tree_tips.py +0 -0
  134. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/rf_distance.py +0 -0
  135. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/root_tree.py +0 -0
  136. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/saturation.py +0 -0
  137. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/simmap_summary.py +0 -0
  138. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/spectral_discordance.py +0 -0
  139. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/spr.py +0 -0
  140. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/spurious_sequence.py +0 -0
  141. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/stochastic_character_map.py +0 -0
  142. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/terminal_branch_stats.py +0 -0
  143. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/threshold_model.py +0 -0
  144. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/tip_labels.py +0 -0
  145. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/tip_to_tip_distance.py +0 -0
  146. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/tip_to_tip_node_distance.py +0 -0
  147. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/total_tree_length.py +0 -0
  148. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/trait_correlation.py +0 -0
  149. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/trait_rate_map.py +0 -0
  150. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/transfer_annotations.py +0 -0
  151. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/tree_space.py +0 -0
  152. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/treeness.py +0 -0
  153. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/treeness_over_rcv.py +0 -0
  154. {phykit-2.6.0 → phykit-2.7.0}/phykit/services/tree/vcv_utils.py +0 -0
  155. {phykit-2.6.0 → phykit-2.7.0}/phykit.egg-info/dependency_links.txt +0 -0
  156. {phykit-2.6.0 → phykit-2.7.0}/phykit.egg-info/requires.txt +0 -0
  157. {phykit-2.6.0 → phykit-2.7.0}/phykit.egg-info/top_level.txt +0 -0
  158. {phykit-2.6.0 → phykit-2.7.0}/setup.cfg +0 -0
  159. {phykit-2.6.0 → phykit-2.7.0}/setup.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: phykit
3
- Version: 2.6.0
3
+ Version: 2.7.0
4
4
  Home-page: https://github.com/jlsteenwyk/phykit
5
5
  Author: Jacob L. Steenwyk
6
6
  Author-email: jlsteenwyk@gmail.com
@@ -74,6 +74,8 @@ ALIAS_TO_HANDLER: dict[str, str] = {
74
74
  "pgwas": "phylo_gwas",
75
75
  "vs": "variable_sites",
76
76
  # Tree aliases
77
+ "topology_landscape": "topology_landscape",
78
+ "topomap": "topology_landscape",
77
79
  "bss": "bipartition_support_stats",
78
80
  "blm": "branch_length_multiplier",
79
81
  "collapse": "collapse_branches",
@@ -0,0 +1,175 @@
1
+ """Validated gene coordinates and nonoverlapping concordance neighborhoods."""
2
+
3
+ import csv
4
+ from collections import Counter, defaultdict
5
+ from pathlib import Path
6
+
7
+ from .topology_landscape import CLASSES, fail
8
+
9
+
10
+ def table_rows(path, required):
11
+ """Read a header-bearing TSV without silently accepting malformed rows."""
12
+ try:
13
+ with open(path, newline="", encoding="utf-8-sig") as handle:
14
+ rows = csv.DictReader(handle, delimiter="\t")
15
+ fields = rows.fieldnames or []
16
+ if len(set(fields)) != len(fields) or not set(required) <= set(fields):
17
+ fail(f"{path}: expected unique TSV columns including {', '.join(required)}.")
18
+ for number, row in enumerate(rows, 2):
19
+ if None in row or any(row.get(key) is None for key in required):
20
+ fail(f"{path}:{number}: malformed TSV row.")
21
+ if any(not row[key].strip() for key in required):
22
+ fail(f"{path}:{number}: required fields cannot be empty.")
23
+ yield number, row
24
+ except (OSError, UnicodeError, csv.Error) as exc:
25
+ fail(f"Cannot read {path}: {exc}")
26
+
27
+
28
+ def read_manifest(path):
29
+ genes = {}
30
+ tree_owners = {}
31
+ for number, row in table_rows(path, ("gene_id", "tree")):
32
+ gene = row["gene_id"]
33
+ tree = Path(row["tree"])
34
+ if not tree.is_absolute():
35
+ tree = Path(path).resolve().parent / tree
36
+ tree = tree.resolve()
37
+ if gene in genes:
38
+ fail(f"{path}:{number}: duplicate gene identifier {gene}.")
39
+ if tree in tree_owners:
40
+ fail(f"{path}:{number}: tree file is assigned to multiple genes: {tree}.")
41
+ if not tree.is_file():
42
+ fail(f"{path}:{number}: missing gene-tree file {tree}.")
43
+ genes[gene] = str(tree)
44
+ tree_owners[tree] = gene
45
+ if not genes:
46
+ fail("Gene-tree manifest contains no genes.")
47
+ return genes
48
+
49
+
50
+ def bed_rows(path):
51
+ try:
52
+ with open(path, encoding="utf-8-sig") as handle:
53
+ for number, line in enumerate(handle, 1):
54
+ if not line.strip() or line.startswith(("#", "track ", "browser ")):
55
+ continue
56
+ fields = line.rstrip("\r\n").split("\t")
57
+ if len(fields) < 4:
58
+ fail(f"{path}:{number}: BED requires at least four tab-separated columns.")
59
+ yield number, dict(zip(("chromosome", "start", "end", "gene_id"), fields))
60
+ except (OSError, UnicodeError) as exc:
61
+ fail(f"Cannot read {path}: {exc}")
62
+
63
+
64
+ def read_coordinates(sources):
65
+ """Merge repeated same-chromosome records to one gene span per reference."""
66
+ coordinates = {}
67
+ duplicates = Counter()
68
+ references = []
69
+ for reference, fmt, path in sources:
70
+ if not reference.strip():
71
+ fail("Reference genome identifiers cannot be empty.")
72
+ if reference not in references:
73
+ references.append(reference)
74
+ if fmt not in ("bed", "tsv"):
75
+ fail("Coordinate format must be bed or tsv.")
76
+ rows = bed_rows(path) if fmt == "bed" else table_rows(
77
+ path, ("gene_id", "chromosome", "start", "end")
78
+ )
79
+ for number, row in rows:
80
+ gene, chromosome = row["gene_id"], row["chromosome"]
81
+ if not gene.strip() or gene == "." or not chromosome.strip():
82
+ fail(f"{path}:{number}: gene and chromosome identifiers are required.")
83
+ try:
84
+ start, end = int(row["start"]), int(row["end"])
85
+ except ValueError:
86
+ fail(f"{path}:{number}: coordinates must be integers.")
87
+ if start < 0 or end <= start:
88
+ fail(f"{path}:{number}: require 0 <= start < end (half-open coordinates).")
89
+ key = (reference, gene)
90
+ if key in coordinates:
91
+ previous = coordinates[key]
92
+ if chromosome != previous["chromosome"]:
93
+ fail(f"Ambiguous mapping: {gene} occurs on multiple chromosomes in {reference}.")
94
+ start, end = min(start, previous["start"]), max(end, previous["end"])
95
+ duplicates[reference] += 1
96
+ coordinates[key] = {
97
+ "reference": reference, "gene_id": gene, "chromosome": chromosome,
98
+ "start": start, "end": end, "anchor": (start + end - 1) // 2,
99
+ }
100
+ if not coordinates:
101
+ fail("Coordinate files contain no gene records.")
102
+ return list(coordinates.values()), {
103
+ "references": references, "merged_records": dict(duplicates),
104
+ }
105
+
106
+
107
+ def summarize(rows):
108
+ """Each reference/gene contributes once; fractions are among resolved genes."""
109
+ unique = {}
110
+ for row in rows:
111
+ unique[(row["reference"], row["gene_id"])] = row["classification"]
112
+ counts = Counter(unique.values())
113
+ total = len(unique)
114
+ informative = sum(counts[c] for c in CLASSES[:3])
115
+ result = {"total_genes": total, "informative_genes": informative}
116
+ for category in CLASSES:
117
+ result[category] = counts[category]
118
+ for category in CLASSES[:3]:
119
+ result[f"{category}_proportion"] = counts[category] / informative if informative else None
120
+ return result
121
+
122
+
123
+ def select_rows(rows, chromosomes=None, interval=None):
124
+ if interval is not None:
125
+ start, end = interval
126
+ if start < 0 or end <= start:
127
+ fail("Interval requires 0 <= start < end.")
128
+ selected = [row for row in rows if (
129
+ (not chromosomes or row["chromosome"] in chromosomes)
130
+ and (interval is None or interval[0] <= row["anchor"] < interval[1])
131
+ )]
132
+ return sorted(selected, key=lambda r: (
133
+ r["reference"], r["chromosome"], r["anchor"], r["gene_id"],
134
+ ))
135
+
136
+
137
+ def neighborhoods(rows, window_bp=None, window_genes=None, interval=None):
138
+ """Assign a gene by its span midpoint, once in each nonoverlapping partition.
139
+
140
+ Physical windows start at zero, or at the selected interval's start.
141
+ Without chromosome lengths they stop at the last observed gene end.
142
+ Gene-count windows are rank bins; equal anchors can straddle bins.
143
+ """
144
+ if (window_bp is None) == (window_genes is None):
145
+ fail("Specify exactly one of physical-distance or gene-count windows.")
146
+ size = window_bp if window_bp is not None else window_genes
147
+ if size <= 0:
148
+ fail("Window size must be positive.")
149
+ by_chromosome = defaultdict(list)
150
+ for row in select_rows(rows, interval=interval):
151
+ by_chromosome[(row["reference"], row["chromosome"])].append(row)
152
+ output = []
153
+ for (reference, chromosome), genes in sorted(by_chromosome.items()):
154
+ if window_bp is not None:
155
+ start = interval[0] if interval else 0
156
+ stop = interval[1] if interval else max(g["end"] for g in genes)
157
+ n_windows = (stop - start + size - 1) // size
158
+ if n_windows > 1_000_000:
159
+ fail("More than one million windows on a chromosome; increase --window-bp.")
160
+ bins = defaultdict(list)
161
+ for gene in genes:
162
+ bins[(gene["anchor"] - start) // size].append(gene)
163
+ windows = ((start + i * size, min(start + (i + 1) * size, stop), bins[i])
164
+ for i in range(n_windows))
165
+ else:
166
+ chunks = (genes[i:i + size] for i in range(0, len(genes), size))
167
+ windows = ((chunk[0]["anchor"], chunk[-1]["anchor"] + 1, chunk)
168
+ for chunk in chunks)
169
+ for index, (window_start, window_end, members) in enumerate(windows, 1):
170
+ output.append(dict(
171
+ reference=reference, chromosome=chromosome, window_index=index,
172
+ start=window_start, end=window_end, window_mode="bp" if window_bp else "genes",
173
+ **summarize(members),
174
+ ))
175
+ return output
@@ -0,0 +1,190 @@
1
+ """Strict, unrooted four-group classification for genomic concordance maps."""
2
+
3
+ import math
4
+ from collections import defaultdict
5
+
6
+ from Bio import Phylo
7
+ from Bio.Phylo.NewickIO import NewickError
8
+
9
+ from ..errors import PhykitUserError
10
+ from .quartet_utils import _collect_clade_tip_sets, canonical_split
11
+
12
+ CLASSES = (
13
+ "topology_1", "topology_2", "topology_3", "unresolved",
14
+ "insufficient_sampling", "incompatible_groups",
15
+ )
16
+
17
+
18
+ def fail(message):
19
+ raise PhykitUserError([message], code=2)
20
+
21
+
22
+ def validate_groups(groups):
23
+ if len(groups) != 4 or any(not taxa for taxa in groups.values()):
24
+ fail("Exactly four named, nonempty taxon groups are required.")
25
+ seen = set()
26
+ for name, taxa in groups.items():
27
+ if not isinstance(name, str) or not name.strip():
28
+ fail("Group names must be nonempty strings.")
29
+ if not isinstance(taxa, (list, tuple, set, frozenset)):
30
+ fail(f"Group {name} must contain a list of taxon names.")
31
+ if any(not isinstance(t, str) or not t.strip() for t in taxa):
32
+ fail(f"Group {name} contains an invalid taxon name.")
33
+ if len(set(taxa)) != len(taxa) or seen.intersection(taxa):
34
+ fail(f"Taxa must be unique and groups disjoint: {name}.")
35
+ seen.update(taxa)
36
+ return {name: frozenset(taxa) for name, taxa in groups.items()}
37
+
38
+
39
+ def read_tree(path):
40
+ try:
41
+ tree = Phylo.read(path, "newick")
42
+ except (OSError, ValueError, IndexError, NewickError) as exc:
43
+ fail(f"Cannot read exactly one Newick tree from {path}: {exc}")
44
+ names = [tip.name for tip in tree.get_terminals()]
45
+ if any(not name for name in names) or len(set(names)) != len(names):
46
+ fail(f"Tree {path} must have unique, nonempty tip names.")
47
+ return tree
48
+
49
+
50
+ def classify_tree(tree, groups, min_support=None, support_scale=100,
51
+ missing_support="collapse"):
52
+ """Require each sampled group to form an unrooted clan, then resolve it.
53
+
54
+ Repeated representations of an induced edge (degree-two roots or paths
55
+ through excluded taxa) use the minimum available numeric support. When
56
+ filtering, any absent label on that path follows missing_support.
57
+ Branch lengths never enter classification.
58
+ """
59
+ groups = validate_groups(groups)
60
+ if support_scale not in (1, 100):
61
+ fail("Support scale must be 1 or 100.")
62
+ if min_support is not None and (
63
+ not math.isfinite(min_support) or not 0 <= min_support <= support_scale
64
+ ):
65
+ fail("Minimum support must be finite and within the selected scale.")
66
+ if missing_support not in ("collapse", "keep", "error"):
67
+ fail("Missing-support policy must be collapse, keep, or error.")
68
+ names = [tip.name for tip in tree.get_terminals()]
69
+ if any(not name for name in names) or len(set(names)) != len(names):
70
+ fail("Gene trees must have unique, nonempty tip names.")
71
+ wanted = frozenset().union(*groups.values())
72
+ sampled = [taxa.intersection(names) for taxa in groups.values()]
73
+ counts = dict(zip(groups, map(len, sampled)))
74
+ result = {
75
+ "classification": "insufficient_sampling", "sampled_counts": counts,
76
+ "sampling_status": "complete" if all(sampled) else "missing_groups",
77
+ "ignored_taxa": sorted(set(names) - wanted), "resolution_support": None,
78
+ "resolution_support_missing": False,
79
+ }
80
+ if not all(sampled):
81
+ return result
82
+ all_taxa = frozenset().union(*sampled)
83
+ clade_tips = _collect_clade_tip_sets(tree, all_taxa)
84
+ evidence = defaultdict(list)
85
+ for clade in tree.find_clades():
86
+ if clade is tree.root or clade.is_terminal():
87
+ continue
88
+ side = clade_tips[id(clade)]
89
+ if not side or side == all_taxa:
90
+ continue
91
+ value = clade.confidence
92
+ if value is not None and (
93
+ not math.isfinite(value) or not 0 <= value <= support_scale
94
+ ):
95
+ fail(f"Support {value} is outside the selected 0-{support_scale} scale.")
96
+ evidence[canonical_split(side, all_taxa)].append(value)
97
+ retained = {}
98
+ for split, values in evidence.items():
99
+ known = [v for v in values if v is not None]
100
+ support = min(known) if known else None
101
+ absent = len(known) != len(values)
102
+ if min_support is not None:
103
+ if absent and missing_support == "error":
104
+ fail("Missing branch support encountered with --missing-support error.")
105
+ if absent and missing_support == "collapse":
106
+ continue
107
+ if support is not None and support < min_support:
108
+ continue
109
+ retained[split] = (support, absent)
110
+
111
+ # Missing a clan-defining edge may mean a polytomy, not contradictory data.
112
+ uncertain_group = False
113
+ for group in sampled:
114
+ if len(group) == 1 or canonical_split(group, all_taxa) in retained:
115
+ continue
116
+ outside = all_taxa - group
117
+ for split in retained:
118
+ left, right = tuple(split)
119
+ if left & group and right & group and left & outside and right & outside:
120
+ result["classification"] = "incompatible_groups"
121
+ return result
122
+ uncertain_group = True
123
+ result["classification"] = "unresolved"
124
+ if uncertain_group:
125
+ return result
126
+ for index, partner in enumerate((1, 2, 3), 1):
127
+ split = canonical_split(sampled[0] | sampled[partner], all_taxa)
128
+ if split in retained:
129
+ result["classification"] = f"topology_{index}"
130
+ result["resolution_support"], result["resolution_support_missing"] = retained[split]
131
+ break
132
+ return result
133
+
134
+
135
+ def groups_from_branch(tree, branch_taxa):
136
+ """Derive four groups around an edge identified by either complete side.
137
+
138
+ Suppress artificial degree-two vertices so selection is root invariant.
139
+ Group A/B lie on the selected side, C/D on its complement; components
140
+ within a side are sorted lexicographically by their complete tip lists.
141
+ """
142
+ graph = defaultdict(set)
143
+ terminals = {c: c.name for c in tree.get_terminals()}
144
+ if len(set(terminals.values())) != len(terminals) or any(
145
+ not name for name in terminals.values()
146
+ ):
147
+ fail("Reference tips must have unique, nonempty names.")
148
+ for clade in tree.find_clades():
149
+ for child in clade.clades:
150
+ graph[clade].add(child)
151
+ graph[child].add(clade)
152
+ for node in list(graph):
153
+ if node in terminals:
154
+ continue
155
+ neighbors = graph[node]
156
+ if len(neighbors) == 1:
157
+ neighbor = next(iter(neighbors))
158
+ graph[neighbor].remove(node)
159
+ del graph[node]
160
+ elif len(neighbors) == 2:
161
+ left, right = neighbors
162
+ graph[left].remove(node)
163
+ graph[right].remove(node)
164
+ graph[left].add(right)
165
+ graph[right].add(left)
166
+ del graph[node]
167
+
168
+ def component(start, blocked):
169
+ found = set()
170
+ stack = [(start, blocked)]
171
+ while stack:
172
+ node, parent = stack.pop()
173
+ if node in terminals:
174
+ found.add(terminals[node])
175
+ stack.extend((n, node) for n in graph[node] if n is not parent)
176
+ return frozenset(found)
177
+
178
+ target = frozenset(branch_taxa)
179
+ for left, neighbors in graph.items():
180
+ for right in neighbors:
181
+ if component(left, right) != target:
182
+ continue
183
+ if len(neighbors) != 3 or len(graph[right]) != 3:
184
+ fail("Selected branch must have two degree-three internal endpoints.")
185
+ sides = []
186
+ for node, other in ((left, right), (right, left)):
187
+ parts = [component(n, node) for n in graph[node] if n is not other]
188
+ sides.extend(sorted(parts, key=lambda x: tuple(sorted(x))))
189
+ return validate_groups(dict(zip(("A", "B", "C", "D"), sides)))
190
+ fail("Branch taxa do not identify a complete side of a reference-tree edge.")
@@ -716,6 +716,8 @@ class Phykit:
716
716
  quartet_network (alias: quartet_net; qnet; nanuq)
717
717
  - quartet-based network inference (NANUQ-style)
718
718
  distinguishing ILS from hybridization
719
+ topology_landscape (alias: topomap)
720
+ map focal gene-tree concordance across reference genomes
719
721
  quartet_pie (alias: qpie; quartet_pie_chart)
720
722
  - phylogram with quartet concordance pie charts
721
723
  at internal nodes
@@ -7617,6 +7619,76 @@ class Phykit:
7617
7619
  _add_json_argument(parser)
7618
7620
  _run_service(parser, argv, NeighborNet)
7619
7621
 
7622
+ @staticmethod
7623
+ def topology_landscape(argv):
7624
+ parser = _new_parser(description=_dedent(f"""\
7625
+ {help_header}
7626
+
7627
+ Map gene-tree support for three focal quartet resolutions to genomic
7628
+ coordinates. Strict mode uses all sampled representatives and requires
7629
+ each group to form an unrooted clan. Polytomies, insufficient sampling,
7630
+ and incompatible groups remain separate; this is concordance mapping,
7631
+ not a likelihood test, confidence estimate, or introgression test.
7632
+
7633
+ Manifest: header-bearing TSV with gene_id and tree columns; relative
7634
+ tree paths are resolved beside the manifest. Coordinates: BED4+ or TSV
7635
+ with gene_id, chromosome, start, end; both are 0-based half-open.
7636
+ Repeated same-reference gene records merge to one span. Its midpoint
7637
+ assigns the gene once to a nonoverlapping neighborhood. Chromosomes
7638
+ are sorted lexicographically; reference genomes are kept separate.
7639
+
7640
+ Groups: JSON object mapping exactly four names to disjoint taxon lists.
7641
+ Group order defines AB|CD, AC|BD, AD|BC. --outgroup moves that group
7642
+ first and labels alternatives by its partner (the sister hypothesis).
7643
+ Alternatively select an internal edge by the full taxon list on one
7644
+ side using --reference-tree and --branch-taxa.
7645
+
7646
+ Related method: Martin and Van Belleghem (2017), Twisst, Genetics,
7647
+ doi:10.1534/genetics.116.194720. This command counts strictly classified
7648
+ genes; it does not implement Twisst's fractional subtree weighting.
7649
+
7650
+ Outputs: PREFIX.genes.tsv, PREFIX.neighborhoods.tsv,
7651
+ PREFIX.overall.tsv, PREFIX.diagnostics.json; optional plots and JSON.
7652
+ Fractions use resolved genes as denominator; empty fractions are null.
7653
+ Aliases: topology_landscape, topomap; pk_topology_landscape, pk_topomap.
7654
+ """))
7655
+ parser.add_argument("--manifest", required=True, help="Gene-ID / Newick-path TSV")
7656
+ parser.add_argument("--coordinates", nargs=3, action="append", required=True,
7657
+ metavar=("REFERENCE", "FORMAT", "PATH"), help="Repeat for BED or TSV files (bed|tsv)")
7658
+ focal = parser.add_mutually_exclusive_group(required=True)
7659
+ focal.add_argument("--groups", help="Four-group JSON file")
7660
+ focal.add_argument("--reference-tree", help="Reference Newick tree")
7661
+ parser.add_argument("--branch-taxa", nargs="+", help="Complete taxon set on one side of the selected edge")
7662
+ parser.add_argument("--outgroup", help="Name of the outgroup in the four-group definition")
7663
+ parser.add_argument("--labels", nargs=3, help="Display labels for topology_1, topology_2, topology_3")
7664
+ parser.add_argument("--min-support", type=float, help="Collapse edges below this threshold")
7665
+ parser.add_argument("--support-scale", type=int, choices=(1, 100), default=100,
7666
+ help="Explicit numeric support scale (default: 100)")
7667
+ parser.add_argument("--missing-support", choices=("collapse", "keep", "error"), default="collapse",
7668
+ help="Absent support policy when --min-support is set; repeated edge labels use minimum support")
7669
+ parser.add_argument("--unmapped", choices=("error", "skip"), default="error",
7670
+ help="Policy for manifest genes absent from all coordinate files")
7671
+ window = parser.add_mutually_exclusive_group()
7672
+ window.add_argument("--window-bp", type=int, default=1000000, help="Physical window length (default: 1000000)")
7673
+ window.add_argument("--window-genes", type=int, help="Genes per rank window, including unresolved genes")
7674
+ parser.add_argument("--chromosome", action="append", help="Chromosome to retain (repeatable)")
7675
+ parser.add_argument("--interval", nargs=2, type=int, metavar=("START", "END"),
7676
+ help="Half-open midpoint range, applied to each selected chromosome")
7677
+ parser.add_argument("--output-prefix", "-o", required=True, help="Output file prefix; parent directory must exist")
7678
+ parser.add_argument("--plot", action="store_true", help="Plot gene tracks, proportions, and gene counts")
7679
+ parser.add_argument("--plot-output", help="Plot path; multiple panels receive numbered filenames")
7680
+ parser.add_argument("--fig-width", type=float, help="Plot width in inches")
7681
+ parser.add_argument("--fig-height", type=float, help="Plot height in inches")
7682
+ parser.add_argument("--dpi", type=int, default=300, help="Plot resolution")
7683
+ parser.add_argument("--title", help="Custom plot title")
7684
+ parser.add_argument("--no-title", action="store_true", help="Hide plot title")
7685
+ parser.add_argument("--legend-position", help="Matplotlib legend position, or none")
7686
+ parser.add_argument("--colors", help="Comma-separated colors in classification order")
7687
+ for name in ("xlabel", "ylabel", "axis", "title"):
7688
+ parser.add_argument(f"--{name}-fontsize", type=float, help=f"{name} font size")
7689
+ _add_json_argument(parser)
7690
+ _run_service(parser, argv, TopologyLandscape)
7691
+
7620
7692
  @staticmethod
7621
7693
  def quartet_pie(argv):
7622
7694
  parser = _new_parser(
@@ -10843,6 +10915,10 @@ def quartet_network(argv=None):
10843
10915
  Phykit.quartet_network(sys.argv[1:])
10844
10916
 
10845
10917
 
10918
+ def topology_landscape(argv=None):
10919
+ Phykit.topology_landscape(sys.argv[1:] if argv is None else argv)
10920
+
10921
+
10846
10922
  def quartet_pie(argv=None):
10847
10923
  Phykit.quartet_pie(sys.argv[1:])
10848
10924
 
@@ -106,6 +106,7 @@ CharacterMap = _LazyServiceFactory("phykit.services.tree.character_map", "Charac
106
106
  PhyloHeatmap = _LazyServiceFactory("phykit.services.tree.phylo_heatmap", "PhyloHeatmap")
107
107
  PruneTree = _LazyServiceFactory("phykit.services.tree.prune_tree", "PruneTree")
108
108
  QuartetPie = _LazyServiceFactory("phykit.services.tree.quartet_pie", "QuartetPie")
109
+ TopologyLandscape = _LazyServiceFactory("phykit.services.tree.topology_landscape", "TopologyLandscape")
109
110
  RenameTreeTips = _LazyServiceFactory("phykit.services.tree.rename_tree_tips", "RenameTreeTips")
110
111
  FitDiscrete = _LazyServiceFactory("phykit.services.tree.fit_discrete", "FitDiscrete")
111
112
  IndependentContrasts = _LazyServiceFactory("phykit.services.tree.independent_contrasts", "IndependentContrasts")