dataframe-toolkit 0.18.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.18.0 → dataframe_toolkit-0.20.0}/PKG-INFO +21 -2
  2. {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.20.0}/README.md +20 -1
  3. {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.20.0}/pyproject.toml +1 -1
  4. {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.20.0}/pyproject.toml.orig +1 -1
  5. {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/__init__.py +1 -0
  6. {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/chi_cmd.py +2 -2
  7. {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/dataset_cmd.py +1 -1
  8. {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/hist_cmd.py +2 -2
  9. {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/line_cmd.py +2 -2
  10. {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/manhattan_cmd.py +288 -41
  11. dataframe_toolkit-0.20.0/src/dftk/commands/qq_cmd.py +310 -0
  12. {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/scat_cmd.py +2 -2
  13. {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.20.0}/src/dftk/common/gwas.py +120 -21
  14. {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.20.0}/src/dftk/common/io.py +59 -7
  15. {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.20.0}/src/dftk/skills/dftk/SKILL.md +4 -1
  16. {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.20.0}/src/dftk/__init__.py +0 -0
  17. {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.20.0}/src/dftk/cli.py +0 -0
  18. {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/annotate_cmd.py +0 -0
  19. {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/append_cmd.py +0 -0
  20. {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/base.py +0 -0
  21. {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/binx_cmd.py +0 -0
  22. {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/clean_cmd.py +0 -0
  23. {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/cleannames_cmd.py +0 -0
  24. {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/concat_cmd.py +0 -0
  25. {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/corr_cmd.py +0 -0
  26. {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/describe_cmd.py +0 -0
  27. {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/eval_cmd.py +0 -0
  28. {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/explode_cmd.py +0 -0
  29. {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/fit_cmd.py +0 -0
  30. {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/func_cmd.py +0 -0
  31. {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/heatmap_cmd.py +0 -0
  32. {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/help.py +0 -0
  33. {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/implode_cmd.py +0 -0
  34. {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/info_cmd.py +0 -0
  35. {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/interp_cmd.py +0 -0
  36. {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/melt_cmd.py +0 -0
  37. {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/merge_cmd.py +0 -0
  38. {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/pairs_cmd.py +0 -0
  39. {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/pivot_cmd.py +0 -0
  40. {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/print_cmd.py +0 -0
  41. {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/query_cmd.py +0 -0
  42. {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/randvar_cmd.py +0 -0
  43. {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/sample_cmd.py +0 -0
  44. {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/scale_cmd.py +0 -0
  45. {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/segid_cmd.py +0 -0
  46. {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/skill_cmd.py +0 -0
  47. {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/split_cmd.py +0 -0
  48. {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/stat_cmd.py +0 -0
  49. {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/test_cmd.py +0 -0
  50. {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/transpose_cmd.py +0 -0
  51. {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.20.0}/src/dftk/commands/wstat_cmd.py +0 -0
  52. {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.20.0}/src/dftk/common/__init__.py +0 -0
  53. {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.20.0}/src/dftk/common/copula.py +0 -0
  54. {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.20.0}/src/dftk/common/docformats.py +0 -0
  55. {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.20.0}/src/dftk/common/evalfuncs.py +0 -0
  56. {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.20.0}/src/dftk/common/plot.py +0 -0
  57. {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.20.0}/src/dftk/common/seed.py +0 -0
  58. {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.20.0}/src/dftk/common/seq.py +0 -0
  59. {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.20.0}/src/dftk/common/stats.py +0 -0
  60. {dataframe_toolkit-0.18.0 → dataframe_toolkit-0.20.0}/src/dftk/io.py +0 -0
  61. {dataframe_toolkit-0.18.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.18.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
@@ -167,6 +167,7 @@ publication-quality output.
167
167
  | `chi` | Corner-resolved chi-plot: whether tail dependence sits in the lower or upper corner |
168
168
  | `heatmap` | Coloured grid of values from a long (`-x -y -v`) or wide (`-y`) table; correlograms from `corr --all`, `--annot`, `--lower` |
169
169
  | `pairs` | Scatter-plot matrix with KDEs (or histograms) on the diagonal; `-g` colours groups, `--upper corr` puts r in the upper triangle |
170
+ | `qq` | QQ plot of p-values: observed against expected -log10(p), confidence band, genomic inflation λ; `-g` one curve and λ per group |
170
171
  | `manhattan` | Genome-wide -log10(p) by position (`Chr`, `pos`, `Pval`, or `--mlogpcol`/`--chi2col`); significance lines, thinning for millions of variants, `-g`/`--subgraphcol` for several scans |
171
172
 
172
173
  ### Utilities
@@ -483,7 +484,25 @@ A p-value below about 1e-308 is stored as 0, which plots as -log10(p) = 323 with
483
484
  dftk dataset gwas -o | dftk manhattan --chi2col Chisq -f manhattan.png
484
485
  ```
485
486
 
486
- Points with p > 0.01 are thinned to one per cell of a grid finer than the figure (`--no-thin` draws all), and points are rasterized: ten million variants take a few seconds and a PDF stays small. `--ylim LO HI` caps the axis, with points above it drawn as triangles on the top edge. Several scans in one table: `--subgraphcol study` draws a panel each, `-g study` a colour each.
487
+ 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
+ ```
497
+
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 λ:
499
+
500
+ ```bash
501
+ dftk dataset gwas -o | dftk qq -f qq.png
502
+ dftk dataset gwas -o | dftk eval -f "Chisq = Chisq * 1.15" -o | dftk qq --chi2col Chisq -f qq.png
503
+ ```
504
+
505
+ `qq --logy` makes its y axis linear up to 10 and logarithmic above, as in `manhattan`.
487
506
 
488
507
  ### Bootstrap confidence intervals
489
508
 
@@ -137,6 +137,7 @@ publication-quality output.
137
137
  | `chi` | Corner-resolved chi-plot: whether tail dependence sits in the lower or upper corner |
138
138
  | `heatmap` | Coloured grid of values from a long (`-x -y -v`) or wide (`-y`) table; correlograms from `corr --all`, `--annot`, `--lower` |
139
139
  | `pairs` | Scatter-plot matrix with KDEs (or histograms) on the diagonal; `-g` colours groups, `--upper corr` puts r in the upper triangle |
140
+ | `qq` | QQ plot of p-values: observed against expected -log10(p), confidence band, genomic inflation λ; `-g` one curve and λ per group |
140
141
  | `manhattan` | Genome-wide -log10(p) by position (`Chr`, `pos`, `Pval`, or `--mlogpcol`/`--chi2col`); significance lines, thinning for millions of variants, `-g`/`--subgraphcol` for several scans |
141
142
 
142
143
  ### Utilities
@@ -453,7 +454,25 @@ A p-value below about 1e-308 is stored as 0, which plots as -log10(p) = 323 with
453
454
  dftk dataset gwas -o | dftk manhattan --chi2col Chisq -f manhattan.png
454
455
  ```
455
456
 
456
- Points with p > 0.01 are thinned to one per cell of a grid finer than the figure (`--no-thin` draws all), and points are rasterized: ten million variants take a few seconds and a PDF stays small. `--ylim LO HI` caps the axis, with points above it drawn as triangles on the top edge. Several scans in one table: `--subgraphcol study` draws a panel each, `-g study` a colour each.
457
+ 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
+ ```
467
+
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 λ:
469
+
470
+ ```bash
471
+ dftk dataset gwas -o | dftk qq -f qq.png
472
+ dftk dataset gwas -o | dftk eval -f "Chisq = Chisq * 1.15" -o | dftk qq --chi2col Chisq -f qq.png
473
+ ```
474
+
475
+ `qq --logy` makes its y axis linear up to 10 and logarithmic above, as in `manhattan`.
457
476
 
458
477
  ### Bootstrap confidence intervals
459
478
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "dataframe-toolkit"
3
- version = "0.18.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.18.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 = [
@@ -66,6 +66,7 @@ COMMAND_GROUPS: list[tuple[str, list[tuple[str, str]]]] = [
66
66
  ("heatmap", "heatmap_cmd:HeatmapCommand"),
67
67
  ("pairs", "pairs_cmd:PairsCommand"),
68
68
  ("manhattan", "manhattan_cmd:ManhattanCommand"),
69
+ ("qq", "qq_cmd:QqCommand"),
69
70
  ],
70
71
  ),
71
72
  (
@@ -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")
@@ -32,7 +32,7 @@ from dftk.common.io import io
32
32
  _DFTK_DATASETS = {
33
33
  "gwas": (
34
34
  "synthetic association scan: SNP, Chr, pos, Pval, Chisq, r2 "
35
- "(~44k variants, six peaks)"
35
+ "(~121k variants, six peaks)"
36
36
  ),
37
37
  }
38
38
 
@@ -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 \\
@@ -103,19 +121,22 @@ def _threshold(value: str) -> float | None:
103
121
  return p
104
122
 
105
123
 
106
- def add_gwas_column_arguments(parser: argparse.ArgumentParser) -> None:
107
- """Column options shared by manhattan and locus."""
124
+ def add_gwas_column_arguments(
125
+ parser: argparse.ArgumentParser, position: bool = True
126
+ ) -> None:
127
+ """Column options shared by manhattan and qq (qq: position=False)."""
108
128
  g = parser.add_argument_group("columns")
109
- g.add_argument(
110
- "--chrcol",
111
- metavar="COL",
112
- help=f"Chromosome column (default: {gwas.DEFAULT_CHR}).",
113
- )
114
- g.add_argument(
115
- "--poscol",
116
- metavar="COL",
117
- help=f"Position column (default: {gwas.DEFAULT_POS}).",
118
- )
129
+ if position:
130
+ g.add_argument(
131
+ "--chrcol",
132
+ metavar="COL",
133
+ help=f"Chromosome column (default: {gwas.DEFAULT_CHR}).",
134
+ )
135
+ g.add_argument(
136
+ "--poscol",
137
+ metavar="COL",
138
+ help=f"Position column (default: {gwas.DEFAULT_POS}).",
139
+ )
119
140
  p = g.add_mutually_exclusive_group()
120
141
  p.add_argument(
121
142
  "--pcol",
@@ -140,6 +161,18 @@ def add_gwas_column_arguments(parser: argparse.ArgumentParser) -> None:
140
161
  )
141
162
 
142
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
+
143
176
  def gwas_table(df: pd.DataFrame, args: argparse.Namespace) -> pd.DataFrame:
144
177
  """Return df with _chrom (label), _pos and _y (-log10 p); rows lacking any dropped.
145
178
 
@@ -174,27 +207,32 @@ def gwas_table(df: pd.DataFrame, args: argparse.Namespace) -> pd.DataFrame:
174
207
  # ---------------------------------------------------------------------------
175
208
 
176
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
+
177
215
  def _ylimits(y: np.ndarray, lines: list[float], args) -> tuple[float, float]:
178
- top = max([float(np.max(y)) if y.size else 1.0, *lines, 1.0]) * 1.05
179
- lo, hi = 0.0, top
216
+ lo, hi = 0.0, _peak(y, lines)
180
217
  if args.ylim is not None:
181
- lo = _float_or(args.ylim[0], lo)
182
- hi = _float_or(args.ylim[1], hi)
218
+ lo = float_or(args.ylim[0], lo)
219
+ hi = float_or(args.ylim[1], hi)
183
220
  return lo, hi
184
221
 
185
222
 
186
- def _float_or(s, fallback: float) -> float:
223
+ def float_or(s, fallback: float) -> float:
187
224
  try:
188
225
  return float(s)
189
226
  except (TypeError, ValueError):
190
227
  return fallback
191
228
 
192
229
 
193
- def _scatter(ax, x, y, hi, args, colours=None, **kw):
194
- """Points below *hi*, and triangles on the top edge for those above it.
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.
195
232
 
196
233
  *colours*: one colour per point (alternating chromosomes), or None to
197
- use kw["color"].
234
+ use kw["color"]. *capmarker*: "v" on a Miami plot's lower half, whose
235
+ y axis points down.
198
236
  """
199
237
  over = y > hi
200
238
  size = args.markersize
@@ -206,26 +244,77 @@ def _scatter(ax, x, y, hi, args, colours=None, **kw):
206
244
  if over.any():
207
245
  common.pop("label", None)
208
246
  ax.scatter(
209
- x[over], np.full(over.sum(), hi), s=size * 4, marker="^",
247
+ x[over], np.full(over.sum(), hi), s=size * 4, marker=capmarker,
210
248
  clip_on=False, c=None if colours is None else colours[over], **common,
211
249
  ) # fmt: skip
212
250
 
213
251
 
214
- 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)
215
308
  centres, labels, bounds = layout
216
309
  x = data["_x"].to_numpy()
217
310
  y = data["_y"].to_numpy()
218
311
  lines = [-np.log10(p) for p in (args.sig, args.suggestive) if p is not None]
219
- lo, hi = _ylimits(y, lines, args)
312
+ lo, hi = ylim if ylim is not None else _ylimits(y, lines, args)
220
313
 
221
314
  groups = None
222
315
  if groupcols:
223
316
  groups = data[groupcols].astype(str).agg("\t".join, axis=1).to_numpy()
224
- keep = (
225
- gwas.thin_mask(x, y, groups=groups)
226
- if args.thin
227
- else np.ones(len(x), dtype=bool)
228
- )
317
+ keep = thin_points(x, y, args, groups)
229
318
  if args.thin and (~keep).any():
230
319
  logger.info("Thinned %d of %d points (p > 0.01)", int((~keep).sum()), len(x))
231
320
 
@@ -240,7 +329,7 @@ def _draw(ax, data: pd.DataFrame, layout, args, groupcols=None) -> None:
240
329
  ):
241
330
  label = make_grouplabel(name, groupcols, args.groupcolformat)
242
331
  colour = WONG_PALETTE[n % len(WONG_PALETTE)]
243
- _scatter(
332
+ scatter_capped(
244
333
  ax, gdf["_x"].to_numpy(), gdf["_y"].to_numpy(), hi, args,
245
334
  color=colour, label=label, zorder=2,
246
335
  ) # fmt: skip
@@ -250,10 +339,14 @@ def _draw(ax, data: pd.DataFrame, layout, args, groupcols=None) -> None:
250
339
  markerscale=3,
251
340
  )
252
341
  else:
253
- colours = np.array(args.colors)[data["_cidx"].to_numpy() % len(args.colors)]
254
- _scatter(
255
- ax, x[keep], y[keep], hi, args, colours=colours[keep], zorder=2,
256
- label=args.legend,
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
347
+ scatter_capped(
348
+ ax, x[keep], y[keep], hi, args, colours=colours[keep],
349
+ capmarker=capmarker, zorder=2, label=args.legend,
257
350
  ) # fmt: skip
258
351
  if args.legend:
259
352
  ax.legend(loc=tuple(args.legendloc) if args.legendloc else "best")
@@ -267,6 +360,8 @@ def _draw(ax, data: pd.DataFrame, layout, args, groupcols=None) -> None:
267
360
  ) # fmt: skip
268
361
 
269
362
  ax.set_ylim(lo, hi)
363
+ if args.logy is not None:
364
+ log_yaxis(ax, args.logy, lo, hi)
270
365
  pad = _gap(bounds)
271
366
  ax.set_xlim(bounds[0][0] - pad, bounds[-1][1] + pad)
272
367
  ax.set_xticks(centres)
@@ -275,6 +370,126 @@ def _draw(ax, data: pd.DataFrame, layout, args, groupcols=None) -> None:
275
370
  ax.spines[["top", "right"]].set_visible(False)
276
371
  ax.set_xlabel(args.xlabel if args.xlabel is not None else "Chromosome")
277
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
278
493
 
279
494
 
280
495
  def _gap(bounds) -> float:
@@ -323,12 +538,35 @@ class ManhattanCommand(BaseCommand):
323
538
  metavar="P|none",
324
539
  help="Suggestive line, as a p-value (default: 1e-5).",
325
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
+ )
326
558
  g.add_argument(
327
559
  "--no-thin",
328
560
  dest="thin",
329
561
  action="store_false",
330
562
  help="Draw every point (default: thin points with p > 0.01).",
331
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
+ )
332
570
  g.add_argument(
333
571
  "--colors",
334
572
  nargs="+",
@@ -361,19 +599,28 @@ class ManhattanCommand(BaseCommand):
361
599
  nargs=2,
362
600
  metavar=("LO", "HI"),
363
601
  help="Y-axis limits in -log10(p); points above HI are drawn as "
364
- "triangles on the top edge.",
602
+ "triangles on the top edge. With --miami the lower half is "
603
+ "negative: --ylim -30 30.",
365
604
  )
366
605
 
367
606
  add_figure_arguments(parser)
368
- parser.set_defaults(size="12x4")
607
+ parser.set_defaults(size=None)
369
608
  add_group_arguments(parser)
370
609
  add_legend_arguments(parser)
371
610
 
372
611
  def execute(self, args: argparse.Namespace) -> None:
373
- df = io.read(args)
612
+ df = io.read(args, columns=gwas_columns(args, position=True))
374
613
  check_cols(df, args.groupcol, "-g/--groupcol")
375
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"
376
621
  data = gwas_table(df, args)
622
+ if args.miami:
623
+ data, args.miami_names = miami_halves(data, args.miami)
377
624
 
378
625
  x, centres, labels, bounds = gwas.genome_positions(data["_chrom"], data["_pos"])
379
626
  data["_x"] = x
@@ -396,8 +643,7 @@ class ManhattanCommand(BaseCommand):
396
643
  fig, axes = make_figure(args, nrows=nrows, ncols=ncols)
397
644
  for idx, (name, gdf) in enumerate(groups):
398
645
  ax = axes[idx // ncols][idx % ncols]
399
- _draw(ax, gdf, layout, args, args.groupcol)
400
- ax.set_title(
646
+ _draw(ax, gdf, layout, args, args.groupcol).set_title(
401
647
  make_grouplabel(name, args.subgraphcol, args.subgraphformat)
402
648
  )
403
649
  for idx in range(len(groups), nrows * ncols):
@@ -406,7 +652,8 @@ class ManhattanCommand(BaseCommand):
406
652
  fig.suptitle(args.title)
407
653
  else:
408
654
  fig, axes = make_figure(args)
409
- _draw(axes[0][0], data, layout, args, args.groupcol)
410
- 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
+ )
411
658
  fig.tight_layout()
412
659
  save_or_show(fig, args)