phykit 2.6.0__tar.gz → 2.8.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.6.0 → phykit-2.8.0}/PKG-INFO +6 -1
  2. {phykit-2.6.0 → phykit-2.8.0}/README.md +5 -0
  3. {phykit-2.6.0 → phykit-2.8.0}/phykit/cli_registry.py +4 -0
  4. phykit-2.8.0/phykit/helpers/boolean_argument_parsing.py +17 -0
  5. phykit-2.8.0/phykit/helpers/genomic_coordinates.py +175 -0
  6. phykit-2.8.0/phykit/helpers/threads.py +110 -0
  7. phykit-2.8.0/phykit/helpers/topology_autocorrelation.py +310 -0
  8. phykit-2.8.0/phykit/helpers/topology_landscape.py +190 -0
  9. {phykit-2.6.0 → phykit-2.8.0}/phykit/helpers/trait_parsing.py +92 -3
  10. {phykit-2.6.0 → phykit-2.8.0}/phykit/phykit.py +290 -118
  11. {phykit-2.6.0 → phykit-2.8.0}/phykit/service_factories.py +2 -0
  12. phykit-2.8.0/phykit/services/alignment/_file_list.py +98 -0
  13. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/alignment/create_concatenation_matrix.py +3 -2
  14. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/alignment/occupancy_filter.py +4 -90
  15. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/alignment/pairwise_identity.py +2 -1
  16. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/alignment/sum_of_pairs_score.py +2 -1
  17. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/alignment/taxon_groups.py +4 -90
  18. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/cont_map.py +2 -81
  19. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/covarying_evolutionary_rates.py +2 -1
  20. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/fit_continuous.py +2 -81
  21. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/hidden_paralogy_check.py +2 -1
  22. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/lb_score.py +3 -2
  23. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/network_signal.py +2 -81
  24. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/ou_shift_detection.py +2 -81
  25. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/ouwie.py +2 -81
  26. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/patristic_distances.py +3 -2
  27. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/phenogram.py +2 -81
  28. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/phylogenetic_signal.py +2 -81
  29. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/polytomy_test.py +2 -1
  30. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/rate_heterogeneity.py +2 -81
  31. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/rf_distance.py +2 -1
  32. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/saturation.py +2 -1
  33. phykit-2.8.0/phykit/services/tree/topology_autocorrelation.py +224 -0
  34. phykit-2.8.0/phykit/services/tree/topology_landscape.py +255 -0
  35. phykit-2.8.0/phykit/version.py +1 -0
  36. {phykit-2.6.0 → phykit-2.8.0}/phykit.egg-info/PKG-INFO +6 -1
  37. {phykit-2.6.0 → phykit-2.8.0}/phykit.egg-info/SOURCES.txt +7 -1
  38. {phykit-2.6.0 → phykit-2.8.0}/phykit.egg-info/entry_points.txt +4 -0
  39. phykit-2.6.0/phykit/helpers/boolean_argument_parsing.py +0 -12
  40. phykit-2.6.0/phykit/helpers/parallel.py +0 -412
  41. phykit-2.6.0/phykit/version.py +0 -1
  42. {phykit-2.6.0 → phykit-2.8.0}/LICENSE.md +0 -0
  43. {phykit-2.6.0 → phykit-2.8.0}/phykit/__init__.py +0 -0
  44. {phykit-2.6.0 → phykit-2.8.0}/phykit/__main__.py +0 -0
  45. {phykit-2.6.0 → phykit-2.8.0}/phykit/errors.py +0 -0
  46. {phykit-2.6.0 → phykit-2.8.0}/phykit/helpers/__init__.py +0 -0
  47. {phykit-2.6.0 → phykit-2.8.0}/phykit/helpers/caching.py +0 -0
  48. {phykit-2.6.0 → phykit-2.8.0}/phykit/helpers/circular_layout.py +0 -0
  49. {phykit-2.6.0 → phykit-2.8.0}/phykit/helpers/color_annotations.py +0 -0
  50. {phykit-2.6.0 → phykit-2.8.0}/phykit/helpers/discrete_models.py +0 -0
  51. {phykit-2.6.0 → phykit-2.8.0}/phykit/helpers/files.py +0 -0
  52. {phykit-2.6.0 → phykit-2.8.0}/phykit/helpers/geological_timescale.py +0 -0
  53. {phykit-2.6.0 → phykit-2.8.0}/phykit/helpers/json_output.py +0 -0
  54. {phykit-2.6.0 → phykit-2.8.0}/phykit/helpers/parsimony_utils.py +0 -0
  55. {phykit-2.6.0 → phykit-2.8.0}/phykit/helpers/pgls_utils.py +0 -0
  56. {phykit-2.6.0 → phykit-2.8.0}/phykit/helpers/plot_config.py +0 -0
  57. {phykit-2.6.0 → phykit-2.8.0}/phykit/helpers/quartet_utils.py +0 -0
  58. {phykit-2.6.0 → phykit-2.8.0}/phykit/helpers/stats_summary.py +0 -0
  59. {phykit-2.6.0 → phykit-2.8.0}/phykit/helpers/streaming.py +0 -0
  60. {phykit-2.6.0 → phykit-2.8.0}/phykit/helpers/tree_paths.py +0 -0
  61. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/__init__.py +0 -0
  62. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/alignment/__init__.py +0 -0
  63. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/alignment/_fasta.py +0 -0
  64. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/alignment/alignment_entropy.py +0 -0
  65. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/alignment/alignment_length.py +0 -0
  66. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/alignment/alignment_length_no_gaps.py +0 -0
  67. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/alignment/alignment_outlier_regions.py +0 -0
  68. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/alignment/alignment_outlier_taxa.py +0 -0
  69. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/alignment/alignment_recoding.py +0 -0
  70. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/alignment/alignment_subsample.py +0 -0
  71. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/alignment/base.py +0 -0
  72. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/alignment/codon_dnds.py +0 -0
  73. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/alignment/column_score.py +0 -0
  74. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/alignment/composition_per_taxon.py +0 -0
  75. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/alignment/compositional_bias_per_site.py +0 -0
  76. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/alignment/dfoil.py +0 -0
  77. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/alignment/dna_threader.py +0 -0
  78. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/alignment/dstatistic.py +0 -0
  79. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/alignment/evolutionary_rate_per_site.py +0 -0
  80. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/alignment/faidx.py +0 -0
  81. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/alignment/gc_content.py +0 -0
  82. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/alignment/identity_matrix.py +0 -0
  83. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/alignment/mask_alignment.py +0 -0
  84. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/alignment/occupancy_per_taxon.py +0 -0
  85. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/alignment/parsimony_informative_sites.py +0 -0
  86. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/alignment/phylo_gwas.py +0 -0
  87. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/alignment/plot_alignment_qc.py +0 -0
  88. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/alignment/rcv.py +0 -0
  89. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/alignment/rcvt.py +0 -0
  90. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/alignment/rename_fasta_entries.py +0 -0
  91. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/alignment/variable_sites.py +0 -0
  92. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/base.py +0 -0
  93. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/__init__.py +0 -0
  94. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/ancestral_reconstruction.py +0 -0
  95. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/base.py +0 -0
  96. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/bipartition_support_stats.py +0 -0
  97. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/branch_length_multiplier.py +0 -0
  98. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/character_map.py +0 -0
  99. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/chronogram.py +0 -0
  100. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/collapse_branches.py +0 -0
  101. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/concordance_asr.py +0 -0
  102. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/consensus_network.py +0 -0
  103. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/consensus_tree.py +0 -0
  104. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/cophylo.py +0 -0
  105. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/density_map.py +0 -0
  106. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/discordance_asymmetry.py +0 -0
  107. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/dtt.py +0 -0
  108. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/dvmc.py +0 -0
  109. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/episodic_rate_covariation.py +0 -0
  110. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/evo_tempo_map.py +0 -0
  111. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/evolutionary_rate.py +0 -0
  112. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/faiths_pd.py +0 -0
  113. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/fit_discrete.py +0 -0
  114. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/hybridization.py +0 -0
  115. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/independent_contrasts.py +0 -0
  116. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/internal_branch_stats.py +0 -0
  117. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/internode_labeler.py +0 -0
  118. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/kf_distance.py +0 -0
  119. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/last_common_ancestor_subtree.py +0 -0
  120. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/ltt.py +0 -0
  121. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/monophyly_check.py +0 -0
  122. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/nearest_neighbor_interchange.py +0 -0
  123. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/neighbor_net.py +0 -0
  124. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/parsimony_score.py +0 -0
  125. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/phylo_anova.py +0 -0
  126. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/phylo_heatmap.py +0 -0
  127. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/phylo_impute.py +0 -0
  128. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/phylo_logistic.py +0 -0
  129. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/phylo_path.py +0 -0
  130. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/phylogenetic_glm.py +0 -0
  131. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/phylogenetic_ordination.py +0 -0
  132. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/phylogenetic_regression.py +0 -0
  133. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/phylomorphospace.py +0 -0
  134. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/print_tree.py +0 -0
  135. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/projected_covarying_rates.py +0 -0
  136. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/prune_tree.py +0 -0
  137. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/quartet_network.py +0 -0
  138. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/quartet_pie.py +0 -0
  139. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/relative_rate_test.py +0 -0
  140. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/rename_tree_tips.py +0 -0
  141. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/root_tree.py +0 -0
  142. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/simmap_summary.py +0 -0
  143. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/spectral_discordance.py +0 -0
  144. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/spr.py +0 -0
  145. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/spurious_sequence.py +0 -0
  146. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/stochastic_character_map.py +0 -0
  147. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/terminal_branch_stats.py +0 -0
  148. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/threshold_model.py +0 -0
  149. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/tip_labels.py +0 -0
  150. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/tip_to_tip_distance.py +0 -0
  151. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/tip_to_tip_node_distance.py +0 -0
  152. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/total_tree_length.py +0 -0
  153. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/trait_correlation.py +0 -0
  154. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/trait_rate_map.py +0 -0
  155. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/transfer_annotations.py +0 -0
  156. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/tree_space.py +0 -0
  157. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/treeness.py +0 -0
  158. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/treeness_over_rcv.py +0 -0
  159. {phykit-2.6.0 → phykit-2.8.0}/phykit/services/tree/vcv_utils.py +0 -0
  160. {phykit-2.6.0 → phykit-2.8.0}/phykit.egg-info/dependency_links.txt +0 -0
  161. {phykit-2.6.0 → phykit-2.8.0}/phykit.egg-info/requires.txt +0 -0
  162. {phykit-2.6.0 → phykit-2.8.0}/phykit.egg-info/top_level.txt +0 -0
  163. {phykit-2.6.0 → phykit-2.8.0}/setup.cfg +0 -0
  164. {phykit-2.6.0 → phykit-2.8.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.8.0
4
4
  Home-page: https://github.com/jlsteenwyk/phykit
5
5
  Author: Jacob L. Steenwyk
6
6
  Author-email: jlsteenwyk@gmail.com
@@ -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.
@@ -74,6 +74,10 @@ 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",
79
+ "topology_autocorrelation": "topology_autocorrelation",
80
+ "topo_ac": "topology_autocorrelation",
77
81
  "bss": "bipartition_support_stats",
78
82
  "blm": "branch_length_multiplier",
79
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,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,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