dataframe-toolkit 0.21.0__tar.gz → 0.22.1__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.21.0 → dataframe_toolkit-0.22.1}/PKG-INFO +10 -2
- {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.1}/README.md +9 -1
- {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.1}/pyproject.toml +1 -1
- {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.1}/pyproject.toml.orig +1 -1
- {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/__init__.py +1 -0
- {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/eval_cmd.py +10 -8
- {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/line_cmd.py +35 -5
- dataframe_toolkit-0.22.1/src/dftk/commands/locus_cmd.py +430 -0
- {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/manhattan_cmd.py +7 -5
- {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/scat_cmd.py +3 -3
- {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/stat_cmd.py +7 -2
- {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.1}/src/dftk/common/evalfuncs.py +93 -27
- {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.1}/src/dftk/skills/dftk/SKILL.md +3 -1
- {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.1}/src/dftk/__init__.py +0 -0
- {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.1}/src/dftk/cli.py +0 -0
- {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/annotate_cmd.py +0 -0
- {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/append_cmd.py +0 -0
- {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/base.py +0 -0
- {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/binx_cmd.py +0 -0
- {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/chi_cmd.py +0 -0
- {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/clean_cmd.py +0 -0
- {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/cleannames_cmd.py +0 -0
- {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/concat_cmd.py +0 -0
- {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/corr_cmd.py +0 -0
- {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/dataset_cmd.py +0 -0
- {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/describe_cmd.py +0 -0
- {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/explode_cmd.py +0 -0
- {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/fit_cmd.py +0 -0
- {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/func_cmd.py +0 -0
- {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/heatmap_cmd.py +0 -0
- {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/help.py +0 -0
- {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/hist_cmd.py +0 -0
- {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/implode_cmd.py +0 -0
- {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/info_cmd.py +0 -0
- {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/interp_cmd.py +0 -0
- {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/melt_cmd.py +0 -0
- {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/merge_cmd.py +0 -0
- {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/pairs_cmd.py +0 -0
- {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/pivot_cmd.py +0 -0
- {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/print_cmd.py +0 -0
- {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/qq_cmd.py +0 -0
- {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/query_cmd.py +0 -0
- {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/randvar_cmd.py +0 -0
- {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/sample_cmd.py +0 -0
- {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/scale_cmd.py +0 -0
- {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/segid_cmd.py +0 -0
- {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/skill_cmd.py +0 -0
- {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/split_cmd.py +0 -0
- {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/test_cmd.py +0 -0
- {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/transpose_cmd.py +0 -0
- {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/wstat_cmd.py +0 -0
- {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.1}/src/dftk/common/__init__.py +0 -0
- {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.1}/src/dftk/common/copula.py +0 -0
- {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.1}/src/dftk/common/docformats.py +0 -0
- {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.1}/src/dftk/common/gwas.py +0 -0
- {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.1}/src/dftk/common/io.py +0 -0
- {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.1}/src/dftk/common/plot.py +0 -0
- {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.1}/src/dftk/common/seed.py +0 -0
- {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.1}/src/dftk/common/seq.py +0 -0
- {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.1}/src/dftk/common/stats.py +0 -0
- {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.1}/src/dftk/io.py +0 -0
- {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.1}/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.22.1
|
|
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
|
|
@@ -162,12 +162,13 @@ publication-quality output.
|
|
|
162
162
|
| Command | Description |
|
|
163
163
|
|---------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
|
164
164
|
| `scat` | Scatter plot; OLS/robust or LOWESS fit (`--fit lowess`, one per group with `-g`), hexagonal binning for large tables (`--hexbin`), bubble size (`--sizecol`), colour (`--colorcol`) |
|
|
165
|
-
| `line` | Line plot; optional error bars (`--yerr`) or
|
|
165
|
+
| `line` | Line plot; optional error bars (`--yerr`) or intervals (`--yci lo,hi`), `-ls none -m o` for points only, and fit overlay |
|
|
166
166
|
| `hist` | Histogram or KDE (`--kde`); normalisation, cumulative mode, mean±σ annotation (`--stats`) |
|
|
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
170
|
| `qq` | QQ plot of p-values: observed against expected -log10(p), confidence band, genomic inflation λ; `-g` one curve and λ per group |
|
|
171
|
+
| `locus` | Regional association plot: -log10(p) in one region coloured by r² with the lead variant (`--ldcol`), lead as a diamond, `--lead`/`--label` by ID or `chr:pos` |
|
|
171
172
|
| `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 |
|
|
172
173
|
|
|
173
174
|
### Utilities
|
|
@@ -509,6 +510,13 @@ dftk dataset gwas -o | dftk eval -f "Chisq = Chisq * 1.15" -o | dftk qq --chi2co
|
|
|
509
510
|
|
|
510
511
|
`qq --logy` makes its y axis linear up to 10 and logarithmic above, as in `manhattan`.
|
|
511
512
|
|
|
513
|
+
`locus` zooms in on one region: -log10(p) against position in Mb, the points coloured by r² with the lead variant (`--ldcol`, five bins, grey where missing) and the lead drawn as a diamond. It plots the rows it gets, so cut the region out with `query` first (input on several chromosomes is an error that suggests a query around the top hit). The lead is the smallest p-value unless `--lead` names one, and `--label` names more variants to write on the plot; both take an ID (`SNP` column, or `--idcol`) or a position like `chr6:32600000`. dftk doesn't compute LD: merge in r² with the lead, e.g. from `plink --r2 --ld-snp`. `dataset gwas` has an `r2` column around each peak:
|
|
514
|
+
|
|
515
|
+
```bash
|
|
516
|
+
dftk dataset gwas -o | dftk query -q "Chr == '6' and pos > 31.6e6 and pos < 33.6e6" -o \
|
|
517
|
+
| dftk locus --ldcol r2 -f locus.png
|
|
518
|
+
```
|
|
519
|
+
|
|
512
520
|
### Bootstrap confidence intervals
|
|
513
521
|
|
|
514
522
|
Bootstrap mode repeats the full stat computation N times on resampled data
|
|
@@ -132,12 +132,13 @@ publication-quality output.
|
|
|
132
132
|
| Command | Description |
|
|
133
133
|
|---------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
|
134
134
|
| `scat` | Scatter plot; OLS/robust or LOWESS fit (`--fit lowess`, one per group with `-g`), hexagonal binning for large tables (`--hexbin`), bubble size (`--sizecol`), colour (`--colorcol`) |
|
|
135
|
-
| `line` | Line plot; optional error bars (`--yerr`) or
|
|
135
|
+
| `line` | Line plot; optional error bars (`--yerr`) or intervals (`--yci lo,hi`), `-ls none -m o` for points only, and fit overlay |
|
|
136
136
|
| `hist` | Histogram or KDE (`--kde`); normalisation, cumulative mode, mean±σ annotation (`--stats`) |
|
|
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
140
|
| `qq` | QQ plot of p-values: observed against expected -log10(p), confidence band, genomic inflation λ; `-g` one curve and λ per group |
|
|
141
|
+
| `locus` | Regional association plot: -log10(p) in one region coloured by r² with the lead variant (`--ldcol`), lead as a diamond, `--lead`/`--label` by ID or `chr:pos` |
|
|
141
142
|
| `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 |
|
|
142
143
|
|
|
143
144
|
### Utilities
|
|
@@ -479,6 +480,13 @@ dftk dataset gwas -o | dftk eval -f "Chisq = Chisq * 1.15" -o | dftk qq --chi2co
|
|
|
479
480
|
|
|
480
481
|
`qq --logy` makes its y axis linear up to 10 and logarithmic above, as in `manhattan`.
|
|
481
482
|
|
|
483
|
+
`locus` zooms in on one region: -log10(p) against position in Mb, the points coloured by r² with the lead variant (`--ldcol`, five bins, grey where missing) and the lead drawn as a diamond. It plots the rows it gets, so cut the region out with `query` first (input on several chromosomes is an error that suggests a query around the top hit). The lead is the smallest p-value unless `--lead` names one, and `--label` names more variants to write on the plot; both take an ID (`SNP` column, or `--idcol`) or a position like `chr6:32600000`. dftk doesn't compute LD: merge in r² with the lead, e.g. from `plink --r2 --ld-snp`. `dataset gwas` has an `r2` column around each peak:
|
|
484
|
+
|
|
485
|
+
```bash
|
|
486
|
+
dftk dataset gwas -o | dftk query -q "Chr == '6' and pos > 31.6e6 and pos < 33.6e6" -o \
|
|
487
|
+
| dftk locus --ldcol r2 -f locus.png
|
|
488
|
+
```
|
|
489
|
+
|
|
482
490
|
### Bootstrap confidence intervals
|
|
483
491
|
|
|
484
492
|
Bootstrap mode repeats the full stat computation N times on resampled data
|
|
@@ -109,14 +109,16 @@ Available special functions:
|
|
|
109
109
|
sum mean std min max median
|
|
110
110
|
|
|
111
111
|
Conditional assignment:
|
|
112
|
-
where(
|
|
113
|
-
— np.where-style
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
112
|
+
where(condition, value if true, value if false)
|
|
113
|
+
— np.where-style. Each argument is a column, a quoted string
|
|
114
|
+
("foo"), a number, or a pandas expression of the columns
|
|
115
|
+
(-tip, tip * 2). The condition must be true or false (or 0
|
|
116
|
+
and 1), e.g. a true/false column or tip > 3; missing counts as
|
|
117
|
+
false. An unquoted word that is not a column is an error.
|
|
118
|
+
Examples:
|
|
119
|
+
dftk dataset tips -o \\
|
|
120
|
+
| dftk eval -f 'label = where(total_bill > 30, "large", "small")'
|
|
121
|
+
dftk dataset tips -o | dftk eval -f "signed = where(sex == 'Male', -tip, tip)"
|
|
120
122
|
|
|
121
123
|
Bitwise:
|
|
122
124
|
applymask(col, mask_col) — col & mask_col
|
|
@@ -42,13 +42,26 @@ from dftk.common.plot import (
|
|
|
42
42
|
# ---------------------------------------------------------------------------
|
|
43
43
|
|
|
44
44
|
|
|
45
|
+
def yci_columns(args) -> list[str]:
|
|
46
|
+
"""The two column names of --yci LO,HI ([] without it)."""
|
|
47
|
+
if not args.yci:
|
|
48
|
+
return []
|
|
49
|
+
cols = [c.strip() for c in args.yci.split(",")]
|
|
50
|
+
if len(cols) != 2 or not all(cols):
|
|
51
|
+
raise ValueError(
|
|
52
|
+
f"--yci takes two column names separated by a comma, e.g. "
|
|
53
|
+
f"--yci cilo,cihi; not {args.yci!r}."
|
|
54
|
+
)
|
|
55
|
+
return cols
|
|
56
|
+
|
|
57
|
+
|
|
45
58
|
def _resolve_yerr(df, args):
|
|
46
59
|
"""Return yerr array for df, or None. Handles --yerr and --yci."""
|
|
47
60
|
if args.yerr is not None:
|
|
48
61
|
err = df[args.yerr].values
|
|
49
62
|
return [err, err]
|
|
50
63
|
if args.yci is not None:
|
|
51
|
-
lo_col, hi_col = args
|
|
64
|
+
lo_col, hi_col = yci_columns(args)
|
|
52
65
|
lo = (df[args.ycol] - df[lo_col]).values
|
|
53
66
|
hi = (df[hi_col] - df[args.ycol]).values
|
|
54
67
|
return [lo, hi]
|
|
@@ -109,6 +122,7 @@ def _line_ax(ax, df, args, title_suffix: str = ""):
|
|
|
109
122
|
legendloc = tuple(args.legendloc) if args.legendloc else "best"
|
|
110
123
|
marker = getattr(args, "marker", "")
|
|
111
124
|
drawstyle = getattr(args, "drawstyle", "default")
|
|
125
|
+
linestyle = getattr(args, "linestyle", "-")
|
|
112
126
|
|
|
113
127
|
if args.groupcol is not None:
|
|
114
128
|
for groupname, gdf in subgraph_groups(
|
|
@@ -124,6 +138,7 @@ def _line_ax(ax, df, args, title_suffix: str = ""):
|
|
|
124
138
|
yerr=yerr,
|
|
125
139
|
marker=marker,
|
|
126
140
|
drawstyle=drawstyle,
|
|
141
|
+
linestyle=linestyle,
|
|
127
142
|
label=label,
|
|
128
143
|
capsize=3,
|
|
129
144
|
)
|
|
@@ -137,6 +152,7 @@ def _line_ax(ax, df, args, title_suffix: str = ""):
|
|
|
137
152
|
yerr=yerr,
|
|
138
153
|
marker=marker,
|
|
139
154
|
drawstyle=drawstyle,
|
|
155
|
+
linestyle=linestyle,
|
|
140
156
|
label=label if label else None,
|
|
141
157
|
capsize=3,
|
|
142
158
|
)
|
|
@@ -179,11 +195,17 @@ Symmetric error bars (mean ± SEM flipper length per species):
|
|
|
179
195
|
dftk dataset penguins -o | dftk stat -c flipper_length_mm -g species -o \\
|
|
180
196
|
| dftk line -x species -y mean --yerr sem
|
|
181
197
|
|
|
182
|
-
Asymmetric
|
|
198
|
+
Asymmetric intervals: mean bill length per species, with a bar over the
|
|
199
|
+
middle 95 % of the values (stat's cilo and cihi are percentiles of the data):
|
|
183
200
|
|
|
184
201
|
dftk dataset penguins -o | dftk stat -c bill_length_mm -g species -o \\
|
|
185
202
|
| dftk line -x species -y mean --yci cilo,cihi
|
|
186
203
|
|
|
204
|
+
Points with intervals and no connecting line (a dot-and-whisker plot):
|
|
205
|
+
|
|
206
|
+
dftk dataset penguins -o | dftk stat -c bill_length_mm -g species -o \\
|
|
207
|
+
| dftk line -x species -y mean --yci cilo,cihi -ls none -m o
|
|
208
|
+
|
|
187
209
|
Subplot grid, one panel per month (year-over-year trend within each month):
|
|
188
210
|
|
|
189
211
|
dftk dataset flights -o | dftk line -x year -y passengers \\
|
|
@@ -232,6 +254,14 @@ class LineCommand(BaseCommand):
|
|
|
232
254
|
metavar="MARKER",
|
|
233
255
|
help="Matplotlib marker style (default: none).",
|
|
234
256
|
)
|
|
257
|
+
s.add_argument(
|
|
258
|
+
"-ls",
|
|
259
|
+
"--linestyle",
|
|
260
|
+
default="-",
|
|
261
|
+
metavar="STYLE",
|
|
262
|
+
help="Matplotlib line style: - -- : -. or none for points only, "
|
|
263
|
+
"e.g. estimates with --yci intervals (default: -).",
|
|
264
|
+
)
|
|
235
265
|
s.add_argument(
|
|
236
266
|
"--drawstyle",
|
|
237
267
|
default="default",
|
|
@@ -288,15 +318,15 @@ class LineCommand(BaseCommand):
|
|
|
288
318
|
if not args.xcol or not args.ycol:
|
|
289
319
|
raise ValueError("--xcol (-x) and --ycol (-y) are required.")
|
|
290
320
|
|
|
291
|
-
|
|
321
|
+
# --yci names two columns in one string: add them by name
|
|
322
|
+
df = io.read(args, columns=option_columns(args, *yci_columns(args)))
|
|
292
323
|
check_cols(df, [args.xcol, args.ycol], "-x/-y")
|
|
293
324
|
check_cols(df, args.groupcol, "-g/--groupcol")
|
|
294
325
|
check_cols(df, args.subgraphcol, "--subgraphcol")
|
|
295
326
|
if args.yerr:
|
|
296
327
|
check_cols(df, [args.yerr], "--yerr")
|
|
297
328
|
if args.yci:
|
|
298
|
-
|
|
299
|
-
check_cols(df, [lo.strip(), hi.strip()], "--yci")
|
|
329
|
+
check_cols(df, yci_columns(args), "--yci")
|
|
300
330
|
|
|
301
331
|
if args.file:
|
|
302
332
|
import matplotlib
|
|
@@ -0,0 +1,430 @@
|
|
|
1
|
+
"""
|
|
2
|
+
dftk.commands.locus_cmd — dftk locus subcommand.
|
|
3
|
+
|
|
4
|
+
Regional association plot, the zoomed-in companion to manhattan: -log10(p)
|
|
5
|
+
of the variants in one region against position (Mb), coloured by LD (r²)
|
|
6
|
+
with a lead variant drawn as a diamond. Column lookup, -log10(p), capped
|
|
7
|
+
points, thinning and the log scale are shared with manhattan.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import argparse
|
|
13
|
+
import logging
|
|
14
|
+
import re
|
|
15
|
+
|
|
16
|
+
import numpy as np
|
|
17
|
+
import pandas as pd
|
|
18
|
+
|
|
19
|
+
from dftk.commands.base import BaseCommand
|
|
20
|
+
from dftk.commands.manhattan_cmd import (
|
|
21
|
+
_threshold,
|
|
22
|
+
add_gwas_column_arguments,
|
|
23
|
+
float_or,
|
|
24
|
+
gwas_table,
|
|
25
|
+
log_yaxis,
|
|
26
|
+
scatter_capped,
|
|
27
|
+
thin_points,
|
|
28
|
+
)
|
|
29
|
+
from dftk.common import gwas
|
|
30
|
+
from dftk.common.io import check_cols, io, option_columns
|
|
31
|
+
from dftk.common.plot import (
|
|
32
|
+
add_figure_arguments,
|
|
33
|
+
apply_style,
|
|
34
|
+
make_figure,
|
|
35
|
+
save_or_show,
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
logger = logging.getLogger(__name__)
|
|
39
|
+
|
|
40
|
+
DEFAULT_ID = "SNP"
|
|
41
|
+
ID_ALIASES = (
|
|
42
|
+
"snp", "id", "rsid", "rs_id", "snpid", "variant_id", "marker", "markername",
|
|
43
|
+
) # fmt: skip
|
|
44
|
+
|
|
45
|
+
# r² bins: 0-0.2, 0.2-0.4, ..., 0.8-1 (dark blue to red), grey when missing
|
|
46
|
+
_LD_EDGES = (0.2, 0.4, 0.6, 0.8)
|
|
47
|
+
_LD_COLOURS = ("#357EBD", "#46B8DA", "#5CB85C", "#EEA236", "#D43F3A")
|
|
48
|
+
_NO_LD_COLOUR = "#BBBBBB"
|
|
49
|
+
_POINT_COLOUR = "#1F4E79" # without --ldcol: manhattan's dark blue
|
|
50
|
+
_LEAD_COLOUR = "#9632B8" # purple diamond
|
|
51
|
+
_SIG_COLOUR = "#D55E00"
|
|
52
|
+
_SUGGESTIVE_COLOUR = "#0072B2"
|
|
53
|
+
|
|
54
|
+
_POSITION = re.compile(r"^(?:chr)?([0-9A-Za-z]+):([0-9][0-9,_]*)$", re.IGNORECASE)
|
|
55
|
+
|
|
56
|
+
_EPILOG = """\
|
|
57
|
+
Input: one row per variant on one chromosome, with a position and a
|
|
58
|
+
p-value, as in manhattan (columns Chr, pos and Pval unless named; common
|
|
59
|
+
spellings found ignoring case; --mlogpcol or --chi2col instead of a
|
|
60
|
+
p-value). The plot covers the rows it is given: cut the region out with
|
|
61
|
+
query first. Input with several chromosomes is an error.
|
|
62
|
+
|
|
63
|
+
The lead variant is drawn as a purple diamond and labelled; it is the
|
|
64
|
+
smallest p-value unless --lead names one. --label writes the names of
|
|
65
|
+
other variants next to their points. A variant is named by position,
|
|
66
|
+
chr6:32600000 (or 6:32600000), or by ID in the ID column (SNP unless
|
|
67
|
+
--idcol names it; rsid, ID, ... found ignoring case). Labels show the ID
|
|
68
|
+
when there is an ID column, the position otherwise. Several rows at one
|
|
69
|
+
position (multi-allelic sites): the one with the smallest p.
|
|
70
|
+
|
|
71
|
+
--ldcol colours the points by r² with the lead variant, in five bins
|
|
72
|
+
(0-0.2, ..., 0.8-1), grey where it is missing. dftk doesn't compute LD:
|
|
73
|
+
r² comes from elsewhere (e.g. plink --r2 --ld-snp rs123 --ld-window-kb
|
|
74
|
+
1000) and is merged in. It must be r² with the variant --lead names;
|
|
75
|
+
dftk can't check that.
|
|
76
|
+
|
|
77
|
+
EXAMPLES
|
|
78
|
+
--------
|
|
79
|
+
Basic locus plot of a region file (Chr, pos, Pval; r2 with the lead):
|
|
80
|
+
|
|
81
|
+
dftk locus region.tsv --ldcol r2 -f locus.png
|
|
82
|
+
|
|
83
|
+
The chr 6 peak of the example scan (its r2 column is r² with the peak's
|
|
84
|
+
top variant), with the region cut out by query:
|
|
85
|
+
|
|
86
|
+
dftk dataset gwas -o \\
|
|
87
|
+
| dftk query -q "Chr == '6' and pos > 31.6e6 and pos < 33.6e6" -o \\
|
|
88
|
+
| dftk locus --ldcol r2 -f locus.png
|
|
89
|
+
|
|
90
|
+
Choose the lead and label a second signal (an ID or a position):
|
|
91
|
+
|
|
92
|
+
dftk dataset gwas -o \\
|
|
93
|
+
| dftk query -q "Chr == '6' and pos > 31.6e6 and pos < 33.6e6" -o \\
|
|
94
|
+
| dftk locus --ldcol r2 --lead sim43271 --label chr6:32436692 -f locus.png
|
|
95
|
+
|
|
96
|
+
Log scale above -log10(p) = 10, so the peak and the weaker signals both
|
|
97
|
+
show:
|
|
98
|
+
|
|
99
|
+
dftk dataset gwas -o \\
|
|
100
|
+
| dftk query -q "Chr == '6' and pos > 31.6e6 and pos < 33.6e6" -o \\
|
|
101
|
+
| dftk locus --chi2col Chisq --ldcol r2 --logy -f locus.png
|
|
102
|
+
"""
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def id_column(df: pd.DataFrame, given: str | None) -> tuple[str | None, str | None]:
|
|
106
|
+
"""(ID column, None), or (None, why not) when there isn't one to use.
|
|
107
|
+
|
|
108
|
+
Looked up as the other columns are, but only an error when a variant
|
|
109
|
+
has to be found by ID (lookup_variant)."""
|
|
110
|
+
try:
|
|
111
|
+
return gwas.find_column(df, given, DEFAULT_ID, ID_ALIASES, "--idcol"), None
|
|
112
|
+
except ValueError as e:
|
|
113
|
+
if given is not None:
|
|
114
|
+
raise
|
|
115
|
+
return None, str(e)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def lookup_variant(
|
|
119
|
+
data: pd.DataFrame, name: str, idcol: str | None, why: str | None
|
|
120
|
+
) -> int:
|
|
121
|
+
"""Index label in *data* of the variant *name*: an ID, or chr:pos.
|
|
122
|
+
|
|
123
|
+
An ID match wins, so IDs like 6:32600000:A:G still work by ID.
|
|
124
|
+
Several matches: the smallest p (largest _y).
|
|
125
|
+
"""
|
|
126
|
+
rows = None
|
|
127
|
+
if idcol is not None:
|
|
128
|
+
hit = data[data[idcol].astype(str) == name]
|
|
129
|
+
if len(hit):
|
|
130
|
+
rows = hit
|
|
131
|
+
if rows is None:
|
|
132
|
+
m = _POSITION.match(name.strip())
|
|
133
|
+
if m:
|
|
134
|
+
chrom = gwas.chrom_label(m.group(1))
|
|
135
|
+
pos = int(m.group(2).replace(",", "").replace("_", ""))
|
|
136
|
+
rows = data[
|
|
137
|
+
(data["_chrom"].map(gwas.chrom_label) == chrom) & (data["_pos"] == pos)
|
|
138
|
+
]
|
|
139
|
+
if rows.empty:
|
|
140
|
+
raise ValueError(f"No variant at {name} (with a p-value).")
|
|
141
|
+
elif idcol is None:
|
|
142
|
+
raise ValueError(
|
|
143
|
+
f"{name!r} isn't a position like chr6:32600000, and there is no "
|
|
144
|
+
f"ID column to look it up in: {why}"
|
|
145
|
+
)
|
|
146
|
+
else:
|
|
147
|
+
raise ValueError(
|
|
148
|
+
f"No variant {name!r} in column {idcol!r} (with a p-value)."
|
|
149
|
+
)
|
|
150
|
+
if len(rows) > 1:
|
|
151
|
+
logger.warning(
|
|
152
|
+
"%d rows match %s; using the one with the smallest p", len(rows), name
|
|
153
|
+
)
|
|
154
|
+
return rows["_y"].idxmax()
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def _ld_colours(r2: np.ndarray) -> np.ndarray:
|
|
158
|
+
colours = np.array(_LD_COLOURS, dtype=object)[np.digitize(r2, _LD_EDGES)]
|
|
159
|
+
colours[~np.isfinite(r2)] = _NO_LD_COLOUR
|
|
160
|
+
return colours
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _label_text(data: pd.DataFrame, row, idcol: str | None) -> str:
|
|
164
|
+
if idcol is not None and pd.notna(data.at[row, idcol]):
|
|
165
|
+
return str(data.at[row, idcol])
|
|
166
|
+
return f"{gwas.chrom_label(data.at[row, '_chrom'])}:{int(data.at[row, '_pos'])}"
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def _draw(ax, data: pd.DataFrame, lead, labels: list, args, idcol) -> None:
|
|
170
|
+
x = data["_pos"].to_numpy(dtype=float) / 1e6
|
|
171
|
+
y = data["_y"].to_numpy()
|
|
172
|
+
lines = [-np.log10(p) for p in (args.sig, args.suggestive) if p is not None]
|
|
173
|
+
lo, hi = 0.0, max([float(y.max()), *lines, 1.0]) * 1.08
|
|
174
|
+
if args.ylim is not None:
|
|
175
|
+
lo, hi = float_or(args.ylim[0], lo), float_or(args.ylim[1], hi)
|
|
176
|
+
|
|
177
|
+
if args.ldcol:
|
|
178
|
+
r2 = pd.to_numeric(data[args.ldcol], errors="coerce").to_numpy(dtype=float)
|
|
179
|
+
colours = _ld_colours(r2)
|
|
180
|
+
# the most LD on top: grey first, then by r²
|
|
181
|
+
order = np.argsort(np.where(np.isfinite(r2), r2, -1.0), kind="stable")
|
|
182
|
+
else:
|
|
183
|
+
colours = np.full(len(x), _POINT_COLOUR, dtype=object)
|
|
184
|
+
order = np.arange(len(x))
|
|
185
|
+
|
|
186
|
+
keep = thin_points(x, y, args)
|
|
187
|
+
marked = data.index.isin([lead, *labels])
|
|
188
|
+
keep |= marked # the lead and labelled variants are always drawn
|
|
189
|
+
if args.thin and (~keep).any():
|
|
190
|
+
logger.info("Thinned %d of %d points (p > 0.01)", int((~keep).sum()), len(x))
|
|
191
|
+
order = order[keep[order]]
|
|
192
|
+
scatter_capped(ax, x[order], y[order], hi, args, colours=colours[order], zorder=2)
|
|
193
|
+
|
|
194
|
+
# lead: a diamond over its point
|
|
195
|
+
i = data.index.get_loc(lead)
|
|
196
|
+
ax.scatter(
|
|
197
|
+
[x[i]], [min(y[i], hi)], s=args.markersize * 6, marker="D",
|
|
198
|
+
color=_LEAD_COLOUR, edgecolors="black", linewidths=0.6, zorder=4,
|
|
199
|
+
clip_on=False,
|
|
200
|
+
) # fmt: skip
|
|
201
|
+
for row in dict.fromkeys([lead, *labels]):
|
|
202
|
+
j = data.index.get_loc(row)
|
|
203
|
+
if row != lead: # a ring shows which point the label belongs to
|
|
204
|
+
ax.scatter(
|
|
205
|
+
[x[j]], [min(y[j], hi)], s=args.markersize * 3, facecolors="none",
|
|
206
|
+
edgecolors="black", linewidths=0.8, zorder=3, clip_on=False,
|
|
207
|
+
) # fmt: skip
|
|
208
|
+
ax.annotate(
|
|
209
|
+
_label_text(data, row, idcol), (x[j], min(y[j], hi)),
|
|
210
|
+
xytext=(0, 5), textcoords="offset points", ha="center", va="bottom",
|
|
211
|
+
fontsize="small", zorder=5, annotation_clip=False,
|
|
212
|
+
) # fmt: skip
|
|
213
|
+
|
|
214
|
+
if args.sig is not None:
|
|
215
|
+
ax.axhline(-np.log10(args.sig), color=_SIG_COLOUR, lw=0.8, ls="--", zorder=1)
|
|
216
|
+
if args.suggestive is not None:
|
|
217
|
+
ax.axhline(
|
|
218
|
+
-np.log10(args.suggestive), color=_SUGGESTIVE_COLOUR, lw=0.8, ls=":",
|
|
219
|
+
zorder=1,
|
|
220
|
+
) # fmt: skip
|
|
221
|
+
|
|
222
|
+
if args.ldcol:
|
|
223
|
+
from matplotlib.lines import Line2D
|
|
224
|
+
|
|
225
|
+
names = ["0.8–1", "0.6–0.8", "0.4–0.6", "0.2–0.4", "0–0.2", "no r²"]
|
|
226
|
+
handles = [
|
|
227
|
+
Line2D([], [], ls="", marker="o", markersize=5, color=c, label=n)
|
|
228
|
+
for c, n in zip((*_LD_COLOURS[::-1], _NO_LD_COLOUR), names, strict=True)
|
|
229
|
+
]
|
|
230
|
+
ax.legend(
|
|
231
|
+
handles=handles, title="r²", fontsize="small", title_fontsize="small",
|
|
232
|
+
loc=tuple(args.legendloc) if args.legendloc else "upper right",
|
|
233
|
+
) # fmt: skip
|
|
234
|
+
|
|
235
|
+
span = max(x.max() - x.min(), 1e-3)
|
|
236
|
+
ax.set_xlim(x.min() - 0.02 * span, x.max() + 0.02 * span)
|
|
237
|
+
ax.set_ylim(lo, hi)
|
|
238
|
+
if args.logy is not None:
|
|
239
|
+
log_yaxis(ax, args.logy, lo, hi)
|
|
240
|
+
ax.spines[["top", "right"]].set_visible(False)
|
|
241
|
+
chrom = gwas.chrom_label(data["_chrom"].iloc[0])
|
|
242
|
+
ax.set_xlabel(
|
|
243
|
+
args.xlabel if args.xlabel is not None else f"Position on chr{chrom} (Mb)"
|
|
244
|
+
)
|
|
245
|
+
ax.set_ylabel(args.ylabel if args.ylabel is not None else r"$-\log_{10}(p)$")
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
class LocusCommand(BaseCommand):
|
|
249
|
+
name = "locus"
|
|
250
|
+
help = "Regional association plot: -log10(p) in one region, coloured by LD (r²)."
|
|
251
|
+
|
|
252
|
+
def add_arguments(self, parser: argparse.ArgumentParser) -> None:
|
|
253
|
+
parser.formatter_class = argparse.RawDescriptionHelpFormatter
|
|
254
|
+
parser.epilog = _EPILOG
|
|
255
|
+
|
|
256
|
+
self.add_read_arguments(parser)
|
|
257
|
+
c = add_gwas_column_arguments(parser)
|
|
258
|
+
c.add_argument(
|
|
259
|
+
"--idcol",
|
|
260
|
+
metavar="COL",
|
|
261
|
+
help=f"Variant ID column, for --lead / --label by ID and for the "
|
|
262
|
+
f"labels (default: {DEFAULT_ID}, if there is one).",
|
|
263
|
+
)
|
|
264
|
+
c.add_argument(
|
|
265
|
+
"--ldcol",
|
|
266
|
+
metavar="COL",
|
|
267
|
+
help="r² with the lead variant: colours the points in five bins, "
|
|
268
|
+
"grey where missing.",
|
|
269
|
+
)
|
|
270
|
+
|
|
271
|
+
g = parser.add_argument_group("locus")
|
|
272
|
+
g.add_argument(
|
|
273
|
+
"--lead",
|
|
274
|
+
metavar="VARIANT",
|
|
275
|
+
help="Lead variant, drawn as a diamond: an ID or chr:pos "
|
|
276
|
+
"(default: the smallest p-value).",
|
|
277
|
+
)
|
|
278
|
+
g.add_argument(
|
|
279
|
+
"--label",
|
|
280
|
+
nargs="+",
|
|
281
|
+
default=[],
|
|
282
|
+
metavar="VARIANT",
|
|
283
|
+
help="Variants to label (IDs or chr:pos); the lead is always labelled.",
|
|
284
|
+
)
|
|
285
|
+
g.add_argument(
|
|
286
|
+
"--sig",
|
|
287
|
+
type=_threshold,
|
|
288
|
+
default=5e-8,
|
|
289
|
+
metavar="P|none",
|
|
290
|
+
help="Significance line, as a p-value (default: 5e-8).",
|
|
291
|
+
)
|
|
292
|
+
g.add_argument(
|
|
293
|
+
"--suggestive",
|
|
294
|
+
type=_threshold,
|
|
295
|
+
default=None,
|
|
296
|
+
metavar="P|none",
|
|
297
|
+
help="Suggestive line, as a p-value (default: none).",
|
|
298
|
+
)
|
|
299
|
+
g.add_argument(
|
|
300
|
+
"--logy",
|
|
301
|
+
nargs="?",
|
|
302
|
+
type=float,
|
|
303
|
+
const=10.0,
|
|
304
|
+
metavar="T",
|
|
305
|
+
help="Log scale above -log10(p) = T, linear below it (default T: 10).",
|
|
306
|
+
)
|
|
307
|
+
g.add_argument(
|
|
308
|
+
"--no-thin",
|
|
309
|
+
dest="thin",
|
|
310
|
+
action="store_false",
|
|
311
|
+
help="Draw every point (default: thin points with p > 0.01).",
|
|
312
|
+
)
|
|
313
|
+
g.add_argument(
|
|
314
|
+
"--markersize",
|
|
315
|
+
type=float,
|
|
316
|
+
default=12.0,
|
|
317
|
+
metavar="S",
|
|
318
|
+
help="Point area in pt² (default: 12).",
|
|
319
|
+
)
|
|
320
|
+
g.add_argument(
|
|
321
|
+
"--alpha",
|
|
322
|
+
type=float,
|
|
323
|
+
default=1.0,
|
|
324
|
+
metavar="A",
|
|
325
|
+
help="Point opacity, 0-1 (default: 1).",
|
|
326
|
+
)
|
|
327
|
+
|
|
328
|
+
a = parser.add_argument_group("axes")
|
|
329
|
+
a.add_argument("-xl", "--xlabel", metavar="TEXT", help="X-axis label.")
|
|
330
|
+
a.add_argument("-yl", "--ylabel", metavar="TEXT", help="Y-axis label.")
|
|
331
|
+
a.add_argument(
|
|
332
|
+
"-ym",
|
|
333
|
+
"--ylim",
|
|
334
|
+
nargs=2,
|
|
335
|
+
metavar=("LO", "HI"),
|
|
336
|
+
help="Y-axis limits in -log10(p); points above HI are drawn as "
|
|
337
|
+
"triangles on the top edge.",
|
|
338
|
+
)
|
|
339
|
+
a.add_argument(
|
|
340
|
+
"--legendloc",
|
|
341
|
+
nargs=2,
|
|
342
|
+
type=float,
|
|
343
|
+
metavar=("X", "Y"),
|
|
344
|
+
help="Position of the r² legend, in axes coordinates "
|
|
345
|
+
"(default: upper right).",
|
|
346
|
+
)
|
|
347
|
+
|
|
348
|
+
add_figure_arguments(parser)
|
|
349
|
+
parser.set_defaults(size="7x4")
|
|
350
|
+
|
|
351
|
+
def execute(self, args: argparse.Namespace) -> None:
|
|
352
|
+
if args.logy is not None and args.logy <= 0:
|
|
353
|
+
raise ValueError(f"--logy must be above 0, not {args.logy:g}.")
|
|
354
|
+
df = io.read(args, columns=_columns(args))
|
|
355
|
+
if args.ldcol:
|
|
356
|
+
check_cols(df, [args.ldcol], "--ldcol")
|
|
357
|
+
idcol, why = id_column(df, args.idcol)
|
|
358
|
+
data = gwas_table(df, args)
|
|
359
|
+
|
|
360
|
+
chroms = pd.unique(data["_chrom"].map(gwas.chrom_label))
|
|
361
|
+
if len(chroms) > 1:
|
|
362
|
+
raise ValueError(_one_region_hint(df, data, args, len(chroms)))
|
|
363
|
+
|
|
364
|
+
data = data.reset_index(drop=True)
|
|
365
|
+
if args.lead is not None:
|
|
366
|
+
lead = lookup_variant(data, args.lead, idcol, why)
|
|
367
|
+
else:
|
|
368
|
+
lead = data["_y"].idxmax()
|
|
369
|
+
labels = [lookup_variant(data, n, idcol, why) for n in args.label]
|
|
370
|
+
logger.info("Lead variant: %s", _label_text(data, lead, idcol))
|
|
371
|
+
|
|
372
|
+
if args.file:
|
|
373
|
+
import matplotlib
|
|
374
|
+
|
|
375
|
+
matplotlib.use("Agg")
|
|
376
|
+
import matplotlib.pyplot as plt
|
|
377
|
+
|
|
378
|
+
if args.usetex:
|
|
379
|
+
plt.rc("text", usetex=True)
|
|
380
|
+
apply_style(args)
|
|
381
|
+
fig, axes = make_figure(args)
|
|
382
|
+
_draw(axes[0][0], data, lead, labels, args, idcol)
|
|
383
|
+
axes[0][0].set_title(args.title or "")
|
|
384
|
+
fig.tight_layout()
|
|
385
|
+
save_or_show(fig, args)
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
def _columns(args: argparse.Namespace):
|
|
389
|
+
"""columns= for io.read: the chromosome, position and p-value columns,
|
|
390
|
+
the ID column (named or found by alias) and the ones options name."""
|
|
391
|
+
named = option_columns(args)
|
|
392
|
+
|
|
393
|
+
def pick(names: list[str]) -> list[str] | None:
|
|
394
|
+
found = gwas.needed_columns(names, args, position=True)
|
|
395
|
+
if found is None:
|
|
396
|
+
return None
|
|
397
|
+
frame = pd.DataFrame(columns=names)
|
|
398
|
+
quiet, gwas.logger.disabled = gwas.logger.disabled, True
|
|
399
|
+
try:
|
|
400
|
+
idcol, _ = id_column(frame, args.idcol)
|
|
401
|
+
except ValueError:
|
|
402
|
+
idcol = None # a missing --idcol is reported on the real read
|
|
403
|
+
finally:
|
|
404
|
+
gwas.logger.disabled = quiet
|
|
405
|
+
extra = [idcol] if idcol is not None else []
|
|
406
|
+
return list(dict.fromkeys(found + extra + named(names)))
|
|
407
|
+
|
|
408
|
+
return pick
|
|
409
|
+
|
|
410
|
+
|
|
411
|
+
def _one_region_hint(df: pd.DataFrame, data: pd.DataFrame, args, n: int) -> str:
|
|
412
|
+
"""The error for input on several chromosomes: a query for 500 kb
|
|
413
|
+
either side of the smallest p-value."""
|
|
414
|
+
chrcol = gwas.find_column(
|
|
415
|
+
df, args.chrcol, gwas.DEFAULT_CHR, gwas.CHR_ALIASES, "--chrcol"
|
|
416
|
+
)
|
|
417
|
+
poscol = gwas.find_column(
|
|
418
|
+
df, args.poscol, gwas.DEFAULT_POS, gwas.POS_ALIASES, "--poscol"
|
|
419
|
+
)
|
|
420
|
+
top = data.loc[data["_y"].idxmax()]
|
|
421
|
+
chrom = top["_chrom"]
|
|
422
|
+
chrom = f"'{chrom}'" if isinstance(chrom, str) else f"{chrom}"
|
|
423
|
+
pos = int(top["_pos"])
|
|
424
|
+
lo, hi = max(pos - 500_000, 0), pos + 500_000
|
|
425
|
+
return (
|
|
426
|
+
f"locus draws one region, but the input has {n} chromosomes. Cut "
|
|
427
|
+
f"the region out first; 500 kb either side of the smallest p-value:\n"
|
|
428
|
+
f' dftk query -q "{chrcol} == {chrom} and {poscol} >= {lo} and '
|
|
429
|
+
f'{poscol} <= {hi}" -o | dftk locus ...'
|
|
430
|
+
)
|
|
@@ -92,9 +92,9 @@ them; points past --sig in red.
|
|
|
92
92
|
Here the second scan is the example scan with every chi-squared halved,
|
|
93
93
|
and melt stacks the two columns into one, with a study column:
|
|
94
94
|
|
|
95
|
-
dftk dataset gwas -o
|
|
96
|
-
| dftk eval -f "half = Chisq / 2" --select Chr pos Chisq half -o
|
|
97
|
-
| dftk melt -i Chr pos -d study -v chi2 -o
|
|
95
|
+
dftk dataset gwas -o \\
|
|
96
|
+
| dftk eval -f "half = Chisq / 2" --select Chr pos Chisq half -o \\
|
|
97
|
+
| dftk melt -i Chr pos -d study -v chi2 -o \\
|
|
98
98
|
| dftk manhattan --chi2col chi2 --miami study --sigcolor red -f miami.png
|
|
99
99
|
|
|
100
100
|
With more than two scans in the column, name the two: --miami study a b.
|
|
@@ -123,8 +123,9 @@ def _threshold(value: str) -> float | None:
|
|
|
123
123
|
|
|
124
124
|
def add_gwas_column_arguments(
|
|
125
125
|
parser: argparse.ArgumentParser, position: bool = True
|
|
126
|
-
) ->
|
|
127
|
-
"""Column options shared by manhattan
|
|
126
|
+
) -> argparse._ArgumentGroup:
|
|
127
|
+
"""Column options shared by manhattan, qq (position=False) and locus;
|
|
128
|
+
returns the group, for more column options."""
|
|
128
129
|
g = parser.add_argument_group("columns")
|
|
129
130
|
if position:
|
|
130
131
|
g.add_argument(
|
|
@@ -159,6 +160,7 @@ def add_gwas_column_arguments(
|
|
|
159
160
|
metavar="N|COL",
|
|
160
161
|
help="Degrees of freedom of --chi2col: a number or a column (default: 1).",
|
|
161
162
|
)
|
|
163
|
+
return g
|
|
162
164
|
|
|
163
165
|
|
|
164
166
|
def gwas_columns(args: argparse.Namespace, position: bool = True):
|
|
@@ -274,17 +274,17 @@ can overshoot the data; a larger --frac or --xlim helps:
|
|
|
274
274
|
Hexagonal binning for large tables (54,000 diamonds), log colour scale and
|
|
275
275
|
log axes; hexagons are binned on the log scale:
|
|
276
276
|
|
|
277
|
-
dftk dataset diamonds -o | dftk scat -x carat -y price
|
|
277
|
+
dftk dataset diamonds -o | dftk scat -x carat -y price \\
|
|
278
278
|
--hexbin --hexlog --logx --logy
|
|
279
279
|
|
|
280
280
|
Colour each hexagon by the mean of another column instead of the count:
|
|
281
281
|
|
|
282
|
-
dftk dataset diamonds -o | dftk scat -x carat -y price
|
|
282
|
+
dftk dataset diamonds -o | dftk scat -x carat -y price \\
|
|
283
283
|
--hexbin --colorcol depth --gridsize 50
|
|
284
284
|
|
|
285
285
|
One hexbin panel per group, all on the same colour scale:
|
|
286
286
|
|
|
287
|
-
dftk dataset diamonds -o | dftk scat -x carat -y price
|
|
287
|
+
dftk dataset diamonds -o | dftk scat -x carat -y price \\
|
|
288
288
|
--hexbin --hexlog --subgraphcol cut --gridsize 40
|
|
289
289
|
|
|
290
290
|
Publication figure (Nature single column, PDF):
|
|
@@ -86,7 +86,10 @@ def _ci(name: str, level: float, method: str):
|
|
|
86
86
|
"""
|
|
87
87
|
|
|
88
88
|
def cifunction(a):
|
|
89
|
-
|
|
89
|
+
# missing values left out, as for the other statistics
|
|
90
|
+
a = np.asarray(a, dtype=float)
|
|
91
|
+
a = a[~np.isnan(a)]
|
|
92
|
+
return np.percentile(a, q=level, method=method) if a.size else np.nan
|
|
90
93
|
|
|
91
94
|
cifunction.__name__ = name
|
|
92
95
|
return cifunction
|
|
@@ -206,7 +209,9 @@ class StatCommand(BaseCommand):
|
|
|
206
209
|
)
|
|
207
210
|
g.add_argument(
|
|
208
211
|
"--confidencelevel",
|
|
209
|
-
help="
|
|
212
|
+
help="Percent of the values between cilo and cihi, which are "
|
|
213
|
+
"percentiles of the data (default: 95.0, the 2.5th and 97.5th); "
|
|
214
|
+
"for a confidence interval of a statistic, see --bootstrap",
|
|
210
215
|
type=float,
|
|
211
216
|
default=95.0,
|
|
212
217
|
metavar="PCT",
|
|
@@ -183,20 +183,39 @@ class _StatsFunc:
|
|
|
183
183
|
return table.apply(lambda row: self.row_func(row.to_numpy()), axis=1)
|
|
184
184
|
|
|
185
185
|
|
|
186
|
-
def
|
|
187
|
-
"""
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
186
|
+
def split_arguments(body: str) -> list[str]:
|
|
187
|
+
"""Split a call's argument string at the commas outside quotes and
|
|
188
|
+
brackets: 'a > 0, "x, y", f(b, c)' gives three arguments."""
|
|
189
|
+
parts, depth, quote, start = [], 0, None, 0
|
|
190
|
+
for i, ch in enumerate(body):
|
|
191
|
+
if quote:
|
|
192
|
+
if ch == quote:
|
|
193
|
+
quote = None
|
|
194
|
+
elif ch in "\"'":
|
|
195
|
+
quote = ch
|
|
196
|
+
elif ch in "([{":
|
|
197
|
+
depth += 1
|
|
198
|
+
elif ch in ")]}":
|
|
199
|
+
depth -= 1
|
|
200
|
+
elif ch == "," and depth == 0:
|
|
201
|
+
parts.append(body[start:i].strip())
|
|
202
|
+
start = i + 1
|
|
203
|
+
parts.append(body[start:].strip())
|
|
204
|
+
return parts
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
_IDENTIFIER = re.compile(r"[A-Za-z_]\w*")
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def _resolve_where_val(val: str, df: pd.DataFrame, role: str):
|
|
211
|
+
"""Resolve a where() argument to a scalar or a Series.
|
|
212
|
+
|
|
213
|
+
In order: a quoted string ("foo" or 'foo') is that text; a column name
|
|
214
|
+
is the column; a number is the number; anything else is a pandas
|
|
215
|
+
expression of the columns (-tip, tip * 2, tip > 3).
|
|
195
216
|
"""
|
|
196
217
|
s = val.strip()
|
|
197
|
-
if (s
|
|
198
|
-
s.startswith("'") and s.endswith("'")
|
|
199
|
-
):
|
|
218
|
+
if len(s) >= 2 and s[0] == s[-1] and s[0] in "\"'":
|
|
200
219
|
return s[1:-1]
|
|
201
220
|
if s in df.columns:
|
|
202
221
|
return df[s]
|
|
@@ -208,26 +227,72 @@ def _resolve_where_val(val: str, df: pd.DataFrame):
|
|
|
208
227
|
return float(s)
|
|
209
228
|
except ValueError:
|
|
210
229
|
pass
|
|
211
|
-
|
|
230
|
+
if s in ("True", "False"):
|
|
231
|
+
return s == "True"
|
|
232
|
+
if _IDENTIFIER.fullmatch(s):
|
|
233
|
+
hint = (
|
|
234
|
+
f" Available columns: {list(df.columns)}"
|
|
235
|
+
if role == "condition"
|
|
236
|
+
else f' For text, quote it: "{s}".'
|
|
237
|
+
)
|
|
238
|
+
raise FormulaMistake(f"where(): the {role} {s!r} is not a column.{hint}")
|
|
239
|
+
try:
|
|
240
|
+
return df.eval(s)
|
|
241
|
+
except Exception as exc:
|
|
242
|
+
raise FormulaMistake(
|
|
243
|
+
f"where(): can't evaluate the {role} {s!r}: {exc}"
|
|
244
|
+
) from None
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def _where_condition(val: str, df: pd.DataFrame) -> np.ndarray:
|
|
248
|
+
"""The condition as a boolean array: a true/false column or expression,
|
|
249
|
+
or numbers 0 and 1. Missing counts as false."""
|
|
250
|
+
cond = _resolve_where_val(val, df, "condition")
|
|
251
|
+
if not isinstance(cond, pd.Series):
|
|
252
|
+
raise FormulaMistake(
|
|
253
|
+
f"where(): the condition {val!r} must be a column or an expression "
|
|
254
|
+
"of columns that is true or false, e.g. where(tip > 3, ...)."
|
|
255
|
+
)
|
|
256
|
+
if pd.api.types.is_bool_dtype(cond):
|
|
257
|
+
return cond.fillna(False).to_numpy(dtype=bool)
|
|
258
|
+
if pd.api.types.is_numeric_dtype(cond) and cond.dropna().isin([0, 1]).all():
|
|
259
|
+
return (cond == 1).to_numpy()
|
|
260
|
+
if cond.dropna().map(lambda v: isinstance(v, (bool, np.bool_))).all():
|
|
261
|
+
return cond.fillna(False).astype(bool).to_numpy()
|
|
262
|
+
shown = [v.item() if hasattr(v, "item") else v for v in pd.unique(cond.dropna())]
|
|
263
|
+
shown = shown[:3]
|
|
264
|
+
raise FormulaMistake(
|
|
265
|
+
f"where(): the condition {val!r} must be true or false (or 0 and 1), "
|
|
266
|
+
f"but it holds values like {shown}. Compare it, e.g. "
|
|
267
|
+
f"where({val} == {shown[0]!r}, ...)."
|
|
268
|
+
if shown
|
|
269
|
+
else f"where(): the condition {val!r} must be true or false."
|
|
270
|
+
)
|
|
212
271
|
|
|
213
272
|
|
|
214
273
|
class _WhereFunc:
|
|
215
|
-
"""Callable for ``where(
|
|
274
|
+
"""Callable for ``where(cond, true_val, false_val)`` using ``np.where``.
|
|
216
275
|
|
|
217
|
-
Receives the full DataFrame so that
|
|
218
|
-
|
|
276
|
+
Receives the full DataFrame so that each argument can be a column, a
|
|
277
|
+
quoted string, a number or a pandas expression (_resolve_where_val).
|
|
219
278
|
"""
|
|
220
279
|
|
|
221
|
-
def __init__(self,
|
|
222
|
-
self.
|
|
280
|
+
def __init__(self, cond: str, true_val: str, false_val: str) -> None:
|
|
281
|
+
self.cond = cond
|
|
223
282
|
self.true_val = true_val
|
|
224
283
|
self.false_val = false_val
|
|
225
284
|
|
|
226
285
|
def __call__(self, df: pd.DataFrame):
|
|
227
|
-
cond =
|
|
228
|
-
true_res = _resolve_where_val(self.true_val, df)
|
|
229
|
-
false_res = _resolve_where_val(self.false_val, df)
|
|
230
|
-
|
|
286
|
+
cond = _where_condition(self.cond, df)
|
|
287
|
+
true_res = _resolve_where_val(self.true_val, df, "value if true")
|
|
288
|
+
false_res = _resolve_where_val(self.false_val, df, "value if false")
|
|
289
|
+
try:
|
|
290
|
+
return np.where(cond, true_res, false_res)
|
|
291
|
+
except TypeError: # text and numbers: numpy has no common type
|
|
292
|
+
return np.where(
|
|
293
|
+
cond, np.asarray(true_res, dtype=object),
|
|
294
|
+
np.asarray(false_res, dtype=object),
|
|
295
|
+
) # fmt: skip
|
|
231
296
|
|
|
232
297
|
|
|
233
298
|
SPECIAL_FUNCTIONS = (
|
|
@@ -292,12 +357,13 @@ def special_function(formula: str, df_columns: list[str]):
|
|
|
292
357
|
)
|
|
293
358
|
|
|
294
359
|
if func_name == "where":
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
"where(
|
|
360
|
+
args = split_arguments(body)
|
|
361
|
+
if len(args) != 3 or not all(args):
|
|
362
|
+
raise FormulaMistake(
|
|
363
|
+
f"where() takes 3 arguments, where(condition, value if true, "
|
|
364
|
+
f"value if false), not {len(args)}: {formula!r}"
|
|
299
365
|
)
|
|
300
|
-
return dest, _WhereFunc(
|
|
366
|
+
return dest, _WhereFunc(*args), []
|
|
301
367
|
|
|
302
368
|
if func_name == "overlap":
|
|
303
369
|
func = partial(lambda x: max(0, min(x[1], x[3]) - max(x[0] - 1, x[2] - 1)))
|
|
@@ -155,7 +155,9 @@ correlogram is `corr --all -o | heatmap -x col1 -y col2 -v correlation
|
|
|
155
155
|
`--sig`/`--suggestive` lines, points with p > 0.01 thinned, `--logy` log
|
|
156
156
|
scale above 10, `--miami COL [UPPER LOWER]` two scans, the second upside
|
|
157
157
|
down below it), `qq` (QQ plot of p-values with a 95 % band and the genomic inflation
|
|
158
|
-
lambda; same p-value options, `-g` one curve and lambda per group, `--logy`)
|
|
158
|
+
lambda; same p-value options, `-g` one curve and lambda per group, `--logy`),
|
|
159
|
+
`locus` (one region, cut out with `query` first: -log10(p) by position, `--ldcol r2`
|
|
160
|
+
colours by LD with the lead, `--lead`/`--label` take an ID or `chr6:32600000`). `-g COL`
|
|
159
161
|
overlays groups, `--subgraphcol COL` makes panels.
|
|
160
162
|
|
|
161
163
|
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
|
{dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.1}/src/dftk/skills/dftk/references/snakemake.md
RENAMED
|
File without changes
|