clipkit 2.10.2__tar.gz → 2.11.3__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 (79) hide show
  1. {clipkit-2.10.2 → clipkit-2.11.3}/PKG-INFO +20 -4
  2. {clipkit-2.10.2 → clipkit-2.11.3}/README.md +3 -2
  3. {clipkit-2.10.2 → clipkit-2.11.3}/clipkit/api.py +41 -5
  4. {clipkit-2.10.2 → clipkit-2.11.3}/clipkit/args_processing.py +10 -2
  5. {clipkit-2.10.2 → clipkit-2.11.3}/clipkit/clipkit.py +36 -1
  6. clipkit-2.11.3/clipkit/guide_tree.py +26 -0
  7. {clipkit-2.10.2 → clipkit-2.11.3}/clipkit/modes.py +4 -0
  8. {clipkit-2.10.2 → clipkit-2.11.3}/clipkit/msa.py +188 -25
  9. clipkit-2.11.3/clipkit/parser.py +396 -0
  10. clipkit-2.11.3/clipkit/plot_report.py +591 -0
  11. {clipkit-2.10.2 → clipkit-2.11.3}/clipkit/smart_gap_helper.py +0 -10
  12. clipkit-2.11.3/clipkit/version.py +1 -0
  13. {clipkit-2.10.2 → clipkit-2.11.3}/clipkit.egg-info/PKG-INFO +20 -4
  14. {clipkit-2.10.2 → clipkit-2.11.3}/clipkit.egg-info/SOURCES.txt +8 -0
  15. clipkit-2.11.3/pyproject.toml +3 -0
  16. {clipkit-2.10.2 → clipkit-2.11.3}/setup.py +8 -3
  17. {clipkit-2.10.2 → clipkit-2.11.3}/tests/integration/test_api.py +60 -0
  18. clipkit-2.11.3/tests/integration/test_block_gappy_mode.py +39 -0
  19. clipkit-2.11.3/tests/integration/test_composition_bias_mode.py +39 -0
  20. clipkit-2.11.3/tests/integration/test_gappyout_mode.py +39 -0
  21. clipkit-2.11.3/tests/integration/test_heterotachy_mode.py +39 -0
  22. {clipkit-2.10.2 → clipkit-2.11.3}/tests/unit/test_args_parsing.py +28 -0
  23. {clipkit-2.10.2 → clipkit-2.11.3}/tests/unit/test_msa.py +45 -0
  24. clipkit-2.11.3/tests/unit/test_parser.py +61 -0
  25. clipkit-2.11.3/tests/unit/test_plot_report.py +30 -0
  26. clipkit-2.10.2/clipkit/parser.py +0 -365
  27. clipkit-2.10.2/clipkit/version.py +0 -1
  28. clipkit-2.10.2/tests/unit/test_parser.py +0 -27
  29. {clipkit-2.10.2 → clipkit-2.11.3}/LICENSE.md +0 -0
  30. {clipkit-2.10.2 → clipkit-2.11.3}/clipkit/__init__.py +0 -0
  31. {clipkit-2.10.2 → clipkit-2.11.3}/clipkit/__main__.py +0 -0
  32. {clipkit-2.10.2 → clipkit-2.11.3}/clipkit/ecomp/__init__.py +0 -0
  33. {clipkit-2.10.2 → clipkit-2.11.3}/clipkit/ecomp/reader.py +0 -0
  34. {clipkit-2.10.2 → clipkit-2.11.3}/clipkit/ecomp/writer.py +0 -0
  35. {clipkit-2.10.2 → clipkit-2.11.3}/clipkit/exceptions.py +0 -0
  36. {clipkit-2.10.2 → clipkit-2.11.3}/clipkit/files.py +0 -0
  37. {clipkit-2.10.2 → clipkit-2.11.3}/clipkit/helpers.py +0 -0
  38. {clipkit-2.10.2 → clipkit-2.11.3}/clipkit/logger.py +0 -0
  39. {clipkit-2.10.2 → clipkit-2.11.3}/clipkit/settings.py +0 -0
  40. {clipkit-2.10.2 → clipkit-2.11.3}/clipkit/site_classification.py +0 -0
  41. {clipkit-2.10.2 → clipkit-2.11.3}/clipkit/stats.py +0 -0
  42. {clipkit-2.10.2 → clipkit-2.11.3}/clipkit/warnings.py +0 -0
  43. {clipkit-2.10.2 → clipkit-2.11.3}/clipkit/write.py +0 -0
  44. {clipkit-2.10.2 → clipkit-2.11.3}/clipkit.egg-info/dependency_links.txt +0 -0
  45. {clipkit-2.10.2 → clipkit-2.11.3}/clipkit.egg-info/entry_points.txt +0 -0
  46. {clipkit-2.10.2 → clipkit-2.11.3}/clipkit.egg-info/requires.txt +0 -0
  47. {clipkit-2.10.2 → clipkit-2.11.3}/clipkit.egg-info/top_level.txt +0 -0
  48. {clipkit-2.10.2 → clipkit-2.11.3}/setup.cfg +0 -0
  49. {clipkit-2.10.2 → clipkit-2.11.3}/tests/__init__.py +0 -0
  50. {clipkit-2.10.2 → clipkit-2.11.3}/tests/conftest.py +0 -0
  51. {clipkit-2.10.2 → clipkit-2.11.3}/tests/integration/__init__.py +0 -0
  52. {clipkit-2.10.2 → clipkit-2.11.3}/tests/integration/test_c3.py +0 -0
  53. {clipkit-2.10.2 → clipkit-2.11.3}/tests/integration/test_codon.py +0 -0
  54. {clipkit-2.10.2 → clipkit-2.11.3}/tests/integration/test_complementary_output.py +0 -0
  55. {clipkit-2.10.2 → clipkit-2.11.3}/tests/integration/test_cst.py +0 -0
  56. {clipkit-2.10.2 → clipkit-2.11.3}/tests/integration/test_ecomp_input.py +0 -0
  57. {clipkit-2.10.2 → clipkit-2.11.3}/tests/integration/test_ends_only.py +0 -0
  58. {clipkit-2.10.2 → clipkit-2.11.3}/tests/integration/test_gappy_mode.py +0 -0
  59. {clipkit-2.10.2 → clipkit-2.11.3}/tests/integration/test_kpi_gappy_mode.py +0 -0
  60. {clipkit-2.10.2 → clipkit-2.11.3}/tests/integration/test_kpi_mode.py +0 -0
  61. {clipkit-2.10.2 → clipkit-2.11.3}/tests/integration/test_kpi_smart_gap_mode.py +0 -0
  62. {clipkit-2.10.2 → clipkit-2.11.3}/tests/integration/test_kpic_gappy_mode.py +0 -0
  63. {clipkit-2.10.2 → clipkit-2.11.3}/tests/integration/test_kpic_mode.py +0 -0
  64. {clipkit-2.10.2 → clipkit-2.11.3}/tests/integration/test_kpic_smart_gap_mode.py +0 -0
  65. {clipkit-2.10.2 → clipkit-2.11.3}/tests/integration/test_smart_gap_mode.py +0 -0
  66. {clipkit-2.10.2 → clipkit-2.11.3}/tests/integration/test_writing_to_different_output_file_formats.py +0 -0
  67. {clipkit-2.10.2 → clipkit-2.11.3}/tests/integration/test_writing_to_log_file.py +0 -0
  68. {clipkit-2.10.2 → clipkit-2.11.3}/tests/unit/__init__.py +0 -0
  69. {clipkit-2.10.2 → clipkit-2.11.3}/tests/unit/ecomp/__init__.py +0 -0
  70. {clipkit-2.10.2 → clipkit-2.11.3}/tests/unit/ecomp/test_reader.py +0 -0
  71. {clipkit-2.10.2 → clipkit-2.11.3}/tests/unit/test_entrypoint.py +0 -0
  72. {clipkit-2.10.2 → clipkit-2.11.3}/tests/unit/test_execution_state.py +0 -0
  73. {clipkit-2.10.2 → clipkit-2.11.3}/tests/unit/test_files.py +0 -0
  74. {clipkit-2.10.2 → clipkit-2.11.3}/tests/unit/test_parallel.py +0 -0
  75. {clipkit-2.10.2 → clipkit-2.11.3}/tests/unit/test_parallel_simple.py +0 -0
  76. {clipkit-2.10.2 → clipkit-2.11.3}/tests/unit/test_parallel_standalone.py +0 -0
  77. {clipkit-2.10.2 → clipkit-2.11.3}/tests/unit/test_smart_gap_helper.py +0 -0
  78. {clipkit-2.10.2 → clipkit-2.11.3}/tests/unit/test_thread_heuristics.py +0 -0
  79. {clipkit-2.10.2 → clipkit-2.11.3}/tests/unit/test_warnings.py +0 -0
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.1
1
+ Metadata-Version: 2.4
2
2
  Name: clipkit
3
- Version: 2.10.2
3
+ Version: 2.11.3
4
4
  Summary: Alignment trimming software for phylogenetics.
5
5
  Home-page: https://github.com/jlsteenwyk/clipkit
6
6
  Author: Jacob L. Steenwyk
@@ -16,6 +16,21 @@ Classifier: Topic :: Scientific/Engineering
16
16
  Requires-Python: >=3.10
17
17
  Description-Content-Type: text/markdown
18
18
  License-File: LICENSE.md
19
+ Requires-Dist: biopython>=1.82; python_version < "3.13"
20
+ Requires-Dist: biopython>=1.84; python_version >= "3.13"
21
+ Requires-Dist: numpy<2.0,>=1.24.0; python_version < "3.12"
22
+ Requires-Dist: numpy<2.1,>=1.26.0; python_version == "3.12"
23
+ Requires-Dist: numpy<2.2,>=2.0.0; python_version >= "3.13"
24
+ Dynamic: author
25
+ Dynamic: author-email
26
+ Dynamic: classifier
27
+ Dynamic: description
28
+ Dynamic: description-content-type
29
+ Dynamic: home-page
30
+ Dynamic: license-file
31
+ Dynamic: requires-dist
32
+ Dynamic: requires-python
33
+ Dynamic: summary
19
34
 
20
35
  <p align="center">
21
36
  <a href="https://github.com/jlsteenwyk/clipkit">
@@ -35,8 +50,8 @@ License-File: LICENSE.md
35
50
  <a href="https://codecov.io/gh/jlsteenwyk/clipkit" alt="Coverage">
36
51
  <img src="https://codecov.io/gh/jlsteenwyk/clipkit/branch/master/graph/badge.svg?token=0J49I6441V">
37
52
  </a>
38
- <a href="https://github.com/jlsteenwyk/clipkit/graphs/contributors" alt="Contributors">
39
- <img src="https://img.shields.io/github/contributors/jlsteenwyk/clipkit">
53
+ <a href="https://github.com/JLSteenwyk/ClipKIT/graphs/contributors" alt="Contributors">
54
+ <img src="https://img.shields.io/github/contributors/JLSteenwyk/ClipKIT">
40
55
  </a>
41
56
  <a href="https://bsky.app/profile/jlsteenwyk.bsky.social" target="_blank" rel="noopener noreferrer">
42
57
  <img src="https://img.shields.io/badge/Bluesky-0285FF?logo=bluesky&logoColor=fff">
@@ -75,6 +90,7 @@ If you found ClipKIT useful, please cite *ClipKIT: a multiple sequence alignment
75
90
  <br />
76
91
 
77
92
  This documentation covers downloading and installing ClipKIT. Details about each function as well as tutorials for using ClipKIT are available in the [online documentation](https://jlsteenwyk.com/ClipKIT/).
93
+ Release automation details are documented in [RELEASE.md](RELEASE.md).
78
94
 
79
95
  <br />
80
96
 
@@ -16,8 +16,8 @@
16
16
  <a href="https://codecov.io/gh/jlsteenwyk/clipkit" alt="Coverage">
17
17
  <img src="https://codecov.io/gh/jlsteenwyk/clipkit/branch/master/graph/badge.svg?token=0J49I6441V">
18
18
  </a>
19
- <a href="https://github.com/jlsteenwyk/clipkit/graphs/contributors" alt="Contributors">
20
- <img src="https://img.shields.io/github/contributors/jlsteenwyk/clipkit">
19
+ <a href="https://github.com/JLSteenwyk/ClipKIT/graphs/contributors" alt="Contributors">
20
+ <img src="https://img.shields.io/github/contributors/JLSteenwyk/ClipKIT">
21
21
  </a>
22
22
  <a href="https://bsky.app/profile/jlsteenwyk.bsky.social" target="_blank" rel="noopener noreferrer">
23
23
  <img src="https://img.shields.io/badge/Bluesky-0285FF?logo=bluesky&logoColor=fff">
@@ -56,6 +56,7 @@ If you found ClipKIT useful, please cite *ClipKIT: a multiple sequence alignment
56
56
  <br />
57
57
 
58
58
  This documentation covers downloading and installing ClipKIT. Details about each function as well as tutorials for using ClipKIT are available in the [online documentation](https://jlsteenwyk.com/ClipKIT/).
59
+ Release automation details are documented in [RELEASE.md](RELEASE.md).
59
60
 
60
61
  <br />
61
62
 
@@ -1,4 +1,4 @@
1
- from typing import TextIO, Union
1
+ from typing import TYPE_CHECKING, Union
2
2
  from tempfile import NamedTemporaryFile
3
3
 
4
4
  from .clipkit import run
@@ -6,6 +6,14 @@ from .files import FileFormat
6
6
  from .helpers import SeqType, write_msa
7
7
  from .logger import logger
8
8
  from .modes import TrimmingMode
9
+ from .plot_report import write_trim_plot_report
10
+
11
+ if TYPE_CHECKING:
12
+ from .clipkit import TrimRun
13
+ from .stats import TrimmingStats
14
+
15
+
16
+ ClipkitReturn = Union[tuple["TrimRun", "TrimmingStats"], tuple[str, "TrimmingStats"]]
9
17
 
10
18
 
11
19
  def clipkit(
@@ -18,11 +26,12 @@ def clipkit(
18
26
  gap_characters=None,
19
27
  input_file_format=FileFormat.fasta,
20
28
  output_file_format=FileFormat.fasta,
21
- sequence_type=SeqType.aa,
29
+ sequence_type: Union[SeqType, str, None] = None,
22
30
  codon: bool = False,
23
31
  ends_only=False,
24
32
  threads: int = 1,
25
- ) -> TextIO:
33
+ plot_trim_report_path: Union[str, None] = None,
34
+ ) -> ClipkitReturn:
26
35
  """
27
36
  If input_file_path is given with no output_file_path -> Bio MSA (multiple sequence alignment object)
28
37
  If input_file_path is given and output_file_path is given -> write to output file
@@ -31,6 +40,16 @@ def clipkit(
31
40
  """
32
41
  if threads < 1:
33
42
  raise ValueError("threads must be an integer >= 1")
43
+ has_raw_alignment = raw_alignment is not None
44
+ has_input_path = input_file_path is not None
45
+ if has_raw_alignment == has_input_path:
46
+ raise ValueError(
47
+ "Provide exactly one of raw_alignment or input_file_path."
48
+ )
49
+ if has_raw_alignment and raw_alignment == "":
50
+ raise ValueError("raw_alignment cannot be empty.")
51
+ if has_input_path and input_file_path == "":
52
+ raise ValueError("input_file_path cannot be empty.")
34
53
 
35
54
  original_logger_disabled = logger.disabled
36
55
  logger.disabled = True
@@ -45,11 +64,19 @@ def clipkit(
45
64
  if not output_file_path:
46
65
  output_temp_file = NamedTemporaryFile()
47
66
 
48
- # override some options not currently available through programmatic interface
67
+ if isinstance(sequence_type, str):
68
+ try:
69
+ sequence_type = SeqType(sequence_type.lower())
70
+ except ValueError as exc:
71
+ raise ValueError(
72
+ "sequence_type must be one of: 'aa', 'nt', SeqType.aa, SeqType.nt, or None."
73
+ ) from exc
74
+
75
+ # override options not currently available through programmatic interface
49
76
  complement = False
50
77
  use_log = False
51
78
  quiet = True
52
- auxiliary_file = None # TODO: implement?
79
+ auxiliary_file = None
53
80
 
54
81
  trim_run, stats = run(
55
82
  input_temp_file.name if input_temp_file else input_file_path,
@@ -69,6 +96,15 @@ def clipkit(
69
96
  threads,
70
97
  )
71
98
 
99
+ if plot_trim_report_path:
100
+ write_trim_plot_report(
101
+ plot_trim_report_path,
102
+ trim_run.msa,
103
+ mode=TrimmingMode(mode).value,
104
+ gaps=trim_run.gaps,
105
+ sequence_type=trim_run.sequence_type.value,
106
+ )
107
+
72
108
  if not output_file_path:
73
109
  return trim_run, stats
74
110
 
@@ -30,9 +30,13 @@ def process_args(args) -> dict:
30
30
  mode = TrimmingMode(args.mode) if args.mode else TrimmingMode.smart_gap
31
31
  if args.gaps is not None:
32
32
  gaps = float(args.gaps)
33
- elif mode == TrimmingMode.entropy:
33
+ elif mode in {
34
+ TrimmingMode.entropy,
35
+ TrimmingMode.composition_bias,
36
+ TrimmingMode.heterotachy,
37
+ }:
34
38
  # Entropy thresholds are normalized to [0, 1], where larger values
35
- # indicate higher per-site character diversity.
39
+ # indicate stronger per-site signal (diversity or compositional skew).
36
40
  gaps = 0.8
37
41
  else:
38
42
  gaps = 0.9
@@ -56,6 +60,9 @@ def process_args(args) -> dict:
56
60
  report_json = getattr(args, "report_json", None)
57
61
  if report_json == "":
58
62
  report_json = f"{output_file}.report.json"
63
+ plot_trim_report = getattr(args, "plot_trim_report", None)
64
+ if plot_trim_report == "":
65
+ plot_trim_report = f"{output_file}.trim_report.html"
59
66
 
60
67
  threads = args.threads if hasattr(args, "threads") else 1
61
68
  if threads < 1:
@@ -88,5 +95,6 @@ def process_args(args) -> dict:
88
95
  dry_run=dry_run,
89
96
  validate_only=validate_only,
90
97
  report_json=report_json,
98
+ plot_trim_report=plot_trim_report,
91
99
  threads=threads,
92
100
  )
@@ -24,10 +24,12 @@ from .helpers import (
24
24
  write_complement,
25
25
  SeqType,
26
26
  )
27
+ from .guide_tree import build_parsimony_guide_tree
27
28
  from .logger import logger, log_file_logger
28
29
  from .modes import TrimmingMode
29
30
  from .msa import MSA
30
31
  from .parser import create_parser
32
+ from .plot_report import write_trim_plot_report
31
33
  from .settings import DEFAULT_AA_GAP_CHARS, DEFAULT_NT_GAP_CHARS
32
34
  from .smart_gap_helper import smart_gap_threshold_determination
33
35
  from .version import __version__ as current_version
@@ -141,12 +143,25 @@ def run(
141
143
  else:
142
144
  output_file_format = FileFormat(output_file_format)
143
145
 
146
+ if gaps is None:
147
+ if mode in {
148
+ TrimmingMode.entropy,
149
+ TrimmingMode.composition_bias,
150
+ TrimmingMode.heterotachy,
151
+ }:
152
+ gaps = 0.8
153
+ else:
154
+ gaps = 0.9
155
+
144
156
  site_positions_to_trim = None
157
+ guide_tree = None
145
158
  if mode == TrimmingMode.cst:
146
159
  aln_length = alignment.get_alignment_length()
147
160
  site_positions_to_trim = (
148
161
  get_custom_sites_to_trim(auxiliary_file, aln_length) or []
149
162
  )
163
+ elif mode == TrimmingMode.heterotachy:
164
+ guide_tree = build_parsimony_guide_tree(alignment)
150
165
 
151
166
  effective_threads = determine_effective_threads(
152
167
  threads,
@@ -168,11 +183,14 @@ def run(
168
183
  gap_characters,
169
184
  seq_records=msa.seq_records,
170
185
  )
186
+ elif mode == TrimmingMode.gappyout:
187
+ gaps = msa.determine_gappyout_gap_threshold()
171
188
 
172
189
  msa.trim(
173
190
  mode,
174
191
  gap_threshold=gaps,
175
192
  site_positions_to_trim=site_positions_to_trim,
193
+ guide_tree=guide_tree,
176
194
  codon=codon,
177
195
  ends_only=ends_only,
178
196
  )
@@ -208,6 +226,7 @@ def execute(
208
226
  dry_run: bool = False,
209
227
  validate_only: bool = False,
210
228
  report_json: Union[str, None] = None,
229
+ plot_trim_report: Union[str, None] = None,
211
230
  auxiliary_file: str = None,
212
231
  threads: int = 1,
213
232
  **kwargs,
@@ -374,6 +393,16 @@ def execute(
374
393
  ),
375
394
  )
376
395
 
396
+ if plot_trim_report:
397
+ write_trim_plot_report(
398
+ plot_trim_report,
399
+ trim_run.msa,
400
+ mode=mode.value,
401
+ gaps=trim_run.gaps,
402
+ sequence_type=trim_run.sequence_type.value,
403
+ )
404
+ logger.info(f"Wrote trim plot report to {plot_trim_report}")
405
+
377
406
  write_output_stats(stats, start_time)
378
407
  finally:
379
408
  if fh is not None:
@@ -394,7 +423,13 @@ def main(argv=None):
394
423
  Function that parses and collects arguments
395
424
  """
396
425
  parser = create_parser()
397
- args = parser.parse_args()
426
+ argv = sys.argv[1:] if argv is None else argv
427
+
428
+ if len(argv) == 0:
429
+ parser.print_help(sys.stderr)
430
+ return
431
+
432
+ args = parser.parse_args(argv)
398
433
 
399
434
  execute(**process_args(args))
400
435
 
@@ -0,0 +1,26 @@
1
+ from Bio.Align import MultipleSeqAlignment
2
+ from Bio.Phylo.BaseTree import Tree
3
+ from Bio.Phylo.TreeConstruction import (
4
+ DistanceCalculator,
5
+ DistanceTreeConstructor,
6
+ NNITreeSearcher,
7
+ ParsimonyScorer,
8
+ ParsimonyTreeConstructor,
9
+ )
10
+
11
+
12
+ def build_parsimony_guide_tree(alignment: MultipleSeqAlignment) -> Tree:
13
+ """
14
+ Build a parsimony guide tree for heterotachy-aware trimming.
15
+
16
+ Uses an NJ tree from identity distances as a start tree, followed by
17
+ NNI-based parsimony optimization.
18
+ """
19
+ distance_calculator = DistanceCalculator("identity")
20
+ distance_matrix = distance_calculator.get_distance(alignment)
21
+ nj_tree = DistanceTreeConstructor().nj(distance_matrix)
22
+
23
+ parsimony_scorer = ParsimonyScorer()
24
+ tree_searcher = NNITreeSearcher(parsimony_scorer)
25
+ parsimony_constructor = ParsimonyTreeConstructor(tree_searcher, nj_tree)
26
+ return parsimony_constructor.build_tree(alignment)
@@ -9,7 +9,11 @@ if TYPE_CHECKING:
9
9
 
10
10
  class TrimmingMode(Enum):
11
11
  gappy = "gappy"
12
+ block_gappy = "block-gappy"
13
+ gappyout = "gappyout"
12
14
  entropy = "entropy"
15
+ composition_bias = "composition-bias"
16
+ heterotachy = "heterotachy"
13
17
  smart_gap = "smart-gap"
14
18
  kpi = "kpi" # keep parsimony informative sites
15
19
  kpi_gappy = "kpi-gappy"
@@ -5,9 +5,9 @@ import numpy as np
5
5
  import math
6
6
  from itertools import chain
7
7
  from typing import Union
8
- from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor, as_completed
9
- from multiprocessing import Pool, cpu_count
10
- from functools import lru_cache
8
+ from concurrent.futures import ThreadPoolExecutor
9
+ from multiprocessing import cpu_count
10
+ from Bio.Phylo.BaseTree import Tree
11
11
 
12
12
  from .modes import TrimmingMode
13
13
  # Always import the standard version for compatibility
@@ -16,10 +16,6 @@ from .site_classification import (
16
16
  determine_site_classification_type,
17
17
  )
18
18
 
19
- # Optimizations are built-in, no need for external modules
20
- USE_OPTIMIZED = True
21
- batch_classify_sites_wrapper = None
22
- calculate_column_frequency_fast = None
23
19
  from .settings import DEFAULT_AA_GAP_CHARS
24
20
  from .stats import TrimmingStats
25
21
 
@@ -78,22 +74,6 @@ def _batch_column_frequencies(seq_array, gap_chars, batch_size=100, normalize_ca
78
74
  return column_frequencies
79
75
 
80
76
 
81
- # Module-level helper functions for parallel processing
82
- def _calculate_column_frequency_helper(args):
83
- """Helper function for parallel processing of column frequencies"""
84
- column, gap_chars = args
85
- col_sorted_unique_values_for, col_counts_per_char = np.unique(
86
- column, return_counts=True
87
- )
88
- freqs = dict(zip(col_sorted_unique_values_for, col_counts_per_char))
89
- for gap_char in gap_chars:
90
- try:
91
- del freqs[gap_char]
92
- except KeyError:
93
- continue
94
- return freqs
95
-
96
-
97
77
  def _calculate_column_frequency_batch_helper(args):
98
78
  """Batch helper for threaded frequency calculation."""
99
79
  columns, gap_chars = args
@@ -131,6 +111,7 @@ class MSA:
131
111
  # Cache for expensive computations
132
112
  self._site_gappyness_cache = None
133
113
  self._site_entropy_cache = None
114
+ self._site_composition_bias_cache = None
134
115
 
135
116
  @staticmethod
136
117
  def from_bio_msa(alignment: MultipleSeqAlignment, gap_chars=None, threads=1) -> "MSA":
@@ -253,6 +234,39 @@ class MSA:
253
234
  self._site_entropy_cache = np.around(entropies, decimals=4)
254
235
  return self._site_entropy_cache
255
236
 
237
+ @property
238
+ def site_composition_bias(self) -> np.ndarray:
239
+ """
240
+ Per-site composition bias score in [0, 1], excluding gap characters.
241
+ Higher values indicate stronger dominance by one/few character states.
242
+ """
243
+ if self._site_composition_bias_cache is not None:
244
+ return self._site_composition_bias_cache
245
+
246
+ col_char_freqs = self.column_character_frequencies
247
+ bias_scores = np.zeros(len(col_char_freqs), dtype=float)
248
+
249
+ for idx, char_freqs in enumerate(col_char_freqs):
250
+ counts = np.array(list(char_freqs.values()), dtype=float)
251
+ total = counts.sum()
252
+
253
+ if total == 0:
254
+ bias_scores[idx] = 0.0
255
+ continue
256
+
257
+ n_states = len(counts)
258
+ if n_states == 1:
259
+ bias_scores[idx] = 1.0
260
+ continue
261
+
262
+ probs = counts / total
263
+ dominance = float(np.sum(np.square(probs)))
264
+ min_dominance = 1.0 / float(n_states)
265
+ bias_scores[idx] = (dominance - min_dominance) / (1.0 - min_dominance)
266
+
267
+ self._site_composition_bias_cache = np.around(bias_scores, decimals=4)
268
+ return self._site_composition_bias_cache
269
+
256
270
  @property
257
271
  def stats(self) -> TrimmingStats:
258
272
  return TrimmingStats(self)
@@ -270,6 +284,7 @@ class MSA:
270
284
  mode: TrimmingMode = TrimmingMode.smart_gap,
271
285
  gap_threshold=None,
272
286
  site_positions_to_trim=None,
287
+ guide_tree: Union[Tree, None] = None,
273
288
  codon=False,
274
289
  ends_only=False,
275
290
  ) -> np.array:
@@ -288,8 +303,9 @@ class MSA:
288
303
  self._site_positions_to_trim = self.determine_site_positions_to_trim(
289
304
  mode,
290
305
  gap_threshold,
291
- codon,
292
- ends_only,
306
+ guide_tree=guide_tree,
307
+ codon=codon,
308
+ ends_only=ends_only,
293
309
  )
294
310
  if len(self._site_positions_to_trim) > 0:
295
311
  self._site_positions_to_keep = np.delete(
@@ -381,13 +397,27 @@ class MSA:
381
397
  self,
382
398
  mode,
383
399
  gap_threshold,
400
+ guide_tree=None,
384
401
  codon=False,
385
402
  ends_only=False,
386
403
  ):
387
404
  if mode in (TrimmingMode.gappy, TrimmingMode.smart_gap):
388
405
  sites_to_trim = np.where(self.site_gappyness >= gap_threshold)[0]
406
+ elif mode == TrimmingMode.block_gappy:
407
+ high_gap_sites = np.where(self.site_gappyness >= gap_threshold)[0]
408
+ sites_to_trim = self._retain_contiguous_sites(high_gap_sites, min_block_size=2)
409
+ elif mode == TrimmingMode.gappyout:
410
+ # Keep sites at the inferred boundary and trim strictly above it.
411
+ sites_to_trim = np.where(self.site_gappyness > gap_threshold)[0]
389
412
  elif mode == TrimmingMode.entropy:
390
413
  sites_to_trim = np.where(self.site_entropy >= gap_threshold)[0]
414
+ elif mode == TrimmingMode.composition_bias:
415
+ sites_to_trim = np.where(self.site_composition_bias >= gap_threshold)[0]
416
+ elif mode == TrimmingMode.heterotachy:
417
+ if guide_tree is None:
418
+ raise ValueError("heterotachy mode requires a guide tree")
419
+ site_heterotachy = self.determine_site_heterotachy(guide_tree)
420
+ sites_to_trim = np.where(site_heterotachy >= gap_threshold)[0]
391
421
  elif mode == TrimmingMode.kpi:
392
422
  site_classification_types = self.site_classification_types
393
423
  sites_to_trim = np.where(
@@ -443,6 +473,139 @@ class MSA:
443
473
 
444
474
  return sites_to_trim
445
475
 
476
+ def determine_site_heterotachy(self, guide_tree: Tree) -> np.ndarray:
477
+ """
478
+ Per-site heterotachy score in [0, 1] based on variation in clade-wise
479
+ normalized entropy across internal clades of a guide tree.
480
+ """
481
+ clade_indices = self._get_internal_clade_indices(guide_tree)
482
+ n_sites = self.seq_records.shape[1]
483
+ if not clade_indices:
484
+ return np.zeros(n_sites, dtype=float)
485
+
486
+ site_scores = np.zeros(n_sites, dtype=float)
487
+ for site_idx in range(n_sites):
488
+ clade_entropies = [
489
+ self._normalized_entropy_for_clade_site(indices, site_idx)
490
+ for indices in clade_indices
491
+ ]
492
+ if len(clade_entropies) < 2:
493
+ site_scores[site_idx] = 0.0
494
+ continue
495
+
496
+ # Standard deviation of values in [0, 1] is bounded by 0.5.
497
+ site_scores[site_idx] = min(1.0, float(np.std(clade_entropies) * 2.0))
498
+
499
+ return np.around(site_scores, decimals=4)
500
+
501
+ def _get_internal_clade_indices(self, guide_tree: Tree) -> list[list[int]]:
502
+ n_seqs = self.seq_records.shape[0]
503
+ if n_seqs < 3:
504
+ return []
505
+
506
+ terminal_to_index = {
507
+ str(info["id"]): idx for idx, info in enumerate(self.header_info)
508
+ }
509
+ clade_indices = []
510
+ seen = set()
511
+ for clade in guide_tree.find_clades(order="level"):
512
+ if clade.is_terminal():
513
+ continue
514
+
515
+ taxa_names = [str(t.name) for t in clade.get_terminals() if t.name is not None]
516
+ indices = sorted(
517
+ terminal_to_index[name]
518
+ for name in taxa_names
519
+ if name in terminal_to_index
520
+ )
521
+ if len(indices) < 2 or len(indices) >= n_seqs:
522
+ continue
523
+
524
+ key = tuple(indices)
525
+ if key in seen:
526
+ continue
527
+ seen.add(key)
528
+ clade_indices.append(indices)
529
+ return clade_indices
530
+
531
+ def _normalized_entropy_for_clade_site(
532
+ self,
533
+ clade_indices: list[int],
534
+ site_idx: int,
535
+ ) -> float:
536
+ column = self.seq_records[clade_indices, site_idx]
537
+ gap_chars_upper = {char.upper() for char in self._gap_chars}
538
+ non_gap = [char for char in column if char.upper() not in gap_chars_upper]
539
+
540
+ if len(non_gap) <= 1:
541
+ return 0.0
542
+
543
+ unique, counts = np.unique(non_gap, return_counts=True)
544
+ if len(unique) <= 1:
545
+ return 0.0
546
+
547
+ probs = counts.astype(float) / float(np.sum(counts))
548
+ raw_entropy = -float(np.sum(probs * np.log2(probs)))
549
+ max_entropy = math.log2(len(unique))
550
+ return raw_entropy / max_entropy if max_entropy > 0 else 0.0
551
+
552
+ @staticmethod
553
+ def _retain_contiguous_sites(
554
+ positions: np.ndarray,
555
+ min_block_size: int = 2,
556
+ ) -> np.ndarray:
557
+ if positions.size == 0:
558
+ return positions
559
+
560
+ contiguous_blocks = []
561
+ start = 0
562
+
563
+ for idx in range(1, len(positions) + 1):
564
+ is_break = idx == len(positions) or positions[idx] != positions[idx - 1] + 1
565
+ if not is_break:
566
+ continue
567
+
568
+ block = positions[start:idx]
569
+ if len(block) >= min_block_size:
570
+ contiguous_blocks.append(block)
571
+ start = idx
572
+
573
+ if not contiguous_blocks:
574
+ return np.array([], dtype=positions.dtype)
575
+
576
+ return np.concatenate(contiguous_blocks)
577
+
578
+ def determine_gappyout_gap_threshold(self) -> float:
579
+ """
580
+ Infer a gap threshold from the empirical gappyness distribution.
581
+
582
+ This gappyout-inspired heuristic finds the largest jump between
583
+ sorted per-site gappyness values and sets the threshold to the
584
+ midpoint of that jump. If no clear jump exists, it falls back to
585
+ a conservative high-quantile threshold.
586
+ """
587
+ gappyness = np.sort(self.site_gappyness.astype(float))
588
+ if gappyness.size == 0:
589
+ return 1.0
590
+
591
+ # Uniform distributions do not expose a natural split.
592
+ if np.allclose(gappyness, gappyness[0]):
593
+ return 1.0
594
+
595
+ jumps = np.diff(gappyness)
596
+ max_jump_idx = int(np.argmax(jumps))
597
+ max_jump = float(jumps[max_jump_idx])
598
+
599
+ if max_jump >= 0.1:
600
+ lower = float(gappyness[max_jump_idx])
601
+ upper = float(gappyness[max_jump_idx + 1])
602
+ threshold = (lower + upper) / 2.0
603
+ else:
604
+ threshold = float(np.quantile(gappyness, 0.95))
605
+ threshold = max(threshold, 0.9)
606
+
607
+ return round(max(0.0, min(1.0, threshold)), 4)
608
+
446
609
  def generate_debug_log_info(self):
447
610
  """
448
611
  Returns tuples of site position, keep or trim, site classification type, and gappyness