dataframe-toolkit 0.17.0__tar.gz → 0.18.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 (61) hide show
  1. {dataframe_toolkit-0.17.0 → dataframe_toolkit-0.18.0}/PKG-INFO +29 -4
  2. {dataframe_toolkit-0.17.0 → dataframe_toolkit-0.18.0}/README.md +28 -3
  3. {dataframe_toolkit-0.17.0 → dataframe_toolkit-0.18.0}/pyproject.toml +1 -1
  4. {dataframe_toolkit-0.17.0 → dataframe_toolkit-0.18.0}/pyproject.toml.orig +1 -1
  5. {dataframe_toolkit-0.17.0 → dataframe_toolkit-0.18.0}/src/dftk/commands/__init__.py +1 -0
  6. {dataframe_toolkit-0.17.0 → dataframe_toolkit-0.18.0}/src/dftk/commands/dataset_cmd.py +26 -4
  7. {dataframe_toolkit-0.17.0 → dataframe_toolkit-0.18.0}/src/dftk/commands/eval_cmd.py +8 -2
  8. dataframe_toolkit-0.18.0/src/dftk/commands/manhattan_cmd.py +412 -0
  9. {dataframe_toolkit-0.17.0 → dataframe_toolkit-0.18.0}/src/dftk/common/evalfuncs.py +62 -5
  10. dataframe_toolkit-0.18.0/src/dftk/common/gwas.py +437 -0
  11. {dataframe_toolkit-0.17.0 → dataframe_toolkit-0.18.0}/src/dftk/common/io.py +30 -13
  12. dataframe_toolkit-0.18.0/src/dftk/common/stats.py +290 -0
  13. {dataframe_toolkit-0.17.0 → dataframe_toolkit-0.18.0}/src/dftk/skills/dftk/SKILL.md +7 -3
  14. dataframe_toolkit-0.17.0/src/dftk/common/stats.py +0 -214
  15. {dataframe_toolkit-0.17.0 → dataframe_toolkit-0.18.0}/src/dftk/__init__.py +0 -0
  16. {dataframe_toolkit-0.17.0 → dataframe_toolkit-0.18.0}/src/dftk/cli.py +0 -0
  17. {dataframe_toolkit-0.17.0 → dataframe_toolkit-0.18.0}/src/dftk/commands/annotate_cmd.py +0 -0
  18. {dataframe_toolkit-0.17.0 → dataframe_toolkit-0.18.0}/src/dftk/commands/append_cmd.py +0 -0
  19. {dataframe_toolkit-0.17.0 → dataframe_toolkit-0.18.0}/src/dftk/commands/base.py +0 -0
  20. {dataframe_toolkit-0.17.0 → dataframe_toolkit-0.18.0}/src/dftk/commands/binx_cmd.py +0 -0
  21. {dataframe_toolkit-0.17.0 → dataframe_toolkit-0.18.0}/src/dftk/commands/chi_cmd.py +0 -0
  22. {dataframe_toolkit-0.17.0 → dataframe_toolkit-0.18.0}/src/dftk/commands/clean_cmd.py +0 -0
  23. {dataframe_toolkit-0.17.0 → dataframe_toolkit-0.18.0}/src/dftk/commands/cleannames_cmd.py +0 -0
  24. {dataframe_toolkit-0.17.0 → dataframe_toolkit-0.18.0}/src/dftk/commands/concat_cmd.py +0 -0
  25. {dataframe_toolkit-0.17.0 → dataframe_toolkit-0.18.0}/src/dftk/commands/corr_cmd.py +0 -0
  26. {dataframe_toolkit-0.17.0 → dataframe_toolkit-0.18.0}/src/dftk/commands/describe_cmd.py +0 -0
  27. {dataframe_toolkit-0.17.0 → dataframe_toolkit-0.18.0}/src/dftk/commands/explode_cmd.py +0 -0
  28. {dataframe_toolkit-0.17.0 → dataframe_toolkit-0.18.0}/src/dftk/commands/fit_cmd.py +0 -0
  29. {dataframe_toolkit-0.17.0 → dataframe_toolkit-0.18.0}/src/dftk/commands/func_cmd.py +0 -0
  30. {dataframe_toolkit-0.17.0 → dataframe_toolkit-0.18.0}/src/dftk/commands/heatmap_cmd.py +0 -0
  31. {dataframe_toolkit-0.17.0 → dataframe_toolkit-0.18.0}/src/dftk/commands/help.py +0 -0
  32. {dataframe_toolkit-0.17.0 → dataframe_toolkit-0.18.0}/src/dftk/commands/hist_cmd.py +0 -0
  33. {dataframe_toolkit-0.17.0 → dataframe_toolkit-0.18.0}/src/dftk/commands/implode_cmd.py +0 -0
  34. {dataframe_toolkit-0.17.0 → dataframe_toolkit-0.18.0}/src/dftk/commands/info_cmd.py +0 -0
  35. {dataframe_toolkit-0.17.0 → dataframe_toolkit-0.18.0}/src/dftk/commands/interp_cmd.py +0 -0
  36. {dataframe_toolkit-0.17.0 → dataframe_toolkit-0.18.0}/src/dftk/commands/line_cmd.py +0 -0
  37. {dataframe_toolkit-0.17.0 → dataframe_toolkit-0.18.0}/src/dftk/commands/melt_cmd.py +0 -0
  38. {dataframe_toolkit-0.17.0 → dataframe_toolkit-0.18.0}/src/dftk/commands/merge_cmd.py +0 -0
  39. {dataframe_toolkit-0.17.0 → dataframe_toolkit-0.18.0}/src/dftk/commands/pairs_cmd.py +0 -0
  40. {dataframe_toolkit-0.17.0 → dataframe_toolkit-0.18.0}/src/dftk/commands/pivot_cmd.py +0 -0
  41. {dataframe_toolkit-0.17.0 → dataframe_toolkit-0.18.0}/src/dftk/commands/print_cmd.py +0 -0
  42. {dataframe_toolkit-0.17.0 → dataframe_toolkit-0.18.0}/src/dftk/commands/query_cmd.py +0 -0
  43. {dataframe_toolkit-0.17.0 → dataframe_toolkit-0.18.0}/src/dftk/commands/randvar_cmd.py +0 -0
  44. {dataframe_toolkit-0.17.0 → dataframe_toolkit-0.18.0}/src/dftk/commands/sample_cmd.py +0 -0
  45. {dataframe_toolkit-0.17.0 → dataframe_toolkit-0.18.0}/src/dftk/commands/scale_cmd.py +0 -0
  46. {dataframe_toolkit-0.17.0 → dataframe_toolkit-0.18.0}/src/dftk/commands/scat_cmd.py +0 -0
  47. {dataframe_toolkit-0.17.0 → dataframe_toolkit-0.18.0}/src/dftk/commands/segid_cmd.py +0 -0
  48. {dataframe_toolkit-0.17.0 → dataframe_toolkit-0.18.0}/src/dftk/commands/skill_cmd.py +0 -0
  49. {dataframe_toolkit-0.17.0 → dataframe_toolkit-0.18.0}/src/dftk/commands/split_cmd.py +0 -0
  50. {dataframe_toolkit-0.17.0 → dataframe_toolkit-0.18.0}/src/dftk/commands/stat_cmd.py +0 -0
  51. {dataframe_toolkit-0.17.0 → dataframe_toolkit-0.18.0}/src/dftk/commands/test_cmd.py +0 -0
  52. {dataframe_toolkit-0.17.0 → dataframe_toolkit-0.18.0}/src/dftk/commands/transpose_cmd.py +0 -0
  53. {dataframe_toolkit-0.17.0 → dataframe_toolkit-0.18.0}/src/dftk/commands/wstat_cmd.py +0 -0
  54. {dataframe_toolkit-0.17.0 → dataframe_toolkit-0.18.0}/src/dftk/common/__init__.py +0 -0
  55. {dataframe_toolkit-0.17.0 → dataframe_toolkit-0.18.0}/src/dftk/common/copula.py +0 -0
  56. {dataframe_toolkit-0.17.0 → dataframe_toolkit-0.18.0}/src/dftk/common/docformats.py +0 -0
  57. {dataframe_toolkit-0.17.0 → dataframe_toolkit-0.18.0}/src/dftk/common/plot.py +0 -0
  58. {dataframe_toolkit-0.17.0 → dataframe_toolkit-0.18.0}/src/dftk/common/seed.py +0 -0
  59. {dataframe_toolkit-0.17.0 → dataframe_toolkit-0.18.0}/src/dftk/common/seq.py +0 -0
  60. {dataframe_toolkit-0.17.0 → dataframe_toolkit-0.18.0}/src/dftk/io.py +0 -0
  61. {dataframe_toolkit-0.17.0 → dataframe_toolkit-0.18.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.0
3
+ Version: 0.18.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,13 @@ 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
+ | `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
171
 
164
172
  ### Utilities
165
173
 
166
174
  | Command | Description |
167
175
  |------------|--------------------------------------------------------------------------|
168
- | `dataset` | Load a curated example dataset from seaborn, statsmodels, or pydataset |
176
+ | `dataset` | Load a curated example dataset from dftk, seaborn, statsmodels, or pydataset |
169
177
  | `sample` | Random row sampling (with or without replacement, by count or fraction) |
170
178
  | `split` | Split a dataframe into one file per group |
171
179
  | `annotate` | Read and write provenance metadata (genome, source, …) in parquet files |
@@ -460,6 +468,23 @@ dftk dataset penguins -o | dftk pivot -i species -g island -v body_mass_g -f cou
460
468
  | dftk heatmap -y species --annot --cmap Blues -f penguin_counts.png
461
469
  ```
462
470
 
471
+ ### Manhattan plots
472
+
473
+ `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:
474
+
475
+ ```bash
476
+ dftk dataset gwas -o | dftk manhattan -f manhattan.png
477
+ dftk dataset gwas -o | dftk manhattan --ylim 0 40 --sig 1e-6 --suggestive none -f manhattan.png
478
+ ```
479
+
480
+ 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`:
481
+
482
+ ```bash
483
+ dftk dataset gwas -o | dftk manhattan --chi2col Chisq -f manhattan.png
484
+ ```
485
+
486
+ 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.
487
+
463
488
  ### Bootstrap confidence intervals
464
489
 
465
490
  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,13 @@ 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
+ | `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
141
 
134
142
  ### Utilities
135
143
 
136
144
  | Command | Description |
137
145
  |------------|--------------------------------------------------------------------------|
138
- | `dataset` | Load a curated example dataset from seaborn, statsmodels, or pydataset |
146
+ | `dataset` | Load a curated example dataset from dftk, seaborn, statsmodels, or pydataset |
139
147
  | `sample` | Random row sampling (with or without replacement, by count or fraction) |
140
148
  | `split` | Split a dataframe into one file per group |
141
149
  | `annotate` | Read and write provenance metadata (genome, source, …) in parquet files |
@@ -430,6 +438,23 @@ dftk dataset penguins -o | dftk pivot -i species -g island -v body_mass_g -f cou
430
438
  | dftk heatmap -y species --annot --cmap Blues -f penguin_counts.png
431
439
  ```
432
440
 
441
+ ### Manhattan plots
442
+
443
+ `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:
444
+
445
+ ```bash
446
+ dftk dataset gwas -o | dftk manhattan -f manhattan.png
447
+ dftk dataset gwas -o | dftk manhattan --ylim 0 40 --sig 1e-6 --suggestive none -f manhattan.png
448
+ ```
449
+
450
+ 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`:
451
+
452
+ ```bash
453
+ dftk dataset gwas -o | dftk manhattan --chi2col Chisq -f manhattan.png
454
+ ```
455
+
456
+ 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.
457
+
433
458
  ### Bootstrap confidence intervals
434
459
 
435
460
  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.0"
3
+ version = "0.18.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.0"
3
+ version = "0.18.0"
4
4
  description = "A command-line toolkit for DataFrame analysis and manipulation"
5
5
  readme = "README.md"
6
6
  authors = [
@@ -65,6 +65,7 @@ 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"),
68
69
  ],
69
70
  ),
70
71
  (
@@ -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
+ "(~44k 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,412 @@
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(parser: argparse.ArgumentParser) -> None:
107
+ """Column options shared by manhattan and locus."""
108
+ g = parser.add_argument_group("columns")
109
+ g.add_argument(
110
+ "--chrcol",
111
+ metavar="COL",
112
+ help=f"Chromosome column (default: {gwas.DEFAULT_CHR}).",
113
+ )
114
+ g.add_argument(
115
+ "--poscol",
116
+ metavar="COL",
117
+ help=f"Position column (default: {gwas.DEFAULT_POS}).",
118
+ )
119
+ p = g.add_mutually_exclusive_group()
120
+ p.add_argument(
121
+ "--pcol",
122
+ metavar="COL",
123
+ help=f"P-value column (default: {gwas.DEFAULT_P}).",
124
+ )
125
+ p.add_argument(
126
+ "--mlogpcol",
127
+ metavar="COL",
128
+ help="Column that already holds -log10(p), instead of a p-value.",
129
+ )
130
+ p.add_argument(
131
+ "--chi2col",
132
+ metavar="COL",
133
+ help="Chi-squared column, instead of a p-value; exact for p below 1e-308.",
134
+ )
135
+ g.add_argument(
136
+ "--chi2df",
137
+ default="1",
138
+ metavar="N|COL",
139
+ help="Degrees of freedom of --chi2col: a number or a column (default: 1).",
140
+ )
141
+
142
+
143
+ def gwas_table(df: pd.DataFrame, args: argparse.Namespace) -> pd.DataFrame:
144
+ """Return df with _chrom (label), _pos and _y (-log10 p); rows lacking any dropped.
145
+
146
+ The other columns are kept (for -g / --subgraphcol).
147
+ """
148
+ chrcol = gwas.find_column(
149
+ df, args.chrcol, gwas.DEFAULT_CHR, gwas.CHR_ALIASES, "--chrcol"
150
+ )
151
+ poscol = gwas.find_column(
152
+ df, args.poscol, gwas.DEFAULT_POS, gwas.POS_ALIASES, "--poscol"
153
+ )
154
+ y, _ = gwas.resolve_neglogp(df, args.pcol, args.mlogpcol, args.chi2col, args.chi2df)
155
+ out = df.copy()
156
+ out["_chrom"] = df[chrcol]
157
+ out["_pos"] = pd.to_numeric(df[poscol], errors="coerce")
158
+ out["_y"] = y
159
+ keep = out["_chrom"].notna() & out["_pos"].notna() & np.isfinite(out["_y"])
160
+ if not keep.all():
161
+ logger.info(
162
+ "Left out %d of %d rows without a chromosome, position or p-value",
163
+ int((~keep).sum()),
164
+ len(out),
165
+ )
166
+ out = out[keep]
167
+ if out.empty:
168
+ raise ValueError("No rows with a chromosome, a position and a p-value.")
169
+ return out
170
+
171
+
172
+ # ---------------------------------------------------------------------------
173
+ # Drawing
174
+ # ---------------------------------------------------------------------------
175
+
176
+
177
+ def _ylimits(y: np.ndarray, lines: list[float], args) -> tuple[float, float]:
178
+ top = max([float(np.max(y)) if y.size else 1.0, *lines, 1.0]) * 1.05
179
+ lo, hi = 0.0, top
180
+ if args.ylim is not None:
181
+ lo = _float_or(args.ylim[0], lo)
182
+ hi = _float_or(args.ylim[1], hi)
183
+ return lo, hi
184
+
185
+
186
+ def _float_or(s, fallback: float) -> float:
187
+ try:
188
+ return float(s)
189
+ except (TypeError, ValueError):
190
+ return fallback
191
+
192
+
193
+ def _scatter(ax, x, y, hi, args, colours=None, **kw):
194
+ """Points below *hi*, and triangles on the top edge for those above it.
195
+
196
+ *colours*: one colour per point (alternating chromosomes), or None to
197
+ use kw["color"].
198
+ """
199
+ over = y > hi
200
+ size = args.markersize
201
+ common = dict(alpha=args.alpha, linewidths=0, **kw)
202
+ ax.scatter(
203
+ x[~over], y[~over], s=size, rasterized=True,
204
+ c=None if colours is None else colours[~over], **common,
205
+ ) # fmt: skip
206
+ if over.any():
207
+ common.pop("label", None)
208
+ ax.scatter(
209
+ x[over], np.full(over.sum(), hi), s=size * 4, marker="^",
210
+ clip_on=False, c=None if colours is None else colours[over], **common,
211
+ ) # fmt: skip
212
+
213
+
214
+ def _draw(ax, data: pd.DataFrame, layout, args, groupcols=None) -> None:
215
+ centres, labels, bounds = layout
216
+ x = data["_x"].to_numpy()
217
+ y = data["_y"].to_numpy()
218
+ lines = [-np.log10(p) for p in (args.sig, args.suggestive) if p is not None]
219
+ lo, hi = _ylimits(y, lines, args)
220
+
221
+ groups = None
222
+ if groupcols:
223
+ groups = data[groupcols].astype(str).agg("\t".join, axis=1).to_numpy()
224
+ keep = (
225
+ gwas.thin_mask(x, y, groups=groups)
226
+ if args.thin
227
+ else np.ones(len(x), dtype=bool)
228
+ )
229
+ if args.thin and (~keep).any():
230
+ logger.info("Thinned %d of %d points (p > 0.01)", int((~keep).sum()), len(x))
231
+
232
+ if groupcols:
233
+ # with colours used for groups, grey bands tell the chromosomes apart
234
+ pad = _gap(bounds)
235
+ for i, (start, end) in enumerate(bounds):
236
+ if i % 2:
237
+ ax.axvspan(start - pad, end + pad, color=_BAND_COLOUR, lw=0, zorder=0)
238
+ for n, (name, gdf) in enumerate(
239
+ subgraph_groups(data[keep], groupcols, args.groupcolorder)
240
+ ):
241
+ label = make_grouplabel(name, groupcols, args.groupcolformat)
242
+ colour = WONG_PALETTE[n % len(WONG_PALETTE)]
243
+ _scatter(
244
+ ax, gdf["_x"].to_numpy(), gdf["_y"].to_numpy(), hi, args,
245
+ color=colour, label=label, zorder=2,
246
+ ) # fmt: skip
247
+ ax.legend(
248
+ loc=tuple(args.legendloc) if args.legendloc else "best",
249
+ title=args.legendtitle,
250
+ markerscale=3,
251
+ )
252
+ else:
253
+ colours = np.array(args.colors)[data["_cidx"].to_numpy() % len(args.colors)]
254
+ _scatter(
255
+ ax, x[keep], y[keep], hi, args, colours=colours[keep], zorder=2,
256
+ label=args.legend,
257
+ ) # fmt: skip
258
+ if args.legend:
259
+ ax.legend(loc=tuple(args.legendloc) if args.legendloc else "best")
260
+
261
+ if args.sig is not None:
262
+ ax.axhline(-np.log10(args.sig), color=_SIG_COLOUR, lw=0.8, ls="--", zorder=3)
263
+ if args.suggestive is not None:
264
+ ax.axhline(
265
+ -np.log10(args.suggestive), color=_SUGGESTIVE_COLOUR, lw=0.8, ls=":",
266
+ zorder=3,
267
+ ) # fmt: skip
268
+
269
+ ax.set_ylim(lo, hi)
270
+ pad = _gap(bounds)
271
+ ax.set_xlim(bounds[0][0] - pad, bounds[-1][1] + pad)
272
+ ax.set_xticks(centres)
273
+ ax.set_xticklabels(_tick_labels(labels, ax))
274
+ ax.tick_params(axis="x", length=0)
275
+ ax.spines[["top", "right"]].set_visible(False)
276
+ ax.set_xlabel(args.xlabel if args.xlabel is not None else "Chromosome")
277
+ ax.set_ylabel(args.ylabel if args.ylabel is not None else r"$-\log_{10}(p)$")
278
+
279
+
280
+ def _gap(bounds) -> float:
281
+ """Half the space between two chromosomes (or 0.5 % of the axis)."""
282
+ if len(bounds) > 1:
283
+ return (bounds[1][0] - bounds[0][1]) / 2
284
+ return max(bounds[0][1] - bounds[0][0], 1.0) * 0.005
285
+
286
+
287
+ def _tick_labels(labels: list[str], ax) -> list[str]:
288
+ """Every chromosome, or every other one when they'd crowd a narrow axes."""
289
+ width_in = ax.get_position().width * ax.figure.get_figwidth()
290
+ if len(labels) <= 1.5 * width_in * 2:
291
+ return labels
292
+ return [c if i % 2 == 0 or not c.isdigit() else "" for i, c in enumerate(labels)]
293
+
294
+
295
+ # ---------------------------------------------------------------------------
296
+ # Command
297
+ # ---------------------------------------------------------------------------
298
+
299
+
300
+ class ManhattanCommand(BaseCommand):
301
+ name = "manhattan"
302
+ help = "Manhattan plot: -log10(p) along the genome (Chr, pos, Pval)."
303
+
304
+ def add_arguments(self, parser: argparse.ArgumentParser) -> None:
305
+ parser.formatter_class = argparse.RawDescriptionHelpFormatter
306
+ parser.epilog = _EPILOG
307
+
308
+ self.add_read_arguments(parser)
309
+ add_gwas_column_arguments(parser)
310
+
311
+ g = parser.add_argument_group("manhattan")
312
+ g.add_argument(
313
+ "--sig",
314
+ type=_threshold,
315
+ default=5e-8,
316
+ metavar="P|none",
317
+ help="Genome-wide significance line, as a p-value (default: 5e-8).",
318
+ )
319
+ g.add_argument(
320
+ "--suggestive",
321
+ type=_threshold,
322
+ default=1e-5,
323
+ metavar="P|none",
324
+ help="Suggestive line, as a p-value (default: 1e-5).",
325
+ )
326
+ g.add_argument(
327
+ "--no-thin",
328
+ dest="thin",
329
+ action="store_false",
330
+ help="Draw every point (default: thin points with p > 0.01).",
331
+ )
332
+ g.add_argument(
333
+ "--colors",
334
+ nargs="+",
335
+ default=list(_CHROM_COLOURS),
336
+ metavar="COLOUR",
337
+ help="Colours that alternate along the chromosomes "
338
+ "(default: dark and light blue).",
339
+ )
340
+ g.add_argument(
341
+ "--markersize",
342
+ type=float,
343
+ default=4.0,
344
+ metavar="S",
345
+ help="Point area in pt² (default: 4).",
346
+ )
347
+ g.add_argument(
348
+ "--alpha",
349
+ type=float,
350
+ default=1.0,
351
+ metavar="A",
352
+ help="Point opacity, 0-1 (default: 1).",
353
+ )
354
+
355
+ a = parser.add_argument_group("axes")
356
+ a.add_argument("-xl", "--xlabel", metavar="TEXT", help="X-axis label.")
357
+ a.add_argument("-yl", "--ylabel", metavar="TEXT", help="Y-axis label.")
358
+ a.add_argument(
359
+ "-ym",
360
+ "--ylim",
361
+ nargs=2,
362
+ metavar=("LO", "HI"),
363
+ help="Y-axis limits in -log10(p); points above HI are drawn as "
364
+ "triangles on the top edge.",
365
+ )
366
+
367
+ add_figure_arguments(parser)
368
+ parser.set_defaults(size="12x4")
369
+ add_group_arguments(parser)
370
+ add_legend_arguments(parser)
371
+
372
+ def execute(self, args: argparse.Namespace) -> None:
373
+ df = io.read(args)
374
+ check_cols(df, args.groupcol, "-g/--groupcol")
375
+ check_cols(df, args.subgraphcol, "--subgraphcol")
376
+ data = gwas_table(df, args)
377
+
378
+ x, centres, labels, bounds = gwas.genome_positions(data["_chrom"], data["_pos"])
379
+ data["_x"] = x
380
+ data["_cidx"], _ = gwas.chrom_index(data["_chrom"])
381
+ layout = (centres, labels, bounds)
382
+
383
+ if args.file:
384
+ import matplotlib
385
+
386
+ matplotlib.use("Agg")
387
+ import matplotlib.pyplot as plt
388
+
389
+ if args.usetex:
390
+ plt.rc("text", usetex=True)
391
+ apply_style(args)
392
+
393
+ if args.subgraphcol is not None:
394
+ groups = subgraph_groups(data, args.subgraphcol, args.subgraphorder)
395
+ nrows, ncols = subgraph_layout(len(groups), args.ncols or 1)
396
+ fig, axes = make_figure(args, nrows=nrows, ncols=ncols)
397
+ for idx, (name, gdf) in enumerate(groups):
398
+ ax = axes[idx // ncols][idx % ncols]
399
+ _draw(ax, gdf, layout, args, args.groupcol)
400
+ ax.set_title(
401
+ make_grouplabel(name, args.subgraphcol, args.subgraphformat)
402
+ )
403
+ for idx in range(len(groups), nrows * ncols):
404
+ axes[idx // ncols][idx % ncols].set_visible(False)
405
+ if args.title:
406
+ fig.suptitle(args.title)
407
+ else:
408
+ fig, axes = make_figure(args)
409
+ _draw(axes[0][0], data, layout, args, args.groupcol)
410
+ axes[0][0].set_title(args.title or "")
411
+ fig.tight_layout()
412
+ save_or_show(fig, args)