bgsmap 1.0.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.
@@ -0,0 +1,26 @@
1
+ # Changelog
2
+
3
+ ## 1.0.0 (2026-11-20)
4
+
5
+ - First stable release of the `bgsmap` package and CLI, formerly `gsmap-burden`.
6
+ - Source archives and wheels use the same version as the CLI and run metadata.
7
+
8
+ ## 0.2.0
9
+
10
+ - Introduce the `bgsmap` package and CLI name and timestamped progress logging to stderr.
11
+ - Introduce primary **continuous analytic Gaussian-tail P values**, using the exact finite-population variance of the conditional within-stratum gene-label permutation distribution (new statistic-level inference; see docs/statistics.md).
12
+ - Write `p_analytic`, `logp_analytic`, `z_analytic`, analytic BH/Holm and corresponding competitive columns into the primary spot/domain result tables.
13
+ - All spatial / competitive region HTML, PDF and report tables use analytic P or `-log10(P)` (computed without float64 underflow). **No plots use `p_empirical`.** Top descriptive gene domain uses analytic competitive P.
14
+ - Optional permutations (`--permutations >=19`) go into standalone `*_permutation_diagnostics.tsv*` files, no longer limit or alter primary P. Default `--permutations 0`.
15
+ - Explicit error if attempting v0.2.0 `plot` on older empirical-only result tables; rerun the analysis first.
16
+ - Retain per-run (per phenotype) multiple testing scope; no cross-phenotype correction is added.
17
+ - Include exact-variance enumeration tests, extreme-tail log P tests, and HTML/PDF regression tests.
18
+ - Gaussian tail approximation requires empirical calibration in rare/sparse burden settings; no guarantee of exact small-P calibration is claimed.
19
+
20
+ ## 0.1.1 (2026-11-12)
21
+
22
+ - Recover `obs_names` via AnnData in backed mode when fast H5AD decoding produces zero GSS spot matches.
23
+ - Preserve exact spot-ID alignment; never align GSS to coordinates by row order.
24
+ - Add informative unmatched-ID diagnostics, alignment match logging, and `inspect --check-spots`.
25
+ - Inspect very-wide Feather GSS using Arrow schema metadata without materializing numerical values.
26
+ - No changes to the burden statistic, permutation algorithm, or existing CLI options.
@@ -0,0 +1,109 @@
1
+ # bgsmap v1.0.0 在 MOSTA E16.5 数据上的安装与使用
2
+
3
+ 适用于已有 gsMap 1.73.7 和 MOSTA GSS 文件的环境。可复用已生成的 GSS。
4
+
5
+ ## 1. 在服务器上安装新 WHL
6
+
7
+ 在保存 `bgsmap-1.0.0-py3-none-any.whl` 的目录中执行以下命令。
8
+
9
+ ```bash
10
+ conda activate gsmap
11
+ python -m pip install './bgsmap-1.0.0-py3-none-any.whl[all]'
12
+
13
+ python -c 'import bgsmap; print(bgsmap.__version__, bgsmap.__file__)'
14
+ bgsmap --version
15
+ ```
16
+
17
+ 预期版本为 `1.0.0`。旧项目的分发名为 `gsmap-burden`,新项目的分发名、导入名和 CLI 均为 `bgsmap`。
18
+
19
+ 也可从源码 ZIP 安装。
20
+
21
+ ```bash
22
+ unzip bgsmap-v1.0.0-source.zip
23
+ cd bgsmap-1.0.0
24
+ python -m pip install '.[all]'
25
+ ```
26
+
27
+ 两种方式**二选一**;推荐 WHL。
28
+
29
+ ## 2. 先执行无大矩阵加载的 spot 匹配检查
30
+
31
+ ```bash
32
+ BGS=/path/to/project
33
+ ROOT=/path/to/dataset
34
+ WORK="$BGS/Height_MOSTA_E16/GWAS/gsmap_work"
35
+ SAMPLE=E16.5_E1S1.MOSTA
36
+ ST="$ROOT/data/gsmap/mouse-e16-mosta/ST/E16.5_E1S1.MOSTA.h5ad"
37
+ GSS="$WORK/$SAMPLE/latent_to_gene/${SAMPLE}_gene_marker_score.feather"
38
+ BURDEN="$BGS/Height_MOSTA_E16/Burden/input/Height_pLoF_QC.tsv"
39
+
40
+ bgsmap inspect \
41
+ --gss "$GSS" \
42
+ --h5ad "$ST" \
43
+ --spatial-key spatial \
44
+ --annotation annotation \
45
+ --check-spots
46
+ ```
47
+
48
+ 预期 `"matched": 121767`。新增的 `inspect` 对 Feather 使用 `pyarrow` 的 schema-only 读取,不会将 121,767 个 spot 列全部转换成 pandas 矩阵。
49
+
50
+ ## 3. 测试运行(解析 P,0 次置换)
51
+
52
+ ```bash
53
+ OUT="$BGS/Height_MOSTA_E16/Burden/Height_pLoF_smoke"
54
+
55
+ bgsmap run \
56
+ --gss "$GSS" \
57
+ --gss-gene-col HUMAN_GENE_SYM \
58
+ --h5ad "$ST" \
59
+ --spatial-key spatial \
60
+ --annotation annotation \
61
+ --burden "$BURDEN" \
62
+ --gene-col gene_symbol \
63
+ --p-col Pvalue_Burden \
64
+ --trait-name Height_pLoF \
65
+ --score-mode logp \
66
+ --p-cap 30 \
67
+ --permutations 0 \
68
+ --chunk-size 32 \
69
+ --seed 42 \
70
+ --out "$OUT"
71
+ ```
72
+
73
+ 如果成功,检查 `run_metadata.json` 中的 `n_spots` 和 `n_genes`。正式主 P 值不依赖 permutation 次数;只有需要额外校准时才使用 `--permutations 999` 等参数。121,767 个 spot 与大量基因的密集矩阵计算仍可能占用较高内存。
74
+
75
+ ## 4. 正式运行(解析 P,0 次置换;按需增加校准置换)
76
+
77
+ ```bash
78
+ OUT="$BGS/Height_MOSTA_E16/Burden/Height_pLoF"
79
+
80
+ bgsmap run \
81
+ --gss "$GSS" \
82
+ --gss-gene-col HUMAN_GENE_SYM \
83
+ --h5ad "$ST" \
84
+ --spatial-key spatial \
85
+ --annotation annotation \
86
+ --burden "$BURDEN" \
87
+ --gene-col gene_symbol \
88
+ --p-col Pvalue_Burden \
89
+ --trait-name Height_pLoF \
90
+ --score-mode logp \
91
+ --p-cap 30 \
92
+ --permutations 0 \
93
+ --chunk-size 32 \
94
+ --seed 42 \
95
+ --out "$OUT"
96
+ ```
97
+
98
+ **注意:** v0.2.0 已重新设计 P 值与全部主图:解析 P 为主,经验 P 仅保存于可选诊断文件(见 `docs/PVALUES_v0.2_CN.md`)。`--match-cols` 可用于条件基因可交换性建模。若使用 `--coords`,仍不自动启用 AnnData 回退。
99
+
100
+ ## 5. 如果仍报 `Only 0 GSS spots...`
101
+
102
+ 请提供:
103
+
104
+ ```bash
105
+ python -c 'import bgsmap; print(bgsmap.__version__, bgsmap.__file__)'
106
+ bgsmap inspect --gss "$GSS" --h5ad "$ST" --annotation annotation --check-spots
107
+ ```
108
+
109
+ 新异常会包括 GSS/H5AD 读取后的前五个 ID,可精确定位是哪个适配器产生了差异。不要在没有逐项确认 spot ID 对应关系时按行顺序强行拼接。
bgsmap-1.0.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 gsMap-burden contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,3 @@
1
+ include CHANGELOG.md INSTALL_MOSTA_CN.md README_CN.md
2
+ recursive-include docs *.md
3
+ recursive-include examples *.json
bgsmap-1.0.0/PKG-INFO ADDED
@@ -0,0 +1,220 @@
1
+ Metadata-Version: 2.4
2
+ Name: bgsmap
3
+ Version: 1.0.0
4
+ Summary: Spatial rare-variant burden enrichment using gsMap gene specificity scores
5
+ Author: gsMap-burden contributors
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/vince595/bgsmap
8
+ Project-URL: Issues, https://github.com/vince595/bgsmap/issues
9
+ Keywords: spatial transcriptomics,burden test,rare variants,gsMap
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
12
+ Requires-Python: >=3.10
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Requires-Dist: numpy<3,>=1.23
16
+ Requires-Dist: pandas<3,>=1.5
17
+ Requires-Dist: scipy<2,>=1.10
18
+ Requires-Dist: matplotlib<4,>=3.6
19
+ Requires-Dist: plotly<7,>=5
20
+ Provides-Extra: feather
21
+ Requires-Dist: pyarrow>=14; extra == "feather"
22
+ Provides-Extra: h5ad
23
+ Requires-Dist: h5py>=3.8; extra == "h5ad"
24
+ Provides-Extra: all
25
+ Requires-Dist: pyarrow>=14; extra == "all"
26
+ Requires-Dist: h5py>=3.8; extra == "all"
27
+ Provides-Extra: dev
28
+ Requires-Dist: pytest>=7; extra == "dev"
29
+ Requires-Dist: build>=1; extra == "dev"
30
+ Requires-Dist: ruff>=0.7; extra == "dev"
31
+ Dynamic: license-file
32
+
33
+ # bgsmap
34
+
35
+ [简体中文](https://github.com/vince595/bgsmap/blob/main/README_CN.md)
36
+
37
+ bgsmap integrates gene-level rare-variant burden summaries with gene specificity scores (GSS) from [gsMap](https://github.com/JianYang-Lab/gsMap). It computes enrichment per spatial spot and domain and exports TSV, interactive HTML, and vector PDF.
38
+
39
+ Version 1.0.0 uses normal-tail approximations for its primary P values and saves optional empirical permutation diagnostics in separate files. See the [statistical model](https://github.com/vince595/bgsmap/blob/main/docs/statistics.md) or the [P-value migration guide (Chinese)](https://github.com/vince595/bgsmap/blob/main/docs/PVALUES_v0.2_CN.md).
40
+
41
+ ## Install
42
+
43
+ Python 3.10 or later. Once bgsmap is published to PyPI, install it with either command:
44
+
45
+ ```bash
46
+ python -m pip install bgsmap
47
+ python -m pip install -i https://pypi.tuna.tsinghua.edu.cn/simple bgsmap
48
+ ```
49
+
50
+ The Tsinghua mirror makes new releases available after it syncs with PyPI. Until then, install from the release wheel or an unpacked source tree:
51
+
52
+ ```bash
53
+ python -m pip install ./bgsmap-1.0.0-py3-none-any.whl
54
+ # Or run this from the unpacked source tree:
55
+ python -m pip install .
56
+ ```
57
+
58
+ For Feather and H5AD support, install `'bgsmap[all]'` from PyPI or `'.[all]'` from source. The `feather` extra also enables Parquet reading. The optional AnnData spot-ID fallback requires a separate `anndata` installation. The `quick` command additionally requires `gsMap` in a compatible Python environment.
59
+
60
+ ```bash
61
+ bgsmap --version
62
+ python -m bgsmap --help
63
+ ```
64
+
65
+ ## Workflow
66
+
67
+ ```text
68
+ Spatial H5AD ── gsMap GNN latent ── gsMap latent-to-gene GSS (gene × spot)
69
+ │
70
+ Gene-level burden summary (gene, p, mask) ── gene ID alignment and QC
71
+ │
72
+ GSS standardization + burden score
73
+ │
74
+ analytic conditional null (optional permutation diagnostics)
75
+ │
76
+ spot / region / competitive continuous P, logP, BH, Holm
77
+ │
78
+ interactive HTML + vector PDF + TSV
79
+ ```
80
+
81
+ Crucially, **no GWAS SNP-to-gene annotation, PLINK LD weights, LD-score generation, or S-LDSC are performed on burden summaries**.
82
+
83
+ ## 1. Demonstration without real data
84
+
85
+ ```bash
86
+ bgsmap demo --out examples/demo_data
87
+ bgsmap run \
88
+ --gss examples/demo_data/GSS.tsv.gz \
89
+ --burden examples/demo_data/burden.tsv.gz \
90
+ --coords examples/demo_data/spatial_coords.tsv \
91
+ --trait-name SyntheticTrait \
92
+ --permutations 0 \
93
+ --out results/demo
94
+ ```
95
+
96
+ The demo generates 160 genes, 96 spots, and a planted Domain 3 signal.
97
+
98
+ Commands print timestamped progress to stderr. The `run` and `inspect` commands write JSON to stdout. To save both streams separately, append `> summary.json 2> run.log` to a `run` command.
99
+
100
+ ## 2. From an existing gsMap GSS matrix (recommended)
101
+
102
+ Upstream gsMap's actual output format is a Feather file, with a `HUMAN_GENE_SYM` gene column and one column per spatial barcode:
103
+
104
+ ```text
105
+ {workdir}/{sample}/latent_to_gene/{sample}_gene_marker_score.feather
106
+ ```
107
+
108
+ Use the **matching** H5AD (same spot barcodes) and a real burden summary. Select the actual annotation and column names by inspection:
109
+
110
+ ```bash
111
+ bgsmap inspect --h5ad /path/to/Visium.h5ad --burden /path/to/Finngen_gene_burden.tsv.gz
112
+
113
+ bgsmap run \
114
+ --gss /path/to/Visium_gene_marker_score.feather \
115
+ --h5ad /path/to/Visium_add_latent.h5ad \
116
+ --annotation domain \
117
+ --burden /path/to/Finngen_gene_burden.tsv.gz \
118
+ --gene-col gene --p-col p \
119
+ --trait-name G6_MIGRAINE \
120
+ --permutations 0 --seed 42 \
121
+ --out results/G6_MIGRAINE
122
+ ```
123
+
124
+ The H5AD reader loads only `/obs` and `/obsm/spatial` (not the expression matrix), and supports AnnData categorical obs encoding. If your domain annotation is stored elsewhere, export `spot,x,y,domain` as TSV and use `--coords` instead of `--h5ad`. A multi-domain annotation is needed for the *competitive* region comparison.
125
+
126
+ To select one mask or trait from a multi-mask/multi-trait summary use `--mask-col Mask --mask Mask1.0.01` or `--trait-col trait --trait G6_MIGRAINE`. Ambiguous duplicate gene tests are **rejected by default**; the optional `--duplicate-policy bonferroni` conservatively corrects the selected minimum p-value for the number of tests per gene. Never mix masks without documenting that strategy.
127
+
128
+ ### Matching burden test power (strongly recommended)
129
+
130
+ A gene's burden p-value distribution can depend on gene length, number of qualifying variants, carrier counts, coverage, variant mask and other factors. Permuting all gene labels without correction is exploratory; for interpretable inference, match genes on available testing-power covariates:
131
+
132
+ ```bash
133
+ bgsmap run \
134
+ --gss /path/to/GSS.feather --h5ad /path/to/Visium.h5ad --annotation domain \
135
+ --burden /path/to/burden.tsv.gz --gene-col Gene --p-col P \
136
+ --covariates /path/to/gene_test_covariates.tsv \
137
+ --match-cols gene_length n_tested_variants \
138
+ --match-bins 4 --permutations 0 \
139
+ --out results/matched
140
+ ```
141
+
142
+ `gene_test_covariates.tsv` needs `gene,gene_length,n_tested_variants`. These columns may instead be present in the burden summary itself, in which case omit `--covariates`. Each joint stratum must contain at least 12 matched genes (small strata error rather than silent fallback). For actual burden results, a **matched null is preferred to an unrestricted gene-label shuffle**, but it is not a proof of calibration; gene-gene correlation and differences in burden test power can remain.
143
+
144
+ ### Mouse tissue versus human burden
145
+
146
+ Original gsMap `latent-to-gene` can convert mouse genes to human symbols with a species–human homolog file. If your existing GSS is *not* already human-annotated, pass a strictly one-to-one table:
147
+
148
+ ```tsv
149
+ st_gene burden_gene
150
+ MouseSymbol1 HumanSymbol1
151
+ MouseSymbol2 HumanSymbol2
152
+ ```
153
+
154
+ and add `--gene-map /path/to/one_to_one.tsv`. This pipeline never silently transforms mouse gene symbols into human genes. The `run_metadata.json` file records the retained gene/spot counts.
155
+
156
+ ## 3. From raw spatial H5AD (reuse original gsMap)
157
+
158
+ ```bash
159
+ pip install gsMap
160
+
161
+ bgsmap quick \
162
+ --h5ad /path/to/V1_Adult_Mouse_Brain_Coronal_Section.h5ad \
163
+ --workdir work/gsMap_precompute --sample-name VisiumCoronal \
164
+ --data-layer counts --annotation domain \
165
+ --homolog-file /path/to/mouse_human_homolog.tsv \
166
+ --burden /path/to/FinnGen_MIGRAINE.tsv.gz \
167
+ --gene-col gene --p-col p \
168
+ --permutations 0 --out results/coronal
169
+ ```
170
+
171
+ `quick` uses upstream `gsMap.find_latent_representation` and `gsMap.latent_to_gene` and then calls this package's gene-level inference. **It has not been integration-tested against your server's gsMap version.** It does not call gsMap's GWAS analysis. To skip expensive GNN training when H5AD already has an embedding, pass `--latent-key latent_GVAE` (replace with your actual `obsm` key). Upstream gsMap may copy the H5AD into its workdir; keep sufficient disk space. Use `--force-gss` to recompute upstream steps.
172
+
173
+ ## 4. Configuration / figures
174
+
175
+ ```bash
176
+ # Edit the input and column names first
177
+ bgsmap run --config examples/visium_finngen.json
178
+ # Regenerate plots from tables that include analytic P values
179
+ bgsmap plot --out results/coronal --trait-name G6_MIGRAINE
180
+ ```
181
+
182
+ Output directory:
183
+
184
+ ```text
185
+ results/coronal/
186
+ ├── aligned_burden.tsv.gz
187
+ ├── spot_results.tsv.gz # spot, x/y, domain, T, p_analytic, logp_analytic, q_bh_analytic, p_holm_analytic
188
+ ├── region_results.tsv # region / competitive analytic p, logp, BH, Holm
189
+ ├── region_permutation_diagnostics.tsv # optional, only if permutations>0
190
+ ├── spot_permutation_diagnostics.tsv.gz # optional, only if permutations>0
191
+ ├── gene_contributions.tsv.gz # descriptive gene contributions
192
+ ├── run_metadata.json # seeds, method and gene/spots overlap
193
+ └── plots/
194
+ ├── report.html # offline report, links to interactive figures
195
+ ├── spatial_enrichment.html # offline Plotly, interactive (self-contained)
196
+ ├── spatial_enrichment.pdf # vector point symbols, two spatial panels
197
+ ├── region_enrichment.html
198
+ ├── region_enrichment.pdf
199
+ └── gene_contributions.pdf
200
+ ```
201
+
202
+ PDFs use Matplotlib vector artists and embedded TrueType text (`pdf.fonttype=42`), editable with Adobe Illustrator (subject to font availability). HTML is standalone and can be opened locally without a web server. Copy the **entire** `plots` folder to preserve report iframe references.
203
+
204
+ ## Statistical model
205
+
206
+ See [the statistical model](https://github.com/vince595/bgsmap/blob/main/docs/statistics.md) for the exact conditional variance formula, Gaussian-tail approximation, competitive test, within-run multiplicity and validity limitations. Evaluate tail calibration on the intended data before drawing research conclusions.
207
+
208
+ ## Development
209
+
210
+ ```bash
211
+ python -m pip install -e '.[all,dev]'
212
+ python -m pytest -q
213
+ python -m build
214
+ ```
215
+
216
+ CI covers Python 3.10 and 3.12. Tests exercise the synthetic analysis and the HTML/PDF outputs.
217
+
218
+ ## License and citation
219
+
220
+ bgsmap is released under the [MIT license](https://github.com/vince595/bgsmap/blob/main/LICENSE). When using GSS computed by gsMap, cite the upstream paper. [Song et al., *Nature* 641, 932–941 (2025).](https://www.nature.com/articles/s41586-025-08757-x)
bgsmap-1.0.0/README.md ADDED
@@ -0,0 +1,188 @@
1
+ # bgsmap
2
+
3
+ [简体中文](https://github.com/vince595/bgsmap/blob/main/README_CN.md)
4
+
5
+ bgsmap integrates gene-level rare-variant burden summaries with gene specificity scores (GSS) from [gsMap](https://github.com/JianYang-Lab/gsMap). It computes enrichment per spatial spot and domain and exports TSV, interactive HTML, and vector PDF.
6
+
7
+ Version 1.0.0 uses normal-tail approximations for its primary P values and saves optional empirical permutation diagnostics in separate files. See the [statistical model](https://github.com/vince595/bgsmap/blob/main/docs/statistics.md) or the [P-value migration guide (Chinese)](https://github.com/vince595/bgsmap/blob/main/docs/PVALUES_v0.2_CN.md).
8
+
9
+ ## Install
10
+
11
+ Python 3.10 or later. Once bgsmap is published to PyPI, install it with either command:
12
+
13
+ ```bash
14
+ python -m pip install bgsmap
15
+ python -m pip install -i https://pypi.tuna.tsinghua.edu.cn/simple bgsmap
16
+ ```
17
+
18
+ The Tsinghua mirror makes new releases available after it syncs with PyPI. Until then, install from the release wheel or an unpacked source tree:
19
+
20
+ ```bash
21
+ python -m pip install ./bgsmap-1.0.0-py3-none-any.whl
22
+ # Or run this from the unpacked source tree:
23
+ python -m pip install .
24
+ ```
25
+
26
+ For Feather and H5AD support, install `'bgsmap[all]'` from PyPI or `'.[all]'` from source. The `feather` extra also enables Parquet reading. The optional AnnData spot-ID fallback requires a separate `anndata` installation. The `quick` command additionally requires `gsMap` in a compatible Python environment.
27
+
28
+ ```bash
29
+ bgsmap --version
30
+ python -m bgsmap --help
31
+ ```
32
+
33
+ ## Workflow
34
+
35
+ ```text
36
+ Spatial H5AD ── gsMap GNN latent ── gsMap latent-to-gene GSS (gene × spot)
37
+ │
38
+ Gene-level burden summary (gene, p, mask) ── gene ID alignment and QC
39
+ │
40
+ GSS standardization + burden score
41
+ │
42
+ analytic conditional null (optional permutation diagnostics)
43
+ │
44
+ spot / region / competitive continuous P, logP, BH, Holm
45
+ │
46
+ interactive HTML + vector PDF + TSV
47
+ ```
48
+
49
+ Crucially, **no GWAS SNP-to-gene annotation, PLINK LD weights, LD-score generation, or S-LDSC are performed on burden summaries**.
50
+
51
+ ## 1. Demonstration without real data
52
+
53
+ ```bash
54
+ bgsmap demo --out examples/demo_data
55
+ bgsmap run \
56
+ --gss examples/demo_data/GSS.tsv.gz \
57
+ --burden examples/demo_data/burden.tsv.gz \
58
+ --coords examples/demo_data/spatial_coords.tsv \
59
+ --trait-name SyntheticTrait \
60
+ --permutations 0 \
61
+ --out results/demo
62
+ ```
63
+
64
+ The demo generates 160 genes, 96 spots, and a planted Domain 3 signal.
65
+
66
+ Commands print timestamped progress to stderr. The `run` and `inspect` commands write JSON to stdout. To save both streams separately, append `> summary.json 2> run.log` to a `run` command.
67
+
68
+ ## 2. From an existing gsMap GSS matrix (recommended)
69
+
70
+ Upstream gsMap's actual output format is a Feather file, with a `HUMAN_GENE_SYM` gene column and one column per spatial barcode:
71
+
72
+ ```text
73
+ {workdir}/{sample}/latent_to_gene/{sample}_gene_marker_score.feather
74
+ ```
75
+
76
+ Use the **matching** H5AD (same spot barcodes) and a real burden summary. Select the actual annotation and column names by inspection:
77
+
78
+ ```bash
79
+ bgsmap inspect --h5ad /path/to/Visium.h5ad --burden /path/to/Finngen_gene_burden.tsv.gz
80
+
81
+ bgsmap run \
82
+ --gss /path/to/Visium_gene_marker_score.feather \
83
+ --h5ad /path/to/Visium_add_latent.h5ad \
84
+ --annotation domain \
85
+ --burden /path/to/Finngen_gene_burden.tsv.gz \
86
+ --gene-col gene --p-col p \
87
+ --trait-name G6_MIGRAINE \
88
+ --permutations 0 --seed 42 \
89
+ --out results/G6_MIGRAINE
90
+ ```
91
+
92
+ The H5AD reader loads only `/obs` and `/obsm/spatial` (not the expression matrix), and supports AnnData categorical obs encoding. If your domain annotation is stored elsewhere, export `spot,x,y,domain` as TSV and use `--coords` instead of `--h5ad`. A multi-domain annotation is needed for the *competitive* region comparison.
93
+
94
+ To select one mask or trait from a multi-mask/multi-trait summary use `--mask-col Mask --mask Mask1.0.01` or `--trait-col trait --trait G6_MIGRAINE`. Ambiguous duplicate gene tests are **rejected by default**; the optional `--duplicate-policy bonferroni` conservatively corrects the selected minimum p-value for the number of tests per gene. Never mix masks without documenting that strategy.
95
+
96
+ ### Matching burden test power (strongly recommended)
97
+
98
+ A gene's burden p-value distribution can depend on gene length, number of qualifying variants, carrier counts, coverage, variant mask and other factors. Permuting all gene labels without correction is exploratory; for interpretable inference, match genes on available testing-power covariates:
99
+
100
+ ```bash
101
+ bgsmap run \
102
+ --gss /path/to/GSS.feather --h5ad /path/to/Visium.h5ad --annotation domain \
103
+ --burden /path/to/burden.tsv.gz --gene-col Gene --p-col P \
104
+ --covariates /path/to/gene_test_covariates.tsv \
105
+ --match-cols gene_length n_tested_variants \
106
+ --match-bins 4 --permutations 0 \
107
+ --out results/matched
108
+ ```
109
+
110
+ `gene_test_covariates.tsv` needs `gene,gene_length,n_tested_variants`. These columns may instead be present in the burden summary itself, in which case omit `--covariates`. Each joint stratum must contain at least 12 matched genes (small strata error rather than silent fallback). For actual burden results, a **matched null is preferred to an unrestricted gene-label shuffle**, but it is not a proof of calibration; gene-gene correlation and differences in burden test power can remain.
111
+
112
+ ### Mouse tissue versus human burden
113
+
114
+ Original gsMap `latent-to-gene` can convert mouse genes to human symbols with a species–human homolog file. If your existing GSS is *not* already human-annotated, pass a strictly one-to-one table:
115
+
116
+ ```tsv
117
+ st_gene burden_gene
118
+ MouseSymbol1 HumanSymbol1
119
+ MouseSymbol2 HumanSymbol2
120
+ ```
121
+
122
+ and add `--gene-map /path/to/one_to_one.tsv`. This pipeline never silently transforms mouse gene symbols into human genes. The `run_metadata.json` file records the retained gene/spot counts.
123
+
124
+ ## 3. From raw spatial H5AD (reuse original gsMap)
125
+
126
+ ```bash
127
+ pip install gsMap
128
+
129
+ bgsmap quick \
130
+ --h5ad /path/to/V1_Adult_Mouse_Brain_Coronal_Section.h5ad \
131
+ --workdir work/gsMap_precompute --sample-name VisiumCoronal \
132
+ --data-layer counts --annotation domain \
133
+ --homolog-file /path/to/mouse_human_homolog.tsv \
134
+ --burden /path/to/FinnGen_MIGRAINE.tsv.gz \
135
+ --gene-col gene --p-col p \
136
+ --permutations 0 --out results/coronal
137
+ ```
138
+
139
+ `quick` uses upstream `gsMap.find_latent_representation` and `gsMap.latent_to_gene` and then calls this package's gene-level inference. **It has not been integration-tested against your server's gsMap version.** It does not call gsMap's GWAS analysis. To skip expensive GNN training when H5AD already has an embedding, pass `--latent-key latent_GVAE` (replace with your actual `obsm` key). Upstream gsMap may copy the H5AD into its workdir; keep sufficient disk space. Use `--force-gss` to recompute upstream steps.
140
+
141
+ ## 4. Configuration / figures
142
+
143
+ ```bash
144
+ # Edit the input and column names first
145
+ bgsmap run --config examples/visium_finngen.json
146
+ # Regenerate plots from tables that include analytic P values
147
+ bgsmap plot --out results/coronal --trait-name G6_MIGRAINE
148
+ ```
149
+
150
+ Output directory:
151
+
152
+ ```text
153
+ results/coronal/
154
+ ├── aligned_burden.tsv.gz
155
+ ├── spot_results.tsv.gz # spot, x/y, domain, T, p_analytic, logp_analytic, q_bh_analytic, p_holm_analytic
156
+ ├── region_results.tsv # region / competitive analytic p, logp, BH, Holm
157
+ ├── region_permutation_diagnostics.tsv # optional, only if permutations>0
158
+ ├── spot_permutation_diagnostics.tsv.gz # optional, only if permutations>0
159
+ ├── gene_contributions.tsv.gz # descriptive gene contributions
160
+ ├── run_metadata.json # seeds, method and gene/spots overlap
161
+ └── plots/
162
+ ├── report.html # offline report, links to interactive figures
163
+ ├── spatial_enrichment.html # offline Plotly, interactive (self-contained)
164
+ ├── spatial_enrichment.pdf # vector point symbols, two spatial panels
165
+ ├── region_enrichment.html
166
+ ├── region_enrichment.pdf
167
+ └── gene_contributions.pdf
168
+ ```
169
+
170
+ PDFs use Matplotlib vector artists and embedded TrueType text (`pdf.fonttype=42`), editable with Adobe Illustrator (subject to font availability). HTML is standalone and can be opened locally without a web server. Copy the **entire** `plots` folder to preserve report iframe references.
171
+
172
+ ## Statistical model
173
+
174
+ See [the statistical model](https://github.com/vince595/bgsmap/blob/main/docs/statistics.md) for the exact conditional variance formula, Gaussian-tail approximation, competitive test, within-run multiplicity and validity limitations. Evaluate tail calibration on the intended data before drawing research conclusions.
175
+
176
+ ## Development
177
+
178
+ ```bash
179
+ python -m pip install -e '.[all,dev]'
180
+ python -m pytest -q
181
+ python -m build
182
+ ```
183
+
184
+ CI covers Python 3.10 and 3.12. Tests exercise the synthetic analysis and the HTML/PDF outputs.
185
+
186
+ ## License and citation
187
+
188
+ bgsmap is released under the [MIT license](https://github.com/vince595/bgsmap/blob/main/LICENSE). When using GSS computed by gsMap, cite the upstream paper. [Song et al., *Nature* 641, 932–941 (2025).](https://www.nature.com/articles/s41586-025-08757-x)