dataframe-toolkit 0.17.1__tar.gz → 0.19.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. {dataframe_toolkit-0.17.1 → dataframe_toolkit-0.19.0}/PKG-INFO +37 -4
  2. {dataframe_toolkit-0.17.1 → dataframe_toolkit-0.19.0}/README.md +36 -3
  3. {dataframe_toolkit-0.17.1 → dataframe_toolkit-0.19.0}/pyproject.toml +1 -1
  4. {dataframe_toolkit-0.17.1 → dataframe_toolkit-0.19.0}/pyproject.toml.orig +1 -1
  5. {dataframe_toolkit-0.17.1 → dataframe_toolkit-0.19.0}/src/dftk/commands/__init__.py +2 -0
  6. {dataframe_toolkit-0.17.1 → dataframe_toolkit-0.19.0}/src/dftk/commands/dataset_cmd.py +26 -4
  7. {dataframe_toolkit-0.17.1 → dataframe_toolkit-0.19.0}/src/dftk/commands/eval_cmd.py +8 -2
  8. dataframe_toolkit-0.19.0/src/dftk/commands/manhattan_cmd.py +415 -0
  9. dataframe_toolkit-0.19.0/src/dftk/commands/qq_cmd.py +287 -0
  10. {dataframe_toolkit-0.17.1 → dataframe_toolkit-0.19.0}/src/dftk/common/evalfuncs.py +62 -5
  11. dataframe_toolkit-0.19.0/src/dftk/common/gwas.py +492 -0
  12. dataframe_toolkit-0.19.0/src/dftk/common/stats.py +290 -0
  13. {dataframe_toolkit-0.17.1 → dataframe_toolkit-0.19.0}/src/dftk/skills/dftk/SKILL.md +7 -2
  14. dataframe_toolkit-0.17.1/src/dftk/common/stats.py +0 -214
  15. {dataframe_toolkit-0.17.1 → dataframe_toolkit-0.19.0}/src/dftk/__init__.py +0 -0
  16. {dataframe_toolkit-0.17.1 → dataframe_toolkit-0.19.0}/src/dftk/cli.py +0 -0
  17. {dataframe_toolkit-0.17.1 → dataframe_toolkit-0.19.0}/src/dftk/commands/annotate_cmd.py +0 -0
  18. {dataframe_toolkit-0.17.1 → dataframe_toolkit-0.19.0}/src/dftk/commands/append_cmd.py +0 -0
  19. {dataframe_toolkit-0.17.1 → dataframe_toolkit-0.19.0}/src/dftk/commands/base.py +0 -0
  20. {dataframe_toolkit-0.17.1 → dataframe_toolkit-0.19.0}/src/dftk/commands/binx_cmd.py +0 -0
  21. {dataframe_toolkit-0.17.1 → dataframe_toolkit-0.19.0}/src/dftk/commands/chi_cmd.py +0 -0
  22. {dataframe_toolkit-0.17.1 → dataframe_toolkit-0.19.0}/src/dftk/commands/clean_cmd.py +0 -0
  23. {dataframe_toolkit-0.17.1 → dataframe_toolkit-0.19.0}/src/dftk/commands/cleannames_cmd.py +0 -0
  24. {dataframe_toolkit-0.17.1 → dataframe_toolkit-0.19.0}/src/dftk/commands/concat_cmd.py +0 -0
  25. {dataframe_toolkit-0.17.1 → dataframe_toolkit-0.19.0}/src/dftk/commands/corr_cmd.py +0 -0
  26. {dataframe_toolkit-0.17.1 → dataframe_toolkit-0.19.0}/src/dftk/commands/describe_cmd.py +0 -0
  27. {dataframe_toolkit-0.17.1 → dataframe_toolkit-0.19.0}/src/dftk/commands/explode_cmd.py +0 -0
  28. {dataframe_toolkit-0.17.1 → dataframe_toolkit-0.19.0}/src/dftk/commands/fit_cmd.py +0 -0
  29. {dataframe_toolkit-0.17.1 → dataframe_toolkit-0.19.0}/src/dftk/commands/func_cmd.py +0 -0
  30. {dataframe_toolkit-0.17.1 → dataframe_toolkit-0.19.0}/src/dftk/commands/heatmap_cmd.py +0 -0
  31. {dataframe_toolkit-0.17.1 → dataframe_toolkit-0.19.0}/src/dftk/commands/help.py +0 -0
  32. {dataframe_toolkit-0.17.1 → dataframe_toolkit-0.19.0}/src/dftk/commands/hist_cmd.py +0 -0
  33. {dataframe_toolkit-0.17.1 → dataframe_toolkit-0.19.0}/src/dftk/commands/implode_cmd.py +0 -0
  34. {dataframe_toolkit-0.17.1 → dataframe_toolkit-0.19.0}/src/dftk/commands/info_cmd.py +0 -0
  35. {dataframe_toolkit-0.17.1 → dataframe_toolkit-0.19.0}/src/dftk/commands/interp_cmd.py +0 -0
  36. {dataframe_toolkit-0.17.1 → dataframe_toolkit-0.19.0}/src/dftk/commands/line_cmd.py +0 -0
  37. {dataframe_toolkit-0.17.1 → dataframe_toolkit-0.19.0}/src/dftk/commands/melt_cmd.py +0 -0
  38. {dataframe_toolkit-0.17.1 → dataframe_toolkit-0.19.0}/src/dftk/commands/merge_cmd.py +0 -0
  39. {dataframe_toolkit-0.17.1 → dataframe_toolkit-0.19.0}/src/dftk/commands/pairs_cmd.py +0 -0
  40. {dataframe_toolkit-0.17.1 → dataframe_toolkit-0.19.0}/src/dftk/commands/pivot_cmd.py +0 -0
  41. {dataframe_toolkit-0.17.1 → dataframe_toolkit-0.19.0}/src/dftk/commands/print_cmd.py +0 -0
  42. {dataframe_toolkit-0.17.1 → dataframe_toolkit-0.19.0}/src/dftk/commands/query_cmd.py +0 -0
  43. {dataframe_toolkit-0.17.1 → dataframe_toolkit-0.19.0}/src/dftk/commands/randvar_cmd.py +0 -0
  44. {dataframe_toolkit-0.17.1 → dataframe_toolkit-0.19.0}/src/dftk/commands/sample_cmd.py +0 -0
  45. {dataframe_toolkit-0.17.1 → dataframe_toolkit-0.19.0}/src/dftk/commands/scale_cmd.py +0 -0
  46. {dataframe_toolkit-0.17.1 → dataframe_toolkit-0.19.0}/src/dftk/commands/scat_cmd.py +0 -0
  47. {dataframe_toolkit-0.17.1 → dataframe_toolkit-0.19.0}/src/dftk/commands/segid_cmd.py +0 -0
  48. {dataframe_toolkit-0.17.1 → dataframe_toolkit-0.19.0}/src/dftk/commands/skill_cmd.py +0 -0
  49. {dataframe_toolkit-0.17.1 → dataframe_toolkit-0.19.0}/src/dftk/commands/split_cmd.py +0 -0
  50. {dataframe_toolkit-0.17.1 → dataframe_toolkit-0.19.0}/src/dftk/commands/stat_cmd.py +0 -0
  51. {dataframe_toolkit-0.17.1 → dataframe_toolkit-0.19.0}/src/dftk/commands/test_cmd.py +0 -0
  52. {dataframe_toolkit-0.17.1 → dataframe_toolkit-0.19.0}/src/dftk/commands/transpose_cmd.py +0 -0
  53. {dataframe_toolkit-0.17.1 → dataframe_toolkit-0.19.0}/src/dftk/commands/wstat_cmd.py +0 -0
  54. {dataframe_toolkit-0.17.1 → dataframe_toolkit-0.19.0}/src/dftk/common/__init__.py +0 -0
  55. {dataframe_toolkit-0.17.1 → dataframe_toolkit-0.19.0}/src/dftk/common/copula.py +0 -0
  56. {dataframe_toolkit-0.17.1 → dataframe_toolkit-0.19.0}/src/dftk/common/docformats.py +0 -0
  57. {dataframe_toolkit-0.17.1 → dataframe_toolkit-0.19.0}/src/dftk/common/io.py +0 -0
  58. {dataframe_toolkit-0.17.1 → dataframe_toolkit-0.19.0}/src/dftk/common/plot.py +0 -0
  59. {dataframe_toolkit-0.17.1 → dataframe_toolkit-0.19.0}/src/dftk/common/seed.py +0 -0
  60. {dataframe_toolkit-0.17.1 → dataframe_toolkit-0.19.0}/src/dftk/common/seq.py +0 -0
  61. {dataframe_toolkit-0.17.1 → dataframe_toolkit-0.19.0}/src/dftk/io.py +0 -0
  62. {dataframe_toolkit-0.17.1 → dataframe_toolkit-0.19.0}/src/dftk/skills/dftk/references/snakemake.md +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: dataframe-toolkit
3
- Version: 0.17.1
3
+ Version: 0.19.0
4
4
  Summary: A command-line toolkit for DataFrame analysis and manipulation
5
5
  Keywords: dataframe,statistics,data analysis,CLI,TSV,pandas
6
6
  Author: Gunnar Pálsson
@@ -43,11 +43,18 @@ statistical modelling and publication-quality figures.
43
43
  **No data file handy?** Every example below uses `dftk dataset` to pull in a
44
44
  small, real dataset, so you can copy-paste any of them and run them right
45
45
  now. Run `dftk dataset --list` to browse everything available (dozens of
46
- datasets from seaborn, statsmodels, and pydataset). `dftk dataset NAME`
47
- searches all three sources in that order and returns the first match, so
46
+ datasets from seaborn, statsmodels, and pydataset, plus `gwas`, a synthetic
47
+ association scan made by dftk). `dftk dataset NAME` searches dftk, seaborn,
48
+ statsmodels and pydataset in that order and returns the first match, so
48
49
  `--source` is optional — pass it only to disambiguate a name that exists in
49
50
  more than one source, or to restrict the search.
50
51
 
52
+ **Cheatsheet:** two landscape pages with the commands, options, SQL idioms,
53
+ plots and pipeline recipes at a glance —
54
+ [dftk-cheatsheet.pdf](https://github.com/hemingur/dataframe-toolkit/blob/main/docs/cheatsheet/dftk-cheatsheet.pdf).
55
+ Every example on it is run against dftk when it is built
56
+ (`python docs/cheatsheet/make_cheatsheet.py`).
57
+
51
58
  ## Installation
52
59
 
53
60
  ```bash
@@ -160,12 +167,14 @@ publication-quality output.
160
167
  | `chi` | Corner-resolved chi-plot: whether tail dependence sits in the lower or upper corner |
161
168
  | `heatmap` | Coloured grid of values from a long (`-x -y -v`) or wide (`-y`) table; correlograms from `corr --all`, `--annot`, `--lower` |
162
169
  | `pairs` | Scatter-plot matrix with KDEs (or histograms) on the diagonal; `-g` colours groups, `--upper corr` puts r in the upper triangle |
170
+ | `qq` | QQ plot of p-values: observed against expected -log10(p), confidence band, genomic inflation λ; `-g` one curve and λ per group |
171
+ | `manhattan` | Genome-wide -log10(p) by position (`Chr`, `pos`, `Pval`, or `--mlogpcol`/`--chi2col`); significance lines, thinning for millions of variants, `-g`/`--subgraphcol` for several scans |
163
172
 
164
173
  ### Utilities
165
174
 
166
175
  | Command | Description |
167
176
  |------------|--------------------------------------------------------------------------|
168
- | `dataset` | Load a curated example dataset from seaborn, statsmodels, or pydataset |
177
+ | `dataset` | Load a curated example dataset from dftk, seaborn, statsmodels, or pydataset |
169
178
  | `sample` | Random row sampling (with or without replacement, by count or fraction) |
170
179
  | `split` | Split a dataframe into one file per group |
171
180
  | `annotate` | Read and write provenance metadata (genome, source, …) in parquet files |
@@ -460,6 +469,30 @@ dftk dataset penguins -o | dftk pivot -i species -g island -v body_mass_g -f cou
460
469
  | dftk heatmap -y species --annot --cmap Blues -f penguin_counts.png
461
470
  ```
462
471
 
472
+ ### Manhattan plots
473
+
474
+ `manhattan` draws -log10(p) of every variant along the genome, chromosomes end to end in order (1–22, X, Y, MT; a `chr` prefix is ignored). The columns are `Chr`, `pos` and `Pval` unless named with `--chrcol`, `--poscol` and `--pcol`; a missing default is looked for under common spellings (`CHR`, `#CHROM`, `BP`, `P`, …). `dataset gwas` is a synthetic scan to try it on:
475
+
476
+ ```bash
477
+ dftk dataset gwas -o | dftk manhattan -f manhattan.png
478
+ dftk dataset gwas -o | dftk manhattan --ylim 0 40 --sig 1e-6 --suggestive none -f manhattan.png
479
+ ```
480
+
481
+ A p-value below about 1e-308 is stored as 0, which plots as -log10(p) = 323 with a warning. A chi-squared column gives the true value however small p is (`--chi2df`, default 1, a number or a column), and `--mlogpcol` takes a column that already holds -log10(p), such as regenie's `LOG10P`:
482
+
483
+ ```bash
484
+ dftk dataset gwas -o | dftk manhattan --chi2col Chisq -f manhattan.png
485
+ ```
486
+
487
+ Points with p > 0.01 are thinned to one per cell of a grid finer than the figure (`--no-thin` draws all), and points are rasterized: ten million variants take a few seconds and a PDF stays small. `--ylim LO HI` caps the axis, with points above it drawn as triangles on the top edge. Several scans in one table: `--subgraphcol study` draws a panel each, `-g study` a colour each.
488
+
489
+ `qq` plots the same p-values (same column options, no chromosome or position needed) against what null tests would give, with a 95 % band (`--ci`) and the genomic inflation factor λ, the median chi-squared over its null median. A curve lifted off the diagonal from the start, λ above about 1.05, points to stratification or other inflation; a few points leaving it at the top are associations. With `-g`, each group gets its own curve and λ:
490
+
491
+ ```bash
492
+ dftk dataset gwas -o | dftk qq -f qq.png
493
+ dftk dataset gwas -o | dftk eval -f "Chisq = Chisq * 1.15" -o | dftk qq --chi2col Chisq -f qq.png
494
+ ```
495
+
463
496
  ### Bootstrap confidence intervals
464
497
 
465
498
  Bootstrap mode repeats the full stat computation N times on resampled data
@@ -13,11 +13,18 @@ statistical modelling and publication-quality figures.
13
13
  **No data file handy?** Every example below uses `dftk dataset` to pull in a
14
14
  small, real dataset, so you can copy-paste any of them and run them right
15
15
  now. Run `dftk dataset --list` to browse everything available (dozens of
16
- datasets from seaborn, statsmodels, and pydataset). `dftk dataset NAME`
17
- searches all three sources in that order and returns the first match, so
16
+ datasets from seaborn, statsmodels, and pydataset, plus `gwas`, a synthetic
17
+ association scan made by dftk). `dftk dataset NAME` searches dftk, seaborn,
18
+ statsmodels and pydataset in that order and returns the first match, so
18
19
  `--source` is optional — pass it only to disambiguate a name that exists in
19
20
  more than one source, or to restrict the search.
20
21
 
22
+ **Cheatsheet:** two landscape pages with the commands, options, SQL idioms,
23
+ plots and pipeline recipes at a glance —
24
+ [dftk-cheatsheet.pdf](https://github.com/hemingur/dataframe-toolkit/blob/main/docs/cheatsheet/dftk-cheatsheet.pdf).
25
+ Every example on it is run against dftk when it is built
26
+ (`python docs/cheatsheet/make_cheatsheet.py`).
27
+
21
28
  ## Installation
22
29
 
23
30
  ```bash
@@ -130,12 +137,14 @@ publication-quality output.
130
137
  | `chi` | Corner-resolved chi-plot: whether tail dependence sits in the lower or upper corner |
131
138
  | `heatmap` | Coloured grid of values from a long (`-x -y -v`) or wide (`-y`) table; correlograms from `corr --all`, `--annot`, `--lower` |
132
139
  | `pairs` | Scatter-plot matrix with KDEs (or histograms) on the diagonal; `-g` colours groups, `--upper corr` puts r in the upper triangle |
140
+ | `qq` | QQ plot of p-values: observed against expected -log10(p), confidence band, genomic inflation λ; `-g` one curve and λ per group |
141
+ | `manhattan` | Genome-wide -log10(p) by position (`Chr`, `pos`, `Pval`, or `--mlogpcol`/`--chi2col`); significance lines, thinning for millions of variants, `-g`/`--subgraphcol` for several scans |
133
142
 
134
143
  ### Utilities
135
144
 
136
145
  | Command | Description |
137
146
  |------------|--------------------------------------------------------------------------|
138
- | `dataset` | Load a curated example dataset from seaborn, statsmodels, or pydataset |
147
+ | `dataset` | Load a curated example dataset from dftk, seaborn, statsmodels, or pydataset |
139
148
  | `sample` | Random row sampling (with or without replacement, by count or fraction) |
140
149
  | `split` | Split a dataframe into one file per group |
141
150
  | `annotate` | Read and write provenance metadata (genome, source, …) in parquet files |
@@ -430,6 +439,30 @@ dftk dataset penguins -o | dftk pivot -i species -g island -v body_mass_g -f cou
430
439
  | dftk heatmap -y species --annot --cmap Blues -f penguin_counts.png
431
440
  ```
432
441
 
442
+ ### Manhattan plots
443
+
444
+ `manhattan` draws -log10(p) of every variant along the genome, chromosomes end to end in order (1–22, X, Y, MT; a `chr` prefix is ignored). The columns are `Chr`, `pos` and `Pval` unless named with `--chrcol`, `--poscol` and `--pcol`; a missing default is looked for under common spellings (`CHR`, `#CHROM`, `BP`, `P`, …). `dataset gwas` is a synthetic scan to try it on:
445
+
446
+ ```bash
447
+ dftk dataset gwas -o | dftk manhattan -f manhattan.png
448
+ dftk dataset gwas -o | dftk manhattan --ylim 0 40 --sig 1e-6 --suggestive none -f manhattan.png
449
+ ```
450
+
451
+ A p-value below about 1e-308 is stored as 0, which plots as -log10(p) = 323 with a warning. A chi-squared column gives the true value however small p is (`--chi2df`, default 1, a number or a column), and `--mlogpcol` takes a column that already holds -log10(p), such as regenie's `LOG10P`:
452
+
453
+ ```bash
454
+ dftk dataset gwas -o | dftk manhattan --chi2col Chisq -f manhattan.png
455
+ ```
456
+
457
+ Points with p > 0.01 are thinned to one per cell of a grid finer than the figure (`--no-thin` draws all), and points are rasterized: ten million variants take a few seconds and a PDF stays small. `--ylim LO HI` caps the axis, with points above it drawn as triangles on the top edge. Several scans in one table: `--subgraphcol study` draws a panel each, `-g study` a colour each.
458
+
459
+ `qq` plots the same p-values (same column options, no chromosome or position needed) against what null tests would give, with a 95 % band (`--ci`) and the genomic inflation factor λ, the median chi-squared over its null median. A curve lifted off the diagonal from the start, λ above about 1.05, points to stratification or other inflation; a few points leaving it at the top are associations. With `-g`, each group gets its own curve and λ:
460
+
461
+ ```bash
462
+ dftk dataset gwas -o | dftk qq -f qq.png
463
+ dftk dataset gwas -o | dftk eval -f "Chisq = Chisq * 1.15" -o | dftk qq --chi2col Chisq -f qq.png
464
+ ```
465
+
433
466
  ### Bootstrap confidence intervals
434
467
 
435
468
  Bootstrap mode repeats the full stat computation N times on resampled data
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "dataframe-toolkit"
3
- version = "0.17.1"
3
+ version = "0.19.0"
4
4
  description = "A command-line toolkit for DataFrame analysis and manipulation"
5
5
  readme = "README.md"
6
6
  keywords = [
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "dataframe-toolkit"
3
- version = "0.17.1"
3
+ version = "0.19.0"
4
4
  description = "A command-line toolkit for DataFrame analysis and manipulation"
5
5
  readme = "README.md"
6
6
  authors = [
@@ -65,6 +65,8 @@ COMMAND_GROUPS: list[tuple[str, list[tuple[str, str]]]] = [
65
65
  ("chi", "chi_cmd:ChiCommand"),
66
66
  ("heatmap", "heatmap_cmd:HeatmapCommand"),
67
67
  ("pairs", "pairs_cmd:PairsCommand"),
68
+ ("manhattan", "manhattan_cmd:ManhattanCommand"),
69
+ ("qq", "qq_cmd:QqCommand"),
68
70
  ],
69
71
  ),
70
72
  (
@@ -1,9 +1,9 @@
1
1
  """
2
2
  dftk.commands.dataset_cmd — the ``dftk dataset`` subcommand.
3
3
 
4
- Provides access to curated example datasets from seaborn, statsmodels,
5
- and (optionally) pydataset. Datasets are written to stdout as TSV or
6
- into the dftk parquet pipe with -o.
4
+ Provides access to curated example datasets from dftk itself (synthetic
5
+ data, e.g. ``gwas``), seaborn, statsmodels, and (optionally) pydataset.
6
+ Datasets are written to stdout as TSV or into the dftk parquet pipe with -o.
7
7
 
8
8
  Examples
9
9
  --------
@@ -28,6 +28,27 @@ from dftk.common.io import io
28
28
  # ---------------------------------------------------------------------------
29
29
 
30
30
 
31
+ # Datasets dftk makes itself (no download, no extra dependency).
32
+ _DFTK_DATASETS = {
33
+ "gwas": (
34
+ "synthetic association scan: SNP, Chr, pos, Pval, Chisq, r2 "
35
+ "(~121k variants, six peaks)"
36
+ ),
37
+ }
38
+
39
+
40
+ def _load_dftk(name: str) -> pd.DataFrame:
41
+ if name == "gwas":
42
+ from dftk.common.gwas import simulate_gwas
43
+
44
+ return simulate_gwas()
45
+ raise ValueError(f"dftk dataset {name!r} not found")
46
+
47
+
48
+ def _list_dftk() -> list[tuple[str, str, str]]:
49
+ return [("dftk", n, d) for n, d in _DFTK_DATASETS.items()]
50
+
51
+
31
52
  def _load_seaborn(name: str) -> pd.DataFrame:
32
53
  import seaborn as sns
33
54
 
@@ -91,6 +112,7 @@ def _list_pydataset() -> list[tuple[str, str, str]]:
91
112
 
92
113
  # Registry — built at import time so choices are accurate
93
114
  _SOURCES: dict[str, tuple] = {
115
+ "dftk": (_load_dftk, _list_dftk),
94
116
  "seaborn": (_load_seaborn, _list_seaborn),
95
117
  "statsmodels": (_load_statsmodels, _list_statsmodels),
96
118
  }
@@ -105,7 +127,7 @@ if _HAS_PYDATASET:
105
127
 
106
128
  class DatasetCommand(BaseCommand):
107
129
  name = "dataset"
108
- help = "Load a curated example dataset (seaborn, statsmodels, pydataset)"
130
+ help = "Load a curated example dataset (dftk, seaborn, statsmodels, pydataset)"
109
131
 
110
132
  def add_arguments(self, parser: argparse.ArgumentParser) -> None:
111
133
  io.parser_output(parser)
@@ -152,7 +152,10 @@ Available special functions:
152
152
  Path functions (applied element-wise):
153
153
  basename dirname exists getsize realpath
154
154
 
155
- Statistical functions (see common/stats.py):
155
+ Statistical functions (see common/stats.py). An argument is a column or
156
+ a number (chi2_to_neglogp(Chisq, 1)); a column with that name wins. The
157
+ conversions (pval2se to pval_to_chi2) run on whole columns, so millions
158
+ of rows take seconds; the exact tests run row by row.
156
159
  binom_test(k, n, p)
157
160
  fisher_test(a, b, c, d) — p-value
158
161
  fisher_OR(a, b, c, d) — odds ratio
@@ -160,10 +163,13 @@ Available special functions:
160
163
  boschloo_OR(a, b, c, d) — odds ratio
161
164
  pval2se(effect, pval)
162
165
  t2pval(t, df)
163
- chi2_to_neglogp(chi2, df)
166
+ chi2_to_neglogp(chi2, df) — exact even where p underflows to 0
164
167
  neglogp_to_chi2(neglogp, df)
165
168
  pval_to_chi2(pval, df)
166
169
  generalized_poisson_nll(x, lam, theta)
170
+ Example:
171
+ dftk dataset gwas -o | dftk eval -f "mlogp = chi2_to_neglogp(Chisq, 1)" -o \\
172
+ | dftk query --query "mlogp > 30"
167
173
 
168
174
 
169
175
  CONSTANT COLUMNS (-c)
@@ -0,0 +1,415 @@
1
+ """
2
+ dftk.commands.manhattan_cmd — dftk manhattan subcommand.
3
+
4
+ Genome-wide association plot: -log10(p) of every variant against its
5
+ position, chromosomes laid end to end in genome order. Column lookup,
6
+ -log10(p), chromosome order and thinning live in common/gwas.py, shared
7
+ with the locus plot.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import argparse
13
+ import logging
14
+
15
+ import numpy as np
16
+ import pandas as pd
17
+
18
+ from dftk.commands.base import BaseCommand
19
+ from dftk.common import gwas
20
+ from dftk.common.io import check_cols, io
21
+ from dftk.common.plot import (
22
+ WONG_PALETTE,
23
+ add_figure_arguments,
24
+ add_group_arguments,
25
+ add_legend_arguments,
26
+ apply_style,
27
+ make_figure,
28
+ make_grouplabel,
29
+ save_or_show,
30
+ subgraph_groups,
31
+ subgraph_layout,
32
+ )
33
+
34
+ logger = logging.getLogger(__name__)
35
+
36
+ _CHROM_COLOURS = ("#1F4E79", "#7FA7CF") # dark / light blue, alternating
37
+ _SIG_COLOUR = "#D55E00" # vermilion (Wong)
38
+ _SUGGESTIVE_COLOUR = "#0072B2" # blue (Wong)
39
+ _BAND_COLOUR = "#EDEDED" # alternate chromosomes' background with -g
40
+
41
+ _EPILOG = """\
42
+ Input: one row per variant with a chromosome, a position and a p-value.
43
+ The columns are Chr, pos and Pval unless named; a missing default is looked
44
+ for under common spellings, ignoring case (CHR, #CHROM, BP, POS, P, …), and
45
+ the column used is logged. Instead of a p-value, give -log10(p) with
46
+ --mlogpcol (regenie's LOG10P) or a chi-squared statistic with --chi2col
47
+ (--chi2df, default 1): p-values below about 1e-308 are stored as 0, and a
48
+ chi-squared column still gives their true -log10(p).
49
+
50
+ Chromosomes are drawn in genome order (1-22, X, Y, XY, MT, then others; a
51
+ "chr" prefix is ignored), each spanning its first to last variant. Points
52
+ with p > 0.01 are thinned to one per cell of a grid finer than the figure
53
+ can show (--no-thin to draw all): a scan of ten million variants draws a
54
+ few hundred thousand points and looks the same. Points are rasterized, so
55
+ a PDF stays small. Rows without a chromosome, position or p-value are
56
+ left out.
57
+
58
+ EXAMPLES
59
+ --------
60
+ Basic Manhattan plot (columns Chr, pos, Pval):
61
+
62
+ dftk manhattan data.tsv -f manhattan.png
63
+ dftk dataset gwas -o | dftk manhattan -f manhattan.png
64
+
65
+ From a chi-squared column (exact even where Pval underflows to 0):
66
+
67
+ dftk dataset gwas -o | dftk manhattan --chi2col Chisq -f manhattan.png
68
+
69
+ Other thresholds; no suggestive line:
70
+
71
+ dftk dataset gwas -o | dftk manhattan --sig 1e-6 --suggestive none -f m.png
72
+
73
+ Cap the y axis at 40 so the smaller peaks show; points above it are drawn
74
+ as triangles on the top edge:
75
+
76
+ dftk dataset gwas -o | dftk manhattan --ylim 0 40 -f manhattan.png
77
+
78
+ Several scans in one table (a study column): one panel each, or one colour
79
+ each with -g:
80
+
81
+ dftk manhattan all_studies.tsv --subgraphcol study -f manhattan.png
82
+ dftk manhattan all_studies.tsv -g study -f manhattan.png
83
+
84
+ Publication figure (Nature double column, PDF):
85
+
86
+ dftk dataset gwas -o | dftk manhattan --size 7.2x2.6 --fontsize publication \\
87
+ -f manhattan.pdf
88
+ """
89
+
90
+
91
+ def _threshold(value: str) -> float | None:
92
+ """--sig / --suggestive: a p-value, or 'none' for no line."""
93
+ if value.lower() == "none":
94
+ return None
95
+ try:
96
+ p = float(value)
97
+ except ValueError:
98
+ raise argparse.ArgumentTypeError(
99
+ f"expected a p-value or 'none', not {value!r}"
100
+ ) from None
101
+ if not 0 < p < 1:
102
+ raise argparse.ArgumentTypeError(f"p-value must be in (0, 1), not {value!r}")
103
+ return p
104
+
105
+
106
+ def add_gwas_column_arguments(
107
+ parser: argparse.ArgumentParser, position: bool = True
108
+ ) -> None:
109
+ """Column options shared by manhattan and qq (qq: position=False)."""
110
+ g = parser.add_argument_group("columns")
111
+ if position:
112
+ g.add_argument(
113
+ "--chrcol",
114
+ metavar="COL",
115
+ help=f"Chromosome column (default: {gwas.DEFAULT_CHR}).",
116
+ )
117
+ g.add_argument(
118
+ "--poscol",
119
+ metavar="COL",
120
+ help=f"Position column (default: {gwas.DEFAULT_POS}).",
121
+ )
122
+ p = g.add_mutually_exclusive_group()
123
+ p.add_argument(
124
+ "--pcol",
125
+ metavar="COL",
126
+ help=f"P-value column (default: {gwas.DEFAULT_P}).",
127
+ )
128
+ p.add_argument(
129
+ "--mlogpcol",
130
+ metavar="COL",
131
+ help="Column that already holds -log10(p), instead of a p-value.",
132
+ )
133
+ p.add_argument(
134
+ "--chi2col",
135
+ metavar="COL",
136
+ help="Chi-squared column, instead of a p-value; exact for p below 1e-308.",
137
+ )
138
+ g.add_argument(
139
+ "--chi2df",
140
+ default="1",
141
+ metavar="N|COL",
142
+ help="Degrees of freedom of --chi2col: a number or a column (default: 1).",
143
+ )
144
+
145
+
146
+ def gwas_table(df: pd.DataFrame, args: argparse.Namespace) -> pd.DataFrame:
147
+ """Return df with _chrom (label), _pos and _y (-log10 p); rows lacking any dropped.
148
+
149
+ The other columns are kept (for -g / --subgraphcol).
150
+ """
151
+ chrcol = gwas.find_column(
152
+ df, args.chrcol, gwas.DEFAULT_CHR, gwas.CHR_ALIASES, "--chrcol"
153
+ )
154
+ poscol = gwas.find_column(
155
+ df, args.poscol, gwas.DEFAULT_POS, gwas.POS_ALIASES, "--poscol"
156
+ )
157
+ y, _ = gwas.resolve_neglogp(df, args.pcol, args.mlogpcol, args.chi2col, args.chi2df)
158
+ out = df.copy()
159
+ out["_chrom"] = df[chrcol]
160
+ out["_pos"] = pd.to_numeric(df[poscol], errors="coerce")
161
+ out["_y"] = y
162
+ keep = out["_chrom"].notna() & out["_pos"].notna() & np.isfinite(out["_y"])
163
+ if not keep.all():
164
+ logger.info(
165
+ "Left out %d of %d rows without a chromosome, position or p-value",
166
+ int((~keep).sum()),
167
+ len(out),
168
+ )
169
+ out = out[keep]
170
+ if out.empty:
171
+ raise ValueError("No rows with a chromosome, a position and a p-value.")
172
+ return out
173
+
174
+
175
+ # ---------------------------------------------------------------------------
176
+ # Drawing
177
+ # ---------------------------------------------------------------------------
178
+
179
+
180
+ def _ylimits(y: np.ndarray, lines: list[float], args) -> tuple[float, float]:
181
+ top = max([float(np.max(y)) if y.size else 1.0, *lines, 1.0]) * 1.05
182
+ lo, hi = 0.0, top
183
+ if args.ylim is not None:
184
+ lo = float_or(args.ylim[0], lo)
185
+ hi = float_or(args.ylim[1], hi)
186
+ return lo, hi
187
+
188
+
189
+ def float_or(s, fallback: float) -> float:
190
+ try:
191
+ return float(s)
192
+ except (TypeError, ValueError):
193
+ return fallback
194
+
195
+
196
+ def scatter_capped(ax, x, y, hi, args, colours=None, **kw):
197
+ """Points below *hi*, and triangles on the top edge for those above it.
198
+
199
+ *colours*: one colour per point (alternating chromosomes), or None to
200
+ use kw["color"].
201
+ """
202
+ over = y > hi
203
+ size = args.markersize
204
+ common = dict(alpha=args.alpha, linewidths=0, **kw)
205
+ ax.scatter(
206
+ x[~over], y[~over], s=size, rasterized=True,
207
+ c=None if colours is None else colours[~over], **common,
208
+ ) # fmt: skip
209
+ if over.any():
210
+ common.pop("label", None)
211
+ ax.scatter(
212
+ x[over], np.full(over.sum(), hi), s=size * 4, marker="^",
213
+ clip_on=False, c=None if colours is None else colours[over], **common,
214
+ ) # fmt: skip
215
+
216
+
217
+ def _draw(ax, data: pd.DataFrame, layout, args, groupcols=None) -> None:
218
+ centres, labels, bounds = layout
219
+ x = data["_x"].to_numpy()
220
+ y = data["_y"].to_numpy()
221
+ lines = [-np.log10(p) for p in (args.sig, args.suggestive) if p is not None]
222
+ lo, hi = _ylimits(y, lines, args)
223
+
224
+ groups = None
225
+ if groupcols:
226
+ groups = data[groupcols].astype(str).agg("\t".join, axis=1).to_numpy()
227
+ keep = (
228
+ gwas.thin_mask(x, y, groups=groups)
229
+ if args.thin
230
+ else np.ones(len(x), dtype=bool)
231
+ )
232
+ if args.thin and (~keep).any():
233
+ logger.info("Thinned %d of %d points (p > 0.01)", int((~keep).sum()), len(x))
234
+
235
+ if groupcols:
236
+ # with colours used for groups, grey bands tell the chromosomes apart
237
+ pad = _gap(bounds)
238
+ for i, (start, end) in enumerate(bounds):
239
+ if i % 2:
240
+ ax.axvspan(start - pad, end + pad, color=_BAND_COLOUR, lw=0, zorder=0)
241
+ for n, (name, gdf) in enumerate(
242
+ subgraph_groups(data[keep], groupcols, args.groupcolorder)
243
+ ):
244
+ label = make_grouplabel(name, groupcols, args.groupcolformat)
245
+ colour = WONG_PALETTE[n % len(WONG_PALETTE)]
246
+ scatter_capped(
247
+ ax, gdf["_x"].to_numpy(), gdf["_y"].to_numpy(), hi, args,
248
+ color=colour, label=label, zorder=2,
249
+ ) # fmt: skip
250
+ ax.legend(
251
+ loc=tuple(args.legendloc) if args.legendloc else "best",
252
+ title=args.legendtitle,
253
+ markerscale=3,
254
+ )
255
+ else:
256
+ colours = np.array(args.colors)[data["_cidx"].to_numpy() % len(args.colors)]
257
+ scatter_capped(
258
+ ax, x[keep], y[keep], hi, args, colours=colours[keep], zorder=2,
259
+ label=args.legend,
260
+ ) # fmt: skip
261
+ if args.legend:
262
+ ax.legend(loc=tuple(args.legendloc) if args.legendloc else "best")
263
+
264
+ if args.sig is not None:
265
+ ax.axhline(-np.log10(args.sig), color=_SIG_COLOUR, lw=0.8, ls="--", zorder=3)
266
+ if args.suggestive is not None:
267
+ ax.axhline(
268
+ -np.log10(args.suggestive), color=_SUGGESTIVE_COLOUR, lw=0.8, ls=":",
269
+ zorder=3,
270
+ ) # fmt: skip
271
+
272
+ ax.set_ylim(lo, hi)
273
+ pad = _gap(bounds)
274
+ ax.set_xlim(bounds[0][0] - pad, bounds[-1][1] + pad)
275
+ ax.set_xticks(centres)
276
+ ax.set_xticklabels(_tick_labels(labels, ax))
277
+ ax.tick_params(axis="x", length=0)
278
+ ax.spines[["top", "right"]].set_visible(False)
279
+ ax.set_xlabel(args.xlabel if args.xlabel is not None else "Chromosome")
280
+ ax.set_ylabel(args.ylabel if args.ylabel is not None else r"$-\log_{10}(p)$")
281
+
282
+
283
+ def _gap(bounds) -> float:
284
+ """Half the space between two chromosomes (or 0.5 % of the axis)."""
285
+ if len(bounds) > 1:
286
+ return (bounds[1][0] - bounds[0][1]) / 2
287
+ return max(bounds[0][1] - bounds[0][0], 1.0) * 0.005
288
+
289
+
290
+ def _tick_labels(labels: list[str], ax) -> list[str]:
291
+ """Every chromosome, or every other one when they'd crowd a narrow axes."""
292
+ width_in = ax.get_position().width * ax.figure.get_figwidth()
293
+ if len(labels) <= 1.5 * width_in * 2:
294
+ return labels
295
+ return [c if i % 2 == 0 or not c.isdigit() else "" for i, c in enumerate(labels)]
296
+
297
+
298
+ # ---------------------------------------------------------------------------
299
+ # Command
300
+ # ---------------------------------------------------------------------------
301
+
302
+
303
+ class ManhattanCommand(BaseCommand):
304
+ name = "manhattan"
305
+ help = "Manhattan plot: -log10(p) along the genome (Chr, pos, Pval)."
306
+
307
+ def add_arguments(self, parser: argparse.ArgumentParser) -> None:
308
+ parser.formatter_class = argparse.RawDescriptionHelpFormatter
309
+ parser.epilog = _EPILOG
310
+
311
+ self.add_read_arguments(parser)
312
+ add_gwas_column_arguments(parser)
313
+
314
+ g = parser.add_argument_group("manhattan")
315
+ g.add_argument(
316
+ "--sig",
317
+ type=_threshold,
318
+ default=5e-8,
319
+ metavar="P|none",
320
+ help="Genome-wide significance line, as a p-value (default: 5e-8).",
321
+ )
322
+ g.add_argument(
323
+ "--suggestive",
324
+ type=_threshold,
325
+ default=1e-5,
326
+ metavar="P|none",
327
+ help="Suggestive line, as a p-value (default: 1e-5).",
328
+ )
329
+ g.add_argument(
330
+ "--no-thin",
331
+ dest="thin",
332
+ action="store_false",
333
+ help="Draw every point (default: thin points with p > 0.01).",
334
+ )
335
+ g.add_argument(
336
+ "--colors",
337
+ nargs="+",
338
+ default=list(_CHROM_COLOURS),
339
+ metavar="COLOUR",
340
+ help="Colours that alternate along the chromosomes "
341
+ "(default: dark and light blue).",
342
+ )
343
+ g.add_argument(
344
+ "--markersize",
345
+ type=float,
346
+ default=4.0,
347
+ metavar="S",
348
+ help="Point area in pt² (default: 4).",
349
+ )
350
+ g.add_argument(
351
+ "--alpha",
352
+ type=float,
353
+ default=1.0,
354
+ metavar="A",
355
+ help="Point opacity, 0-1 (default: 1).",
356
+ )
357
+
358
+ a = parser.add_argument_group("axes")
359
+ a.add_argument("-xl", "--xlabel", metavar="TEXT", help="X-axis label.")
360
+ a.add_argument("-yl", "--ylabel", metavar="TEXT", help="Y-axis label.")
361
+ a.add_argument(
362
+ "-ym",
363
+ "--ylim",
364
+ nargs=2,
365
+ metavar=("LO", "HI"),
366
+ help="Y-axis limits in -log10(p); points above HI are drawn as "
367
+ "triangles on the top edge.",
368
+ )
369
+
370
+ add_figure_arguments(parser)
371
+ parser.set_defaults(size="12x4")
372
+ add_group_arguments(parser)
373
+ add_legend_arguments(parser)
374
+
375
+ def execute(self, args: argparse.Namespace) -> None:
376
+ df = io.read(args)
377
+ check_cols(df, args.groupcol, "-g/--groupcol")
378
+ check_cols(df, args.subgraphcol, "--subgraphcol")
379
+ data = gwas_table(df, args)
380
+
381
+ x, centres, labels, bounds = gwas.genome_positions(data["_chrom"], data["_pos"])
382
+ data["_x"] = x
383
+ data["_cidx"], _ = gwas.chrom_index(data["_chrom"])
384
+ layout = (centres, labels, bounds)
385
+
386
+ if args.file:
387
+ import matplotlib
388
+
389
+ matplotlib.use("Agg")
390
+ import matplotlib.pyplot as plt
391
+
392
+ if args.usetex:
393
+ plt.rc("text", usetex=True)
394
+ apply_style(args)
395
+
396
+ if args.subgraphcol is not None:
397
+ groups = subgraph_groups(data, args.subgraphcol, args.subgraphorder)
398
+ nrows, ncols = subgraph_layout(len(groups), args.ncols or 1)
399
+ fig, axes = make_figure(args, nrows=nrows, ncols=ncols)
400
+ for idx, (name, gdf) in enumerate(groups):
401
+ ax = axes[idx // ncols][idx % ncols]
402
+ _draw(ax, gdf, layout, args, args.groupcol)
403
+ ax.set_title(
404
+ make_grouplabel(name, args.subgraphcol, args.subgraphformat)
405
+ )
406
+ for idx in range(len(groups), nrows * ncols):
407
+ axes[idx // ncols][idx % ncols].set_visible(False)
408
+ if args.title:
409
+ fig.suptitle(args.title)
410
+ else:
411
+ fig, axes = make_figure(args)
412
+ _draw(axes[0][0], data, layout, args, args.groupcol)
413
+ axes[0][0].set_title(args.title or "")
414
+ fig.tight_layout()
415
+ save_or_show(fig, args)