phykit 2.7.0__tar.gz → 2.9.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 (164) hide show
  1. {phykit-2.7.0 → phykit-2.9.0}/PKG-INFO +9 -4
  2. {phykit-2.7.0 → phykit-2.9.0}/README.md +5 -0
  3. {phykit-2.7.0 → phykit-2.9.0}/phykit/cli_registry.py +2 -0
  4. phykit-2.9.0/phykit/helpers/boolean_argument_parsing.py +17 -0
  5. phykit-2.9.0/phykit/helpers/threads.py +110 -0
  6. phykit-2.9.0/phykit/helpers/topology_autocorrelation.py +310 -0
  7. {phykit-2.7.0 → phykit-2.9.0}/phykit/helpers/trait_parsing.py +92 -3
  8. {phykit-2.7.0 → phykit-2.9.0}/phykit/phykit.py +215 -119
  9. {phykit-2.7.0 → phykit-2.9.0}/phykit/service_factories.py +1 -0
  10. phykit-2.9.0/phykit/services/alignment/_file_list.py +98 -0
  11. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/alignment/create_concatenation_matrix.py +3 -2
  12. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/alignment/occupancy_filter.py +4 -90
  13. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/alignment/pairwise_identity.py +2 -1
  14. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/alignment/sum_of_pairs_score.py +2 -1
  15. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/alignment/taxon_groups.py +4 -90
  16. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/cont_map.py +2 -81
  17. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/covarying_evolutionary_rates.py +2 -1
  18. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/fit_continuous.py +2 -81
  19. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/hidden_paralogy_check.py +2 -1
  20. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/lb_score.py +3 -2
  21. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/network_signal.py +2 -81
  22. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/ou_shift_detection.py +2 -81
  23. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/ouwie.py +2 -81
  24. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/patristic_distances.py +3 -2
  25. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/phenogram.py +2 -81
  26. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/phylogenetic_signal.py +2 -81
  27. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/polytomy_test.py +2 -1
  28. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/rate_heterogeneity.py +2 -81
  29. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/rf_distance.py +2 -1
  30. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/saturation.py +2 -1
  31. phykit-2.9.0/phykit/services/tree/topology_autocorrelation.py +224 -0
  32. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/topology_landscape.py +21 -14
  33. phykit-2.9.0/phykit/version.py +1 -0
  34. {phykit-2.7.0 → phykit-2.9.0}/phykit.egg-info/PKG-INFO +9 -4
  35. {phykit-2.7.0 → phykit-2.9.0}/phykit.egg-info/SOURCES.txt +4 -1
  36. {phykit-2.7.0 → phykit-2.9.0}/phykit.egg-info/entry_points.txt +2 -0
  37. {phykit-2.7.0 → phykit-2.9.0}/setup.py +3 -3
  38. phykit-2.7.0/phykit/helpers/boolean_argument_parsing.py +0 -12
  39. phykit-2.7.0/phykit/helpers/parallel.py +0 -412
  40. phykit-2.7.0/phykit/version.py +0 -1
  41. {phykit-2.7.0 → phykit-2.9.0}/LICENSE.md +0 -0
  42. {phykit-2.7.0 → phykit-2.9.0}/phykit/__init__.py +0 -0
  43. {phykit-2.7.0 → phykit-2.9.0}/phykit/__main__.py +0 -0
  44. {phykit-2.7.0 → phykit-2.9.0}/phykit/errors.py +0 -0
  45. {phykit-2.7.0 → phykit-2.9.0}/phykit/helpers/__init__.py +0 -0
  46. {phykit-2.7.0 → phykit-2.9.0}/phykit/helpers/caching.py +0 -0
  47. {phykit-2.7.0 → phykit-2.9.0}/phykit/helpers/circular_layout.py +0 -0
  48. {phykit-2.7.0 → phykit-2.9.0}/phykit/helpers/color_annotations.py +0 -0
  49. {phykit-2.7.0 → phykit-2.9.0}/phykit/helpers/discrete_models.py +0 -0
  50. {phykit-2.7.0 → phykit-2.9.0}/phykit/helpers/files.py +0 -0
  51. {phykit-2.7.0 → phykit-2.9.0}/phykit/helpers/genomic_coordinates.py +0 -0
  52. {phykit-2.7.0 → phykit-2.9.0}/phykit/helpers/geological_timescale.py +0 -0
  53. {phykit-2.7.0 → phykit-2.9.0}/phykit/helpers/json_output.py +0 -0
  54. {phykit-2.7.0 → phykit-2.9.0}/phykit/helpers/parsimony_utils.py +0 -0
  55. {phykit-2.7.0 → phykit-2.9.0}/phykit/helpers/pgls_utils.py +0 -0
  56. {phykit-2.7.0 → phykit-2.9.0}/phykit/helpers/plot_config.py +0 -0
  57. {phykit-2.7.0 → phykit-2.9.0}/phykit/helpers/quartet_utils.py +0 -0
  58. {phykit-2.7.0 → phykit-2.9.0}/phykit/helpers/stats_summary.py +0 -0
  59. {phykit-2.7.0 → phykit-2.9.0}/phykit/helpers/streaming.py +0 -0
  60. {phykit-2.7.0 → phykit-2.9.0}/phykit/helpers/topology_landscape.py +0 -0
  61. {phykit-2.7.0 → phykit-2.9.0}/phykit/helpers/tree_paths.py +0 -0
  62. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/__init__.py +0 -0
  63. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/alignment/__init__.py +0 -0
  64. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/alignment/_fasta.py +0 -0
  65. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/alignment/alignment_entropy.py +0 -0
  66. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/alignment/alignment_length.py +0 -0
  67. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/alignment/alignment_length_no_gaps.py +0 -0
  68. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/alignment/alignment_outlier_regions.py +0 -0
  69. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/alignment/alignment_outlier_taxa.py +0 -0
  70. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/alignment/alignment_recoding.py +0 -0
  71. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/alignment/alignment_subsample.py +0 -0
  72. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/alignment/base.py +0 -0
  73. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/alignment/codon_dnds.py +0 -0
  74. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/alignment/column_score.py +0 -0
  75. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/alignment/composition_per_taxon.py +0 -0
  76. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/alignment/compositional_bias_per_site.py +0 -0
  77. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/alignment/dfoil.py +0 -0
  78. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/alignment/dna_threader.py +0 -0
  79. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/alignment/dstatistic.py +0 -0
  80. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/alignment/evolutionary_rate_per_site.py +0 -0
  81. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/alignment/faidx.py +0 -0
  82. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/alignment/gc_content.py +0 -0
  83. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/alignment/identity_matrix.py +0 -0
  84. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/alignment/mask_alignment.py +0 -0
  85. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/alignment/occupancy_per_taxon.py +0 -0
  86. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/alignment/parsimony_informative_sites.py +0 -0
  87. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/alignment/phylo_gwas.py +0 -0
  88. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/alignment/plot_alignment_qc.py +0 -0
  89. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/alignment/rcv.py +0 -0
  90. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/alignment/rcvt.py +0 -0
  91. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/alignment/rename_fasta_entries.py +0 -0
  92. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/alignment/variable_sites.py +0 -0
  93. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/base.py +0 -0
  94. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/__init__.py +0 -0
  95. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/ancestral_reconstruction.py +0 -0
  96. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/base.py +0 -0
  97. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/bipartition_support_stats.py +0 -0
  98. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/branch_length_multiplier.py +0 -0
  99. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/character_map.py +0 -0
  100. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/chronogram.py +0 -0
  101. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/collapse_branches.py +0 -0
  102. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/concordance_asr.py +0 -0
  103. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/consensus_network.py +0 -0
  104. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/consensus_tree.py +0 -0
  105. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/cophylo.py +0 -0
  106. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/density_map.py +0 -0
  107. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/discordance_asymmetry.py +0 -0
  108. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/dtt.py +0 -0
  109. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/dvmc.py +0 -0
  110. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/episodic_rate_covariation.py +0 -0
  111. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/evo_tempo_map.py +0 -0
  112. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/evolutionary_rate.py +0 -0
  113. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/faiths_pd.py +0 -0
  114. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/fit_discrete.py +0 -0
  115. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/hybridization.py +0 -0
  116. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/independent_contrasts.py +0 -0
  117. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/internal_branch_stats.py +0 -0
  118. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/internode_labeler.py +0 -0
  119. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/kf_distance.py +0 -0
  120. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/last_common_ancestor_subtree.py +0 -0
  121. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/ltt.py +0 -0
  122. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/monophyly_check.py +0 -0
  123. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/nearest_neighbor_interchange.py +0 -0
  124. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/neighbor_net.py +0 -0
  125. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/parsimony_score.py +0 -0
  126. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/phylo_anova.py +0 -0
  127. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/phylo_heatmap.py +0 -0
  128. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/phylo_impute.py +0 -0
  129. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/phylo_logistic.py +0 -0
  130. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/phylo_path.py +0 -0
  131. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/phylogenetic_glm.py +0 -0
  132. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/phylogenetic_ordination.py +0 -0
  133. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/phylogenetic_regression.py +0 -0
  134. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/phylomorphospace.py +0 -0
  135. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/print_tree.py +0 -0
  136. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/projected_covarying_rates.py +0 -0
  137. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/prune_tree.py +0 -0
  138. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/quartet_network.py +0 -0
  139. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/quartet_pie.py +0 -0
  140. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/relative_rate_test.py +0 -0
  141. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/rename_tree_tips.py +0 -0
  142. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/root_tree.py +0 -0
  143. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/simmap_summary.py +0 -0
  144. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/spectral_discordance.py +0 -0
  145. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/spr.py +0 -0
  146. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/spurious_sequence.py +0 -0
  147. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/stochastic_character_map.py +0 -0
  148. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/terminal_branch_stats.py +0 -0
  149. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/threshold_model.py +0 -0
  150. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/tip_labels.py +0 -0
  151. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/tip_to_tip_distance.py +0 -0
  152. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/tip_to_tip_node_distance.py +0 -0
  153. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/total_tree_length.py +0 -0
  154. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/trait_correlation.py +0 -0
  155. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/trait_rate_map.py +0 -0
  156. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/transfer_annotations.py +0 -0
  157. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/tree_space.py +0 -0
  158. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/treeness.py +0 -0
  159. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/treeness_over_rcv.py +0 -0
  160. {phykit-2.7.0 → phykit-2.9.0}/phykit/services/tree/vcv_utils.py +0 -0
  161. {phykit-2.7.0 → phykit-2.9.0}/phykit.egg-info/dependency_links.txt +0 -0
  162. {phykit-2.7.0 → phykit-2.9.0}/phykit.egg-info/requires.txt +0 -0
  163. {phykit-2.7.0 → phykit-2.9.0}/phykit.egg-info/top_level.txt +0 -0
  164. {phykit-2.7.0 → phykit-2.9.0}/setup.cfg +0 -0
@@ -1,18 +1,18 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: phykit
3
- Version: 2.7.0
3
+ Version: 2.9.0
4
4
  Home-page: https://github.com/jlsteenwyk/phykit
5
5
  Author: Jacob L. Steenwyk
6
6
  Author-email: jlsteenwyk@gmail.com
7
7
  Classifier: Operating System :: OS Independent
8
8
  Classifier: Intended Audience :: Science/Research
9
9
  Classifier: Programming Language :: Python
10
- Classifier: Programming Language :: Python :: 3.10
11
- Classifier: Programming Language :: Python :: 3.11
12
10
  Classifier: Programming Language :: Python :: 3.12
13
11
  Classifier: Programming Language :: Python :: 3.13
12
+ Classifier: Programming Language :: Python :: 3.14
13
+ Classifier: Programming Language :: Python :: 3.15
14
14
  Classifier: Topic :: Scientific/Engineering
15
- Requires-Python: >=3.10
15
+ Requires-Python: >=3.12
16
16
  Description-Content-Type: text/markdown
17
17
  License-File: LICENSE.md
18
18
  Requires-Dist: biopython>=1.82
@@ -152,3 +152,8 @@ To test phykit installation, launch the help message
152
152
  ```shell
153
153
  phykit -h
154
154
  ```
155
+
156
+ ## Release Maintenance
157
+
158
+ See the [Bioconda automation guide](scripts/bioconda/README.md) for release-triggered
159
+ recipe synchronization, credential setup, dry runs, and failure recovery.
@@ -118,3 +118,8 @@ To test phykit installation, launch the help message
118
118
  ```shell
119
119
  phykit -h
120
120
  ```
121
+
122
+ ## Release Maintenance
123
+
124
+ See the [Bioconda automation guide](scripts/bioconda/README.md) for release-triggered
125
+ recipe synchronization, credential setup, dry runs, and failure recovery.
@@ -76,6 +76,8 @@ ALIAS_TO_HANDLER: dict[str, str] = {
76
76
  # Tree aliases
77
77
  "topology_landscape": "topology_landscape",
78
78
  "topomap": "topology_landscape",
79
+ "topology_autocorrelation": "topology_autocorrelation",
80
+ "topo_ac": "topology_autocorrelation",
79
81
  "bss": "bipartition_support_stats",
80
82
  "blm": "branch_length_multiplier",
81
83
  "collapse": "collapse_branches",
@@ -0,0 +1,17 @@
1
+ def str2bool(v):
2
+ """Parse case-insensitive boolean strings, passing bool objects through.
3
+
4
+ Accept true/t/1/yes/y as True and false/f/0/no/n as False.
5
+ Invalid strings raise argparse.ArgumentTypeError.
6
+ """
7
+ if isinstance(v, bool):
8
+ return v
9
+ value = v.lower()
10
+ if value in ("true", "t", "1", "yes", "y"):
11
+ return True
12
+ elif value in ("false", "f", "0", "no", "n"):
13
+ return False
14
+ else:
15
+ import argparse
16
+
17
+ raise argparse.ArgumentTypeError("Boolean value expected.")
@@ -0,0 +1,110 @@
1
+ """
2
+ Global thread limit shared by every PhyKIT command.
3
+
4
+ The limit comes from the ``--threads`` option (accepted by every command) or
5
+ the ``PHYKIT_THREADS`` environment variable. It caps the number of worker
6
+ processes PhyKIT starts and the number of threads used by numeric libraries
7
+ (BLAS/OpenMP via NumPy, SciPy, scikit-learn, numba). Those libraries read
8
+ their environment variables when first imported, which in PhyKIT always
9
+ happens after argument parsing because services are loaded lazily.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import os
15
+
16
+ from ..errors import PhykitUserError
17
+
18
+
19
+ PHYKIT_THREADS_ENV = "PHYKIT_THREADS"
20
+ THREAD_ENV_VARS = (
21
+ "OMP_NUM_THREADS",
22
+ "OPENBLAS_NUM_THREADS",
23
+ "MKL_NUM_THREADS",
24
+ "VECLIB_MAXIMUM_THREADS",
25
+ "NUMEXPR_NUM_THREADS",
26
+ "NUMBA_NUM_THREADS",
27
+ )
28
+ _OPTION = "--threads"
29
+
30
+
31
+ def _parse_positive_int(value: str | None) -> int | None:
32
+ try:
33
+ parsed = int(value)
34
+ except (TypeError, ValueError):
35
+ return None
36
+ return parsed if parsed >= 1 else None
37
+
38
+
39
+ def _invalid_value_error(value: str | None) -> PhykitUserError:
40
+ shown = "nothing" if value is None else repr(value)
41
+ return PhykitUserError(
42
+ [f"{_OPTION} requires a positive integer, got {shown}"], code=2
43
+ )
44
+
45
+
46
+ def extract_threads_option(argv: list[str]) -> tuple[int | None, list[str]]:
47
+ """Remove ``--threads N`` / ``--threads=N`` from argv.
48
+
49
+ Returns the requested thread count (last occurrence wins) and the
50
+ remaining arguments.
51
+ """
52
+ value = None
53
+ rest = []
54
+ i = 0
55
+ while i < len(argv):
56
+ arg = argv[i]
57
+ if arg == _OPTION:
58
+ raw = argv[i + 1] if i + 1 < len(argv) else None
59
+ i += 2
60
+ elif arg.startswith(_OPTION + "="):
61
+ raw = arg[len(_OPTION) + 1:]
62
+ i += 1
63
+ else:
64
+ rest.append(arg)
65
+ i += 1
66
+ continue
67
+ value = _parse_positive_int(raw)
68
+ if value is None:
69
+ raise _invalid_value_error(raw)
70
+ return value, rest
71
+
72
+
73
+ def apply_thread_limit(n: int, override: bool = True) -> None:
74
+ """Export the thread limit so PhyKIT, numeric libraries, and worker
75
+ processes all see it."""
76
+ os.environ[PHYKIT_THREADS_ENV] = str(n)
77
+ for name in THREAD_ENV_VARS:
78
+ if override:
79
+ os.environ[name] = str(n)
80
+ else:
81
+ os.environ.setdefault(name, str(n))
82
+
83
+
84
+ def thread_limit() -> int | None:
85
+ """Return the active thread limit, or None when unlimited."""
86
+ return _parse_positive_int(os.environ.get(PHYKIT_THREADS_ENV))
87
+
88
+
89
+ def limit_workers(n: int) -> int:
90
+ """Cap a worker count at the active thread limit (never below 1)."""
91
+ limit = thread_limit()
92
+ if limit is not None:
93
+ n = min(n, limit)
94
+ return max(1, n)
95
+
96
+
97
+ def configure_threads(argv: list[str]) -> list[str]:
98
+ """Apply ``--threads`` (or ``PHYKIT_THREADS``) and return argv without it.
99
+
100
+ An explicit ``--threads`` overrides any numeric-library variables already
101
+ set; ``PHYKIT_THREADS`` alone only fills in the ones that are unset.
102
+ """
103
+ value, rest = extract_threads_option(argv)
104
+ if value is not None:
105
+ apply_thread_limit(value)
106
+ else:
107
+ env_value = thread_limit()
108
+ if env_value is not None:
109
+ apply_thread_limit(env_value, override=False)
110
+ return rest
@@ -0,0 +1,310 @@
1
+ """Distance-binned categorical agreement and chromosome-stratified block marks."""
2
+
3
+ import itertools
4
+ from collections import Counter, defaultdict
5
+
6
+ import numpy as np
7
+
8
+ from .genomic_coordinates import select_rows, table_rows
9
+ from .topology_landscape import CLASSES, fail
10
+
11
+ METRICS = ("agreement", *CLASSES[:3])
12
+
13
+
14
+ def validate_edges(edges):
15
+ if len(edges) < 2 or edges[0] != 0 or any(
16
+ isinstance(x, bool) or not isinstance(x, (int, np.integer)) for x in edges
17
+ ) or any(b <= a for a, b in itertools.pairwise(edges)):
18
+ fail("Distance edges must be strictly increasing integers starting at zero.")
19
+ if len(edges) > 1001 or edges[-1] > 2**62:
20
+ fail("Use at most 1000 distance bins with maximum distance <= 2**62.")
21
+ return np.asarray(edges, dtype=np.int64)
22
+
23
+
24
+ def validate_rows(rows):
25
+ """Reject duplicate mappings and inconsistent cross-reference labels."""
26
+ seen, labels = set(), {}
27
+ output = []
28
+ for row in rows:
29
+ row = dict(row)
30
+ for key in ("reference", "chromosome", "gene_id"):
31
+ if not isinstance(row.get(key), str) or not row[key].strip() or row[key] == ".":
32
+ fail(f"Invalid or missing {key} in classified genes.")
33
+ key = (row["reference"], row["gene_id"])
34
+ if key in seen:
35
+ fail(f"Duplicate classified gene mapping: {key}.")
36
+ seen.add(key)
37
+ category = row.get("classification")
38
+ if category not in CLASSES:
39
+ fail(f"Unknown topology classification: {category}.")
40
+ if row["gene_id"] in labels and labels[row["gene_id"]] != category:
41
+ fail(f"Conflicting classifications across references: {row['gene_id']}.")
42
+ labels[row["gene_id"]] = category
43
+ for field in ("start", "end", "anchor"):
44
+ try:
45
+ value = row[field]
46
+ if isinstance(value, (bool, float)):
47
+ raise TypeError
48
+ row[field] = int(value)
49
+ except (KeyError, TypeError, ValueError):
50
+ fail(f"Classified gene {field} must be an integer.")
51
+ if not 0 <= row["start"] < row["end"] <= 2**62:
52
+ fail("Classified coordinates require 0 <= start < end <= 2**62.")
53
+ if row["anchor"] != (row["start"] + row["end"] - 1) // 2:
54
+ fail("Classified gene anchor does not match the gene-span midpoint.")
55
+ output.append(row)
56
+ if not output:
57
+ fail("No classified genes provided.")
58
+ return select_rows(output)
59
+
60
+
61
+ def read_classified(path):
62
+ required = ("reference", "chromosome", "gene_id", "start", "end", "anchor", "classification")
63
+ return validate_rows([row for _, row in table_rows(path, required)])
64
+
65
+
66
+ def baseline(counts):
67
+ """Finite-population joint probabilities, with NaNs for fewer than two genes."""
68
+ counts = np.asarray(counts, dtype=float)
69
+ n = counts.sum(axis=-1)
70
+ denominator = n * (n - 1)
71
+ joint = np.divide(counts * (counts - 1), denominator[..., None],
72
+ out=np.full_like(counts, np.nan), where=denominator[..., None] > 0)
73
+ return np.concatenate((joint.sum(axis=-1, keepdims=True), joint), axis=-1)
74
+
75
+
76
+ def chromosome_marks(genes, edges, block_size=None):
77
+ """Compute symmetric endpoint marks without storing individual gene pairs.
78
+
79
+ Each bin uses range searches and topology prefix sums. Difference arrays
80
+ identify participating right endpoints, avoiding materialized pair lists.
81
+ """
82
+ edges = validate_edges(edges)
83
+ genes = sorted(genes, key=lambda r: (r["anchor"], r["gene_id"]))
84
+ if not genes:
85
+ fail("Cannot analyze an empty chromosome.")
86
+ start, stop = genes[0]["anchor"], genes[-1]["anchor"] + 1
87
+ span = stop - start
88
+ if block_size is not None and (not isinstance(block_size, int) or block_size <= 0):
89
+ fail("Block sizes must be positive integers.")
90
+ nblocks = max(1, span // block_size) if block_size else 1
91
+ if nblocks > 100_000 or nblocks * (len(edges) - 1) > 2_000_000:
92
+ fail("Too many block/bin combinations; increase block size or reduce bins.")
93
+ # Integer quotient/remainder partitions avoid coordinate multiplication overflow.
94
+ width, remainder = divmod(span, nblocks)
95
+ bounds = start + np.arange(nblocks + 1, dtype=np.int64) * width
96
+ bounds += np.minimum(np.arange(nblocks + 1), remainder)
97
+ all_x = np.asarray([g["anchor"] for g in genes], dtype=np.int64)
98
+ all_block = np.searchsorted(bounds, all_x, side="right") - 1
99
+ classes = np.asarray([CLASSES.index(g["classification"]) for g in genes])
100
+ class_counts = np.zeros((nblocks, 6), dtype=np.int64)
101
+ np.add.at(class_counts, (all_block, classes), 1)
102
+ resolved = classes < 3
103
+ x, y, blocks = all_x[resolved], classes[resolved], all_block[resolved]
104
+ n, nbins = len(x), len(edges) - 1
105
+ pair_marks = np.zeros((nblocks, nbins, 4), dtype=float)
106
+ bootstrap_marks = np.zeros_like(pair_marks)
107
+ participants = np.zeros(nbins, dtype=np.int64)
108
+ prefix = np.zeros((n + 1, 3), dtype=np.int64)
109
+ if n:
110
+ prefix[1:] = np.cumsum(np.eye(3, dtype=np.int64)[y], axis=0)
111
+ indices = np.arange(n)
112
+ for b, (lower, upper) in enumerate(itertools.pairwise(edges)):
113
+ left = np.maximum(indices + 1, np.searchsorted(x, x + lower, side="left"))
114
+ right = np.maximum(left, np.searchsorted(x, x + upper, side="left"))
115
+ counts = right - left
116
+ previous_left = np.searchsorted(x, x - upper, side="right")
117
+ previous_right = np.minimum(indices, np.searchsorted(x, x - lower, side="right"))
118
+ previous_counts = previous_right - previous_left
119
+ np.add.at(pair_marks[:, b, 0], blocks, (counts + previous_counts) / 2)
120
+ for k in range(3):
121
+ neighbor_count = (prefix[right, k] - prefix[left, k] + prefix[previous_right, k]
122
+ - prefix[previous_left, k])
123
+ joint = neighbor_count * (y == k) / 2
124
+ np.add.at(pair_marks[:, b, k + 1], blocks, joint)
125
+ # Allocate the linear frequency term to its own gene, preserving
126
+ # exact pair totals while avoiding boundary-induced noncancellation.
127
+ frequency = np.count_nonzero(y == k) / n if n else 0
128
+ correction = frequency * ((counts + previous_counts) * (y == k) - neighbor_count) / 2
129
+ np.add.at(bootstrap_marks[:, b, k + 1], blocks, joint + correction)
130
+ difference = np.zeros(n + 1, dtype=np.int64)
131
+ np.add.at(difference, left, 1)
132
+ np.add.at(difference, right, -1)
133
+ participants[b] = np.count_nonzero((counts > 0) | (np.cumsum(difference[:-1]) > 0))
134
+ bootstrap_marks[:, :, 0] = pair_marks[:, :, 0]
135
+ return {
136
+ "reference": genes[0]["reference"], "chromosome": genes[0]["chromosome"],
137
+ "bounds": bounds, "class_counts": class_counts, "pair_marks": pair_marks,
138
+ "bootstrap_marks": bootstrap_marks,
139
+ "participants": participants,
140
+ }
141
+
142
+
143
+ def estimate(pair_counts, gene_counts):
144
+ """Return observed, baseline, and excess arrays with final axis METRICS."""
145
+ pair_counts = np.asarray(pair_counts, dtype=float)
146
+ totals = pair_counts[..., :1]
147
+ successes = np.concatenate((pair_counts[..., 1:].sum(axis=-1, keepdims=True),
148
+ pair_counts[..., 1:]), axis=-1)
149
+ observed = np.divide(successes, totals, out=np.full_like(successes, np.nan), where=totals > 0)
150
+ expected = np.broadcast_to(np.expand_dims(baseline(gene_counts), -2), observed.shape).copy()
151
+ expected = np.where(totals > 0, expected, np.nan)
152
+ return observed, expected, observed - expected
153
+
154
+
155
+ def _number(value):
156
+ return float(value) if np.isfinite(value) else None
157
+
158
+
159
+ def records(reference, chromosome, pairs, observed, expected, participants, contributors, edges):
160
+ output = []
161
+ for b, (lower, upper) in enumerate(itertools.pairwise(edges)):
162
+ for k, metric in enumerate(METRICS):
163
+ output.append({
164
+ "reference": reference, "chromosome": chromosome, "distance_start": int(lower),
165
+ "distance_end": int(upper), "metric": metric, "pair_count": int(pairs[b]),
166
+ "contributing_genes": int(participants[b]),
167
+ "contributing_chromosomes": int(contributors[b]),
168
+ "observed": _number(observed[b, k]), "baseline": _number(expected[b, k]),
169
+ "excess": _number(observed[b, k] - expected[b, k]),
170
+ "enrichment_ratio": _number(observed[b, k] / expected[b, k])
171
+ if expected[b, k] > 0 else None,
172
+ })
173
+ return output
174
+
175
+
176
+ def analyze(rows, edges, block_size=None):
177
+ """Chromosome and pair-weighted reference estimates, with reusable block marks."""
178
+ rows, edges = validate_rows(rows), validate_edges(edges)
179
+ grouped = defaultdict(list)
180
+ for row in rows:
181
+ grouped[(row["reference"], row["chromosome"])].append(row)
182
+ marks, chromosome_rows, reference_rows, diagnostics = [], [], [], []
183
+ pooled = {}
184
+ for (ref, chrom), genes in sorted(grouped.items()):
185
+ m = chromosome_marks(genes, edges, block_size)
186
+ marks.append(m)
187
+ counts = m["pair_marks"].sum(axis=0)
188
+ obs, exp, _ = estimate(counts, m["class_counts"][:, :3].sum(axis=0))
189
+ pairs = counts[:, 0]
190
+ chromosome_rows.extend(records(ref, chrom, pairs, obs, exp, m["participants"], pairs > 0, edges))
191
+ if ref not in pooled:
192
+ pooled[ref] = [np.zeros_like(counts), np.zeros_like(exp),
193
+ np.zeros_like(pairs), np.zeros_like(pairs)]
194
+ total, weighted, participants, contributors = pooled[ref]
195
+ total += counts
196
+ weighted += np.nan_to_num(exp) * pairs[:, None]
197
+ participants += m["participants"]
198
+ contributors += pairs > 0
199
+ c = Counter(g["classification"] for g in genes)
200
+ diagnostics.append({"reference": ref, "chromosome": chrom, "total_genes": len(genes),
201
+ "resolved_genes": sum(c[k] for k in CLASSES[:3]),
202
+ "classifications": {k: c[k] for k in CLASSES},
203
+ "first_anchor": genes[0]["anchor"], "last_anchor": genes[-1]["anchor"]})
204
+ for ref, (counts, weighted, participants, contributors) in sorted(pooled.items()):
205
+ pairs = counts[:, 0]
206
+ successes = np.column_stack((counts[:, 1:].sum(axis=1), counts[:, 1:]))
207
+ obs = np.divide(successes, pairs[:, None], out=np.full_like(weighted, np.nan),
208
+ where=pairs[:, None] > 0)
209
+ exp = np.divide(weighted, pairs[:, None], out=np.full_like(weighted, np.nan),
210
+ where=pairs[:, None] > 0)
211
+ reference_rows.extend(records(ref, None, pairs, obs, exp, participants, contributors, edges))
212
+ return {"reference_estimates": reference_rows, "chromosome_estimates": chromosome_rows,
213
+ "chromosome_diagnostics": diagnostics}, marks
214
+
215
+
216
+ def bootstrap_reference(marks, replicates, rng):
217
+ """Resample original marks within chromosomes; never assemble new genomes."""
218
+ nbins = marks[0]["pair_marks"].shape[1]
219
+ draws = np.full((replicates, nbins, 4), np.nan)
220
+ for first in range(0, replicates, 100):
221
+ size = min(100, replicates - first)
222
+ totals = np.zeros((size, nbins, 1))
223
+ successes = np.zeros((size, nbins, 4))
224
+ expectations = np.zeros_like(successes)
225
+ valid = np.ones((size, nbins, 1), dtype=bool)
226
+ for m in marks:
227
+ blocks = len(m["class_counts"])
228
+ weights = rng.multinomial(blocks, np.full(blocks, 1 / blocks), size=size)
229
+ counts = weights @ m["class_counts"][:, :3]
230
+ pairs = (weights @ m["bootstrap_marks"].reshape(blocks, -1)).reshape(size, nbins, 4)
231
+ q = baseline(counts)[:, None, :]
232
+ denominator = pairs[:, :, :1]
233
+ valid &= (counts.sum(axis=1)[:, None, None] >= 2) | (denominator == 0)
234
+ totals += denominator
235
+ successes += np.concatenate((pairs[:, :, 1:].sum(axis=2, keepdims=True),
236
+ pairs[:, :, 1:]), axis=2)
237
+ expectations += np.nan_to_num(q) * denominator
238
+ np.divide(successes - expectations, totals, out=draws[first:first + size],
239
+ where=(totals > 0) & valid)
240
+ return draws
241
+
242
+
243
+ def uncertainty(rows, edges, block_sizes, replicates=999, seed=0):
244
+ """Pointwise marked-block intervals and explicit block-size sensitivity."""
245
+ edges = validate_edges(edges)
246
+ if (not isinstance(seed, int) or seed < 0 or not isinstance(replicates, int)
247
+ or replicates < 499 or replicates > 100_000):
248
+ fail("Inference requires a nonnegative integer seed and 499-100000 replicates.")
249
+ if (len(set(block_sizes)) < 2 or any(not isinstance(s, int) or s <= 0 for s in block_sizes)):
250
+ fail("Inference requires at least two distinct positive integer block sizes.")
251
+ if replicates * (len(edges) - 1) > 5_000_000:
252
+ fail("Too many replicate/bin combinations; reduce replicates or bins.")
253
+ output, block_diagnostics = [], []
254
+ for block_size in sorted(set(block_sizes)):
255
+ _, all_marks = analyze(rows, edges, block_size)
256
+ by_reference = defaultdict(list)
257
+ for m in all_marks:
258
+ by_reference[m["reference"]].append(m)
259
+ for b, counts in enumerate(m["class_counts"]):
260
+ block_diagnostics.append({
261
+ "reference": m["reference"], "chromosome": m["chromosome"],
262
+ "requested_block_bp": block_size, "block_index": b + 1,
263
+ "start": int(m["bounds"][b]), "end": int(m["bounds"][b + 1]),
264
+ "total_genes": int(counts.sum()), "resolved_genes": int(counts[:3].sum()),
265
+ **{name: int(counts[k]) for k, name in enumerate(CLASSES)},
266
+ })
267
+ for ref_index, (reference, marks) in enumerate(sorted(by_reference.items())):
268
+ rng = np.random.default_rng(np.random.SeedSequence([seed, block_size, ref_index]))
269
+ draws = bootstrap_reference(marks, replicates, rng)
270
+ for b, (lower, upper) in enumerate(itertools.pairwise(edges)):
271
+ contributors = [m for m in marks if m["pair_marks"][:, b, 0].sum() > 0]
272
+ common = []
273
+ if not contributors:
274
+ common.append("no_pairs")
275
+ if any(np.count_nonzero(m["pair_marks"][:, b, 0]) < 20 for m in contributors):
276
+ common.append("fewer_than_20_pair_occupied_blocks")
277
+ if any(np.min(np.diff(m["bounds"])) < 5 * int(upper) for m in contributors):
278
+ common.append("blocks_shorter_than_5x_bin_distance")
279
+ for k, metric in enumerate(METRICS):
280
+ values = draws[:, b, k]
281
+ values = values[np.isfinite(values)]
282
+ reasons = list(common)
283
+ if len(values) < 0.95 * replicates:
284
+ reasons.append("too_few_valid_replicates")
285
+ if len(values) and np.ptp(values) < 1e-12:
286
+ reasons.append("degenerate_bootstrap")
287
+ low, high = np.quantile(values, [0.025, 0.975]) if not reasons else (np.nan, np.nan)
288
+ output.append({
289
+ "reference": reference, "distance_start": int(lower), "distance_end": int(upper),
290
+ "metric": metric, "requested_block_bp": block_size,
291
+ "replicates": replicates, "valid_replicates": len(values), "seed": seed,
292
+ "confidence_level": 0.95, "interval_type": "pointwise_percentile",
293
+ "lower": _number(low), "upper": _number(high),
294
+ "status": "withheld" if reasons else "available",
295
+ "reasons": reasons, "block_size_sensitive": None,
296
+ })
297
+ grouped = defaultdict(list)
298
+ for row in output:
299
+ grouped[(row["reference"], row["distance_start"], row["metric"])].append(row)
300
+ for group in grouped.values():
301
+ available = [r for r in group if r["status"] == "available"]
302
+ if len(available) >= 2:
303
+ widths = [r["upper"] - r["lower"] for r in available]
304
+ sensitive = max(widths) > 2 * min(widths)
305
+ for row in group:
306
+ row["block_size_sensitive"] = sensitive
307
+ else:
308
+ for row in group:
309
+ row["reasons"].append("insufficient_admissible_block_sizes_for_sensitivity")
310
+ return output, block_diagnostics
@@ -1,9 +1,8 @@
1
1
  """
2
2
  Shared trait file parsing utilities.
3
3
 
4
- Provides a single implementation for parsing tab-delimited multi-trait
5
- files with a header row, used across phylogenetic regression, signal,
6
- ordination, path analysis, ANOVA, and other comparative methods.
4
+ Parses headerless single-trait files and headered multi-trait files while
5
+ preserving the distinct input contracts of the consuming services.
7
6
  """
8
7
  from math import isfinite
9
8
  import sys
@@ -11,6 +10,96 @@ import sys
11
10
  from ..errors import PhykitUserError
12
11
 
13
12
 
13
+ def parse_single_trait_file(path: str, tree_tips: list[str]) -> dict[str, float]:
14
+ """Parse the legacy headerless two-column format used by trait services.
15
+
16
+ Preserve duplicate-row overwrites, non-finite values, diagnostics, and
17
+ overlap ordering. This contract differs from the headered multi-trait parser.
18
+ """
19
+ try:
20
+ traits = {}
21
+ with open(path) as f:
22
+ for line_num, line in enumerate(f, 1):
23
+ line = line.strip()
24
+ if not line or line[0] == "#":
25
+ continue
26
+ parts = line.split("\t", 2)
27
+ if len(parts) != 2:
28
+ column_count = line.count("\t") + 1
29
+ raise PhykitUserError(
30
+ [
31
+ f"Line {line_num} in trait file has {column_count} columns; expected 2.",
32
+ "Each line should be: taxon_name<tab>trait_value",
33
+ ],
34
+ code=2,
35
+ )
36
+ taxon, value_str = parts
37
+ try:
38
+ traits[taxon] = float(value_str)
39
+ except ValueError:
40
+ raise PhykitUserError(
41
+ [
42
+ f"Non-numeric trait value '{value_str}' for taxon '{taxon}' on line {line_num}.",
43
+ ],
44
+ code=2,
45
+ )
46
+ except FileNotFoundError:
47
+ raise PhykitUserError(
48
+ [
49
+ f"{path} corresponds to no such file or directory.",
50
+ "Please check filename and pathing",
51
+ ],
52
+ code=2,
53
+ )
54
+
55
+ if (
56
+ len(tree_tips) >= 3
57
+ and len(tree_tips) == len(traits)
58
+ and next(iter(traits)) == tree_tips[0]
59
+ and next(reversed(traits)) == tree_tips[-1]
60
+ and list(traits) == tree_tips
61
+ ):
62
+ return traits
63
+
64
+ tree_tip_set = set(tree_tips)
65
+ if (
66
+ len(tree_tip_set) >= 3
67
+ and len(tree_tip_set) == len(traits)
68
+ and tree_tip_set == traits.keys()
69
+ ):
70
+ return traits
71
+
72
+ trait_taxa_set = set(traits)
73
+ shared = tree_tip_set & trait_taxa_set
74
+
75
+ tree_only = tree_tip_set - trait_taxa_set
76
+ trait_only = trait_taxa_set - tree_tip_set
77
+
78
+ if tree_only:
79
+ print(
80
+ f"Warning: {len(tree_only)} taxa in tree but not in trait file: "
81
+ f"{', '.join(sorted(tree_only))}",
82
+ file=sys.stderr,
83
+ )
84
+ if trait_only:
85
+ print(
86
+ f"Warning: {len(trait_only)} taxa in trait file but not in tree: "
87
+ f"{', '.join(sorted(trait_only))}",
88
+ file=sys.stderr,
89
+ )
90
+
91
+ if len(shared) < 3:
92
+ raise PhykitUserError(
93
+ [
94
+ f"Only {len(shared)} shared taxa between tree and trait file.",
95
+ "At least 3 shared taxa are required.",
96
+ ],
97
+ code=2,
98
+ )
99
+
100
+ return {taxon: traits[taxon] for taxon in shared}
101
+
102
+
14
103
  def _split_tsv_line(line: str) -> list[str]:
15
104
  return [part.strip() for part in line.rstrip("\r\n").split("\t")]
16
105