dataframe-toolkit 0.18.0__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.
- {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.19.0}/PKG-INFO +9 -1
- {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.19.0}/README.md +8 -0
- {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.19.0}/pyproject.toml +1 -1
- {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.19.0}/pyproject.toml.orig +1 -1
- {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.19.0}/src/dftk/commands/__init__.py +1 -0
- {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.19.0}/src/dftk/commands/dataset_cmd.py +1 -1
- {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.19.0}/src/dftk/commands/manhattan_cmd.py +21 -18
- dataframe_toolkit-0.19.0/src/dftk/commands/qq_cmd.py +287 -0
- {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.19.0}/src/dftk/common/gwas.py +65 -10
- {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.19.0}/src/dftk/skills/dftk/SKILL.md +3 -1
- {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.19.0}/src/dftk/__init__.py +0 -0
- {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.19.0}/src/dftk/cli.py +0 -0
- {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.19.0}/src/dftk/commands/annotate_cmd.py +0 -0
- {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.19.0}/src/dftk/commands/append_cmd.py +0 -0
- {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.19.0}/src/dftk/commands/base.py +0 -0
- {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.19.0}/src/dftk/commands/binx_cmd.py +0 -0
- {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.19.0}/src/dftk/commands/chi_cmd.py +0 -0
- {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.19.0}/src/dftk/commands/clean_cmd.py +0 -0
- {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.19.0}/src/dftk/commands/cleannames_cmd.py +0 -0
- {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.19.0}/src/dftk/commands/concat_cmd.py +0 -0
- {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.19.0}/src/dftk/commands/corr_cmd.py +0 -0
- {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.19.0}/src/dftk/commands/describe_cmd.py +0 -0
- {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.19.0}/src/dftk/commands/eval_cmd.py +0 -0
- {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.19.0}/src/dftk/commands/explode_cmd.py +0 -0
- {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.19.0}/src/dftk/commands/fit_cmd.py +0 -0
- {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.19.0}/src/dftk/commands/func_cmd.py +0 -0
- {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.19.0}/src/dftk/commands/heatmap_cmd.py +0 -0
- {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.19.0}/src/dftk/commands/help.py +0 -0
- {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.19.0}/src/dftk/commands/hist_cmd.py +0 -0
- {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.19.0}/src/dftk/commands/implode_cmd.py +0 -0
- {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.19.0}/src/dftk/commands/info_cmd.py +0 -0
- {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.19.0}/src/dftk/commands/interp_cmd.py +0 -0
- {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.19.0}/src/dftk/commands/line_cmd.py +0 -0
- {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.19.0}/src/dftk/commands/melt_cmd.py +0 -0
- {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.19.0}/src/dftk/commands/merge_cmd.py +0 -0
- {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.19.0}/src/dftk/commands/pairs_cmd.py +0 -0
- {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.19.0}/src/dftk/commands/pivot_cmd.py +0 -0
- {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.19.0}/src/dftk/commands/print_cmd.py +0 -0
- {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.19.0}/src/dftk/commands/query_cmd.py +0 -0
- {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.19.0}/src/dftk/commands/randvar_cmd.py +0 -0
- {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.19.0}/src/dftk/commands/sample_cmd.py +0 -0
- {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.19.0}/src/dftk/commands/scale_cmd.py +0 -0
- {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.19.0}/src/dftk/commands/scat_cmd.py +0 -0
- {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.19.0}/src/dftk/commands/segid_cmd.py +0 -0
- {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.19.0}/src/dftk/commands/skill_cmd.py +0 -0
- {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.19.0}/src/dftk/commands/split_cmd.py +0 -0
- {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.19.0}/src/dftk/commands/stat_cmd.py +0 -0
- {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.19.0}/src/dftk/commands/test_cmd.py +0 -0
- {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.19.0}/src/dftk/commands/transpose_cmd.py +0 -0
- {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.19.0}/src/dftk/commands/wstat_cmd.py +0 -0
- {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.19.0}/src/dftk/common/__init__.py +0 -0
- {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.19.0}/src/dftk/common/copula.py +0 -0
- {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.19.0}/src/dftk/common/docformats.py +0 -0
- {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.19.0}/src/dftk/common/evalfuncs.py +0 -0
- {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.19.0}/src/dftk/common/io.py +0 -0
- {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.19.0}/src/dftk/common/plot.py +0 -0
- {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.19.0}/src/dftk/common/seed.py +0 -0
- {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.19.0}/src/dftk/common/seq.py +0 -0
- {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.19.0}/src/dftk/common/stats.py +0 -0
- {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.19.0}/src/dftk/io.py +0 -0
- {dataframe_toolkit-0.18.0 → 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.
|
|
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
|
|
@@ -167,6 +167,7 @@ publication-quality output.
|
|
|
167
167
|
| `chi` | Corner-resolved chi-plot: whether tail dependence sits in the lower or upper corner |
|
|
168
168
|
| `heatmap` | Coloured grid of values from a long (`-x -y -v`) or wide (`-y`) table; correlograms from `corr --all`, `--annot`, `--lower` |
|
|
169
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 |
|
|
170
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 |
|
|
171
172
|
|
|
172
173
|
### Utilities
|
|
@@ -485,6 +486,13 @@ dftk dataset gwas -o | dftk manhattan --chi2col Chisq -f manhattan.png
|
|
|
485
486
|
|
|
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.
|
|
487
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
|
+
|
|
488
496
|
### Bootstrap confidence intervals
|
|
489
497
|
|
|
490
498
|
Bootstrap mode repeats the full stat computation N times on resampled data
|
|
@@ -137,6 +137,7 @@ publication-quality output.
|
|
|
137
137
|
| `chi` | Corner-resolved chi-plot: whether tail dependence sits in the lower or upper corner |
|
|
138
138
|
| `heatmap` | Coloured grid of values from a long (`-x -y -v`) or wide (`-y`) table; correlograms from `corr --all`, `--annot`, `--lower` |
|
|
139
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 |
|
|
140
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 |
|
|
141
142
|
|
|
142
143
|
### Utilities
|
|
@@ -455,6 +456,13 @@ dftk dataset gwas -o | dftk manhattan --chi2col Chisq -f manhattan.png
|
|
|
455
456
|
|
|
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.
|
|
457
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
|
+
|
|
458
466
|
### Bootstrap confidence intervals
|
|
459
467
|
|
|
460
468
|
Bootstrap mode repeats the full stat computation N times on resampled data
|
|
@@ -103,19 +103,22 @@ def _threshold(value: str) -> float | None:
|
|
|
103
103
|
return p
|
|
104
104
|
|
|
105
105
|
|
|
106
|
-
def add_gwas_column_arguments(
|
|
107
|
-
|
|
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)."""
|
|
108
110
|
g = parser.add_argument_group("columns")
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
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
|
+
)
|
|
119
122
|
p = g.add_mutually_exclusive_group()
|
|
120
123
|
p.add_argument(
|
|
121
124
|
"--pcol",
|
|
@@ -178,19 +181,19 @@ def _ylimits(y: np.ndarray, lines: list[float], args) -> tuple[float, float]:
|
|
|
178
181
|
top = max([float(np.max(y)) if y.size else 1.0, *lines, 1.0]) * 1.05
|
|
179
182
|
lo, hi = 0.0, top
|
|
180
183
|
if args.ylim is not None:
|
|
181
|
-
lo =
|
|
182
|
-
hi =
|
|
184
|
+
lo = float_or(args.ylim[0], lo)
|
|
185
|
+
hi = float_or(args.ylim[1], hi)
|
|
183
186
|
return lo, hi
|
|
184
187
|
|
|
185
188
|
|
|
186
|
-
def
|
|
189
|
+
def float_or(s, fallback: float) -> float:
|
|
187
190
|
try:
|
|
188
191
|
return float(s)
|
|
189
192
|
except (TypeError, ValueError):
|
|
190
193
|
return fallback
|
|
191
194
|
|
|
192
195
|
|
|
193
|
-
def
|
|
196
|
+
def scatter_capped(ax, x, y, hi, args, colours=None, **kw):
|
|
194
197
|
"""Points below *hi*, and triangles on the top edge for those above it.
|
|
195
198
|
|
|
196
199
|
*colours*: one colour per point (alternating chromosomes), or None to
|
|
@@ -240,7 +243,7 @@ def _draw(ax, data: pd.DataFrame, layout, args, groupcols=None) -> None:
|
|
|
240
243
|
):
|
|
241
244
|
label = make_grouplabel(name, groupcols, args.groupcolformat)
|
|
242
245
|
colour = WONG_PALETTE[n % len(WONG_PALETTE)]
|
|
243
|
-
|
|
246
|
+
scatter_capped(
|
|
244
247
|
ax, gdf["_x"].to_numpy(), gdf["_y"].to_numpy(), hi, args,
|
|
245
248
|
color=colour, label=label, zorder=2,
|
|
246
249
|
) # fmt: skip
|
|
@@ -251,7 +254,7 @@ def _draw(ax, data: pd.DataFrame, layout, args, groupcols=None) -> None:
|
|
|
251
254
|
)
|
|
252
255
|
else:
|
|
253
256
|
colours = np.array(args.colors)[data["_cidx"].to_numpy() % len(args.colors)]
|
|
254
|
-
|
|
257
|
+
scatter_capped(
|
|
255
258
|
ax, x[keep], y[keep], hi, args, colours=colours[keep], zorder=2,
|
|
256
259
|
label=args.legend,
|
|
257
260
|
) # fmt: skip
|
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
"""
|
|
2
|
+
dftk.commands.qq_cmd — dftk qq subcommand.
|
|
3
|
+
|
|
4
|
+
QQ plot of p-values: observed -log10(p), sorted, against what n null tests
|
|
5
|
+
would give, with a confidence band and the genomic inflation factor lambda.
|
|
6
|
+
Takes the p-values the same ways as manhattan (helpers in common/gwas.py).
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import argparse
|
|
12
|
+
import logging
|
|
13
|
+
|
|
14
|
+
import numpy as np
|
|
15
|
+
import pandas as pd
|
|
16
|
+
|
|
17
|
+
from dftk.commands.base import BaseCommand
|
|
18
|
+
from dftk.commands.manhattan_cmd import (
|
|
19
|
+
add_gwas_column_arguments,
|
|
20
|
+
float_or,
|
|
21
|
+
scatter_capped,
|
|
22
|
+
)
|
|
23
|
+
from dftk.common import gwas
|
|
24
|
+
from dftk.common.io import check_cols, io
|
|
25
|
+
from dftk.common.plot import (
|
|
26
|
+
WONG_PALETTE,
|
|
27
|
+
add_figure_arguments,
|
|
28
|
+
add_group_arguments,
|
|
29
|
+
add_legend_arguments,
|
|
30
|
+
apply_style,
|
|
31
|
+
make_figure,
|
|
32
|
+
make_grouplabel,
|
|
33
|
+
save_or_show,
|
|
34
|
+
subgraph_groups,
|
|
35
|
+
subgraph_layout,
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
logger = logging.getLogger(__name__)
|
|
39
|
+
|
|
40
|
+
_POINT_COLOUR = "#1F4E79" # the manhattan plot's dark blue
|
|
41
|
+
_BAND_COLOUR = "#BBBBBB"
|
|
42
|
+
|
|
43
|
+
_EPILOG = """\
|
|
44
|
+
Each point is one test: its -log10(p) (y) against the -log10(p) the same
|
|
45
|
+
rank would have if every test were null (x; the i-th smallest of n
|
|
46
|
+
uniform p-values averages i/(n+1)). Points on the diagonal: no signal. A
|
|
47
|
+
few points leaving it at the top right: associations. The whole curve
|
|
48
|
+
lifted off the diagonal from the start: inflation, e.g. population
|
|
49
|
+
stratification or relatedness. The grey band holds 95 % (--ci) of null
|
|
50
|
+
points at each rank.
|
|
51
|
+
|
|
52
|
+
lambda (genomic inflation factor) is the median chi-squared divided by its
|
|
53
|
+
null median (0.455 for 1 df), from the p-values whichever column they come
|
|
54
|
+
from; it is written on the plot and logged. About 1: no inflation. For a
|
|
55
|
+
chi-squared column with other degrees of freedom, give --chi2df.
|
|
56
|
+
|
|
57
|
+
P-values: the Pval column unless named, as in manhattan: --pcol,
|
|
58
|
+
--mlogpcol (already -log10(p)) or --chi2col (exact where p underflows to
|
|
59
|
+
0). Points near the origin are thinned to one per cell of a fine grid
|
|
60
|
+
(--no-thin to draw all); every point with p < 0.01 is drawn.
|
|
61
|
+
|
|
62
|
+
EXAMPLES
|
|
63
|
+
--------
|
|
64
|
+
Basic QQ plot (a Pval column):
|
|
65
|
+
|
|
66
|
+
dftk qq data.tsv -f qq.png
|
|
67
|
+
dftk dataset gwas -o | dftk qq -f qq.png
|
|
68
|
+
|
|
69
|
+
From a chi-squared column, here inflated by 15 % (lambda 1.02 → 1.18):
|
|
70
|
+
|
|
71
|
+
dftk dataset gwas -o | dftk eval -f "Chisq = Chisq * 1.15" -o \\
|
|
72
|
+
| dftk qq --chi2col Chisq -f qq.png
|
|
73
|
+
|
|
74
|
+
Cap the y axis; points above it are drawn as triangles on the top edge:
|
|
75
|
+
|
|
76
|
+
dftk dataset gwas -o | dftk qq --ylim 0 20 -f qq.png
|
|
77
|
+
|
|
78
|
+
Several scans (a study column), or one scan split by allele-frequency bin:
|
|
79
|
+
one curve and one lambda each with -g, or a panel each with --subgraphcol:
|
|
80
|
+
|
|
81
|
+
dftk qq all_studies.tsv -g study -f qq.png
|
|
82
|
+
|
|
83
|
+
lambda as a table, without the plot:
|
|
84
|
+
|
|
85
|
+
dftk dataset gwas -o | dftk eval -f "chi2 = pval_to_chi2(Pval, 1)" -o \\
|
|
86
|
+
| dftk stat -c chi2 -o | dftk eval -f "lam = median / 0.4549" --select median lam
|
|
87
|
+
(add -g study to stat for one row per study)
|
|
88
|
+
"""
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def qq_table(df: pd.DataFrame, args: argparse.Namespace) -> pd.DataFrame:
|
|
92
|
+
"""df with _y = -log10(p); rows without a p-value left out."""
|
|
93
|
+
y, _ = gwas.resolve_neglogp(df, args.pcol, args.mlogpcol, args.chi2col, args.chi2df)
|
|
94
|
+
out = df.assign(_y=y)
|
|
95
|
+
keep = np.isfinite(out["_y"])
|
|
96
|
+
if not keep.all():
|
|
97
|
+
logger.info(
|
|
98
|
+
"Left out %d of %d rows without a p-value", int((~keep).sum()), len(out)
|
|
99
|
+
)
|
|
100
|
+
out = out[keep]
|
|
101
|
+
if out.empty:
|
|
102
|
+
raise ValueError("No rows with a p-value.")
|
|
103
|
+
return out
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _lambda_df(args) -> float:
|
|
107
|
+
"""Degrees of freedom for lambda: --chi2df if it is a number, else 1."""
|
|
108
|
+
if args.chi2col is None:
|
|
109
|
+
return 1.0
|
|
110
|
+
try:
|
|
111
|
+
return float(args.chi2df)
|
|
112
|
+
except ValueError:
|
|
113
|
+
return 1.0 # per-row df: lambda on the 1-df scale
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _series(y: np.ndarray, args):
|
|
117
|
+
"""(expected, observed) for one curve, largest first, and its lambda."""
|
|
118
|
+
obs = np.sort(y)[::-1]
|
|
119
|
+
exp = gwas.qq_expected(len(obs))
|
|
120
|
+
return exp, obs, gwas.inflation_lambda(obs, _lambda_df(args))
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _draw(ax, data: pd.DataFrame, args, groupcols=None) -> None:
|
|
124
|
+
if groupcols:
|
|
125
|
+
groups = [
|
|
126
|
+
(
|
|
127
|
+
make_grouplabel(name, groupcols, args.groupcolformat),
|
|
128
|
+
gdf["_y"].to_numpy(),
|
|
129
|
+
)
|
|
130
|
+
for name, gdf in subgraph_groups(data, groupcols, args.groupcolorder)
|
|
131
|
+
]
|
|
132
|
+
else:
|
|
133
|
+
groups = [(args.legend, data["_y"].to_numpy())]
|
|
134
|
+
|
|
135
|
+
curves = [(label, *_series(y, args)) for label, y in groups]
|
|
136
|
+
top = max(max(c[1][0], c[2][0]) for c in curves) * 1.05
|
|
137
|
+
lo, hi = 0.0, top
|
|
138
|
+
if args.ylim is not None:
|
|
139
|
+
lo, hi = float_or(args.ylim[0], lo), float_or(args.ylim[1], hi)
|
|
140
|
+
xmax = max(c[1][0] for c in curves) * 1.02
|
|
141
|
+
|
|
142
|
+
if args.ci:
|
|
143
|
+
# one band, for the curve with the most tests (the others' are nested)
|
|
144
|
+
n = max(len(c[2]) for c in curves)
|
|
145
|
+
bx, blo, bhi = gwas.qq_band(n, args.ci)
|
|
146
|
+
ax.fill_between(bx, blo, bhi, color=_BAND_COLOUR, alpha=0.5, lw=0, zorder=0)
|
|
147
|
+
ax.plot([0, xmax], [0, xmax], color="black", lw=0.8, zorder=1)
|
|
148
|
+
|
|
149
|
+
for n, (label, exp, obs, lam) in enumerate(curves):
|
|
150
|
+
logger.info(
|
|
151
|
+
"lambda %s= %.4f (%d tests)", f"({label}) " if label else "", lam, len(obs)
|
|
152
|
+
)
|
|
153
|
+
keep = gwas.thin_mask(exp, obs) if args.thin else np.ones(len(obs), bool)
|
|
154
|
+
colour = WONG_PALETTE[n % len(WONG_PALETTE)] if groupcols else _POINT_COLOUR
|
|
155
|
+
if groupcols and args.show_lambda:
|
|
156
|
+
label = f"{label} (λ = {lam:.3f})"
|
|
157
|
+
scatter_capped(
|
|
158
|
+
ax, exp[keep], obs[keep], hi, args, color=colour, label=label, zorder=2
|
|
159
|
+
)
|
|
160
|
+
|
|
161
|
+
if groupcols or args.legend:
|
|
162
|
+
ax.legend(
|
|
163
|
+
loc=tuple(args.legendloc) if args.legendloc else "lower right",
|
|
164
|
+
title=args.legendtitle,
|
|
165
|
+
markerscale=3,
|
|
166
|
+
)
|
|
167
|
+
if args.show_lambda and not groupcols:
|
|
168
|
+
ax.text(
|
|
169
|
+
0.03, 0.97, f"λ = {curves[0][3]:.3f}", transform=ax.transAxes,
|
|
170
|
+
ha="left", va="top",
|
|
171
|
+
) # fmt: skip
|
|
172
|
+
|
|
173
|
+
ax.set_xlim(0, xmax)
|
|
174
|
+
ax.set_ylim(lo, hi)
|
|
175
|
+
ax.spines[["top", "right"]].set_visible(False)
|
|
176
|
+
ax.set_xlabel(
|
|
177
|
+
args.xlabel if args.xlabel is not None else r"Expected $-\log_{10}(p)$"
|
|
178
|
+
)
|
|
179
|
+
ax.set_ylabel(
|
|
180
|
+
args.ylabel if args.ylabel is not None else r"Observed $-\log_{10}(p)$"
|
|
181
|
+
)
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
class QqCommand(BaseCommand):
|
|
185
|
+
name = "qq"
|
|
186
|
+
help = "QQ plot of p-values with a confidence band and genomic inflation (lambda)."
|
|
187
|
+
|
|
188
|
+
def add_arguments(self, parser: argparse.ArgumentParser) -> None:
|
|
189
|
+
parser.formatter_class = argparse.RawDescriptionHelpFormatter
|
|
190
|
+
parser.epilog = _EPILOG
|
|
191
|
+
|
|
192
|
+
self.add_read_arguments(parser)
|
|
193
|
+
add_gwas_column_arguments(parser, position=False)
|
|
194
|
+
|
|
195
|
+
g = parser.add_argument_group("qq")
|
|
196
|
+
g.add_argument(
|
|
197
|
+
"--ci",
|
|
198
|
+
type=float,
|
|
199
|
+
default=0.95,
|
|
200
|
+
metavar="LEVEL",
|
|
201
|
+
help="Confidence band level (default: 0.95).",
|
|
202
|
+
)
|
|
203
|
+
g.add_argument(
|
|
204
|
+
"--no-ci", dest="ci", action="store_const", const=None, help="No band."
|
|
205
|
+
)
|
|
206
|
+
g.add_argument(
|
|
207
|
+
"--no-lambda",
|
|
208
|
+
dest="show_lambda",
|
|
209
|
+
action="store_false",
|
|
210
|
+
help="Don't write lambda on the plot (it is still logged).",
|
|
211
|
+
)
|
|
212
|
+
g.add_argument(
|
|
213
|
+
"--no-thin",
|
|
214
|
+
dest="thin",
|
|
215
|
+
action="store_false",
|
|
216
|
+
help="Draw every point (default: thin points with p > 0.01).",
|
|
217
|
+
)
|
|
218
|
+
g.add_argument(
|
|
219
|
+
"--markersize",
|
|
220
|
+
type=float,
|
|
221
|
+
default=6.0,
|
|
222
|
+
metavar="S",
|
|
223
|
+
help="Point area in pt² (default: 6).",
|
|
224
|
+
)
|
|
225
|
+
g.add_argument(
|
|
226
|
+
"--alpha",
|
|
227
|
+
type=float,
|
|
228
|
+
default=1.0,
|
|
229
|
+
metavar="A",
|
|
230
|
+
help="Point opacity, 0-1 (default: 1).",
|
|
231
|
+
)
|
|
232
|
+
|
|
233
|
+
a = parser.add_argument_group("axes")
|
|
234
|
+
a.add_argument("-xl", "--xlabel", metavar="TEXT", help="X-axis label.")
|
|
235
|
+
a.add_argument("-yl", "--ylabel", metavar="TEXT", help="Y-axis label.")
|
|
236
|
+
a.add_argument(
|
|
237
|
+
"-ym",
|
|
238
|
+
"--ylim",
|
|
239
|
+
nargs=2,
|
|
240
|
+
metavar=("LO", "HI"),
|
|
241
|
+
help="Y-axis limits in -log10(p); points above HI are drawn as "
|
|
242
|
+
"triangles on the top edge.",
|
|
243
|
+
)
|
|
244
|
+
|
|
245
|
+
add_figure_arguments(parser)
|
|
246
|
+
parser.set_defaults(size="5x5")
|
|
247
|
+
add_group_arguments(parser)
|
|
248
|
+
add_legend_arguments(parser)
|
|
249
|
+
|
|
250
|
+
def execute(self, args: argparse.Namespace) -> None:
|
|
251
|
+
if args.ci is not None and not 0 < args.ci < 1:
|
|
252
|
+
raise ValueError(f"--ci must be between 0 and 1, not {args.ci}.")
|
|
253
|
+
df = io.read(args)
|
|
254
|
+
check_cols(df, args.groupcol, "-g/--groupcol")
|
|
255
|
+
check_cols(df, args.subgraphcol, "--subgraphcol")
|
|
256
|
+
data = qq_table(df, args)
|
|
257
|
+
|
|
258
|
+
if args.file:
|
|
259
|
+
import matplotlib
|
|
260
|
+
|
|
261
|
+
matplotlib.use("Agg")
|
|
262
|
+
import matplotlib.pyplot as plt
|
|
263
|
+
|
|
264
|
+
if args.usetex:
|
|
265
|
+
plt.rc("text", usetex=True)
|
|
266
|
+
apply_style(args)
|
|
267
|
+
|
|
268
|
+
if args.subgraphcol is not None:
|
|
269
|
+
groups = subgraph_groups(data, args.subgraphcol, args.subgraphorder)
|
|
270
|
+
nrows, ncols = subgraph_layout(len(groups), args.ncols)
|
|
271
|
+
fig, axes = make_figure(args, nrows=nrows, ncols=ncols)
|
|
272
|
+
for idx, (name, gdf) in enumerate(groups):
|
|
273
|
+
ax = axes[idx // ncols][idx % ncols]
|
|
274
|
+
_draw(ax, gdf, args, args.groupcol)
|
|
275
|
+
ax.set_title(
|
|
276
|
+
make_grouplabel(name, args.subgraphcol, args.subgraphformat)
|
|
277
|
+
)
|
|
278
|
+
for idx in range(len(groups), nrows * ncols):
|
|
279
|
+
axes[idx // ncols][idx % ncols].set_visible(False)
|
|
280
|
+
if args.title:
|
|
281
|
+
fig.suptitle(args.title)
|
|
282
|
+
else:
|
|
283
|
+
fig, axes = make_figure(args)
|
|
284
|
+
_draw(axes[0][0], data, args, args.groupcol)
|
|
285
|
+
axes[0][0].set_title(args.title or "")
|
|
286
|
+
fig.tight_layout()
|
|
287
|
+
save_or_show(fig, args)
|
|
@@ -207,6 +207,57 @@ def _chi2_df(data: pd.DataFrame, chi2df: str | float) -> np.ndarray | float:
|
|
|
207
207
|
return value
|
|
208
208
|
|
|
209
209
|
|
|
210
|
+
# ---------------------------------------------------------------------------
|
|
211
|
+
# QQ plot: expected -log10(p), confidence band, genomic inflation
|
|
212
|
+
# ---------------------------------------------------------------------------
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def qq_expected(n: int) -> np.ndarray:
|
|
216
|
+
"""Expected -log10(p) of the n sorted null p-values, largest first.
|
|
217
|
+
|
|
218
|
+
The i-th smallest of n uniform p-values has expectation i / (n + 1).
|
|
219
|
+
"""
|
|
220
|
+
return -np.log10(np.arange(1, n + 1) / (n + 1))
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def qq_band(n: int, level: float = 0.95, points: int = 500):
|
|
224
|
+
"""Pointwise band for the sorted -log10(p) of n null tests.
|
|
225
|
+
|
|
226
|
+
The i-th smallest of n uniform p-values is Beta(i, n - i + 1). The band
|
|
227
|
+
is computed at about *points* ranks spread evenly on the log scale (all
|
|
228
|
+
ranks when n is small). Returns (expected, lower, upper), -log10 scale.
|
|
229
|
+
"""
|
|
230
|
+
from scipy.stats import beta
|
|
231
|
+
|
|
232
|
+
if n <= points:
|
|
233
|
+
i = np.arange(1, n + 1)
|
|
234
|
+
else:
|
|
235
|
+
i = np.unique(np.round(np.geomspace(1, n, points)).astype(np.int64))
|
|
236
|
+
tail = (1 - level) / 2
|
|
237
|
+
lower = -np.log10(beta.ppf(1 - tail, i, n - i + 1))
|
|
238
|
+
upper = -np.log10(beta.ppf(tail, i, n - i + 1))
|
|
239
|
+
return -np.log10(i / (n + 1)), lower, upper
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def inflation_lambda(neglogp: np.ndarray, df: float = 1) -> float:
|
|
243
|
+
"""Genomic inflation: median chi-squared over its null median.
|
|
244
|
+
|
|
245
|
+
From -log10(p), so it works whichever column the p-values came from and
|
|
246
|
+
a p-value of 0 (underflow) doesn't matter. *df* is the degrees of
|
|
247
|
+
freedom of the test (1 for most association scans).
|
|
248
|
+
"""
|
|
249
|
+
from scipy.stats import chi2
|
|
250
|
+
|
|
251
|
+
from dftk.common.stats import neglogp_chi2_array
|
|
252
|
+
|
|
253
|
+
v = np.asarray(neglogp, dtype=float)
|
|
254
|
+
v = v[np.isfinite(v)]
|
|
255
|
+
if v.size == 0:
|
|
256
|
+
return float("nan")
|
|
257
|
+
median_chi2 = float(neglogp_chi2_array(np.median(v), df))
|
|
258
|
+
return median_chi2 / float(chi2.ppf(0.5, df))
|
|
259
|
+
|
|
260
|
+
|
|
210
261
|
# ---------------------------------------------------------------------------
|
|
211
262
|
# Chromosomes
|
|
212
263
|
# ---------------------------------------------------------------------------
|
|
@@ -361,23 +412,27 @@ _PEAKS = [
|
|
|
361
412
|
]
|
|
362
413
|
|
|
363
414
|
|
|
364
|
-
def simulate_gwas(
|
|
415
|
+
def simulate_gwas(
|
|
416
|
+
n_background: int = 120_000, n_near: int = 150, seed: int = 20261112
|
|
417
|
+
) -> pd.DataFrame:
|
|
365
418
|
"""A synthetic association scan for examples: no real people or variants.
|
|
366
419
|
|
|
367
420
|
Columns: SNP, Chr, pos, Pval, Chisq (1 df), r2. Background variants are
|
|
368
421
|
null. Six peaks each have a causal variant (r2 = 1, the top hit of its
|
|
369
|
-
peak, chi-squared as in _PEAKS) and neighbours whose z-scores
|
|
370
|
-
through linkage disequilibrium, z = r * z_lead + sqrt(1 - r^2)
|
|
371
|
-
with r2 falling off over ~100 kb, capped so the causal variant
|
|
372
|
-
top hit
|
|
373
|
-
|
|
374
|
-
|
|
422
|
+
peak, chi-squared as in _PEAKS) and *n_near* neighbours whose z-scores
|
|
423
|
+
follow it through linkage disequilibrium, z = r * z_lead + sqrt(1 - r^2)
|
|
424
|
+
* noise, with r2 falling off over ~100 kb, capped so the causal variant
|
|
425
|
+
stays the top hit. The peaks are about 1 % of the rows, so the genomic
|
|
426
|
+
inflation lambda is close to 1 as in a real scan. r2 is the r2 with the
|
|
427
|
+
nearest peak's causal variant, given within 1 Mb of it and empty
|
|
428
|
+
elsewhere. Deterministic for a given *seed*. numpy only (no scipy).
|
|
375
429
|
"""
|
|
376
430
|
rng = np.random.default_rng(seed)
|
|
377
431
|
names = list(_CHR_MB)
|
|
378
432
|
weights = np.array([_CHR_MB[c] for c in names], dtype=float)
|
|
379
|
-
|
|
380
|
-
|
|
433
|
+
which = rng.choice(len(names), size=n_background, p=weights / weights.sum())
|
|
434
|
+
chrom = np.array(names)[which]
|
|
435
|
+
pos = 1 + (rng.random(n_background) * weights[which] * 1_000_000).astype(np.int64)
|
|
381
436
|
z = rng.standard_normal(n_background)
|
|
382
437
|
r2 = np.full(n_background, np.nan)
|
|
383
438
|
|
|
@@ -390,7 +445,7 @@ def simulate_gwas(n_background: int = 40_000, seed: int = 20261112) -> pd.DataFr
|
|
|
390
445
|
r2[bg] = rng.beta(0.7, 8, size=dist.size) * np.exp(-dist / 3e5)
|
|
391
446
|
z[bg] = _ld_z(z_lead, r2[bg], z[bg])
|
|
392
447
|
# dense variants around the lead, the causal one first
|
|
393
|
-
near = rng.normal(lead, 250_000, size=
|
|
448
|
+
near = rng.normal(lead, 250_000, size=n_near).astype(np.int64)
|
|
394
449
|
near = near[(near > 0) & (near != lead)]
|
|
395
450
|
dist = np.abs(near - lead)
|
|
396
451
|
r2_near = np.exp(-dist / 100_000) * rng.beta(4, 1.5, size=near.size)
|
|
@@ -151,7 +151,9 @@ correlogram is `corr --all -o | heatmap -x col1 -y col2 -v correlation
|
|
|
151
151
|
--annot --vmin -1 --vmax 1`), `pairs` (scatter-plot matrix with KDEs on the diagonal; `-c COL…`,
|
|
152
152
|
`-g COL`, `--upper corr`), `manhattan` (genome-wide -log10(p); columns
|
|
153
153
|
`Chr`, `pos`, `Pval` by default, `--chi2col COL` when p underflows to 0,
|
|
154
|
-
`--sig`/`--suggestive` lines, points with p > 0.01 thinned)
|
|
154
|
+
`--sig`/`--suggestive` lines, points with p > 0.01 thinned), `qq` (QQ plot
|
|
155
|
+
of p-values with a 95 % band and the genomic inflation lambda; same
|
|
156
|
+
p-value options, `-g` one curve and lambda per group). `-g COL`
|
|
155
157
|
overlays groups, `--subgraphcol COL` makes panels.
|
|
156
158
|
|
|
157
159
|
Other: `dataset NAME` loads a bundled example table, `annotate FILE.parquet`
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{dataframe_toolkit-0.18.0 → dataframe_toolkit-0.19.0}/src/dftk/skills/dftk/references/snakemake.md
RENAMED
|
File without changes
|