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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.20.0}/PKG-INFO +13 -2
  2. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.20.0}/README.md +12 -1
  3. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.20.0}/pyproject.toml +1 -1
  4. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.20.0}/pyproject.toml.orig +1 -1
  5. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/chi_cmd.py +2 -2
  6. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/hist_cmd.py +2 -2
  7. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/line_cmd.py +2 -2
  8. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/manhattan_cmd.py +268 -24
  9. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/qq_cmd.py +26 -3
  10. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/scat_cmd.py +2 -2
  11. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.20.0}/src/dftk/common/gwas.py +55 -11
  12. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.20.0}/src/dftk/common/io.py +59 -7
  13. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.20.0}/src/dftk/skills/dftk/SKILL.md +4 -3
  14. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.20.0}/src/dftk/__init__.py +0 -0
  15. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.20.0}/src/dftk/cli.py +0 -0
  16. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/__init__.py +0 -0
  17. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/annotate_cmd.py +0 -0
  18. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/append_cmd.py +0 -0
  19. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/base.py +0 -0
  20. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/binx_cmd.py +0 -0
  21. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/clean_cmd.py +0 -0
  22. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/cleannames_cmd.py +0 -0
  23. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/concat_cmd.py +0 -0
  24. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/corr_cmd.py +0 -0
  25. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/dataset_cmd.py +0 -0
  26. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/describe_cmd.py +0 -0
  27. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/eval_cmd.py +0 -0
  28. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/explode_cmd.py +0 -0
  29. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/fit_cmd.py +0 -0
  30. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/func_cmd.py +0 -0
  31. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/heatmap_cmd.py +0 -0
  32. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/help.py +0 -0
  33. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/implode_cmd.py +0 -0
  34. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/info_cmd.py +0 -0
  35. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/interp_cmd.py +0 -0
  36. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/melt_cmd.py +0 -0
  37. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/merge_cmd.py +0 -0
  38. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/pairs_cmd.py +0 -0
  39. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/pivot_cmd.py +0 -0
  40. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/print_cmd.py +0 -0
  41. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/query_cmd.py +0 -0
  42. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/randvar_cmd.py +0 -0
  43. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/sample_cmd.py +0 -0
  44. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/scale_cmd.py +0 -0
  45. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/segid_cmd.py +0 -0
  46. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/skill_cmd.py +0 -0
  47. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/split_cmd.py +0 -0
  48. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/stat_cmd.py +0 -0
  49. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/test_cmd.py +0 -0
  50. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/transpose_cmd.py +0 -0
  51. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/wstat_cmd.py +0 -0
  52. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.20.0}/src/dftk/common/__init__.py +0 -0
  53. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.20.0}/src/dftk/common/copula.py +0 -0
  54. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.20.0}/src/dftk/common/docformats.py +0 -0
  55. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.20.0}/src/dftk/common/evalfuncs.py +0 -0
  56. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.20.0}/src/dftk/common/plot.py +0 -0
  57. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.20.0}/src/dftk/common/seed.py +0 -0
  58. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.20.0}/src/dftk/common/seq.py +0 -0
  59. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.20.0}/src/dftk/common/stats.py +0 -0
  60. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.20.0}/src/dftk/io.py +0 -0
  61. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.20.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.19.0
3
+ Version: 0.20.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
@@ -484,7 +484,16 @@ A p-value below about 1e-308 is stored as 0, which plots as -log10(p) = 323 with
484
484
  dftk dataset gwas -o | dftk manhattan --chi2col Chisq -f manhattan.png
485
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
+ 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. `--logy` instead keeps every peak: the axis is linear up to -log10(p) = 10 and logarithmic above it (`--logy 5` moves the switch), so a peak at 380 and one at 8 both show. `--sigcolor red` colours the points past the `--sig` line.
488
+
489
+ Several scans in one table: `--subgraphcol study` draws a panel each, `-g study` a colour each, and `--miami study` draws two of them face to face (a Miami plot): the first on top, the second upside down below it, with the chromosome numbers between them. The column must hold two values, or name the two to draw (`--miami study a b`, top first). Here the second scan is the example one with every chi-squared halved:
490
+
491
+ ```bash
492
+ dftk dataset gwas -o \
493
+ | dftk eval -f "half = Chisq / 2" --select Chr pos Chisq half -o \
494
+ | dftk melt -i Chr pos -d study -v chi2 -o \
495
+ | dftk manhattan --chi2col chi2 --miami study --sigcolor red -f miami.png
496
+ ```
488
497
 
489
498
  `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
499
 
@@ -493,6 +502,8 @@ dftk dataset gwas -o | dftk qq -f qq.png
493
502
  dftk dataset gwas -o | dftk eval -f "Chisq = Chisq * 1.15" -o | dftk qq --chi2col Chisq -f qq.png
494
503
  ```
495
504
 
505
+ `qq --logy` makes its y axis linear up to 10 and logarithmic above, as in `manhattan`.
506
+
496
507
  ### Bootstrap confidence intervals
497
508
 
498
509
  Bootstrap mode repeats the full stat computation N times on resampled data
@@ -454,7 +454,16 @@ A p-value below about 1e-308 is stored as 0, which plots as -log10(p) = 323 with
454
454
  dftk dataset gwas -o | dftk manhattan --chi2col Chisq -f manhattan.png
455
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
+ 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. `--logy` instead keeps every peak: the axis is linear up to -log10(p) = 10 and logarithmic above it (`--logy 5` moves the switch), so a peak at 380 and one at 8 both show. `--sigcolor red` colours the points past the `--sig` line.
458
+
459
+ Several scans in one table: `--subgraphcol study` draws a panel each, `-g study` a colour each, and `--miami study` draws two of them face to face (a Miami plot): the first on top, the second upside down below it, with the chromosome numbers between them. The column must hold two values, or name the two to draw (`--miami study a b`, top first). Here the second scan is the example one with every chi-squared halved:
460
+
461
+ ```bash
462
+ dftk dataset gwas -o \
463
+ | dftk eval -f "half = Chisq / 2" --select Chr pos Chisq half -o \
464
+ | dftk melt -i Chr pos -d study -v chi2 -o \
465
+ | dftk manhattan --chi2col chi2 --miami study --sigcolor red -f miami.png
466
+ ```
458
467
 
459
468
  `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
469
 
@@ -463,6 +472,8 @@ dftk dataset gwas -o | dftk qq -f qq.png
463
472
  dftk dataset gwas -o | dftk eval -f "Chisq = Chisq * 1.15" -o | dftk qq --chi2col Chisq -f qq.png
464
473
  ```
465
474
 
475
+ `qq --logy` makes its y axis linear up to 10 and logarithmic above, as in `manhattan`.
476
+
466
477
  ### Bootstrap confidence intervals
467
478
 
468
479
  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.19.0"
3
+ version = "0.20.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.19.0"
3
+ version = "0.20.0"
4
4
  description = "A command-line toolkit for DataFrame analysis and manipulation"
5
5
  readme = "README.md"
6
6
  authors = [
@@ -15,7 +15,7 @@ import numpy as np
15
15
 
16
16
  from dftk.commands.base import BaseCommand
17
17
  from dftk.common.copula import corner_chi, pseudo_observations
18
- from dftk.common.io import check_cols, io
18
+ from dftk.common.io import check_cols, io, option_columns
19
19
  from dftk.common.plot import (
20
20
  add_figure_arguments,
21
21
  add_group_arguments,
@@ -153,7 +153,7 @@ class ChiCommand(BaseCommand):
153
153
  if not args.xcol or not args.ycol:
154
154
  raise ValueError("--xcol (-x) and --ycol (-y) are required.")
155
155
 
156
- df = io.read(args)
156
+ df = io.read(args, columns=option_columns(args))
157
157
  check_cols(df, [args.xcol, args.ycol], "-x/-y")
158
158
  check_cols(df, args.groupcol, "-g/--groupcol")
159
159
  check_cols(df, args.subgraphcol, "--subgraphcol")
@@ -18,7 +18,7 @@ import argparse
18
18
  import numpy as np
19
19
 
20
20
  from dftk.commands.base import BaseCommand
21
- from dftk.common.io import check_cols, io
21
+ from dftk.common.io import check_cols, io, option_columns
22
22
  from dftk.common.plot import (
23
23
  add_figure_arguments,
24
24
  add_group_arguments,
@@ -281,7 +281,7 @@ class HistCommand(BaseCommand):
281
281
  )
282
282
 
283
283
  def execute(self, args: argparse.Namespace) -> None:
284
- df = io.read(args)
284
+ df = io.read(args, columns=option_columns(args))
285
285
  check_cols(df, [args.xcol], "-x/--xcol")
286
286
  check_cols(df, args.groupcol, "-g/--groupcol")
287
287
  check_cols(df, args.subgraphcol, "--subgraphcol")
@@ -20,7 +20,7 @@ import matplotlib.lines as mlines
20
20
  import numpy as np
21
21
 
22
22
  from dftk.commands.base import BaseCommand
23
- from dftk.common.io import check_cols, io
23
+ from dftk.common.io import check_cols, io, option_columns
24
24
  from dftk.common.plot import (
25
25
  add_figure_arguments,
26
26
  add_group_arguments,
@@ -288,7 +288,7 @@ class LineCommand(BaseCommand):
288
288
  if not args.xcol or not args.ycol:
289
289
  raise ValueError("--xcol (-x) and --ycol (-y) are required.")
290
290
 
291
- df = io.read(args)
291
+ df = io.read(args, columns=option_columns(args))
292
292
  check_cols(df, [args.xcol, args.ycol], "-x/-y")
293
293
  check_cols(df, args.groupcol, "-g/--groupcol")
294
294
  check_cols(df, args.subgraphcol, "--subgraphcol")
@@ -17,7 +17,7 @@ import pandas as pd
17
17
 
18
18
  from dftk.commands.base import BaseCommand
19
19
  from dftk.common import gwas
20
- from dftk.common.io import check_cols, io
20
+ from dftk.common.io import check_cols, io, option_columns
21
21
  from dftk.common.plot import (
22
22
  WONG_PALETTE,
23
23
  add_figure_arguments,
@@ -75,12 +75,30 @@ as triangles on the top edge:
75
75
 
76
76
  dftk dataset gwas -o | dftk manhattan --ylim 0 40 -f manhattan.png
77
77
 
78
+ Or log-scale it above -log10(p) = 10 (linear below), so a peak at 380
79
+ and one at 8 both show:
80
+
81
+ dftk dataset gwas -o | dftk manhattan --chi2col Chisq --logy -f manhattan.png
82
+
78
83
  Several scans in one table (a study column): one panel each, or one colour
79
84
  each with -g:
80
85
 
81
86
  dftk manhattan all_studies.tsv --subgraphcol study -f manhattan.png
82
87
  dftk manhattan all_studies.tsv -g study -f manhattan.png
83
88
 
89
+ Two scans face to face (a Miami plot): the first value of the study column
90
+ on top, the second upside down below it, the chromosome numbers between
91
+ them; points past --sig in red.
92
+ Here the second scan is the example scan with every chi-squared halved,
93
+ and melt stacks the two columns into one, with a study column:
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 \
98
+ | dftk manhattan --chi2col chi2 --miami study --sigcolor red -f miami.png
99
+
100
+ With more than two scans in the column, name the two: --miami study a b.
101
+
84
102
  Publication figure (Nature double column, PDF):
85
103
 
86
104
  dftk dataset gwas -o | dftk manhattan --size 7.2x2.6 --fontsize publication \\
@@ -143,6 +161,18 @@ def add_gwas_column_arguments(
143
161
  )
144
162
 
145
163
 
164
+ def gwas_columns(args: argparse.Namespace, position: bool = True):
165
+ """columns= for io.read: the chromosome, position and p-value columns
166
+ (found as gwas_table will find them) and the ones options name."""
167
+ named = option_columns(args)
168
+
169
+ def pick(names: list[str]) -> list[str] | None:
170
+ found = gwas.needed_columns(names, args, position)
171
+ return None if found is None else found + named(names)
172
+
173
+ return pick
174
+
175
+
146
176
  def gwas_table(df: pd.DataFrame, args: argparse.Namespace) -> pd.DataFrame:
147
177
  """Return df with _chrom (label), _pos and _y (-log10 p); rows lacking any dropped.
148
178
 
@@ -177,9 +207,13 @@ def gwas_table(df: pd.DataFrame, args: argparse.Namespace) -> pd.DataFrame:
177
207
  # ---------------------------------------------------------------------------
178
208
 
179
209
 
210
+ def _peak(y: np.ndarray, lines: list[float]) -> float:
211
+ """Default top of the y axis: the highest point or line, plus 5 %."""
212
+ return max([float(np.max(y)) if y.size else 1.0, *lines, 1.0]) * 1.05
213
+
214
+
180
215
  def _ylimits(y: np.ndarray, lines: list[float], args) -> tuple[float, float]:
181
- top = max([float(np.max(y)) if y.size else 1.0, *lines, 1.0]) * 1.05
182
- lo, hi = 0.0, top
216
+ lo, hi = 0.0, _peak(y, lines)
183
217
  if args.ylim is not None:
184
218
  lo = float_or(args.ylim[0], lo)
185
219
  hi = float_or(args.ylim[1], hi)
@@ -193,11 +227,12 @@ def float_or(s, fallback: float) -> float:
193
227
  return fallback
194
228
 
195
229
 
196
- def scatter_capped(ax, x, y, hi, args, colours=None, **kw):
197
- """Points below *hi*, and triangles on the top edge for those above it.
230
+ def scatter_capped(ax, x, y, hi, args, colours=None, capmarker="^", **kw):
231
+ """Points below *hi*, and triangles on the edge for those above it.
198
232
 
199
233
  *colours*: one colour per point (alternating chromosomes), or None to
200
- use kw["color"].
234
+ use kw["color"]. *capmarker*: "v" on a Miami plot's lower half, whose
235
+ y axis points down.
201
236
  """
202
237
  over = y > hi
203
238
  size = args.markersize
@@ -209,26 +244,77 @@ def scatter_capped(ax, x, y, hi, args, colours=None, **kw):
209
244
  if over.any():
210
245
  common.pop("label", None)
211
246
  ax.scatter(
212
- x[over], np.full(over.sum(), hi), s=size * 4, marker="^",
247
+ x[over], np.full(over.sum(), hi), s=size * 4, marker=capmarker,
213
248
  clip_on=False, c=None if colours is None else colours[over], **common,
214
249
  ) # fmt: skip
215
250
 
216
251
 
217
- def _draw(ax, data: pd.DataFrame, layout, args, groupcols=None) -> None:
252
+ def thin_points(x, y, args, groups=None) -> np.ndarray:
253
+ """gwas.thin_mask on the y axis as drawn: with --logy, the grid is
254
+ even on the symmetric-log scale, so a stretched linear part (a small T)
255
+ is not left sparse. Every point with p <= 0.01 is still kept."""
256
+ if not args.thin:
257
+ return np.ones(len(x), dtype=bool)
258
+ keep_above = 2.0
259
+ if args.logy is not None:
260
+ from matplotlib.scale import SymmetricalLogTransform
261
+
262
+ tf = SymmetricalLogTransform(10, args.logy, 1.0)
263
+ y = tf.transform(np.asarray(y, dtype=float))
264
+ keep_above = float(tf.transform(np.array([keep_above]))[0])
265
+ return gwas.thin_mask(x, y, keep_above=keep_above, groups=groups)
266
+
267
+
268
+ def log_yaxis(ax, linthresh: float, lo: float, hi: float) -> None:
269
+ """Symmetric-log y axis: linear up to *linthresh*, log10 above it.
270
+
271
+ Ticks: a few on the linear part, then 1, 2, 5 times each power of ten
272
+ (only the powers when that would crowd the axis).
273
+ Labels as plain numbers.
274
+ """
275
+ from matplotlib.ticker import FuncFormatter, MaxNLocator, NullLocator
276
+
277
+ ax.set_yscale("symlog", linthresh=linthresh, linscale=1.0)
278
+ top = hi
279
+ lin = MaxNLocator(nbins=3, steps=[1, 2, 2.5, 5, 10]).tick_values(0, linthresh)
280
+ pos = {float(t) for t in lin if 0 <= t <= linthresh}
281
+ k0 = int(np.floor(np.log10(linthresh)))
282
+ k1 = int(np.ceil(np.log10(max(top, linthresh))))
283
+ for mults in ((1, 2, 5), (1,)):
284
+ log = {
285
+ m * 10.0**k
286
+ for k in range(k0, k1 + 1)
287
+ for m in mults
288
+ if linthresh < m * 10.0**k <= top
289
+ }
290
+ if len(log) <= 6:
291
+ break
292
+ pos |= log
293
+ ax.set_yticks([t for t in sorted(pos) if lo <= t <= hi])
294
+ ax.yaxis.set_minor_locator(NullLocator())
295
+ ax.yaxis.set_major_formatter(FuncFormatter(lambda v, _: f"{v:g}"))
296
+
297
+
298
+ def _draw(
299
+ ax, data: pd.DataFrame, layout, args, groupcols=None, ylim=None, capmarker="^"
300
+ ):
301
+ """Draw one scan (or -g groups) on *ax*; return the axes for the title.
302
+
303
+ With --miami, *ax* is split in two (_draw_miami). *ylim*: (lo, hi)
304
+ instead of the limits from the data and --ylim.
305
+ """
306
+ if args.miami and ylim is None:
307
+ return _draw_miami(ax, data, layout, args)
218
308
  centres, labels, bounds = layout
219
309
  x = data["_x"].to_numpy()
220
310
  y = data["_y"].to_numpy()
221
311
  lines = [-np.log10(p) for p in (args.sig, args.suggestive) if p is not None]
222
- lo, hi = _ylimits(y, lines, args)
312
+ lo, hi = ylim if ylim is not None else _ylimits(y, lines, args)
223
313
 
224
314
  groups = None
225
315
  if groupcols:
226
316
  groups = data[groupcols].astype(str).agg("\t".join, axis=1).to_numpy()
227
- keep = (
228
- gwas.thin_mask(x, y, groups=groups)
229
- if args.thin
230
- else np.ones(len(x), dtype=bool)
231
- )
317
+ keep = thin_points(x, y, args, groups)
232
318
  if args.thin and (~keep).any():
233
319
  logger.info("Thinned %d of %d points (p > 0.01)", int((~keep).sum()), len(x))
234
320
 
@@ -253,10 +339,14 @@ def _draw(ax, data: pd.DataFrame, layout, args, groupcols=None) -> None:
253
339
  markerscale=3,
254
340
  )
255
341
  else:
256
- colours = np.array(args.colors)[data["_cidx"].to_numpy() % len(args.colors)]
342
+ colours = np.array(args.colors, dtype=object)[
343
+ data["_cidx"].to_numpy() % len(args.colors)
344
+ ]
345
+ if args.sigcolor and args.sig is not None:
346
+ colours[y >= -np.log10(args.sig)] = args.sigcolor
257
347
  scatter_capped(
258
- ax, x[keep], y[keep], hi, args, colours=colours[keep], zorder=2,
259
- label=args.legend,
348
+ ax, x[keep], y[keep], hi, args, colours=colours[keep],
349
+ capmarker=capmarker, zorder=2, label=args.legend,
260
350
  ) # fmt: skip
261
351
  if args.legend:
262
352
  ax.legend(loc=tuple(args.legendloc) if args.legendloc else "best")
@@ -270,6 +360,8 @@ def _draw(ax, data: pd.DataFrame, layout, args, groupcols=None) -> None:
270
360
  ) # fmt: skip
271
361
 
272
362
  ax.set_ylim(lo, hi)
363
+ if args.logy is not None:
364
+ log_yaxis(ax, args.logy, lo, hi)
273
365
  pad = _gap(bounds)
274
366
  ax.set_xlim(bounds[0][0] - pad, bounds[-1][1] + pad)
275
367
  ax.set_xticks(centres)
@@ -278,6 +370,126 @@ def _draw(ax, data: pd.DataFrame, layout, args, groupcols=None) -> None:
278
370
  ax.spines[["top", "right"]].set_visible(False)
279
371
  ax.set_xlabel(args.xlabel if args.xlabel is not None else "Chromosome")
280
372
  ax.set_ylabel(args.ylabel if args.ylabel is not None else r"$-\log_{10}(p)$")
373
+ return ax
374
+
375
+
376
+ # Space between a Miami plot's halves, for the chromosome numbers: in
377
+ # multiples of the tick-label font size
378
+ _MIAMI_GAP_EM = 2.2
379
+
380
+
381
+ def _draw_miami(ax, data: pd.DataFrame, layout, args):
382
+ """Split *ax* into two scans, the lower one upside down, with the
383
+ chromosome numbers in the gap between them; return the upper axes."""
384
+ import matplotlib.pyplot as plt
385
+ from matplotlib.scale import SymmetricalLogTransform
386
+
387
+ upper_name, lower_name = args.miami_names
388
+ halves = [data[data["_half"] == h] for h in (0, 1)]
389
+ lines = [-np.log10(p) for p in (args.sig, args.suggestive) if p is not None]
390
+ tops = [_peak(h["_y"].to_numpy(), lines) for h in halves]
391
+ if args.ylim is not None:
392
+ # signed: --ylim -20 40 caps the lower half at 20, the upper at 40
393
+ tops[0] = float_or(args.ylim[1], tops[0])
394
+ low = float_or(args.ylim[0], 0.0)
395
+ if low:
396
+ tops[1] = abs(low)
397
+
398
+ # heights in proportion, so both halves have the same scale
399
+ if args.logy is not None:
400
+ tf = SymmetricalLogTransform(10, args.logy, 1.0)
401
+ ratios = [float(tf.transform(np.array([t]))[0]) for t in tops]
402
+ else:
403
+ ratios = tops
404
+
405
+ fig = ax.figure
406
+ spec = ax.get_subplotspec()
407
+ ax.remove()
408
+ panel_in = spec.get_position(fig).height * fig.get_figheight()
409
+ font_pt = _font_pt(plt.rcParams["xtick.labelsize"])
410
+ gap_in = _MIAMI_GAP_EM * font_pt / 72
411
+ # hspace is in units of the mean axes height
412
+ hspace = 2 * gap_in / max(panel_in - gap_in, 0.1)
413
+ grid = spec.subgridspec(2, 1, height_ratios=ratios, hspace=hspace)
414
+ upper = fig.add_subplot(grid[0])
415
+ lower = fig.add_subplot(grid[1], sharex=upper)
416
+
417
+ _draw(upper, halves[0], layout, args, ylim=(0.0, tops[0]))
418
+ _draw(lower, halves[1], layout, args, ylim=(0.0, tops[1]), capmarker="v")
419
+
420
+ # lower half upside down: 0 at the top, by the upper half's 0
421
+ lower.set_ylim(tops[1], 0.0)
422
+ lower.spines[["bottom", "right"]].set_visible(False)
423
+ lower.spines["top"].set_visible(True)
424
+ lower.tick_params(axis="x", labelbottom=False)
425
+ # chromosome numbers in the middle of the gap. The gap is hspace mean
426
+ # axes heights, and the upper half 2 r0 / (r0 + r1) of one, whatever
427
+ # size the layout gives them, so its middle is a fixed upper-axes y
428
+ from matplotlib.transforms import blended_transform_factory
429
+
430
+ middle = -hspace * sum(ratios) / (4 * ratios[0])
431
+ upper.tick_params(axis="x", labelbottom=False)
432
+ to_gap = blended_transform_factory(upper.transData, upper.transAxes)
433
+ for x, label in zip(layout[0], _tick_labels(layout[1], upper), strict=True):
434
+ upper.text(
435
+ x, middle, label, transform=to_gap, ha="center", va="center_baseline",
436
+ fontsize=font_pt, clip_on=False,
437
+ ) # fmt: skip
438
+ upper.set_xlabel("")
439
+ lower.set_xlabel(args.xlabel or "")
440
+ for half, name, (y, va) in (
441
+ (upper, upper_name, (0.98, "top")),
442
+ (lower, lower_name, (0.02, "bottom")),
443
+ ):
444
+ half.text(0.01, y, name, transform=half.transAxes, ha="left", va=va)
445
+ return upper
446
+
447
+
448
+ def _font_pt(size) -> float:
449
+ """A matplotlib font size (points or a name like "medium") in points."""
450
+ from matplotlib.font_manager import FontProperties
451
+
452
+ return FontProperties(size=size).get_size_in_points()
453
+
454
+
455
+ def miami_halves(data: pd.DataFrame, spec: list[str]) -> tuple[pd.DataFrame, list]:
456
+ """Add _half (0 for the upper scan, 1 for the lower) from --miami COL [UPPER LOWER].
457
+
458
+ With COL alone it must hold exactly two values, the first one in the
459
+ table drawn above; with UPPER and LOWER, rows with other values are
460
+ left out.
461
+ """
462
+ col, *names = spec
463
+ check_cols(data, [col], "--miami")
464
+ if len(names) not in (0, 2):
465
+ raise ValueError(
466
+ "--miami takes a column, or a column and the two values to draw "
467
+ f"(above, below), not {len(spec)} arguments."
468
+ )
469
+ values = data[col].astype(str)
470
+ if names:
471
+ found = set(values)
472
+ missing = [n for n in names if n not in found]
473
+ if missing:
474
+ raise ValueError(
475
+ f"--miami: {missing} not in column {col!r}; it holds "
476
+ f"{sorted(found)[:10]}"
477
+ )
478
+ if names[0] == names[1]:
479
+ raise ValueError("--miami: the two values must differ.")
480
+ else:
481
+ names = list(pd.unique(values))
482
+ if len(names) != 2:
483
+ raise ValueError(
484
+ f"--miami: column {col!r} holds {len(names)} values, not 2; "
485
+ f"name the two to draw: --miami {col} UPPER LOWER"
486
+ )
487
+ keep = values.isin(names).to_numpy()
488
+ if not keep.all():
489
+ logger.info("--miami: left out %d rows of other values", int((~keep).sum()))
490
+ out = data[keep].copy()
491
+ out["_half"] = (values[keep] == names[1]).astype(int).to_numpy()
492
+ return out, names
281
493
 
282
494
 
283
495
  def _gap(bounds) -> float:
@@ -326,12 +538,35 @@ class ManhattanCommand(BaseCommand):
326
538
  metavar="P|none",
327
539
  help="Suggestive line, as a p-value (default: 1e-5).",
328
540
  )
541
+ g.add_argument(
542
+ "--miami",
543
+ nargs="+",
544
+ metavar="COL",
545
+ help="Two scans in one plot, the second upside down under the first "
546
+ "(a Miami plot): --miami COL [UPPER LOWER]. COL alone must hold two "
547
+ "values, the first drawn above; or name the two to draw.",
548
+ )
549
+ g.add_argument(
550
+ "--logy",
551
+ nargs="?",
552
+ type=float,
553
+ const=10.0,
554
+ metavar="T",
555
+ help="Log scale above -log10(p) = T, linear below it (default T: 10), "
556
+ "so a peak of 300 and one of 10 both show.",
557
+ )
329
558
  g.add_argument(
330
559
  "--no-thin",
331
560
  dest="thin",
332
561
  action="store_false",
333
562
  help="Draw every point (default: thin points with p > 0.01).",
334
563
  )
564
+ g.add_argument(
565
+ "--sigcolor",
566
+ metavar="COLOUR",
567
+ help="Colour for points past the --sig line (default: the "
568
+ "chromosome colours; not with -g).",
569
+ )
335
570
  g.add_argument(
336
571
  "--colors",
337
572
  nargs="+",
@@ -364,19 +599,28 @@ class ManhattanCommand(BaseCommand):
364
599
  nargs=2,
365
600
  metavar=("LO", "HI"),
366
601
  help="Y-axis limits in -log10(p); points above HI are drawn as "
367
- "triangles on the top edge.",
602
+ "triangles on the top edge. With --miami the lower half is "
603
+ "negative: --ylim -30 30.",
368
604
  )
369
605
 
370
606
  add_figure_arguments(parser)
371
- parser.set_defaults(size="12x4")
607
+ parser.set_defaults(size=None)
372
608
  add_group_arguments(parser)
373
609
  add_legend_arguments(parser)
374
610
 
375
611
  def execute(self, args: argparse.Namespace) -> None:
376
- df = io.read(args)
612
+ df = io.read(args, columns=gwas_columns(args, position=True))
377
613
  check_cols(df, args.groupcol, "-g/--groupcol")
378
614
  check_cols(df, args.subgraphcol, "--subgraphcol")
615
+ if args.miami and args.groupcol:
616
+ raise ValueError("--miami and -g/--groupcol can't be combined.")
617
+ if args.logy is not None and args.logy <= 0:
618
+ raise ValueError(f"--logy must be above 0, not {args.logy:g}.")
619
+ if args.size is None:
620
+ args.size = "12x6" if args.miami else "12x4"
379
621
  data = gwas_table(df, args)
622
+ if args.miami:
623
+ data, args.miami_names = miami_halves(data, args.miami)
380
624
 
381
625
  x, centres, labels, bounds = gwas.genome_positions(data["_chrom"], data["_pos"])
382
626
  data["_x"] = x
@@ -399,8 +643,7 @@ class ManhattanCommand(BaseCommand):
399
643
  fig, axes = make_figure(args, nrows=nrows, ncols=ncols)
400
644
  for idx, (name, gdf) in enumerate(groups):
401
645
  ax = axes[idx // ncols][idx % ncols]
402
- _draw(ax, gdf, layout, args, args.groupcol)
403
- ax.set_title(
646
+ _draw(ax, gdf, layout, args, args.groupcol).set_title(
404
647
  make_grouplabel(name, args.subgraphcol, args.subgraphformat)
405
648
  )
406
649
  for idx in range(len(groups), nrows * ncols):
@@ -409,7 +652,8 @@ class ManhattanCommand(BaseCommand):
409
652
  fig.suptitle(args.title)
410
653
  else:
411
654
  fig, axes = make_figure(args)
412
- _draw(axes[0][0], data, layout, args, args.groupcol)
413
- axes[0][0].set_title(args.title or "")
655
+ _draw(axes[0][0], data, layout, args, args.groupcol).set_title(
656
+ args.title or ""
657
+ )
414
658
  fig.tight_layout()
415
659
  save_or_show(fig, args)
@@ -18,7 +18,10 @@ from dftk.commands.base import BaseCommand
18
18
  from dftk.commands.manhattan_cmd import (
19
19
  add_gwas_column_arguments,
20
20
  float_or,
21
+ gwas_columns,
22
+ log_yaxis,
21
23
  scatter_capped,
24
+ thin_points,
22
25
  )
23
26
  from dftk.common import gwas
24
27
  from dftk.common.io import check_cols, io
@@ -75,6 +78,11 @@ Cap the y axis; points above it are drawn as triangles on the top edge:
75
78
 
76
79
  dftk dataset gwas -o | dftk qq --ylim 0 20 -f qq.png
77
80
 
81
+ Or log-scale it above -log10(p) = 10, so the strongest hits and the bulk
82
+ both show:
83
+
84
+ dftk dataset gwas -o | dftk qq --chi2col Chisq --logy -f qq.png
85
+
78
86
  Several scans (a study column), or one scan split by allele-frequency bin:
79
87
  one curve and one lambda each with -g, or a panel each with --subgraphcol:
80
88
 
@@ -144,13 +152,15 @@ def _draw(ax, data: pd.DataFrame, args, groupcols=None) -> None:
144
152
  n = max(len(c[2]) for c in curves)
145
153
  bx, blo, bhi = gwas.qq_band(n, args.ci)
146
154
  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)
155
+ # many vertices, so the diagonal bends correctly on a --logy axis
156
+ diag = np.linspace(0, xmax, 200)
157
+ ax.plot(diag, diag, color="black", lw=0.8, zorder=1)
148
158
 
149
159
  for n, (label, exp, obs, lam) in enumerate(curves):
150
160
  logger.info(
151
161
  "lambda %s= %.4f (%d tests)", f"({label}) " if label else "", lam, len(obs)
152
162
  )
153
- keep = gwas.thin_mask(exp, obs) if args.thin else np.ones(len(obs), bool)
163
+ keep = thin_points(exp, obs, args)
154
164
  colour = WONG_PALETTE[n % len(WONG_PALETTE)] if groupcols else _POINT_COLOUR
155
165
  if groupcols and args.show_lambda:
156
166
  label = f"{label} (λ = {lam:.3f})"
@@ -172,6 +182,8 @@ def _draw(ax, data: pd.DataFrame, args, groupcols=None) -> None:
172
182
 
173
183
  ax.set_xlim(0, xmax)
174
184
  ax.set_ylim(lo, hi)
185
+ if args.logy is not None:
186
+ log_yaxis(ax, args.logy, lo, hi)
175
187
  ax.spines[["top", "right"]].set_visible(False)
176
188
  ax.set_xlabel(
177
189
  args.xlabel if args.xlabel is not None else r"Expected $-\log_{10}(p)$"
@@ -209,6 +221,15 @@ class QqCommand(BaseCommand):
209
221
  action="store_false",
210
222
  help="Don't write lambda on the plot (it is still logged).",
211
223
  )
224
+ g.add_argument(
225
+ "--logy",
226
+ nargs="?",
227
+ type=float,
228
+ const=10.0,
229
+ metavar="T",
230
+ help="Log scale above observed -log10(p) = T, linear below it "
231
+ "(default T: 10).",
232
+ )
212
233
  g.add_argument(
213
234
  "--no-thin",
214
235
  dest="thin",
@@ -248,9 +269,11 @@ class QqCommand(BaseCommand):
248
269
  add_legend_arguments(parser)
249
270
 
250
271
  def execute(self, args: argparse.Namespace) -> None:
272
+ if args.logy is not None and args.logy <= 0:
273
+ raise ValueError(f"--logy must be above 0, not {args.logy:g}.")
251
274
  if args.ci is not None and not 0 < args.ci < 1:
252
275
  raise ValueError(f"--ci must be between 0 and 1, not {args.ci}.")
253
- df = io.read(args)
276
+ df = io.read(args, columns=gwas_columns(args, position=False))
254
277
  check_cols(df, args.groupcol, "-g/--groupcol")
255
278
  check_cols(df, args.subgraphcol, "--subgraphcol")
256
279
  data = qq_table(df, args)
@@ -21,7 +21,7 @@ import matplotlib.lines as mlines
21
21
  import numpy as np
22
22
 
23
23
  from dftk.commands.base import BaseCommand
24
- from dftk.common.io import check_cols, io
24
+ from dftk.common.io import check_cols, io, option_columns
25
25
  from dftk.common.plot import (
26
26
  add_figure_arguments,
27
27
  add_group_arguments,
@@ -396,7 +396,7 @@ class ScatCommand(BaseCommand):
396
396
  if not args.xcol or not args.ycol:
397
397
  raise ValueError("--xcol (-x) and --ycol (-y) are required.")
398
398
 
399
- df = io.read(args)
399
+ df = io.read(args, columns=option_columns(args))
400
400
  check_cols(df, [args.xcol, args.ycol], "-x/-y")
401
401
  check_cols(df, args.groupcol, "-g/--groupcol")
402
402
  check_cols(df, args.subgraphcol, "--subgraphcol")
@@ -135,19 +135,18 @@ def neglogp_from_chi2(chi2: pd.Series | np.ndarray, df) -> np.ndarray:
135
135
  return chi2_neglogp_array(np.asarray(chi2, dtype=float), df)
136
136
 
137
137
 
138
- def resolve_neglogp(
138
+ def p_source(
139
139
  data: pd.DataFrame,
140
140
  pcol: str | None = None,
141
141
  mlogpcol: str | None = None,
142
142
  chi2col: str | None = None,
143
- chi2df: str | float = 1,
144
- ) -> tuple[np.ndarray, str]:
145
- """Return (-log10(p) values, source column) from whichever column is given.
143
+ ) -> tuple[str, str]:
144
+ """Return (kind, column) of the p-values: kind is "p", "mlogp" or "chi2".
146
145
 
147
146
  At most one of *pcol*, *mlogpcol* and *chi2col* may be given. With none,
148
147
  look for ``Pval`` (or a p-value spelling), then a -log10(p) spelling
149
- (regenie's ``LOG10P``), then a chi-squared one. *chi2df* is a number or
150
- the name of a column holding each row's degrees of freedom.
148
+ (regenie's ``LOG10P``), then a chi-squared one. Only the column names
149
+ of *data* are used, so an empty frame with the file's columns will do.
151
150
  """
152
151
  given = [o for o in (pcol, mlogpcol, chi2col) if o is not None]
153
152
  if len(given) > 1:
@@ -186,14 +185,59 @@ def resolve_neglogp(
186
185
  )
187
186
 
188
187
  if pcol is not None:
189
- return neglogp_from_p(data[pcol]), pcol
188
+ return "p", pcol
190
189
  if mlogpcol is not None:
191
190
  find_column(data, mlogpcol, mlogpcol, (), "--mlogpcol")
192
- return check_neglogp(data[mlogpcol], mlogpcol), mlogpcol
193
-
191
+ return "mlogp", mlogpcol
194
192
  find_column(data, chi2col, chi2col, (), "--chi2col")
195
- dfs = _chi2_df(data, chi2df)
196
- return neglogp_from_chi2(data[chi2col], dfs), chi2col
193
+ return "chi2", chi2col
194
+
195
+
196
+ def resolve_neglogp(
197
+ data: pd.DataFrame,
198
+ pcol: str | None = None,
199
+ mlogpcol: str | None = None,
200
+ chi2col: str | None = None,
201
+ chi2df: str | float = 1,
202
+ ) -> tuple[np.ndarray, str]:
203
+ """Return (-log10(p) values, source column) from whichever column is given.
204
+
205
+ The column is chosen by p_source. *chi2df* is a number or the name of a
206
+ column holding each row's degrees of freedom.
207
+ """
208
+ kind, col = p_source(data, pcol, mlogpcol, chi2col)
209
+ if kind == "p":
210
+ return neglogp_from_p(data[col]), col
211
+ if kind == "mlogp":
212
+ return check_neglogp(data[col], col), col
213
+ return neglogp_from_chi2(data[col], _chi2_df(data, chi2df)), col
214
+
215
+
216
+ def needed_columns(names: list[str], args, position: bool = True) -> list[str] | None:
217
+ """The columns manhattan / qq need, found from a file's column names.
218
+
219
+ Chromosome, position (unless *position* is False) and p-value columns,
220
+ under the same names the command will pick; the other columns options
221
+ name (-g, --subgraphcol, --chi2df, --miami) come from io.option_columns.
222
+ None (read every column) when they can't be found here: the command
223
+ then reports the problem with the whole table in hand.
224
+ """
225
+ frame = pd.DataFrame(columns=names)
226
+ quiet, logger.disabled = logger.disabled, True # logged again on the real read
227
+ try:
228
+ cols = [p_source(frame, args.pcol, args.mlogpcol, args.chi2col)[1]]
229
+ if position:
230
+ cols.append(
231
+ find_column(frame, args.chrcol, DEFAULT_CHR, CHR_ALIASES, "--chrcol")
232
+ )
233
+ cols.append(
234
+ find_column(frame, args.poscol, DEFAULT_POS, POS_ALIASES, "--poscol")
235
+ )
236
+ except ValueError:
237
+ return None
238
+ finally:
239
+ logger.disabled = quiet
240
+ return cols
197
241
 
198
242
 
199
243
  def _chi2_df(data: pd.DataFrame, chi2df: str | float) -> np.ndarray | float:
@@ -104,9 +104,51 @@ def _warn_noheader_parquet(args: argparse.Namespace) -> None:
104
104
  )
105
105
 
106
106
 
107
- def _read_pipe_parquet(path: str) -> pd.DataFrame:
107
+ def _parquet_columns(path: str, columns) -> list[str] | None:
108
+ """The columns to load from the parquet file *path*; None for all.
109
+
110
+ *columns* is a list of names, or a function that gets the file's column
111
+ names and returns the ones to load (or None for all). Names the file
112
+ doesn't have are dropped, so the command's own "column not found"
113
+ error stays the same.
114
+ """
115
+ if columns is None:
116
+ return None
117
+ import pyarrow.parquet as pq
118
+
119
+ names = pq.read_schema(path).names
120
+ want = columns(names) if callable(columns) else columns
121
+ if want is None:
122
+ return None
123
+ present = set(names)
124
+ keep = [c for c in dict.fromkeys(want) if c in present]
125
+ logging.debug("Reading %d of %d parquet columns: %s", len(keep), len(names), keep)
126
+ return keep
127
+
128
+
129
+ def option_columns(args: argparse.Namespace, *more: str | None):
130
+ """columns= for io.read: the columns some option of *args* names.
131
+
132
+ Every string among the option values (and in lists of them) that is a
133
+ column of the file, plus *more*. A value that only happens to match a
134
+ column name (a title, say) just loads one column more.
135
+ """
136
+
137
+ def strings(value):
138
+ if isinstance(value, str):
139
+ yield value
140
+ elif isinstance(value, (list, tuple)):
141
+ for item in value:
142
+ yield from strings(item)
143
+
144
+ said = {s for v in vars(args).values() for s in strings(v)}
145
+ said.update(m for m in more if m is not None)
146
+ return lambda names: [n for n in names if n in said]
147
+
148
+
149
+ def _read_pipe_parquet(path: str, columns=None) -> pd.DataFrame:
108
150
  """Read the parquet file *path* named on stdin; delete it if it's dftk's temp."""
109
- df = pd.read_parquet(path)
151
+ df = pd.read_parquet(path, columns=_parquet_columns(path, columns))
110
152
  df.attrs["_parquet_meta"] = _read_parquet_meta(path)
111
153
  if _is_temp_pipe_path(path):
112
154
  try:
@@ -353,8 +395,14 @@ class io:
353
395
  return parser
354
396
 
355
397
  @staticmethod
356
- def read(args: argparse.Namespace) -> pd.DataFrame:
357
- """Read a dataframe from the source described in *args*."""
398
+ def read(args: argparse.Namespace, columns=None) -> pd.DataFrame:
399
+ """Read a dataframe from the source described in *args*.
400
+
401
+ *columns*, for parquet input only: the columns to load, as a list or
402
+ as a function of the file's column names (see option_columns). The
403
+ rest are never read. Ignored with --prequery, whose expressions
404
+ can use any column, and for text input, which is read whole anyway.
405
+ """
358
406
 
359
407
  filename: str | None = getattr(args, "DATAFILE", None)
360
408
  backend: str = getattr(args, "backend", "pandas")
@@ -363,6 +411,8 @@ class io:
363
411
  header: int | None = None if noheader else 0
364
412
  readasobject = getattr(args, "readasobject", None)
365
413
  prequery: list[str] = getattr(args, "prequery", [])
414
+ if prequery:
415
+ columns = None
366
416
 
367
417
  dtype = None
368
418
  if readasobject is not None:
@@ -436,7 +486,7 @@ class io:
436
486
  rest = stream.read()
437
487
  if not rest.strip():
438
488
  _warn_noheader_parquet(args)
439
- return _read_pipe_parquet(path)
489
+ return _read_pipe_parquet(path, columns)
440
490
  stream = _io.BytesIO(rest)
441
491
  if backend == "duckdb" and duckdb is not None:
442
492
  return _spooled_csv_with_duckdb(first, stream)
@@ -460,7 +510,7 @@ class io:
460
510
  f"'...' expects a .parquet path on stdin, got {pipe_path!r}"
461
511
  )
462
512
  _warn_noheader_parquet(args)
463
- df = _read_pipe_parquet(pipe_path)
513
+ df = _read_pipe_parquet(pipe_path, columns)
464
514
 
465
515
  elif filename is not None and filename != "-":
466
516
  # Named file
@@ -473,7 +523,9 @@ class io:
473
523
  )
474
524
  if filename.endswith(".parquet"):
475
525
  _warn_noheader_parquet(args)
476
- df = pd.read_parquet(filename)
526
+ df = pd.read_parquet(
527
+ filename, columns=_parquet_columns(filename, columns)
528
+ )
477
529
  df.attrs["_parquet_meta"] = _read_parquet_meta(filename)
478
530
  elif os.path.exists(filename) and not os.path.isfile(filename):
479
531
  # A pipe, e.g. <(grep -v '^#' file) or <(dftk CMD -o): it can
@@ -151,9 +151,10 @@ 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), `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`
154
+ `--sig`/`--suggestive` lines, points with p > 0.01 thinned, `--logy` log
155
+ scale above 10, `--miami COL [UPPER LOWER]` two scans, the second upside
156
+ down below it), `qq` (QQ plot of p-values with a 95 % band and the genomic inflation
157
+ lambda; same p-value options, `-g` one curve and lambda per group, `--logy`). `-g COL`
157
158
  overlays groups, `--subgraphcol COL` makes panels.
158
159
 
159
160
  Other: `dataset NAME` loads a bundled example table, `annotate FILE.parquet`