clipkit 2.12.1__tar.gz → 2.12.2__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 (37) hide show
  1. {clipkit-2.12.1 → clipkit-2.12.2}/PKG-INFO +1 -1
  2. {clipkit-2.12.1 → clipkit-2.12.2}/clipkit/clipkit.py +1 -0
  3. {clipkit-2.12.1 → clipkit-2.12.2}/clipkit/msa.py +155 -150
  4. {clipkit-2.12.1 → clipkit-2.12.2}/clipkit/smart_gap_helper.py +5 -3
  5. clipkit-2.12.2/clipkit/version.py +1 -0
  6. {clipkit-2.12.1 → clipkit-2.12.2}/clipkit.egg-info/PKG-INFO +1 -1
  7. clipkit-2.12.1/clipkit/version.py +0 -1
  8. {clipkit-2.12.1 → clipkit-2.12.2}/LICENSE.md +0 -0
  9. {clipkit-2.12.1 → clipkit-2.12.2}/README.md +0 -0
  10. {clipkit-2.12.1 → clipkit-2.12.2}/clipkit/__init__.py +0 -0
  11. {clipkit-2.12.1 → clipkit-2.12.2}/clipkit/__main__.py +0 -0
  12. {clipkit-2.12.1 → clipkit-2.12.2}/clipkit/api.py +0 -0
  13. {clipkit-2.12.1 → clipkit-2.12.2}/clipkit/args_processing.py +0 -0
  14. {clipkit-2.12.1 → clipkit-2.12.2}/clipkit/ecomp/__init__.py +0 -0
  15. {clipkit-2.12.1 → clipkit-2.12.2}/clipkit/ecomp/reader.py +0 -0
  16. {clipkit-2.12.1 → clipkit-2.12.2}/clipkit/ecomp/writer.py +0 -0
  17. {clipkit-2.12.1 → clipkit-2.12.2}/clipkit/exceptions.py +0 -0
  18. {clipkit-2.12.1 → clipkit-2.12.2}/clipkit/files.py +0 -0
  19. {clipkit-2.12.1 → clipkit-2.12.2}/clipkit/guide_tree.py +0 -0
  20. {clipkit-2.12.1 → clipkit-2.12.2}/clipkit/helpers.py +0 -0
  21. {clipkit-2.12.1 → clipkit-2.12.2}/clipkit/logger.py +0 -0
  22. {clipkit-2.12.1 → clipkit-2.12.2}/clipkit/modes.py +0 -0
  23. {clipkit-2.12.1 → clipkit-2.12.2}/clipkit/parser.py +0 -0
  24. {clipkit-2.12.1 → clipkit-2.12.2}/clipkit/plot_report.py +0 -0
  25. {clipkit-2.12.1 → clipkit-2.12.2}/clipkit/settings.py +0 -0
  26. {clipkit-2.12.1 → clipkit-2.12.2}/clipkit/site_classification.py +0 -0
  27. {clipkit-2.12.1 → clipkit-2.12.2}/clipkit/stats.py +0 -0
  28. {clipkit-2.12.1 → clipkit-2.12.2}/clipkit/warnings.py +0 -0
  29. {clipkit-2.12.1 → clipkit-2.12.2}/clipkit/write.py +0 -0
  30. {clipkit-2.12.1 → clipkit-2.12.2}/clipkit.egg-info/SOURCES.txt +0 -0
  31. {clipkit-2.12.1 → clipkit-2.12.2}/clipkit.egg-info/dependency_links.txt +0 -0
  32. {clipkit-2.12.1 → clipkit-2.12.2}/clipkit.egg-info/entry_points.txt +0 -0
  33. {clipkit-2.12.1 → clipkit-2.12.2}/clipkit.egg-info/requires.txt +0 -0
  34. {clipkit-2.12.1 → clipkit-2.12.2}/clipkit.egg-info/top_level.txt +0 -0
  35. {clipkit-2.12.1 → clipkit-2.12.2}/pyproject.toml +0 -0
  36. {clipkit-2.12.1 → clipkit-2.12.2}/setup.cfg +0 -0
  37. {clipkit-2.12.1 → clipkit-2.12.2}/setup.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: clipkit
3
- Version: 2.12.1
3
+ Version: 2.12.2
4
4
  Summary: Alignment trimming software for phylogenetics.
5
5
  Home-page: https://github.com/jlsteenwyk/clipkit
6
6
  Author: Jacob L. Steenwyk
@@ -182,6 +182,7 @@ def run(
182
182
  alignment,
183
183
  gap_characters,
184
184
  seq_records=msa.seq_records,
185
+ gaps_dist=msa.site_gappyness,
185
186
  )
186
187
  elif mode == TrimmingMode.gappyout:
187
188
  gaps = msa.determine_gappyout_gap_threshold()
@@ -3,10 +3,7 @@ from Bio.Seq import Seq
3
3
  from Bio.SeqRecord import SeqRecord
4
4
  import numpy as np
5
5
  import math
6
- from itertools import chain
7
6
  from typing import Union
8
- from concurrent.futures import ThreadPoolExecutor
9
- from multiprocessing import cpu_count
10
7
  from Bio.Phylo.BaseTree import Tree
11
8
 
12
9
  from .modes import TrimmingMode
@@ -20,72 +17,68 @@ from .settings import DEFAULT_AA_GAP_CHARS
20
17
  from .stats import TrimmingStats
21
18
 
22
19
 
23
- # Vectorized helper functions
24
- def _vectorized_column_frequencies(seq_array, gap_chars, normalize_case=True):
25
- """
26
- Vectorized calculation of character frequencies for all columns at once
27
- using NumPy operations.
28
- """
29
- n_cols = seq_array.shape[1]
30
- column_frequencies = []
31
-
32
- # Convert to uppercase once
33
- seq_array_upper = np.char.upper(seq_array) if normalize_case else seq_array
34
-
35
- for i in range(n_cols):
36
- column = seq_array_upper[:, i]
37
- unique, counts = np.unique(column, return_counts=True)
38
- freqs = dict(zip(unique, counts))
39
-
40
- # Remove gap characters
41
- for gap_char in gap_chars:
42
- freqs.pop(gap_char, None)
43
-
44
- column_frequencies.append(freqs)
45
-
46
- return column_frequencies
47
-
48
-
49
- def _batch_column_frequencies(seq_array, gap_chars, batch_size=100, normalize_case=True):
50
- """
51
- Process columns in batches for better memory efficiency
52
- """
53
- n_cols = seq_array.shape[1]
54
- column_frequencies = []
55
-
56
- # Convert to uppercase once for the entire array
57
- seq_array_upper = np.char.upper(seq_array) if normalize_case else seq_array
58
-
59
- for start_idx in range(0, n_cols, batch_size):
60
- end_idx = min(start_idx + batch_size, n_cols)
61
- batch = seq_array_upper[:, start_idx:end_idx]
62
-
63
- for i in range(batch.shape[1]):
64
- column = batch[:, i]
65
- unique, counts = np.unique(column, return_counts=True)
66
- freqs = dict(zip(unique, counts))
67
-
68
- # Remove gap characters
69
- for gap_char in gap_chars:
70
- freqs.pop(gap_char, None)
71
-
72
- column_frequencies.append(freqs)
73
-
74
- return column_frequencies
75
-
76
-
77
- def _calculate_column_frequency_batch_helper(args):
78
- """Batch helper for threaded frequency calculation."""
79
- columns, gap_chars = args
80
- frequencies = []
81
- for i in range(columns.shape[1]):
82
- column = columns[:, i]
83
- unique, counts = np.unique(column, return_counts=True)
84
- freqs = dict(zip(unique, counts))
85
- for gap_char in gap_chars:
86
- freqs.pop(gap_char, None)
87
- frequencies.append(freqs)
88
- return frequencies
20
+ # Counting a batch at a time bounds the temporary integer matrix while still
21
+ # letting np.bincount process many columns in one compiled operation.
22
+ _COLUMN_COUNT_BATCH_SIZE = 1024
23
+ _MAX_DENSE_CODE_SPAN = 512
24
+ _MIN_CELLS_FOR_COLUMN_COUNTING = 1_000_000
25
+
26
+
27
+ def _column_character_counts(seq_array: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
28
+ """Return sorted character states and their counts in every column."""
29
+ n_rows, n_cols = seq_array.shape
30
+ if n_rows == 0 or n_cols == 0:
31
+ return np.empty(0, dtype="U1"), np.empty((0, n_cols), dtype=np.int64)
32
+
33
+ if n_rows <= np.iinfo(np.uint8).max:
34
+ count_dtype = np.uint8
35
+ elif n_rows <= np.iinfo(np.uint16).max:
36
+ count_dtype = np.uint16
37
+ elif n_rows <= np.iinfo(np.uint32).max:
38
+ count_dtype = np.uint32
39
+ else:
40
+ count_dtype = np.uint64
41
+
42
+ code_points = seq_array.view(np.uint32).reshape(seq_array.shape)
43
+ min_code = int(code_points.min())
44
+ max_code = int(code_points.max())
45
+ code_span = max_code - min_code + 1
46
+
47
+ if code_span <= _MAX_DENSE_CODE_SPAN:
48
+ counts = np.empty((code_span, n_cols), dtype=count_dtype)
49
+ offsets = np.arange(_COLUMN_COUNT_BATCH_SIZE, dtype=np.int64) * code_span
50
+
51
+ for start_idx in range(0, n_cols, _COLUMN_COUNT_BATCH_SIZE):
52
+ end_idx = min(start_idx + _COLUMN_COUNT_BATCH_SIZE, n_cols)
53
+ width = end_idx - start_idx
54
+ encoded = code_points[:, start_idx:end_idx].astype(np.int64)
55
+ encoded -= min_code
56
+ encoded += offsets[:width]
57
+ counts[:, start_idx:end_idx] = np.bincount(
58
+ encoded.ravel(), minlength=width * code_span
59
+ ).reshape(width, code_span).T
60
+
61
+ present = np.any(counts, axis=1)
62
+ states = np.array(
63
+ [chr(min_code + offset) for offset in np.flatnonzero(present)],
64
+ dtype="U1",
65
+ )
66
+ return states, counts[present]
67
+
68
+ # Unusually wide Unicode alphabets would make the dense code-point table
69
+ # wasteful. Compact them to their observed, sorted states instead.
70
+ states = np.unique(seq_array)
71
+ counts = np.empty((len(states), n_cols), dtype=count_dtype)
72
+ offsets = np.arange(_COLUMN_COUNT_BATCH_SIZE, dtype=np.int64) * len(states)
73
+ for start_idx in range(0, n_cols, _COLUMN_COUNT_BATCH_SIZE):
74
+ end_idx = min(start_idx + _COLUMN_COUNT_BATCH_SIZE, n_cols)
75
+ width = end_idx - start_idx
76
+ encoded = np.searchsorted(states, seq_array[:, start_idx:end_idx])
77
+ encoded += offsets[:width]
78
+ counts[:, start_idx:end_idx] = np.bincount(
79
+ encoded.ravel(), minlength=width * len(states)
80
+ ).reshape(width, len(states)).T
81
+ return states, counts
89
82
 
90
83
 
91
84
  class MSA:
@@ -104,6 +97,7 @@ class MSA:
104
97
  self._site_positions_to_trim = np.array([])
105
98
  self._site_classification_types = None
106
99
  self._column_character_frequencies = None
100
+ self._column_character_count_cache = {}
107
101
  self._gap_chars = gap_chars or DEFAULT_AA_GAP_CHARS
108
102
  self._codon_size = 3
109
103
  self._threads = threads
@@ -152,12 +146,22 @@ class MSA:
152
146
 
153
147
  def _to_bio_msa(self, sites) -> MultipleSeqAlignment:
154
148
  # NOTE: we use the description as the id to preserve the full sequence description - see issue #20
149
+ if sites.shape[1] == 0:
150
+ sequence_rows = [""] * sites.shape[0]
151
+ elif sites.dtype.kind == "U" and sites.dtype.itemsize == np.dtype("U1").itemsize:
152
+ contiguous_sites = np.ascontiguousarray(sites)
153
+ sequence_rows = (
154
+ contiguous_sites.view(f"U{sites.shape[1]}").reshape(-1).tolist()
155
+ )
156
+ else:
157
+ sequence_rows = ["".join(rec) for rec in sites.tolist()]
158
+
155
159
  return MultipleSeqAlignment(
156
160
  [
157
161
  SeqRecord(
158
- Seq("".join(rec)), id=str(info["description"]), description=""
162
+ Seq(rec), id=str(info["description"]), description=""
159
163
  )
160
- for rec, info in zip(sites.tolist(), self.header_info)
164
+ for rec, info in zip(sequence_rows, self.header_info)
161
165
  ]
162
166
  )
163
167
 
@@ -192,9 +196,16 @@ class MSA:
192
196
  if self._site_gappyness_cache is not None:
193
197
  return self._site_gappyness_cache
194
198
 
195
- # Vectorized calculation using broadcasting
196
- site_gappyness = (np.isin(self.seq_records, self._gap_chars)).mean(axis=0)
199
+ if self.seq_records.size < _MIN_CELLS_FOR_COLUMN_COUNTING:
200
+ site_gappyness = np.isin(self.seq_records, self._gap_chars).mean(axis=0)
201
+ else:
202
+ states, counts = self._get_column_character_counts(
203
+ normalize_case=False, cache_key="gappyness"
204
+ )
205
+ gap_counts = counts[np.isin(states, self._gap_chars)].sum(axis=0)
206
+ site_gappyness = gap_counts / self.seq_records.shape[0]
197
207
  self._site_gappyness_cache = np.around(site_gappyness, decimals=4)
208
+ self._column_character_count_cache.pop(("gappyness", False), None)
198
209
  return self._site_gappyness_cache
199
210
 
200
211
  @property
@@ -211,24 +222,15 @@ class MSA:
211
222
  if self._site_entropy_cache is not None:
212
223
  return self._site_entropy_cache
213
224
 
214
- seq_array = (
215
- np.char.upper(self.seq_records)
216
- if self._requires_uppercase_normalization
217
- else self.seq_records
225
+ _, counts_by_state = self._get_non_gap_character_counts(
226
+ normalize_gap_chars=True, cache_key="entropy"
218
227
  )
219
- n_cols = seq_array.shape[1]
228
+ n_cols = counts_by_state.shape[1]
220
229
  entropies = np.zeros(n_cols, dtype=float)
221
- gap_chars_upper = {gap.upper() for gap in self._gap_chars}
222
230
 
223
231
  for col_idx in range(n_cols):
224
- column = seq_array[:, col_idx]
225
- unique, counts = np.unique(column, return_counts=True)
226
-
227
- non_gap_counts = [
228
- count
229
- for char, count in zip(unique, counts)
230
- if char.upper() not in gap_chars_upper
231
- ]
232
+ non_gap_counts = counts_by_state[:, col_idx]
233
+ non_gap_counts = non_gap_counts[non_gap_counts > 0]
232
234
 
233
235
  if len(non_gap_counts) <= 1:
234
236
  continue
@@ -240,6 +242,9 @@ class MSA:
240
242
  entropies[col_idx] = raw_entropy / max_entropy if max_entropy > 0 else 0.0
241
243
 
242
244
  self._site_entropy_cache = np.around(entropies, decimals=4)
245
+ self._column_character_count_cache.pop(
246
+ ("entropy", self._requires_uppercase_normalization), None
247
+ )
243
248
  return self._site_entropy_cache
244
249
 
245
250
  @property
@@ -251,11 +256,12 @@ class MSA:
251
256
  if self._site_composition_bias_cache is not None:
252
257
  return self._site_composition_bias_cache
253
258
 
254
- col_char_freqs = self.column_character_frequencies
255
- bias_scores = np.zeros(len(col_char_freqs), dtype=float)
259
+ _, counts_by_state = self._get_non_gap_character_counts()
260
+ bias_scores = np.zeros(counts_by_state.shape[1], dtype=float)
256
261
 
257
- for idx, char_freqs in enumerate(col_char_freqs):
258
- counts = np.array(list(char_freqs.values()), dtype=float)
262
+ for idx in range(counts_by_state.shape[1]):
263
+ counts = counts_by_state[:, idx]
264
+ counts = counts[counts > 0].astype(float)
259
265
  total = counts.sum()
260
266
 
261
267
  if total == 0:
@@ -325,77 +331,76 @@ class MSA:
325
331
  if self._column_character_frequencies is not None:
326
332
  return self._column_character_frequencies
327
333
 
328
- # Adaptive threshold based on alignment size and thread count
329
- # Lower threshold for better parallel efficiency
330
- parallel_threshold = max(1000, 5000 // self._threads)
331
-
332
- # Use vectorized or parallel processing based on size
333
- if self._original_length < 500:
334
- # Small alignments: use vectorized numpy operations
335
- self._column_character_frequencies = _vectorized_column_frequencies(
336
- self.seq_records,
337
- self.gap_chars,
338
- normalize_case=self._requires_uppercase_normalization,
339
- )
340
- elif self._threads > 1 and self._original_length > parallel_threshold:
341
- # Large alignments with multiple threads: use thread-level parallelism
342
- # to avoid process-pool serialization overhead.
343
- seq_array_upper = (
344
- np.char.upper(self.seq_records)
345
- if self._requires_uppercase_normalization
346
- else self.seq_records
347
- )
348
-
349
- # Dynamic worker calculation
350
- n_workers = min(self._threads, max(2, min(self._original_length // 500, cpu_count())))
351
-
352
- # Batch columns to avoid creating one task per column.
353
- batch_size = max(200, self._original_length // (n_workers * 8))
354
- args_list = [
355
- (seq_array_upper[:, start_idx:min(start_idx + batch_size, self._original_length)], self.gap_chars)
356
- for start_idx in range(0, self._original_length, batch_size)
357
- ]
358
-
359
- with ThreadPoolExecutor(max_workers=n_workers) as executor:
360
- batch_results = list(
361
- executor.map(
362
- _calculate_column_frequency_batch_helper,
363
- args_list,
334
+ states, counts_by_state = self._get_non_gap_character_counts()
335
+ self._column_character_frequencies = []
336
+ for col_idx in range(counts_by_state.shape[1]):
337
+ present = counts_by_state[:, col_idx] > 0
338
+ self._column_character_frequencies.append(
339
+ dict(
340
+ zip(
341
+ states[present],
342
+ counts_by_state[present, col_idx].astype(np.int64),
364
343
  )
365
344
  )
366
- self._column_character_frequencies = list(
367
- chain.from_iterable(batch_results)
368
- )
369
- else:
370
- # Medium alignments or single-threaded: use batch processing
371
- self._column_character_frequencies = _batch_column_frequencies(
372
- self.seq_records,
373
- self.gap_chars,
374
- batch_size=200,
375
- normalize_case=self._requires_uppercase_normalization,
376
345
  )
377
346
 
378
- # Ensure we always return the frequencies (not None)
379
- if self._column_character_frequencies is None:
380
- self._column_character_frequencies = _batch_column_frequencies(
381
- self.seq_records,
382
- self.gap_chars,
383
- batch_size=200,
384
- normalize_case=self._requires_uppercase_normalization,
347
+ return self._column_character_frequencies
348
+
349
+ def _get_column_character_counts(
350
+ self, normalize_case: bool, cache_key: str = "frequencies"
351
+ ) -> tuple[np.ndarray, np.ndarray]:
352
+ normalize_case = normalize_case and self._requires_uppercase_normalization
353
+ key = (cache_key, normalize_case)
354
+ if key not in self._column_character_count_cache:
355
+ seq_array = (
356
+ np.char.upper(self.seq_records)
357
+ if normalize_case
358
+ else self.seq_records
385
359
  )
360
+ self._column_character_count_cache[key] = _column_character_counts(seq_array)
361
+ return self._column_character_count_cache[key]
386
362
 
387
- return self._column_character_frequencies
363
+ def _get_non_gap_character_counts(
364
+ self,
365
+ normalize_gap_chars: bool = False,
366
+ cache_key: str = "frequencies",
367
+ ) -> tuple[np.ndarray, np.ndarray]:
368
+ states, counts = self._get_column_character_counts(
369
+ normalize_case=True, cache_key=cache_key
370
+ )
371
+ gap_chars = (
372
+ [gap.upper() for gap in self._gap_chars]
373
+ if normalize_gap_chars
374
+ else self._gap_chars
375
+ )
376
+ non_gap_states = ~np.isin(states, gap_chars)
377
+ return states[non_gap_states], counts[non_gap_states]
388
378
 
389
379
  @property
390
380
  def site_classification_types(self):
391
381
  if self._site_classification_types is not None:
392
382
  return self._site_classification_types
393
383
 
394
- col_char_freqs = self.column_character_frequencies
395
- # Local classification avoids high process-pool overhead from pickling
396
- # tens of thousands of per-column dict objects.
397
- site_classification_types = np.array(
398
- [determine_site_classification_type(freq) for freq in col_char_freqs]
384
+ if self._original_length == 0:
385
+ self._site_classification_types = np.array([])
386
+ return self._site_classification_types
387
+
388
+ _, counts_by_state = self._get_non_gap_character_counts()
389
+ observed_states = np.count_nonzero(counts_by_state, axis=0)
390
+ states_occurring_at_least_twice = np.count_nonzero(
391
+ counts_by_state >= 2, axis=0
392
+ )
393
+
394
+ site_classification_types = np.empty(self._original_length, dtype=object)
395
+ site_classification_types.fill(SiteClassificationType.other)
396
+ site_classification_types[
397
+ (states_occurring_at_least_twice == 1) & (observed_states > 1)
398
+ ] = SiteClassificationType.singleton
399
+ site_classification_types[
400
+ (states_occurring_at_least_twice == 1) & (observed_states == 1)
401
+ ] = SiteClassificationType.constant
402
+ site_classification_types[states_occurring_at_least_twice >= 2] = (
403
+ SiteClassificationType.parsimony_informative
399
404
  )
400
405
 
401
406
  self._site_classification_types = site_classification_types
@@ -9,6 +9,7 @@ def smart_gap_threshold_determination(
9
9
  alignment: MultipleSeqAlignment,
10
10
  gap_chars: list,
11
11
  seq_records: Optional[np.ndarray] = None,
12
+ gaps_dist: Optional[np.ndarray] = None,
12
13
  ) -> float:
13
14
  alignment_length = (
14
15
  seq_records.shape[1]
@@ -17,9 +18,10 @@ def smart_gap_threshold_determination(
17
18
  )
18
19
 
19
20
  # get distribution of gaps rounded to the fourth decimal place
20
- gaps_dist = get_gaps_distribution_optimized(
21
- alignment, gap_chars, seq_records=seq_records
22
- )
21
+ if gaps_dist is None:
22
+ gaps_dist = get_gaps_distribution_optimized(
23
+ alignment, gap_chars, seq_records=seq_records
24
+ )
23
25
 
24
26
  # count freq of gaps and convert to sorted np array
25
27
  gaps_arr = count_and_sort_gaps_optimized(gaps_dist)
@@ -0,0 +1 @@
1
+ __version__ = "2.12.2"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: clipkit
3
- Version: 2.12.1
3
+ Version: 2.12.2
4
4
  Summary: Alignment trimming software for phylogenetics.
5
5
  Home-page: https://github.com/jlsteenwyk/clipkit
6
6
  Author: Jacob L. Steenwyk
@@ -1 +0,0 @@
1
- __version__ = "2.12.1"
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes