seqtree 1.3.3__tar.gz → 1.4.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.
- {seqtree-1.3.3 → seqtree-1.4.0}/CHANGELOG.md +10 -0
- {seqtree-1.3.3 → seqtree-1.4.0}/CMakeLists.txt +1 -0
- {seqtree-1.3.3 → seqtree-1.4.0}/PKG-INFO +27 -28
- {seqtree-1.3.3 → seqtree-1.4.0}/README.md +26 -27
- seqtree-1.4.0/assets/workflow-dark.svg +70 -0
- seqtree-1.4.0/assets/workflow-light.svg +70 -0
- seqtree-1.4.0/assets/workflow.png +0 -0
- seqtree-1.4.0/include/seqtree/parallel.hpp +252 -0
- seqtree-1.4.0/include/seqtree/ranked_neighborhood.hpp +32 -0
- {seqtree-1.3.3 → seqtree-1.4.0}/pyproject.toml +1 -1
- {seqtree-1.3.3 → seqtree-1.4.0}/python/seqtree/gapblock.py +2 -2
- {seqtree-1.3.3 → seqtree-1.4.0}/src/_bindings.cpp +71 -0
- {seqtree-1.3.3 → seqtree-1.4.0}/src/gapblock.cpp +2 -2
- seqtree-1.4.0/src/ranked_neighborhood.cpp +144 -0
- seqtree-1.3.3/include/seqtree/parallel.hpp +0 -134
- {seqtree-1.3.3 → seqtree-1.4.0}/.gitattributes +0 -0
- {seqtree-1.3.3 → seqtree-1.4.0}/.gitignore +0 -0
- {seqtree-1.3.3 → seqtree-1.4.0}/LICENSE +0 -0
- {seqtree-1.3.3 → seqtree-1.4.0}/include/seqtree/kmer_index.hpp +0 -0
- {seqtree-1.3.3 → seqtree-1.4.0}/include/seqtree/seqtree.hpp +0 -0
- {seqtree-1.3.3 → seqtree-1.4.0}/include/seqtree/text_index.hpp +0 -0
- {seqtree-1.3.3 → seqtree-1.4.0}/include/seqtree/types.hpp +0 -0
- {seqtree-1.3.3 → seqtree-1.4.0}/python/seqtree/__init__.py +0 -0
- {seqtree-1.3.3 → seqtree-1.4.0}/python/seqtree/control.py +0 -0
- {seqtree-1.3.3 → seqtree-1.4.0}/python/seqtree/data/control_human_trb_aa.txt.gz +0 -0
- {seqtree-1.3.3 → seqtree-1.4.0}/python/seqtree/distance.py +0 -0
- {seqtree-1.3.3 → seqtree-1.4.0}/python/seqtree/evalue.py +0 -0
- {seqtree-1.3.3 → seqtree-1.4.0}/python/seqtree/layout.py +0 -0
- {seqtree-1.3.3 → seqtree-1.4.0}/python/seqtree/pairwise.py +0 -0
- {seqtree-1.3.3 → seqtree-1.4.0}/python/seqtree/pmhc.py +0 -0
- {seqtree-1.3.3 → seqtree-1.4.0}/python/seqtree/pmhc_evalue.py +0 -0
- {seqtree-1.3.3 → seqtree-1.4.0}/python/seqtree/py.typed +0 -0
- {seqtree-1.3.3 → seqtree-1.4.0}/python/seqtree/seeds.py +0 -0
- {seqtree-1.3.3 → seqtree-1.4.0}/python/seqtree/text_evalue.py +0 -0
- {seqtree-1.3.3 → seqtree-1.4.0}/src/alignment_max.cpp +0 -0
- {seqtree-1.3.3 → seqtree-1.4.0}/src/atomic_write.hpp +0 -0
- {seqtree-1.3.3 → seqtree-1.4.0}/src/blosum45.inc +0 -0
- {seqtree-1.3.3 → seqtree-1.4.0}/src/blosum62.inc +0 -0
- {seqtree-1.3.3 → seqtree-1.4.0}/src/blosum80.inc +0 -0
- {seqtree-1.3.3 → seqtree-1.4.0}/src/codec.cpp +0 -0
- {seqtree-1.3.3 → seqtree-1.4.0}/src/count_unit.hpp +0 -0
- {seqtree-1.3.3 → seqtree-1.4.0}/src/distance.cpp +0 -0
- {seqtree-1.3.3 → seqtree-1.4.0}/src/engine_seqtm.cpp +0 -0
- {seqtree-1.3.3 → seqtree-1.4.0}/src/engine_seqtrie.cpp +0 -0
- {seqtree-1.3.3 → seqtree-1.4.0}/src/engines.hpp +0 -0
- {seqtree-1.3.3 → seqtree-1.4.0}/src/index.cpp +0 -0
- {seqtree-1.3.3 → seqtree-1.4.0}/src/kmer_index.cpp +0 -0
- {seqtree-1.3.3 → seqtree-1.4.0}/src/pairwise.cpp +0 -0
- {seqtree-1.3.3 → seqtree-1.4.0}/src/pairwise_detail.hpp +0 -0
- {seqtree-1.3.3 → seqtree-1.4.0}/src/pam100.inc +0 -0
- {seqtree-1.3.3 → seqtree-1.4.0}/src/pam250.inc +0 -0
- {seqtree-1.3.3 → seqtree-1.4.0}/src/positional_matrix.cpp +0 -0
- {seqtree-1.3.3 → seqtree-1.4.0}/src/searcher.cpp +0 -0
- {seqtree-1.3.3 → seqtree-1.4.0}/src/structural.inc +0 -0
- {seqtree-1.3.3 → seqtree-1.4.0}/src/substitution_matrix.cpp +0 -0
- {seqtree-1.3.3 → seqtree-1.4.0}/src/text_index.cpp +0 -0
- {seqtree-1.3.3 → seqtree-1.4.0}/src/trie.cpp +0 -0
- {seqtree-1.3.3 → seqtree-1.4.0}/src/trie.hpp +0 -0
|
@@ -5,6 +5,16 @@ versioning: breaking changes need a **major** bump.
|
|
|
5
5
|
|
|
6
6
|
## Unreleased
|
|
7
7
|
|
|
8
|
+
## 1.4.0
|
|
9
|
+
|
|
10
|
+
- Add a native grouped ranked-neighborhood reducer with tie-inclusive radii,
|
|
11
|
+
fixed target and competitor pools, optional weights, and bounded output.
|
|
12
|
+
|
|
13
|
+
## 1.3.4
|
|
14
|
+
|
|
15
|
+
- Clamp oversized CPU/thread requests to the available budget instead of aborting.
|
|
16
|
+
Preserve automatic selection, explicit smaller budgets and bounded native workers.
|
|
17
|
+
|
|
8
18
|
## 1.3.3
|
|
9
19
|
|
|
10
20
|
- Cap automatic native CPU budgets at 16 allocated CPUs; preserve larger explicit
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.2
|
|
2
2
|
Name: seqtree
|
|
3
|
-
Version: 1.
|
|
3
|
+
Version: 1.4.0
|
|
4
4
|
Summary: Fast fuzzy search over biological sequences (C++ core, Python bindings)
|
|
5
5
|
Keywords: sequence-search,fuzzy-matching,CDR3,immunology,bioinformatics,trie
|
|
6
6
|
Author-Email: ISALGO laboratory <mikhail.shugay@gmail.com>
|
|
@@ -42,6 +42,12 @@ Fast fuzzy search over biological sequences (amino-acid or nucleotide), as a C++
|
|
|
42
42
|
core with a minimal Python binding. Build an immutable index once, then search
|
|
43
43
|
single queries or massive batches in parallel.
|
|
44
44
|
|
|
45
|
+
<picture>
|
|
46
|
+
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/antigenomics/seqtree/master/assets/workflow-dark.svg">
|
|
47
|
+
<source srcset="https://raw.githubusercontent.com/antigenomics/seqtree/master/assets/workflow-light.svg">
|
|
48
|
+
<img alt="seqtree workflow: inputs, batched processing and outputs. Schematic illustrations." src="https://raw.githubusercontent.com/antigenomics/seqtree/master/assets/workflow.png" width="100%">
|
|
49
|
+
</picture>
|
|
50
|
+
|
|
45
51
|
## Install
|
|
46
52
|
|
|
47
53
|
```fish
|
|
@@ -52,7 +58,7 @@ Prebuilt wheels cover **Linux x86-64**, **macOS arm64 (Apple Silicon)**, and **W
|
|
|
52
58
|
There are **no Intel/x86-64 macOS wheels** — Intel Macs build from source (see below), which just
|
|
53
59
|
needs a C++20 compiler and CMake (pulled in automatically by the build).
|
|
54
60
|
|
|
55
|
-
##
|
|
61
|
+
## Quick start
|
|
56
62
|
|
|
57
63
|
```python
|
|
58
64
|
import seqtree
|
|
@@ -63,29 +69,12 @@ p = seqtree.SearchParams(max_subs=2, engine="seqtm")
|
|
|
63
69
|
for hit in idx.search("CASSLAPGATNEKLFF", p):
|
|
64
70
|
print(hit.ref_id, hit.score, hit.n_subs)
|
|
65
71
|
|
|
66
|
-
#
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
# matrix-weighted budget. Name seqtrie -- engine="auto" always means seqtm.
|
|
70
|
-
# gap_open must follow the matrix: 2 * blosum62.scale() == 28, not the default 1.
|
|
71
|
-
pm = seqtree.SearchParams(matrix="blosum62", max_penalty=12, engine="seqtrie", gap_open=28)
|
|
72
|
-
top = idx.search_top("CASSLAPGATNEKLFF", pm, k=5)
|
|
73
|
-
|
|
74
|
-
# alignment on demand
|
|
75
|
-
aln = idx.align(0, "CASSLELGATNEKLFF", p)
|
|
76
|
-
print(aln.aligned_query, aln.aligned_ref, aln.ops)
|
|
77
|
-
|
|
78
|
-
# batch-vs-batch (auto-indexes the larger set)
|
|
79
|
-
pairs = seqtree.pairwise_batch(query_set, db_set, p, alphabet="aa")
|
|
80
|
-
|
|
81
|
-
# a short query against a long TEXT (a proteome), one index for every query length
|
|
82
|
-
tix = seqtree.TextIndex.build(proteome_records, alphabet="aa", k=4)
|
|
83
|
-
res = tix.search_batch(peptides, max_subs=2, threads=0)
|
|
84
|
-
for hit in res[0]:
|
|
85
|
-
print(hit.ref_id, hit.offset, hit.n_subs, hit.mismatches)
|
|
72
|
+
# Batch search uses the automatic budget (allocated physical cores).
|
|
73
|
+
queries = ["CASSLAPGATNEKLFF", "CASSLELGATNEKLFF"]
|
|
74
|
+
results = idx.search_batch(queries, p)
|
|
86
75
|
```
|
|
87
76
|
|
|
88
|
-
|
|
77
|
+
Significance, gap blocks, alignment and distances are in
|
|
89
78
|
[More examples](#more-examples) below, and the
|
|
90
79
|
[docs](https://antigenomics.github.io/seqtree/) explain the why.
|
|
91
80
|
|
|
@@ -168,7 +157,7 @@ Beyond search, seqtree ships:
|
|
|
168
157
|
C++ call (`numpy.asarray` wraps the result with no copy) — no `python-Levenshtein` or `rapidfuzz`
|
|
169
158
|
dependency needed. Hamming requires equal lengths (it raises otherwise); comparison is
|
|
170
159
|
case-sensitive. The same module *enumerates* a Hamming ball as well as scoring one:
|
|
171
|
-
`neighbourhood(seq, r)` lists its `19·L + 1` members, and `neighbourhood_union(seqs, r)` takes
|
|
160
|
+
`neighbourhood(seq, r=1)` lists its `19·L + 1` amino-acid members, and `neighbourhood_union(seqs, r)` takes
|
|
172
161
|
the union over many centres with each distinct sequence emitted **once** — deduplicated during
|
|
173
162
|
the walk, so the `Σ 19·L_i` multiset never exists. For a tight specificity group that is a 41.7%
|
|
174
163
|
saving, not a rounding correction.
|
|
@@ -278,6 +267,20 @@ Figures (throughput, scaling, matrix-scoring overhead, collisions, E-value matri
|
|
|
278
267
|
detection) and the full methodology are in the [benchmarks docs](https://antigenomics.github.io/seqtree/benchmarks.html).
|
|
279
268
|
Set `RUN_BENCHMARK=1` for the large tiers.
|
|
280
269
|
|
|
270
|
+
## Parallel processing
|
|
271
|
+
|
|
272
|
+
CPU budgets use `threads=0` for automatic parallel work, using physical cores within the allocation.
|
|
273
|
+
Use `1` for serial work or a positive
|
|
274
|
+
count to select logical CPUs within the scheduler/container allocation.
|
|
275
|
+
|
|
276
|
+
Automatic sizing counts distinct physical cores within the process affinity mask,
|
|
277
|
+
then respects scheduler and container limits. When topology is unavailable, it
|
|
278
|
+
uses the available logical CPU count. A 40-logical-CPU, 20-core node therefore
|
|
279
|
+
uses up to 20 workers automatically; an explicit budget may use SMT threads.
|
|
280
|
+
Windows uses native core topology, process affinity and the current job CPU-rate
|
|
281
|
+
limit. Processes spanning processor groups must be bound to one group. Parent
|
|
282
|
+
job quotas are not exposed by this query; supply a budget within any parent limit.
|
|
283
|
+
|
|
281
284
|
## Development
|
|
282
285
|
|
|
283
286
|
This repo follows **git-flow**:
|
|
@@ -305,7 +308,3 @@ and tie, count, exclusion and unsupported-value semantics.
|
|
|
305
308
|
|
|
306
309
|
The public [seqtree skill](skills/seqtree/SKILL.md) guides use of the C++20 library
|
|
307
310
|
and Python bindings for sequence search, alignment, distances, and batch operations.
|
|
308
|
-
|
|
309
|
-
CPU budgets use `threads=0` for automatic parallel work, capped at 16 allocated CPUs.
|
|
310
|
-
Use `1` for serial work or a positive
|
|
311
|
-
count to override the automatic cap within the scheduler/container allocation.
|
|
@@ -10,6 +10,12 @@ Fast fuzzy search over biological sequences (amino-acid or nucleotide), as a C++
|
|
|
10
10
|
core with a minimal Python binding. Build an immutable index once, then search
|
|
11
11
|
single queries or massive batches in parallel.
|
|
12
12
|
|
|
13
|
+
<picture>
|
|
14
|
+
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/antigenomics/seqtree/master/assets/workflow-dark.svg">
|
|
15
|
+
<source srcset="https://raw.githubusercontent.com/antigenomics/seqtree/master/assets/workflow-light.svg">
|
|
16
|
+
<img alt="seqtree workflow: inputs, batched processing and outputs. Schematic illustrations." src="https://raw.githubusercontent.com/antigenomics/seqtree/master/assets/workflow.png" width="100%">
|
|
17
|
+
</picture>
|
|
18
|
+
|
|
13
19
|
## Install
|
|
14
20
|
|
|
15
21
|
```fish
|
|
@@ -20,7 +26,7 @@ Prebuilt wheels cover **Linux x86-64**, **macOS arm64 (Apple Silicon)**, and **W
|
|
|
20
26
|
There are **no Intel/x86-64 macOS wheels** — Intel Macs build from source (see below), which just
|
|
21
27
|
needs a C++20 compiler and CMake (pulled in automatically by the build).
|
|
22
28
|
|
|
23
|
-
##
|
|
29
|
+
## Quick start
|
|
24
30
|
|
|
25
31
|
```python
|
|
26
32
|
import seqtree
|
|
@@ -31,29 +37,12 @@ p = seqtree.SearchParams(max_subs=2, engine="seqtm")
|
|
|
31
37
|
for hit in idx.search("CASSLAPGATNEKLFF", p):
|
|
32
38
|
print(hit.ref_id, hit.score, hit.n_subs)
|
|
33
39
|
|
|
34
|
-
#
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
# matrix-weighted budget. Name seqtrie -- engine="auto" always means seqtm.
|
|
38
|
-
# gap_open must follow the matrix: 2 * blosum62.scale() == 28, not the default 1.
|
|
39
|
-
pm = seqtree.SearchParams(matrix="blosum62", max_penalty=12, engine="seqtrie", gap_open=28)
|
|
40
|
-
top = idx.search_top("CASSLAPGATNEKLFF", pm, k=5)
|
|
41
|
-
|
|
42
|
-
# alignment on demand
|
|
43
|
-
aln = idx.align(0, "CASSLELGATNEKLFF", p)
|
|
44
|
-
print(aln.aligned_query, aln.aligned_ref, aln.ops)
|
|
45
|
-
|
|
46
|
-
# batch-vs-batch (auto-indexes the larger set)
|
|
47
|
-
pairs = seqtree.pairwise_batch(query_set, db_set, p, alphabet="aa")
|
|
48
|
-
|
|
49
|
-
# a short query against a long TEXT (a proteome), one index for every query length
|
|
50
|
-
tix = seqtree.TextIndex.build(proteome_records, alphabet="aa", k=4)
|
|
51
|
-
res = tix.search_batch(peptides, max_subs=2, threads=0)
|
|
52
|
-
for hit in res[0]:
|
|
53
|
-
print(hit.ref_id, hit.offset, hit.n_subs, hit.mismatches)
|
|
40
|
+
# Batch search uses the automatic budget (allocated physical cores).
|
|
41
|
+
queries = ["CASSLAPGATNEKLFF", "CASSLELGATNEKLFF"]
|
|
42
|
+
results = idx.search_batch(queries, p)
|
|
54
43
|
```
|
|
55
44
|
|
|
56
|
-
|
|
45
|
+
Significance, gap blocks, alignment and distances are in
|
|
57
46
|
[More examples](#more-examples) below, and the
|
|
58
47
|
[docs](https://antigenomics.github.io/seqtree/) explain the why.
|
|
59
48
|
|
|
@@ -136,7 +125,7 @@ Beyond search, seqtree ships:
|
|
|
136
125
|
C++ call (`numpy.asarray` wraps the result with no copy) — no `python-Levenshtein` or `rapidfuzz`
|
|
137
126
|
dependency needed. Hamming requires equal lengths (it raises otherwise); comparison is
|
|
138
127
|
case-sensitive. The same module *enumerates* a Hamming ball as well as scoring one:
|
|
139
|
-
`neighbourhood(seq, r)` lists its `19·L + 1` members, and `neighbourhood_union(seqs, r)` takes
|
|
128
|
+
`neighbourhood(seq, r=1)` lists its `19·L + 1` amino-acid members, and `neighbourhood_union(seqs, r)` takes
|
|
140
129
|
the union over many centres with each distinct sequence emitted **once** — deduplicated during
|
|
141
130
|
the walk, so the `Σ 19·L_i` multiset never exists. For a tight specificity group that is a 41.7%
|
|
142
131
|
saving, not a rounding correction.
|
|
@@ -246,6 +235,20 @@ Figures (throughput, scaling, matrix-scoring overhead, collisions, E-value matri
|
|
|
246
235
|
detection) and the full methodology are in the [benchmarks docs](https://antigenomics.github.io/seqtree/benchmarks.html).
|
|
247
236
|
Set `RUN_BENCHMARK=1` for the large tiers.
|
|
248
237
|
|
|
238
|
+
## Parallel processing
|
|
239
|
+
|
|
240
|
+
CPU budgets use `threads=0` for automatic parallel work, using physical cores within the allocation.
|
|
241
|
+
Use `1` for serial work or a positive
|
|
242
|
+
count to select logical CPUs within the scheduler/container allocation.
|
|
243
|
+
|
|
244
|
+
Automatic sizing counts distinct physical cores within the process affinity mask,
|
|
245
|
+
then respects scheduler and container limits. When topology is unavailable, it
|
|
246
|
+
uses the available logical CPU count. A 40-logical-CPU, 20-core node therefore
|
|
247
|
+
uses up to 20 workers automatically; an explicit budget may use SMT threads.
|
|
248
|
+
Windows uses native core topology, process affinity and the current job CPU-rate
|
|
249
|
+
limit. Processes spanning processor groups must be bound to one group. Parent
|
|
250
|
+
job quotas are not exposed by this query; supply a budget within any parent limit.
|
|
251
|
+
|
|
249
252
|
## Development
|
|
250
253
|
|
|
251
254
|
This repo follows **git-flow**:
|
|
@@ -273,7 +276,3 @@ and tie, count, exclusion and unsupported-value semantics.
|
|
|
273
276
|
|
|
274
277
|
The public [seqtree skill](skills/seqtree/SKILL.md) guides use of the C++20 library
|
|
275
278
|
and Python bindings for sequence search, alignment, distances, and batch operations.
|
|
276
|
-
|
|
277
|
-
CPU budgets use `threads=0` for automatic parallel work, capped at 16 allocated CPUs.
|
|
278
|
-
Use `1` for serial work or a positive
|
|
279
|
-
count to override the automatic cap within the scheduler/container allocation.
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="760" viewBox="0 0 1200 760" role="img" aria-labelledby="title desc"><title id="title">From sequence collections to fast batch search</title><desc id="desc">Build an immutable index once; submit queries together. Illustrations are schematic, not measured results.</desc><!-- Editable schematic, not measured observations. PNG: rsvg-convert assets/workflow-light.svg -o assets/workflow.png -->
|
|
2
|
+
<rect width="1200" height="760" fill="#1a2332"/><g font-family="Arial, Helvetica, sans-serif">
|
|
3
|
+
<text x="56" y="72" font-size="32" fill="#eef2f7" font-weight="700">From sequence collections to fast batch search</text>
|
|
4
|
+
<text x="56" y="110" font-size="19" fill="#9cadbf" font-weight="400">Build an immutable index once; submit queries together.</text>
|
|
5
|
+
<path d="M56 142 H1144" fill="none" stroke="#354254" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/>
|
|
6
|
+
<rect x="80" y="220" width="72" height="7" fill="#83b5e7" opacity="0.95"/>
|
|
7
|
+
<rect x="158" y="220" width="28" height="7" fill="#ffbd59" opacity="0.95"/>
|
|
8
|
+
<rect x="192" y="220" width="70" height="7" fill="#25c39d" opacity="0.95"/>
|
|
9
|
+
<rect x="80" y="240" width="72" height="7" fill="#83b5e7" opacity="0.83"/>
|
|
10
|
+
<rect x="158" y="240" width="28" height="7" fill="#ffbd59" opacity="0.83"/>
|
|
11
|
+
<rect x="192" y="240" width="70" height="7" fill="#25c39d" opacity="0.83"/>
|
|
12
|
+
<rect x="80" y="260" width="72" height="7" fill="#83b5e7" opacity="0.71"/>
|
|
13
|
+
<rect x="158" y="260" width="28" height="7" fill="#ffbd59" opacity="0.71"/>
|
|
14
|
+
<rect x="192" y="260" width="70" height="7" fill="#25c39d" opacity="0.71"/>
|
|
15
|
+
<rect x="80" y="280" width="72" height="7" fill="#83b5e7" opacity="0.59"/>
|
|
16
|
+
<rect x="158" y="280" width="28" height="7" fill="#ffbd59" opacity="0.59"/>
|
|
17
|
+
<rect x="192" y="280" width="70" height="7" fill="#25c39d" opacity="0.59"/>
|
|
18
|
+
<circle cx="565" cy="200" r="9" fill="#25c39d" stroke="#25c39d" stroke-width="2"/>
|
|
19
|
+
<circle cx="495" cy="250" r="9" fill="#25c39d" stroke="#25c39d" stroke-width="2"/>
|
|
20
|
+
<circle cx="635" cy="250" r="9" fill="#25c39d" stroke="#25c39d" stroke-width="2"/>
|
|
21
|
+
<circle cx="460" cy="308" r="9" fill="#25c39d" stroke="#25c39d" stroke-width="2"/>
|
|
22
|
+
<circle cx="530" cy="308" r="9" fill="#25c39d" stroke="#25c39d" stroke-width="2"/>
|
|
23
|
+
<circle cx="605" cy="308" r="9" fill="#25c39d" stroke="#25c39d" stroke-width="2"/>
|
|
24
|
+
<circle cx="675" cy="308" r="9" fill="#25c39d" stroke="#25c39d" stroke-width="2"/>
|
|
25
|
+
<path d="M565 209 L495 241" fill="none" stroke="#9cadbf" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/>
|
|
26
|
+
<path d="M565 209 L635 241" fill="none" stroke="#9cadbf" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/>
|
|
27
|
+
<path d="M495 259 L460 299" fill="none" stroke="#9cadbf" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/>
|
|
28
|
+
<path d="M495 259 L530 299" fill="none" stroke="#9cadbf" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/>
|
|
29
|
+
<path d="M635 259 L605 299" fill="none" stroke="#9cadbf" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/>
|
|
30
|
+
<path d="M635 259 L675 299" fill="none" stroke="#9cadbf" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/>
|
|
31
|
+
<rect x="842" y="220" width="72" height="7" fill="#83b5e7" opacity="0.95"/>
|
|
32
|
+
<rect x="920" y="220" width="28" height="7" fill="#ffbd59" opacity="0.95"/>
|
|
33
|
+
<rect x="954" y="220" width="70" height="7" fill="#25c39d" opacity="0.95"/>
|
|
34
|
+
<rect x="842" y="240" width="72" height="7" fill="#83b5e7" opacity="0.83"/>
|
|
35
|
+
<rect x="920" y="240" width="28" height="7" fill="#ffbd59" opacity="0.83"/>
|
|
36
|
+
<rect x="954" y="240" width="70" height="7" fill="#25c39d" opacity="0.83"/>
|
|
37
|
+
<rect x="842" y="260" width="72" height="7" fill="#83b5e7" opacity="0.71"/>
|
|
38
|
+
<rect x="920" y="260" width="28" height="7" fill="#ffbd59" opacity="0.71"/>
|
|
39
|
+
<rect x="954" y="260" width="70" height="7" fill="#25c39d" opacity="0.71"/>
|
|
40
|
+
<rect x="842" y="280" width="72" height="7" fill="#83b5e7" opacity="0.59"/>
|
|
41
|
+
<rect x="920" y="280" width="28" height="7" fill="#ffbd59" opacity="0.59"/>
|
|
42
|
+
<rect x="954" y="280" width="70" height="7" fill="#25c39d" opacity="0.59"/>
|
|
43
|
+
<path d="M355 258 h40 m-8 -7 8 7 -8 7" fill="none" stroke="#9cadbf" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/>
|
|
44
|
+
<path d="M745 258 h40 m-8 -7 8 7 -8 7" fill="none" stroke="#9cadbf" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/>
|
|
45
|
+
<text x="56" y="386" font-size="24" fill="#eef2f7" font-weight="700">Reference collection</text>
|
|
46
|
+
<text x="56" y="420" font-size="17" fill="#9cadbf" font-weight="400">Amino-acid or nucleotide sequences</text>
|
|
47
|
+
<text x="56" y="447" font-size="17" fill="#9cadbf" font-weight="400">Caller-owned IDs and annotations</text>
|
|
48
|
+
<text x="446" y="386" font-size="24" fill="#eef2f7" font-weight="700">Immutable native index</text>
|
|
49
|
+
<text x="446" y="420" font-size="17" fill="#9cadbf" font-weight="400">Whole-sequence or substring search</text>
|
|
50
|
+
<text x="446" y="447" font-size="17" fill="#9cadbf" font-weight="400">Shared read-only reference state</text>
|
|
51
|
+
<text x="836" y="386" font-size="24" fill="#eef2f7" font-weight="700">One batch of queries</text>
|
|
52
|
+
<text x="836" y="420" font-size="17" fill="#9cadbf" font-weight="400">Hits, alignments and reductions</text>
|
|
53
|
+
<text x="836" y="447" font-size="17" fill="#9cadbf" font-weight="400">Automatic allocation-aware parallelism</text>
|
|
54
|
+
<path d="M56 483 H1144" fill="none" stroke="#354254" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/>
|
|
55
|
+
<rect x="56" y="522" width="27" height="4" fill="#83b5e7" opacity="1"/>
|
|
56
|
+
<text x="56" y="566" font-size="23" fill="#eef2f7" font-weight="700">Indexed search</text>
|
|
57
|
+
<text x="56" y="603" font-size="16" fill="#9cadbf" font-weight="400">Bounded fuzzy matches and top hits.</text>
|
|
58
|
+
<text x="56" y="629" font-size="16" fill="#9cadbf" font-weight="400">TextIndex finds substrings in long records.</text>
|
|
59
|
+
<rect x="446" y="522" width="27" height="4" fill="#25c39d" opacity="1"/>
|
|
60
|
+
<text x="446" y="566" font-size="23" fill="#eef2f7" font-weight="700">Pairwise operations</text>
|
|
61
|
+
<text x="446" y="603" font-size="16" fill="#9cadbf" font-weight="400">Affine alignment and sequence distances.</text>
|
|
62
|
+
<text x="446" y="629" font-size="16" fill="#9cadbf" font-weight="400">Gap-block scoring and matrix reductions.</text>
|
|
63
|
+
<rect x="836" y="522" width="27" height="4" fill="#ffbd59" opacity="1"/>
|
|
64
|
+
<text x="836" y="566" font-size="23" fill="#eef2f7" font-weight="700">Composable outputs</text>
|
|
65
|
+
<text x="836" y="603" font-size="16" fill="#9cadbf" font-weight="400">Map ref_id back to your reference rows.</text>
|
|
66
|
+
<text x="836" y="629" font-size="16" fill="#9cadbf" font-weight="400">Biological interpretation stays downstream.</text>
|
|
67
|
+
<path d="M56 678 H1144" fill="none" stroke="#354254" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/>
|
|
68
|
+
<text x="56" y="719" font-size="17" fill="#9cadbf" font-weight="400">C++20 + Python API</text>
|
|
69
|
+
<text x="735" y="719" font-size="16" fill="#9cadbf" font-weight="400">Batch APIs · shared resources · automatic CPU budgets</text>
|
|
70
|
+
</g></svg>
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="760" viewBox="0 0 1200 760" role="img" aria-labelledby="title desc"><title id="title">From sequence collections to fast batch search</title><desc id="desc">Build an immutable index once; submit queries together. Illustrations are schematic, not measured results.</desc><!-- Editable schematic, not measured observations. PNG: rsvg-convert assets/workflow-light.svg -o assets/workflow.png -->
|
|
2
|
+
<rect width="1200" height="760" fill="#ffffff"/><g font-family="Arial, Helvetica, sans-serif">
|
|
3
|
+
<text x="56" y="72" font-size="32" fill="#1a2332" font-weight="700">From sequence collections to fast batch search</text>
|
|
4
|
+
<text x="56" y="110" font-size="19" fill="#54657a" font-weight="400">Build an immutable index once; submit queries together.</text>
|
|
5
|
+
<path d="M56 142 H1144" fill="none" stroke="#e6e9ee" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/>
|
|
6
|
+
<rect x="80" y="220" width="72" height="7" fill="#3f75ac" opacity="0.95"/>
|
|
7
|
+
<rect x="158" y="220" width="28" height="7" fill="#b17b20" opacity="0.95"/>
|
|
8
|
+
<rect x="192" y="220" width="70" height="7" fill="#168b78" opacity="0.95"/>
|
|
9
|
+
<rect x="80" y="240" width="72" height="7" fill="#3f75ac" opacity="0.83"/>
|
|
10
|
+
<rect x="158" y="240" width="28" height="7" fill="#b17b20" opacity="0.83"/>
|
|
11
|
+
<rect x="192" y="240" width="70" height="7" fill="#168b78" opacity="0.83"/>
|
|
12
|
+
<rect x="80" y="260" width="72" height="7" fill="#3f75ac" opacity="0.71"/>
|
|
13
|
+
<rect x="158" y="260" width="28" height="7" fill="#b17b20" opacity="0.71"/>
|
|
14
|
+
<rect x="192" y="260" width="70" height="7" fill="#168b78" opacity="0.71"/>
|
|
15
|
+
<rect x="80" y="280" width="72" height="7" fill="#3f75ac" opacity="0.59"/>
|
|
16
|
+
<rect x="158" y="280" width="28" height="7" fill="#b17b20" opacity="0.59"/>
|
|
17
|
+
<rect x="192" y="280" width="70" height="7" fill="#168b78" opacity="0.59"/>
|
|
18
|
+
<circle cx="565" cy="200" r="9" fill="#168b78" stroke="#168b78" stroke-width="2"/>
|
|
19
|
+
<circle cx="495" cy="250" r="9" fill="#168b78" stroke="#168b78" stroke-width="2"/>
|
|
20
|
+
<circle cx="635" cy="250" r="9" fill="#168b78" stroke="#168b78" stroke-width="2"/>
|
|
21
|
+
<circle cx="460" cy="308" r="9" fill="#168b78" stroke="#168b78" stroke-width="2"/>
|
|
22
|
+
<circle cx="530" cy="308" r="9" fill="#168b78" stroke="#168b78" stroke-width="2"/>
|
|
23
|
+
<circle cx="605" cy="308" r="9" fill="#168b78" stroke="#168b78" stroke-width="2"/>
|
|
24
|
+
<circle cx="675" cy="308" r="9" fill="#168b78" stroke="#168b78" stroke-width="2"/>
|
|
25
|
+
<path d="M565 209 L495 241" fill="none" stroke="#54657a" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/>
|
|
26
|
+
<path d="M565 209 L635 241" fill="none" stroke="#54657a" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/>
|
|
27
|
+
<path d="M495 259 L460 299" fill="none" stroke="#54657a" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/>
|
|
28
|
+
<path d="M495 259 L530 299" fill="none" stroke="#54657a" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/>
|
|
29
|
+
<path d="M635 259 L605 299" fill="none" stroke="#54657a" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/>
|
|
30
|
+
<path d="M635 259 L675 299" fill="none" stroke="#54657a" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/>
|
|
31
|
+
<rect x="842" y="220" width="72" height="7" fill="#3f75ac" opacity="0.95"/>
|
|
32
|
+
<rect x="920" y="220" width="28" height="7" fill="#b17b20" opacity="0.95"/>
|
|
33
|
+
<rect x="954" y="220" width="70" height="7" fill="#168b78" opacity="0.95"/>
|
|
34
|
+
<rect x="842" y="240" width="72" height="7" fill="#3f75ac" opacity="0.83"/>
|
|
35
|
+
<rect x="920" y="240" width="28" height="7" fill="#b17b20" opacity="0.83"/>
|
|
36
|
+
<rect x="954" y="240" width="70" height="7" fill="#168b78" opacity="0.83"/>
|
|
37
|
+
<rect x="842" y="260" width="72" height="7" fill="#3f75ac" opacity="0.71"/>
|
|
38
|
+
<rect x="920" y="260" width="28" height="7" fill="#b17b20" opacity="0.71"/>
|
|
39
|
+
<rect x="954" y="260" width="70" height="7" fill="#168b78" opacity="0.71"/>
|
|
40
|
+
<rect x="842" y="280" width="72" height="7" fill="#3f75ac" opacity="0.59"/>
|
|
41
|
+
<rect x="920" y="280" width="28" height="7" fill="#b17b20" opacity="0.59"/>
|
|
42
|
+
<rect x="954" y="280" width="70" height="7" fill="#168b78" opacity="0.59"/>
|
|
43
|
+
<path d="M355 258 h40 m-8 -7 8 7 -8 7" fill="none" stroke="#54657a" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/>
|
|
44
|
+
<path d="M745 258 h40 m-8 -7 8 7 -8 7" fill="none" stroke="#54657a" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/>
|
|
45
|
+
<text x="56" y="386" font-size="24" fill="#1a2332" font-weight="700">Reference collection</text>
|
|
46
|
+
<text x="56" y="420" font-size="17" fill="#54657a" font-weight="400">Amino-acid or nucleotide sequences</text>
|
|
47
|
+
<text x="56" y="447" font-size="17" fill="#54657a" font-weight="400">Caller-owned IDs and annotations</text>
|
|
48
|
+
<text x="446" y="386" font-size="24" fill="#1a2332" font-weight="700">Immutable native index</text>
|
|
49
|
+
<text x="446" y="420" font-size="17" fill="#54657a" font-weight="400">Whole-sequence or substring search</text>
|
|
50
|
+
<text x="446" y="447" font-size="17" fill="#54657a" font-weight="400">Shared read-only reference state</text>
|
|
51
|
+
<text x="836" y="386" font-size="24" fill="#1a2332" font-weight="700">One batch of queries</text>
|
|
52
|
+
<text x="836" y="420" font-size="17" fill="#54657a" font-weight="400">Hits, alignments and reductions</text>
|
|
53
|
+
<text x="836" y="447" font-size="17" fill="#54657a" font-weight="400">Automatic allocation-aware parallelism</text>
|
|
54
|
+
<path d="M56 483 H1144" fill="none" stroke="#e6e9ee" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/>
|
|
55
|
+
<rect x="56" y="522" width="27" height="4" fill="#3f75ac" opacity="1"/>
|
|
56
|
+
<text x="56" y="566" font-size="23" fill="#1a2332" font-weight="700">Indexed search</text>
|
|
57
|
+
<text x="56" y="603" font-size="16" fill="#54657a" font-weight="400">Bounded fuzzy matches and top hits.</text>
|
|
58
|
+
<text x="56" y="629" font-size="16" fill="#54657a" font-weight="400">TextIndex finds substrings in long records.</text>
|
|
59
|
+
<rect x="446" y="522" width="27" height="4" fill="#168b78" opacity="1"/>
|
|
60
|
+
<text x="446" y="566" font-size="23" fill="#1a2332" font-weight="700">Pairwise operations</text>
|
|
61
|
+
<text x="446" y="603" font-size="16" fill="#54657a" font-weight="400">Affine alignment and sequence distances.</text>
|
|
62
|
+
<text x="446" y="629" font-size="16" fill="#54657a" font-weight="400">Gap-block scoring and matrix reductions.</text>
|
|
63
|
+
<rect x="836" y="522" width="27" height="4" fill="#b17b20" opacity="1"/>
|
|
64
|
+
<text x="836" y="566" font-size="23" fill="#1a2332" font-weight="700">Composable outputs</text>
|
|
65
|
+
<text x="836" y="603" font-size="16" fill="#54657a" font-weight="400">Map ref_id back to your reference rows.</text>
|
|
66
|
+
<text x="836" y="629" font-size="16" fill="#54657a" font-weight="400">Biological interpretation stays downstream.</text>
|
|
67
|
+
<path d="M56 678 H1144" fill="none" stroke="#e6e9ee" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/>
|
|
68
|
+
<text x="56" y="719" font-size="17" fill="#54657a" font-weight="400">C++20 + Python API</text>
|
|
69
|
+
<text x="735" y="719" font-size="16" fill="#54657a" font-weight="400">Batch APIs · shared resources · automatic CPU budgets</text>
|
|
70
|
+
</g></svg>
|
|
Binary file
|
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
#pragma once
|
|
2
|
+
// One parallel-for scaffold for the whole tree. Every batch entry point in seqtree used to
|
|
3
|
+
// carry its own copy of this: an atomic cursor, an adaptive chunk, an exception_ptr, a vector
|
|
4
|
+
// of threads, and a rethrow after the join. Seven copies drifted -- one of them had no
|
|
5
|
+
// exception plumbing at all.
|
|
6
|
+
#include <algorithm>
|
|
7
|
+
#include <atomic>
|
|
8
|
+
#include <cstddef>
|
|
9
|
+
#include <cstdint>
|
|
10
|
+
#include <cstdlib>
|
|
11
|
+
#include <exception>
|
|
12
|
+
#include <fstream>
|
|
13
|
+
#include <filesystem>
|
|
14
|
+
#include <sstream>
|
|
15
|
+
#include <mutex>
|
|
16
|
+
#include <set>
|
|
17
|
+
#include <string>
|
|
18
|
+
#include <stdexcept>
|
|
19
|
+
#include <thread>
|
|
20
|
+
#include <vector>
|
|
21
|
+
|
|
22
|
+
#ifdef __linux__
|
|
23
|
+
#include <sched.h>
|
|
24
|
+
#elif defined(__APPLE__)
|
|
25
|
+
#include <sys/sysctl.h>
|
|
26
|
+
#elif defined(_WIN32)
|
|
27
|
+
#ifndef NOMINMAX
|
|
28
|
+
#define NOMINMAX
|
|
29
|
+
#endif
|
|
30
|
+
#ifndef WIN32_LEAN_AND_MEAN
|
|
31
|
+
#define WIN32_LEAN_AND_MEAN
|
|
32
|
+
#endif
|
|
33
|
+
#include <windows.h>
|
|
34
|
+
#endif
|
|
35
|
+
|
|
36
|
+
namespace seqtree {
|
|
37
|
+
|
|
38
|
+
inline unsigned cpu_rate_budget(unsigned available, unsigned system_cpus, unsigned rate) {
|
|
39
|
+
if (!rate || rate > 10000) throw std::invalid_argument("invalid Windows CPU rate limit");
|
|
40
|
+
return std::min(available, std::max(1u, unsigned(uint64_t(system_cpus) * rate / 10000)));
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
#ifdef _WIN32
|
|
44
|
+
inline std::pair<unsigned, unsigned> windows_cpu_budget() {
|
|
45
|
+
const HANDLE process = GetCurrentProcess();
|
|
46
|
+
USHORT group_count = 1, group = 0;
|
|
47
|
+
if (!GetProcessGroupAffinity(process, &group_count, &group) || group_count != 1)
|
|
48
|
+
throw std::runtime_error("CPU budgeting requires a single Windows processor group; bind the process to one group");
|
|
49
|
+
DWORD_PTR mask = 0, system_mask = 0;
|
|
50
|
+
if (!GetProcessAffinityMask(process, &mask, &system_mask) || !mask)
|
|
51
|
+
throw std::runtime_error("cannot read Windows process CPU affinity");
|
|
52
|
+
unsigned logical = 0;
|
|
53
|
+
for (auto bits = mask; bits; bits &= bits - 1) ++logical;
|
|
54
|
+
DWORD bytes = 0;
|
|
55
|
+
GetLogicalProcessorInformationEx(RelationProcessorCore, nullptr, &bytes);
|
|
56
|
+
if (!bytes) throw std::runtime_error("cannot read Windows physical CPU topology");
|
|
57
|
+
std::vector<unsigned char> buffer(bytes);
|
|
58
|
+
if (!GetLogicalProcessorInformationEx(RelationProcessorCore,
|
|
59
|
+
reinterpret_cast<PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX>(buffer.data()), &bytes))
|
|
60
|
+
throw std::runtime_error("cannot read Windows physical CPU topology");
|
|
61
|
+
unsigned physical = 0;
|
|
62
|
+
for (size_t offset = 0; offset < bytes;) {
|
|
63
|
+
const auto* info = reinterpret_cast<const SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX*>(buffer.data() + offset);
|
|
64
|
+
if (!info->Size || offset + info->Size > bytes)
|
|
65
|
+
throw std::runtime_error("invalid Windows physical CPU topology");
|
|
66
|
+
bool allowed = false;
|
|
67
|
+
for (WORD i = 0; i < info->Processor.GroupCount; ++i)
|
|
68
|
+
allowed |= info->Processor.GroupMask[i].Group == group &&
|
|
69
|
+
(info->Processor.GroupMask[i].Mask & mask) != 0;
|
|
70
|
+
physical += allowed;
|
|
71
|
+
offset += info->Size;
|
|
72
|
+
}
|
|
73
|
+
if (!physical) throw std::runtime_error("Windows affinity contains no physical cores");
|
|
74
|
+
BOOL in_job = FALSE;
|
|
75
|
+
if (!IsProcessInJob(process, nullptr, &in_job))
|
|
76
|
+
throw std::runtime_error("cannot inspect Windows CPU job membership");
|
|
77
|
+
if (in_job) {
|
|
78
|
+
JOBOBJECT_CPU_RATE_CONTROL_INFORMATION rate{};
|
|
79
|
+
if (!QueryInformationJobObject(nullptr, JobObjectCpuRateControlInformation, &rate, sizeof(rate), nullptr))
|
|
80
|
+
throw std::runtime_error("cannot inspect Windows CPU job limit");
|
|
81
|
+
if (rate.ControlFlags & JOB_OBJECT_CPU_RATE_CONTROL_ENABLE) {
|
|
82
|
+
unsigned fraction = 0;
|
|
83
|
+
if (rate.ControlFlags & JOB_OBJECT_CPU_RATE_CONTROL_HARD_CAP) fraction = rate.CpuRate;
|
|
84
|
+
else if (rate.ControlFlags & JOB_OBJECT_CPU_RATE_CONTROL_MIN_MAX_RATE) fraction = rate.MaxRate;
|
|
85
|
+
if (fraction) {
|
|
86
|
+
const auto total = GetActiveProcessorCount(ALL_PROCESSOR_GROUPS);
|
|
87
|
+
logical = cpu_rate_budget(logical, total, fraction);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
return {logical, std::min(logical, physical)};
|
|
92
|
+
}
|
|
93
|
+
#endif
|
|
94
|
+
|
|
95
|
+
// Resolve once per batch; affinity/quota limits can change between calls.
|
|
96
|
+
inline unsigned available_cpus() {
|
|
97
|
+
unsigned count = std::max(1u, std::thread::hardware_concurrency());
|
|
98
|
+
#ifdef __linux__
|
|
99
|
+
cpu_set_t affinity;
|
|
100
|
+
if (sched_getaffinity(0, sizeof(affinity), &affinity) == 0)
|
|
101
|
+
count = std::min(count, unsigned(std::max(1, CPU_COUNT(&affinity))));
|
|
102
|
+
namespace fs = std::filesystem;
|
|
103
|
+
const fs::path root("/sys/fs/cgroup");
|
|
104
|
+
std::vector<fs::path> bases{root, root / "cpu", root / "cpu,cpuacct", root / "cpuacct,cpu"};
|
|
105
|
+
std::vector<fs::path> paths = bases;
|
|
106
|
+
std::ifstream membership("/proc/self/cgroup");
|
|
107
|
+
std::string line;
|
|
108
|
+
while (std::getline(membership, line)) {
|
|
109
|
+
const auto first = line.find(':');
|
|
110
|
+
const auto second = line.find(':', first + 1);
|
|
111
|
+
if (first == std::string::npos || second == std::string::npos) continue;
|
|
112
|
+
const auto controllers = line.substr(first + 1, second - first - 1);
|
|
113
|
+
if (!controllers.empty() && ("," + controllers + ",").find(",cpu,") == std::string::npos) continue;
|
|
114
|
+
const fs::path relative = fs::path(line.substr(second + 1)).relative_path();
|
|
115
|
+
bool safe = true;
|
|
116
|
+
for (const auto& component : relative) if (component == "..") safe = false;
|
|
117
|
+
if (!safe) continue;
|
|
118
|
+
for (const auto& base : bases) {
|
|
119
|
+
if (controllers.empty() && base != root) continue;
|
|
120
|
+
for (auto path = base / relative; path != base; path = path.parent_path())
|
|
121
|
+
paths.push_back(path);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
for (const auto& path : paths) {
|
|
125
|
+
std::string quota_text;
|
|
126
|
+
uint64_t period = 0;
|
|
127
|
+
std::ifstream v2(path / "cpu.max");
|
|
128
|
+
if (!(v2 >> quota_text >> period)) {
|
|
129
|
+
std::ifstream v1quota(path / "cpu.cfs_quota_us"), v1period(path / "cpu.cfs_period_us");
|
|
130
|
+
if (!(v1quota >> quota_text) || !(v1period >> period)) continue;
|
|
131
|
+
}
|
|
132
|
+
if (quota_text == "max" || quota_text == "-1" || !period) continue;
|
|
133
|
+
uint64_t quota = 0;
|
|
134
|
+
std::istringstream parsed(quota_text);
|
|
135
|
+
if (parsed >> quota && quota)
|
|
136
|
+
count = unsigned(std::min<uint64_t>(count, std::max<uint64_t>(1, quota / period)));
|
|
137
|
+
}
|
|
138
|
+
for (const char* name : {"SLURM_CPUS_PER_TASK", "SLURM_CPUS_ON_NODE"}) {
|
|
139
|
+
if (const char* value = std::getenv(name)) {
|
|
140
|
+
char* end = nullptr;
|
|
141
|
+
const auto allocated = std::strtoul(value, &end, 10);
|
|
142
|
+
if (end != value && !*end && allocated)
|
|
143
|
+
count = unsigned(std::min<unsigned long>(count, allocated));
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
#elif defined(_WIN32)
|
|
147
|
+
count = std::min(count, windows_cpu_budget().first);
|
|
148
|
+
#endif
|
|
149
|
+
return count;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
inline unsigned physical_cores_for_cpus(const std::vector<unsigned>& cpus,
|
|
153
|
+
unsigned available,
|
|
154
|
+
const std::string& root = "/sys/devices/system/cpu/") {
|
|
155
|
+
std::set<std::pair<int, int>> cores;
|
|
156
|
+
for (unsigned cpu : cpus) {
|
|
157
|
+
const auto path = root + "cpu" + std::to_string(cpu) + "/topology/";
|
|
158
|
+
int package, core;
|
|
159
|
+
if (!(std::ifstream(path + "physical_package_id") >> package) ||
|
|
160
|
+
!(std::ifstream(path + "core_id") >> core) || package < 0 || core < 0) return available;
|
|
161
|
+
cores.emplace(package, core);
|
|
162
|
+
}
|
|
163
|
+
return cores.empty() ? available : std::min(available, unsigned(cores.size()));
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
// Topology is separate from the logical allocation: explicit budgets may use SMT.
|
|
167
|
+
inline unsigned physical_cpus() {
|
|
168
|
+
const unsigned available = available_cpus();
|
|
169
|
+
#ifdef __linux__
|
|
170
|
+
cpu_set_t affinity;
|
|
171
|
+
if (sched_getaffinity(0, sizeof(affinity), &affinity) == 0) {
|
|
172
|
+
std::vector<unsigned> cpus;
|
|
173
|
+
for (int cpu = 0; cpu < CPU_SETSIZE; ++cpu)
|
|
174
|
+
if (CPU_ISSET(cpu, &affinity)) cpus.push_back(unsigned(cpu));
|
|
175
|
+
return physical_cores_for_cpus(cpus, available);
|
|
176
|
+
}
|
|
177
|
+
#elif defined(__APPLE__)
|
|
178
|
+
unsigned physical = available;
|
|
179
|
+
size_t size = sizeof(physical);
|
|
180
|
+
if (sysctlbyname("hw.physicalcpu", &physical, &size, nullptr, 0) == 0 && physical)
|
|
181
|
+
return std::min(available, physical);
|
|
182
|
+
#elif defined(_WIN32)
|
|
183
|
+
return windows_cpu_budget().second;
|
|
184
|
+
#endif
|
|
185
|
+
return available;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// Runs body(i, local) for every i in [0, n), across nt workers pulling contiguous chunks off
|
|
189
|
+
// one atomic cursor. `threads <= 0` selects available physical cores; positive counts may use logical CPUs.
|
|
190
|
+
//
|
|
191
|
+
// `make_local()` is called once per worker and its result handed to every body() that worker
|
|
192
|
+
// runs -- that is how a Searcher or a scratch buffer gets allocated once per thread rather
|
|
193
|
+
// than once per item. Return a dummy for kernels that need no state.
|
|
194
|
+
//
|
|
195
|
+
// The chunk is adaptive: large batches keep ~1024 items per grab so the atomic is not the
|
|
196
|
+
// bottleneck, small ones split ~8 chunks per thread so no worker goes idle. Raise `chunk_min`
|
|
197
|
+
// when the per-item output struct is small enough that neighbouring workers would share a
|
|
198
|
+
// cache line (TextIndex's QueryOut is ~80 bytes, so it passes 8).
|
|
199
|
+
//
|
|
200
|
+
// Workers catch, the first exception is kept, and it is rethrown after the join. This is not
|
|
201
|
+
// optional: an exception escaping a std::thread entry function calls std::terminate, which
|
|
202
|
+
// from Python is an uncatchable SIGABRT rather than a raise.
|
|
203
|
+
template <class MakeLocal, class Body>
|
|
204
|
+
void parallel_for(size_t n, int threads, MakeLocal make_local, Body body,
|
|
205
|
+
size_t chunk_min = 1, size_t chunk_max = 1024) {
|
|
206
|
+
const unsigned available = available_cpus();
|
|
207
|
+
unsigned nt = threads > 0 ? unsigned(threads) : physical_cpus();
|
|
208
|
+
nt = std::min({nt, available, 999u});
|
|
209
|
+
if (n == 0) return;
|
|
210
|
+
nt = unsigned(std::min<size_t>(nt, n)); // Do not start idle workers for absent work.
|
|
211
|
+
|
|
212
|
+
// A serial budget runs on the calling thread; spawning one worker only adds overhead.
|
|
213
|
+
if (nt == 1) {
|
|
214
|
+
auto local = make_local();
|
|
215
|
+
for (size_t i = 0; i < n; ++i) body(i, local);
|
|
216
|
+
return;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
std::atomic<size_t> next{0};
|
|
220
|
+
const size_t chunk = std::clamp<size_t>(n / (size_t(nt) * 8), chunk_min, chunk_max);
|
|
221
|
+
std::exception_ptr err;
|
|
222
|
+
std::mutex emu;
|
|
223
|
+
|
|
224
|
+
auto worker = [&] {
|
|
225
|
+
// Scratch construction can allocate and throw too. Nothing may escape the entry point.
|
|
226
|
+
try {
|
|
227
|
+
auto local = make_local();
|
|
228
|
+
for (;;) {
|
|
229
|
+
const size_t start = next.fetch_add(chunk);
|
|
230
|
+
if (start >= n) break;
|
|
231
|
+
const size_t end = std::min(n, start + chunk);
|
|
232
|
+
for (size_t i = start; i < end; ++i) {
|
|
233
|
+
body(i, local);
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
} catch (...) {
|
|
237
|
+
std::lock_guard<std::mutex> lk(emu);
|
|
238
|
+
if (!err) err = std::current_exception();
|
|
239
|
+
}
|
|
240
|
+
};
|
|
241
|
+
|
|
242
|
+
// A failed thread launch must also join workers already started before unwinding.
|
|
243
|
+
std::vector<std::jthread> pool;
|
|
244
|
+
pool.reserve(nt);
|
|
245
|
+
// The caller is one compute thread: a budget B creates only B-1 OS workers.
|
|
246
|
+
for (unsigned t = 1; t < nt; ++t) pool.emplace_back(worker);
|
|
247
|
+
worker();
|
|
248
|
+
for (auto& th : pool) th.join();
|
|
249
|
+
if (err) std::rethrow_exception(err);
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
} // namespace seqtree
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
#pragma once
|
|
2
|
+
|
|
3
|
+
#include <cstddef>
|
|
4
|
+
#include <cstdint>
|
|
5
|
+
#include <optional>
|
|
6
|
+
#include <span>
|
|
7
|
+
#include <vector>
|
|
8
|
+
|
|
9
|
+
namespace seqtree {
|
|
10
|
+
|
|
11
|
+
class RankedNeighborhood {
|
|
12
|
+
public:
|
|
13
|
+
using Pools = std::vector<std::vector<uint32_t>>;
|
|
14
|
+
using Weights = std::vector<std::optional<std::vector<double>>>;
|
|
15
|
+
|
|
16
|
+
RankedNeighborhood(Pools targets, Pools controls, Weights target_weights = {},
|
|
17
|
+
Weights control_weights = {});
|
|
18
|
+
|
|
19
|
+
const std::vector<size_t>& rank_offsets() const { return offsets_; }
|
|
20
|
+
|
|
21
|
+
// Row-major (query, packed rank slot, field): radius, count, sum, target mass, control mass.
|
|
22
|
+
std::vector<double> reduce(std::span<const double> distances, size_t rows, size_t columns,
|
|
23
|
+
bool distinct, double taper_unit, int threads, size_t max_result_bytes) const;
|
|
24
|
+
|
|
25
|
+
private:
|
|
26
|
+
Pools targets_, controls_;
|
|
27
|
+
Weights target_weights_, control_weights_;
|
|
28
|
+
std::vector<size_t> offsets_{0};
|
|
29
|
+
size_t min_columns_ = 0;
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
} // namespace seqtree
|
|
@@ -51,12 +51,12 @@ from ._core import gapblock_paired_topk_batch as _gapblock_paired_topk_batch
|
|
|
51
51
|
from ._core import gapblock_paired_count_batch as _gapblock_paired_count_batch
|
|
52
52
|
from ._core import gapblock_paired_sum_count_batch as _gapblock_paired_sum_count_batch
|
|
53
53
|
|
|
54
|
-
from ._core import gapblock_grouped_count_batch as _gapblock_grouped_count_batch, _GroupedGeometry
|
|
54
|
+
from ._core import gapblock_grouped_count_batch as _gapblock_grouped_count_batch, _GroupedGeometry, RankedNeighborhood
|
|
55
55
|
|
|
56
56
|
__all__ = [
|
|
57
57
|
"gapblock_score", "score_matrix", "ball_batch", "group_audit_batch", "topk_batch", "count_batch", "paired_topk_batch", "paired_count_batch", "paired_sum_count_batch", "deletion_variants", "central_prior", "profile_prior",
|
|
58
58
|
"frame_prior", "positions_prior", "embed_in_frame", "gap_cost", "GapBlockIndex", "ScoreMatrix",
|
|
59
|
-
"IslandProfile", "PairedFeatureOffsets", "grouped_count_batch", "grouped_paired_sum_count_batch",
|
|
59
|
+
"IslandProfile", "PairedFeatureOffsets", "RankedNeighborhood", "grouped_count_batch", "grouped_paired_sum_count_batch",
|
|
60
60
|
]
|
|
61
61
|
|
|
62
62
|
#: A prior value large enough that no layout carrying it can ever win, yet small enough that
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
#include "seqtree/seqtree.hpp"
|
|
2
2
|
#include "seqtree/kmer_index.hpp"
|
|
3
|
+
#include "seqtree/ranked_neighborhood.hpp"
|
|
3
4
|
#include "seqtree/text_index.hpp"
|
|
4
5
|
|
|
5
6
|
#include <nanobind/nanobind.h>
|
|
@@ -12,6 +13,7 @@
|
|
|
12
13
|
#include <nanobind/stl/vector.h>
|
|
13
14
|
|
|
14
15
|
#include <algorithm>
|
|
16
|
+
#include <cstring>
|
|
15
17
|
#include <exception>
|
|
16
18
|
#include <optional>
|
|
17
19
|
#include <string>
|
|
@@ -350,6 +352,49 @@ PyType_Slot kCountBufferSlots[] = {
|
|
|
350
352
|
{Py_bf_releasebuffer,(void*)release_view},{0,nullptr}
|
|
351
353
|
};
|
|
352
354
|
|
|
355
|
+
struct RankedBlock {
|
|
356
|
+
std::vector<double> data;
|
|
357
|
+
size_t rows, slots;
|
|
358
|
+
};
|
|
359
|
+
|
|
360
|
+
int ranked_block_getbuffer(PyObject* obj, Py_buffer* view, int flags) {
|
|
361
|
+
if (flags & PyBUF_WRITABLE) {
|
|
362
|
+
PyErr_SetString(PyExc_BufferError, "ranked neighborhood blocks are read-only");
|
|
363
|
+
return -1;
|
|
364
|
+
}
|
|
365
|
+
const auto* block = nb::inst_ptr<RankedBlock>(obj);
|
|
366
|
+
const Py_ssize_t shape[] = {Py_ssize_t(block->rows), Py_ssize_t(block->slots), 5};
|
|
367
|
+
const Py_ssize_t strides[] = {Py_ssize_t(sizeof(double) * 5 * block->slots),
|
|
368
|
+
Py_ssize_t(sizeof(double) * 5), Py_ssize_t(sizeof(double))};
|
|
369
|
+
fill_view(obj, view, flags, const_cast<double*>(block->data.data()), 3, shape, strides, sizeof(double), "d");
|
|
370
|
+
return 0;
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
PyType_Slot kRankedBlockSlots[] = {
|
|
374
|
+
{Py_bf_getbuffer, (void*)ranked_block_getbuffer},
|
|
375
|
+
{Py_bf_releasebuffer, (void*)release_view},
|
|
376
|
+
{0, nullptr}
|
|
377
|
+
};
|
|
378
|
+
|
|
379
|
+
RankedBlock reduce_ranked(const RankedNeighborhood& reducer, const nb::object& distances,
|
|
380
|
+
bool distinct, double taper_unit, int threads, size_t max_result_bytes) {
|
|
381
|
+
struct DistanceView {
|
|
382
|
+
Py_buffer view{};
|
|
383
|
+
~DistanceView() { if (view.obj) PyBuffer_Release(&view); }
|
|
384
|
+
} buffer;
|
|
385
|
+
auto& view = buffer.view;
|
|
386
|
+
if (PyObject_GetBuffer(distances.ptr(), &view, PyBUF_C_CONTIGUOUS | PyBUF_FORMAT) < 0)
|
|
387
|
+
throw nb::python_error();
|
|
388
|
+
if (view.ndim != 2 || view.itemsize != sizeof(double) || std::strcmp(view.format, "d") != 0 ||
|
|
389
|
+
reinterpret_cast<uintptr_t>(view.buf) % alignof(double))
|
|
390
|
+
throw nb::value_error("distances must be a C-contiguous aligned float64 matrix");
|
|
391
|
+
const auto rows = size_t(view.shape[0]), columns = size_t(view.shape[1]);
|
|
392
|
+
const std::span data(static_cast<const double*>(view.buf), size_t(view.len) / sizeof(double));
|
|
393
|
+
nb::gil_scoped_release release;
|
|
394
|
+
return {reducer.reduce(data, rows, columns, distinct, taper_unit, threads, max_result_bytes),
|
|
395
|
+
rows, reducer.rank_offsets().back()};
|
|
396
|
+
}
|
|
397
|
+
|
|
353
398
|
// A read-only 1-D typed window onto memory a TextResult owns. Same reasoning as ScoreMatrix:
|
|
354
399
|
// seqtree has no runtime dependencies, so the way out is the buffer protocol, not an ndarray.
|
|
355
400
|
// `owner` is a strong reference to the TextResult, so a view outlives the dict it came from.
|
|
@@ -930,6 +975,32 @@ NB_MODULE(_core, m) {
|
|
|
930
975
|
.def(nb::init<std::vector<std::vector<int32_t>>, std::vector<std::vector<int32_t>>, std::vector<std::vector<int32_t>>, double, int32_t>(),
|
|
931
976
|
nb::arg("query_codes"), nb::arg("reference_codes"), nb::arg("costs"), nb::arg("weight")=1.0, nb::arg("scale")=1);
|
|
932
977
|
|
|
978
|
+
nb::class_<RankedBlock>(m, "_RankedBlock", nb::type_slots(kRankedBlockSlots));
|
|
979
|
+
nb::class_<RankedNeighborhood>(m, "RankedNeighborhood", R"doc(
|
|
980
|
+
Prepare aligned target and competitor pools of strictly increasing reference indices.
|
|
981
|
+
Supply optional per-key weights as already normalized masses, or None for a uniform pool.
|
|
982
|
+
Target width fixes the maximum of one and ceil(log(width)) ranks, or zero for an empty target.
|
|
983
|
+
)doc")
|
|
984
|
+
.def(nb::init<RankedNeighborhood::Pools, RankedNeighborhood::Pools, RankedNeighborhood::Weights,
|
|
985
|
+
RankedNeighborhood::Weights>(),
|
|
986
|
+
nb::arg("targets"), nb::arg("controls"), nb::kw_only(),
|
|
987
|
+
nb::arg("target_weights") = RankedNeighborhood::Weights{},
|
|
988
|
+
nb::arg("control_weights") = RankedNeighborhood::Weights{})
|
|
989
|
+
.def_prop_ro("rank_offsets", &RankedNeighborhood::rank_offsets,
|
|
990
|
+
"Prefix offsets for each target's fixed rank slots.")
|
|
991
|
+
.def("reduce", &reduce_ranked, nb::arg("distances"), nb::kw_only(), nb::arg("distinct") = false,
|
|
992
|
+
nb::arg("taper_unit") = 0., nb::arg("threads") = 0,
|
|
993
|
+
nb::arg("max_result_bytes") = size_t(64) * 1024 * 1024, R"doc(
|
|
994
|
+
Reduce one C-contiguous aligned float64 query-by-reference distance block.
|
|
995
|
+
Positive infinity masks a key and preserves its fixed pool exposure.
|
|
996
|
+
Return a read-only float64 buffer of shape (queries, rank_offsets[-1], 5), with
|
|
997
|
+
fields radius, inclusive target count, target distance sum, target mass, and control mass.
|
|
998
|
+
Unused ranks have infinite radius and zero aggregate fields.
|
|
999
|
+
Distinct mode visits each occupied radius once; otherwise tied key ranks repeat.
|
|
1000
|
+
A positive taper unit extends both masses linearly to zero two units beyond the radius.
|
|
1001
|
+
Counts and sums remain inclusive and unweighted in both cases.
|
|
1002
|
+
)doc");
|
|
1003
|
+
|
|
933
1004
|
m.def("gapblock_matrix", &py_gapblock_matrix, nb::arg("queries"), nb::arg("refs"),
|
|
934
1005
|
nb::arg("alphabet") = "aa", nb::arg("matrix") = std::nullopt, nb::arg("gap_open") = 1,
|
|
935
1006
|
nb::arg("gap_extend") = 1, nb::arg("prior") = std::vector<int32_t>{},
|
|
@@ -1143,8 +1143,8 @@ GroupedCountBatch::GroupedCountBatch(const std::vector<std::string>& qa, const s
|
|
|
1143
1143
|
beta->query_groups,beta->reference_groups,beta->group_distances,
|
|
1144
1144
|
beta->query_weights,beta->reference_weights,beta->features,&bound_b);
|
|
1145
1145
|
} else if (!qb.empty() || !rb.empty()) throw std::invalid_argument("paired axes require beta geometry");
|
|
1146
|
-
if (threads<0
|
|
1147
|
-
throw std::invalid_argument("worker count
|
|
1146
|
+
if (threads<0)
|
|
1147
|
+
throw std::invalid_argument("worker count must be nonnegative");
|
|
1148
1148
|
in.cuts=std::move(cuts); in.offsets=std::move(offsets); in.labels=std::move(labels);
|
|
1149
1149
|
if (!in.return_hits) in.prepare_bins();
|
|
1150
1150
|
in.target_peptides=std::move(target_peptides); in.exclusive=std::move(exclusive);
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
#include "seqtree/ranked_neighborhood.hpp"
|
|
2
|
+
#include "seqtree/parallel.hpp"
|
|
3
|
+
|
|
4
|
+
#include <algorithm>
|
|
5
|
+
#include <iterator>
|
|
6
|
+
#include <cmath>
|
|
7
|
+
#include <limits>
|
|
8
|
+
#include <stdexcept>
|
|
9
|
+
#include <utility>
|
|
10
|
+
|
|
11
|
+
namespace seqtree {
|
|
12
|
+
namespace {
|
|
13
|
+
|
|
14
|
+
constexpr double inf = std::numeric_limits<double>::infinity();
|
|
15
|
+
constexpr size_t fields = 5;
|
|
16
|
+
|
|
17
|
+
size_t validate(const RankedNeighborhood::Pools& pools, RankedNeighborhood::Weights& weights) {
|
|
18
|
+
if (weights.empty()) weights.resize(pools.size());
|
|
19
|
+
if (weights.size() != pools.size()) throw std::invalid_argument("weights must align with pools");
|
|
20
|
+
size_t columns = 0;
|
|
21
|
+
for (size_t i = 0; i < pools.size(); ++i) {
|
|
22
|
+
const auto& pool = pools[i];
|
|
23
|
+
if (!std::is_sorted(pool.begin(), pool.end()) || std::adjacent_find(pool.begin(), pool.end()) != pool.end())
|
|
24
|
+
throw std::invalid_argument("reference indices in each pool must be strictly increasing");
|
|
25
|
+
if (!pool.empty()) columns = std::max(columns, size_t(pool.back()) + 1);
|
|
26
|
+
if (const auto& w = weights[i]; w && (w->size() != pool.size() ||
|
|
27
|
+
std::any_of(w->begin(), w->end(), [](double value) { return !std::isfinite(value) || value < 0; })))
|
|
28
|
+
throw std::invalid_argument("each weight vector must contain one finite nonnegative value per key");
|
|
29
|
+
}
|
|
30
|
+
return columns;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
struct Scratch {
|
|
34
|
+
std::vector<double> ordered, radii, bins;
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
void add_pool(std::span<const double> row, const std::vector<uint32_t>& pool,
|
|
38
|
+
const std::optional<std::vector<double>>& weights, std::span<const double> radii,
|
|
39
|
+
std::span<double> result, bool target, double taper_unit) {
|
|
40
|
+
const auto weight = weights ? weights->data() : nullptr;
|
|
41
|
+
const size_t mass = target ? 3 : 4;
|
|
42
|
+
const auto last = radii.back();
|
|
43
|
+
for (size_t i = 0; i < pool.size(); ++i) {
|
|
44
|
+
const auto d = row[pool[i]];
|
|
45
|
+
if (d > last && (!taper_unit || (d - last) / taper_unit >= 2)) continue;
|
|
46
|
+
const size_t bin = std::lower_bound(radii.begin(), radii.end(), d) - radii.begin();
|
|
47
|
+
const double w = weight ? weight[i] : 1;
|
|
48
|
+
if (bin < radii.size()) {
|
|
49
|
+
auto slot = result.subspan(fields * bin, fields);
|
|
50
|
+
if (target) {
|
|
51
|
+
++slot[1];
|
|
52
|
+
slot[2] += d;
|
|
53
|
+
}
|
|
54
|
+
slot[mass] += w;
|
|
55
|
+
}
|
|
56
|
+
if (taper_unit) {
|
|
57
|
+
for (size_t j = bin; j > 0; --j) {
|
|
58
|
+
const double factor = 1 - .5 * ((d - radii[j - 1]) / taper_unit);
|
|
59
|
+
if (factor <= 0) break;
|
|
60
|
+
// Offset past the inclusive mass fields. Soft contributions must not propagate
|
|
61
|
+
// to the next rank when we turn the hard bins into cumulative totals.
|
|
62
|
+
result[fields * radii.size() + 2 * (j - 1) + (target ? 0 : 1)] += w * factor;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
} // namespace
|
|
69
|
+
|
|
70
|
+
RankedNeighborhood::RankedNeighborhood(Pools targets, Pools controls, Weights target_weights, Weights control_weights)
|
|
71
|
+
: targets_(std::move(targets)), controls_(std::move(controls)),
|
|
72
|
+
target_weights_(std::move(target_weights)), control_weights_(std::move(control_weights)) {
|
|
73
|
+
if (targets_.size() != controls_.size()) throw std::invalid_argument("target and control pools must align");
|
|
74
|
+
min_columns_ = std::max(validate(targets_, target_weights_), validate(controls_, control_weights_));
|
|
75
|
+
for (const auto& pool : targets_) {
|
|
76
|
+
const size_t cap = pool.empty() ? 0 : std::max<size_t>(1, std::ceil(std::log(pool.size())));
|
|
77
|
+
offsets_.push_back(offsets_.back() + cap);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
std::vector<double> RankedNeighborhood::reduce(std::span<const double> distances, size_t rows, size_t columns,
|
|
82
|
+
bool distinct, double taper_unit, int threads,
|
|
83
|
+
size_t max_result_bytes) const {
|
|
84
|
+
if ((columns && rows > distances.size() / columns) || rows * columns != distances.size())
|
|
85
|
+
throw std::invalid_argument("distance block shape does not match its values");
|
|
86
|
+
if (columns < min_columns_) throw std::invalid_argument("distance block has too few reference columns");
|
|
87
|
+
if (!std::isfinite(taper_unit) || taper_unit < 0) throw std::invalid_argument("taper unit must be finite and nonnegative");
|
|
88
|
+
const size_t slots = offsets_.back();
|
|
89
|
+
if (rows && slots > max_result_bytes / sizeof(double) / fields / rows)
|
|
90
|
+
throw std::invalid_argument("ranked result exceeds byte budget; reduce a smaller query block");
|
|
91
|
+
std::vector<double> output(rows * slots * fields);
|
|
92
|
+
parallel_for(rows, threads, [] { return Scratch{}; }, [&](size_t q, Scratch& scratch) {
|
|
93
|
+
const auto row = distances.subspan(q * columns, columns);
|
|
94
|
+
if (std::any_of(row.begin(), row.end(), [](double d) { return !(d >= 0); }))
|
|
95
|
+
throw std::invalid_argument("distances must be nonnegative or positive infinity");
|
|
96
|
+
if (!slots) return;
|
|
97
|
+
auto& [ordered, radii, bins] = scratch;
|
|
98
|
+
auto query = std::span(output).subspan(q * slots * fields, slots * fields);
|
|
99
|
+
for (size_t g = 0; g < targets_.size(); ++g) {
|
|
100
|
+
const size_t cap = offsets_[g + 1] - offsets_[g];
|
|
101
|
+
if (!cap) continue;
|
|
102
|
+
const auto group = query.subspan(offsets_[g] * fields, cap * fields);
|
|
103
|
+
for (size_t i = 0; i < cap; ++i) group[i * fields] = inf;
|
|
104
|
+
ordered.clear();
|
|
105
|
+
for (const auto id : targets_[g])
|
|
106
|
+
if (row[id] != inf) ordered.push_back(row[id]);
|
|
107
|
+
if (ordered.empty()) continue;
|
|
108
|
+
if (distinct) {
|
|
109
|
+
std::sort(ordered.begin(), ordered.end());
|
|
110
|
+
ordered.erase(std::unique(ordered.begin(), ordered.end()), ordered.end());
|
|
111
|
+
} else {
|
|
112
|
+
std::partial_sort(ordered.begin(), ordered.begin() + std::min(cap, ordered.size()), ordered.end());
|
|
113
|
+
}
|
|
114
|
+
ordered.resize(std::min(cap, ordered.size()));
|
|
115
|
+
radii.clear();
|
|
116
|
+
std::unique_copy(ordered.begin(), ordered.end(), std::back_inserter(radii));
|
|
117
|
+
bins.assign(radii.size() * (fields + (taper_unit ? 2 : 0)), 0);
|
|
118
|
+
add_pool(row, targets_[g], target_weights_[g], radii, bins, true, taper_unit);
|
|
119
|
+
add_pool(row, controls_[g], control_weights_[g], radii, bins, false, taper_unit);
|
|
120
|
+
|
|
121
|
+
for (size_t i = 0; i < radii.size(); ++i) {
|
|
122
|
+
bins[i * fields] = radii[i];
|
|
123
|
+
if (i)
|
|
124
|
+
for (size_t j = 1; j < fields; ++j) bins[i * fields + j] += bins[(i - 1) * fields + j];
|
|
125
|
+
}
|
|
126
|
+
if (taper_unit) {
|
|
127
|
+
const size_t soft = radii.size() * fields;
|
|
128
|
+
for (size_t i = 0; i < radii.size(); ++i) {
|
|
129
|
+
bins[i * fields + 3] += bins[soft + 2 * i];
|
|
130
|
+
bins[i * fields + 4] += bins[soft + 2 * i + 1];
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
size_t bin = 0;
|
|
135
|
+
for (size_t i = 0; i < ordered.size(); ++i) {
|
|
136
|
+
if (ordered[i] != radii[bin]) ++bin;
|
|
137
|
+
std::copy_n(bins.begin() + bin * fields, fields, group.begin() + i * fields);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
});
|
|
141
|
+
return output;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
} // namespace seqtree
|
|
@@ -1,134 +0,0 @@
|
|
|
1
|
-
#pragma once
|
|
2
|
-
// One parallel-for scaffold for the whole tree. Every batch entry point in seqtree used to
|
|
3
|
-
// carry its own copy of this: an atomic cursor, an adaptive chunk, an exception_ptr, a vector
|
|
4
|
-
// of threads, and a rethrow after the join. Seven copies drifted -- one of them had no
|
|
5
|
-
// exception plumbing at all.
|
|
6
|
-
#include <algorithm>
|
|
7
|
-
#include <atomic>
|
|
8
|
-
#include <cstddef>
|
|
9
|
-
#include <cstdint>
|
|
10
|
-
#include <cstdlib>
|
|
11
|
-
#include <exception>
|
|
12
|
-
#include <fstream>
|
|
13
|
-
#include <mutex>
|
|
14
|
-
#include <stdexcept>
|
|
15
|
-
#include <thread>
|
|
16
|
-
#include <vector>
|
|
17
|
-
|
|
18
|
-
#ifdef __linux__
|
|
19
|
-
#include <sched.h>
|
|
20
|
-
#elif defined(__APPLE__)
|
|
21
|
-
#include <sys/sysctl.h>
|
|
22
|
-
#elif defined(_WIN32)
|
|
23
|
-
#ifndef NOMINMAX
|
|
24
|
-
#define NOMINMAX
|
|
25
|
-
#endif
|
|
26
|
-
#ifndef WIN32_LEAN_AND_MEAN
|
|
27
|
-
#define WIN32_LEAN_AND_MEAN
|
|
28
|
-
#endif
|
|
29
|
-
#include <windows.h>
|
|
30
|
-
#endif
|
|
31
|
-
|
|
32
|
-
namespace seqtree {
|
|
33
|
-
|
|
34
|
-
// Resolve once per batch; affinity/quota limits can change between calls.
|
|
35
|
-
inline unsigned available_cpus() {
|
|
36
|
-
unsigned count = std::max(1u, std::thread::hardware_concurrency());
|
|
37
|
-
#ifdef __linux__
|
|
38
|
-
cpu_set_t affinity;
|
|
39
|
-
if (sched_getaffinity(0, sizeof(affinity), &affinity) == 0)
|
|
40
|
-
count = std::min(count, unsigned(std::max(1, CPU_COUNT(&affinity))));
|
|
41
|
-
std::ifstream limits("/sys/fs/cgroup/cpu.max");
|
|
42
|
-
uint64_t quota, period;
|
|
43
|
-
if (limits >> quota >> period && period)
|
|
44
|
-
count = unsigned(std::min<uint64_t>(count, std::max<uint64_t>(1, quota / period)));
|
|
45
|
-
for (const char* name : {"SLURM_CPUS_PER_TASK", "SLURM_CPUS_ON_NODE"}) {
|
|
46
|
-
if (const char* value = std::getenv(name)) {
|
|
47
|
-
char* end = nullptr;
|
|
48
|
-
const auto allocated = std::strtoul(value, &end, 10);
|
|
49
|
-
if (end != value && !*end && allocated)
|
|
50
|
-
count = unsigned(std::min<unsigned long>(count, allocated));
|
|
51
|
-
}
|
|
52
|
-
}
|
|
53
|
-
#elif defined(__APPLE__)
|
|
54
|
-
unsigned physical = count;
|
|
55
|
-
size_t size = sizeof(physical);
|
|
56
|
-
if (sysctlbyname("hw.physicalcpu", &physical, &size, nullptr, 0) == 0 && physical)
|
|
57
|
-
count = std::min(count, physical);
|
|
58
|
-
#elif defined(_WIN32)
|
|
59
|
-
DWORD_PTR process_mask, system_mask;
|
|
60
|
-
if (GetProcessAffinityMask(GetCurrentProcess(), &process_mask, &system_mask)) {
|
|
61
|
-
unsigned allowed = 0;
|
|
62
|
-
for (; process_mask; process_mask &= process_mask - 1) ++allowed;
|
|
63
|
-
if (allowed) count = std::min(count, allowed);
|
|
64
|
-
}
|
|
65
|
-
#endif
|
|
66
|
-
return count;
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
// Runs body(i, local) for every i in [0, n), across nt workers pulling contiguous chunks off
|
|
70
|
-
// one atomic cursor. `threads <= 0` selects up to 16 available CPUs; positive counts may exceed that cap.
|
|
71
|
-
//
|
|
72
|
-
// `make_local()` is called once per worker and its result handed to every body() that worker
|
|
73
|
-
// runs -- that is how a Searcher or a scratch buffer gets allocated once per thread rather
|
|
74
|
-
// than once per item. Return a dummy for kernels that need no state.
|
|
75
|
-
//
|
|
76
|
-
// The chunk is adaptive: large batches keep ~1024 items per grab so the atomic is not the
|
|
77
|
-
// bottleneck, small ones split ~8 chunks per thread so no worker goes idle. Raise `chunk_min`
|
|
78
|
-
// when the per-item output struct is small enough that neighbouring workers would share a
|
|
79
|
-
// cache line (TextIndex's QueryOut is ~80 bytes, so it passes 8).
|
|
80
|
-
//
|
|
81
|
-
// Workers catch, the first exception is kept, and it is rethrown after the join. This is not
|
|
82
|
-
// optional: an exception escaping a std::thread entry function calls std::terminate, which
|
|
83
|
-
// from Python is an uncatchable SIGABRT rather than a raise.
|
|
84
|
-
template <class MakeLocal, class Body>
|
|
85
|
-
void parallel_for(size_t n, int threads, MakeLocal make_local, Body body,
|
|
86
|
-
size_t chunk_min = 1, size_t chunk_max = 1024) {
|
|
87
|
-
const unsigned available = available_cpus();
|
|
88
|
-
unsigned nt = threads > 0 ? unsigned(threads) : std::min(available, 16u);
|
|
89
|
-
if (nt > available || nt >= 1000)
|
|
90
|
-
throw std::invalid_argument("worker count exceeds the available CPU budget; request fewer threads");
|
|
91
|
-
if (n == 0) return;
|
|
92
|
-
nt = unsigned(std::min<size_t>(nt, n)); // Do not start idle workers for absent work.
|
|
93
|
-
|
|
94
|
-
// A serial budget runs on the calling thread; spawning one worker only adds overhead.
|
|
95
|
-
if (nt == 1) {
|
|
96
|
-
auto local = make_local();
|
|
97
|
-
for (size_t i = 0; i < n; ++i) body(i, local);
|
|
98
|
-
return;
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
std::atomic<size_t> next{0};
|
|
102
|
-
const size_t chunk = std::clamp<size_t>(n / (size_t(nt) * 8), chunk_min, chunk_max);
|
|
103
|
-
std::exception_ptr err;
|
|
104
|
-
std::mutex emu;
|
|
105
|
-
|
|
106
|
-
auto worker = [&] {
|
|
107
|
-
// Scratch construction can allocate and throw too. Nothing may escape the entry point.
|
|
108
|
-
try {
|
|
109
|
-
auto local = make_local();
|
|
110
|
-
for (;;) {
|
|
111
|
-
const size_t start = next.fetch_add(chunk);
|
|
112
|
-
if (start >= n) break;
|
|
113
|
-
const size_t end = std::min(n, start + chunk);
|
|
114
|
-
for (size_t i = start; i < end; ++i) {
|
|
115
|
-
body(i, local);
|
|
116
|
-
}
|
|
117
|
-
}
|
|
118
|
-
} catch (...) {
|
|
119
|
-
std::lock_guard<std::mutex> lk(emu);
|
|
120
|
-
if (!err) err = std::current_exception();
|
|
121
|
-
}
|
|
122
|
-
};
|
|
123
|
-
|
|
124
|
-
// A failed thread launch must also join workers already started before unwinding.
|
|
125
|
-
std::vector<std::jthread> pool;
|
|
126
|
-
pool.reserve(nt);
|
|
127
|
-
// The caller is one compute thread: a budget B creates only B-1 OS workers.
|
|
128
|
-
for (unsigned t = 1; t < nt; ++t) pool.emplace_back(worker);
|
|
129
|
-
worker();
|
|
130
|
-
for (auto& th : pool) th.join();
|
|
131
|
-
if (err) std::rethrow_exception(err);
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
} // namespace seqtree
|
|
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
|
|
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
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|