dataframe-toolkit 0.21.0__tar.gz → 0.22.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.0}/PKG-INFO +9 -1
  2. {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.0}/README.md +8 -0
  3. {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.0}/pyproject.toml +1 -1
  4. {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.0}/pyproject.toml.orig +1 -1
  5. {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/__init__.py +1 -0
  6. dataframe_toolkit-0.22.0/src/dftk/commands/locus_cmd.py +430 -0
  7. {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/manhattan_cmd.py +4 -2
  8. {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.0}/src/dftk/skills/dftk/SKILL.md +3 -1
  9. {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.0}/src/dftk/__init__.py +0 -0
  10. {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.0}/src/dftk/cli.py +0 -0
  11. {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/annotate_cmd.py +0 -0
  12. {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/append_cmd.py +0 -0
  13. {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/base.py +0 -0
  14. {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/binx_cmd.py +0 -0
  15. {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/chi_cmd.py +0 -0
  16. {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/clean_cmd.py +0 -0
  17. {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/cleannames_cmd.py +0 -0
  18. {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/concat_cmd.py +0 -0
  19. {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/corr_cmd.py +0 -0
  20. {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/dataset_cmd.py +0 -0
  21. {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/describe_cmd.py +0 -0
  22. {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/eval_cmd.py +0 -0
  23. {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/explode_cmd.py +0 -0
  24. {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/fit_cmd.py +0 -0
  25. {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/func_cmd.py +0 -0
  26. {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/heatmap_cmd.py +0 -0
  27. {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/help.py +0 -0
  28. {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/hist_cmd.py +0 -0
  29. {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/implode_cmd.py +0 -0
  30. {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/info_cmd.py +0 -0
  31. {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/interp_cmd.py +0 -0
  32. {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/line_cmd.py +0 -0
  33. {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/melt_cmd.py +0 -0
  34. {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/merge_cmd.py +0 -0
  35. {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/pairs_cmd.py +0 -0
  36. {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/pivot_cmd.py +0 -0
  37. {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/print_cmd.py +0 -0
  38. {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/qq_cmd.py +0 -0
  39. {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/query_cmd.py +0 -0
  40. {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/randvar_cmd.py +0 -0
  41. {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/sample_cmd.py +0 -0
  42. {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/scale_cmd.py +0 -0
  43. {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/scat_cmd.py +0 -0
  44. {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/segid_cmd.py +0 -0
  45. {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/skill_cmd.py +0 -0
  46. {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/split_cmd.py +0 -0
  47. {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/stat_cmd.py +0 -0
  48. {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/test_cmd.py +0 -0
  49. {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/transpose_cmd.py +0 -0
  50. {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/wstat_cmd.py +0 -0
  51. {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.0}/src/dftk/common/__init__.py +0 -0
  52. {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.0}/src/dftk/common/copula.py +0 -0
  53. {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.0}/src/dftk/common/docformats.py +0 -0
  54. {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.0}/src/dftk/common/evalfuncs.py +0 -0
  55. {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.0}/src/dftk/common/gwas.py +0 -0
  56. {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.0}/src/dftk/common/io.py +0 -0
  57. {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.0}/src/dftk/common/plot.py +0 -0
  58. {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.0}/src/dftk/common/seed.py +0 -0
  59. {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.0}/src/dftk/common/seq.py +0 -0
  60. {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.0}/src/dftk/common/stats.py +0 -0
  61. {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.0}/src/dftk/io.py +0 -0
  62. {dataframe_toolkit-0.21.0 → dataframe_toolkit-0.22.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.21.0
3
+ Version: 0.22.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
@@ -168,6 +168,7 @@ publication-quality output.
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
@@ -138,6 +138,7 @@ publication-quality output.
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
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "dataframe-toolkit"
3
- version = "0.21.0"
3
+ version = "0.22.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.21.0"
3
+ version = "0.22.0"
4
4
  description = "A command-line toolkit for DataFrame analysis and manipulation"
5
5
  readme = "README.md"
6
6
  authors = [
@@ -67,6 +67,7 @@ COMMAND_GROUPS: list[tuple[str, list[tuple[str, str]]]] = [
67
67
  ("pairs", "pairs_cmd:PairsCommand"),
68
68
  ("manhattan", "manhattan_cmd:ManhattanCommand"),
69
69
  ("qq", "qq_cmd:QqCommand"),
70
+ ("locus", "locus_cmd:LocusCommand"),
70
71
  ],
71
72
  ),
72
73
  (
@@ -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
+ )
@@ -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
- ) -> None:
127
- """Column options shared by manhattan and qq (qq: position=False)."""
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):
@@ -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`). `-g COL`
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`