dataframe-toolkit 0.22.1__tar.gz → 0.24.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 (65) hide show
  1. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.24.0}/PKG-INFO +29 -3
  2. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.24.0}/README.md +28 -2
  3. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.24.0}/pyproject.toml +1 -1
  4. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.24.0}/pyproject.toml.orig +1 -1
  5. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.24.0}/src/dftk/commands/__init__.py +3 -0
  6. dataframe_toolkit-0.24.0/src/dftk/commands/box_cmd.py +326 -0
  7. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.24.0}/src/dftk/commands/dataset_cmd.py +9 -0
  8. dataframe_toolkit-0.24.0/src/dftk/commands/forest_cmd.py +710 -0
  9. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.24.0}/src/dftk/commands/hist_cmd.py +8 -0
  10. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.24.0}/src/dftk/commands/line_cmd.py +13 -0
  11. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.24.0}/src/dftk/commands/manhattan_cmd.py +1 -0
  12. dataframe_toolkit-0.24.0/src/dftk/commands/phewas_cmd.py +421 -0
  13. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.24.0}/src/dftk/commands/scat_cmd.py +139 -15
  14. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.24.0}/src/dftk/common/gwas.py +102 -0
  15. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.24.0}/src/dftk/common/plot.py +76 -0
  16. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.24.0}/src/dftk/skills/dftk/SKILL.md +14 -4
  17. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.24.0}/src/dftk/__init__.py +0 -0
  18. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.24.0}/src/dftk/cli.py +0 -0
  19. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.24.0}/src/dftk/commands/annotate_cmd.py +0 -0
  20. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.24.0}/src/dftk/commands/append_cmd.py +0 -0
  21. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.24.0}/src/dftk/commands/base.py +0 -0
  22. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.24.0}/src/dftk/commands/binx_cmd.py +0 -0
  23. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.24.0}/src/dftk/commands/chi_cmd.py +0 -0
  24. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.24.0}/src/dftk/commands/clean_cmd.py +0 -0
  25. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.24.0}/src/dftk/commands/cleannames_cmd.py +0 -0
  26. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.24.0}/src/dftk/commands/concat_cmd.py +0 -0
  27. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.24.0}/src/dftk/commands/corr_cmd.py +0 -0
  28. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.24.0}/src/dftk/commands/describe_cmd.py +0 -0
  29. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.24.0}/src/dftk/commands/eval_cmd.py +0 -0
  30. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.24.0}/src/dftk/commands/explode_cmd.py +0 -0
  31. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.24.0}/src/dftk/commands/fit_cmd.py +0 -0
  32. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.24.0}/src/dftk/commands/func_cmd.py +0 -0
  33. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.24.0}/src/dftk/commands/heatmap_cmd.py +0 -0
  34. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.24.0}/src/dftk/commands/help.py +0 -0
  35. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.24.0}/src/dftk/commands/implode_cmd.py +0 -0
  36. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.24.0}/src/dftk/commands/info_cmd.py +0 -0
  37. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.24.0}/src/dftk/commands/interp_cmd.py +0 -0
  38. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.24.0}/src/dftk/commands/locus_cmd.py +0 -0
  39. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.24.0}/src/dftk/commands/melt_cmd.py +0 -0
  40. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.24.0}/src/dftk/commands/merge_cmd.py +0 -0
  41. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.24.0}/src/dftk/commands/pairs_cmd.py +0 -0
  42. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.24.0}/src/dftk/commands/pivot_cmd.py +0 -0
  43. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.24.0}/src/dftk/commands/print_cmd.py +0 -0
  44. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.24.0}/src/dftk/commands/qq_cmd.py +0 -0
  45. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.24.0}/src/dftk/commands/query_cmd.py +0 -0
  46. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.24.0}/src/dftk/commands/randvar_cmd.py +0 -0
  47. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.24.0}/src/dftk/commands/sample_cmd.py +0 -0
  48. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.24.0}/src/dftk/commands/scale_cmd.py +0 -0
  49. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.24.0}/src/dftk/commands/segid_cmd.py +0 -0
  50. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.24.0}/src/dftk/commands/skill_cmd.py +0 -0
  51. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.24.0}/src/dftk/commands/split_cmd.py +0 -0
  52. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.24.0}/src/dftk/commands/stat_cmd.py +0 -0
  53. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.24.0}/src/dftk/commands/test_cmd.py +0 -0
  54. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.24.0}/src/dftk/commands/transpose_cmd.py +0 -0
  55. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.24.0}/src/dftk/commands/wstat_cmd.py +0 -0
  56. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.24.0}/src/dftk/common/__init__.py +0 -0
  57. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.24.0}/src/dftk/common/copula.py +0 -0
  58. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.24.0}/src/dftk/common/docformats.py +0 -0
  59. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.24.0}/src/dftk/common/evalfuncs.py +0 -0
  60. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.24.0}/src/dftk/common/io.py +0 -0
  61. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.24.0}/src/dftk/common/seed.py +0 -0
  62. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.24.0}/src/dftk/common/seq.py +0 -0
  63. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.24.0}/src/dftk/common/stats.py +0 -0
  64. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.24.0}/src/dftk/io.py +0 -0
  65. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.24.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.22.1
3
+ Version: 0.24.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
@@ -44,7 +44,7 @@ statistical modelling and publication-quality figures.
44
44
  small, real dataset, so you can copy-paste any of them and run them right
45
45
  now. Run `dftk dataset --list` to browse everything available (dozens of
46
46
  datasets from seaborn, statsmodels, and pydataset, plus `gwas`, a synthetic
47
- association scan made by dftk). `dftk dataset NAME` searches dftk, seaborn,
47
+ association scan, and `phewas`, a synthetic phenome-wide scan, both made by dftk). `dftk dataset NAME` searches dftk, seaborn,
48
48
  statsmodels and pydataset in that order and returns the first match, so
49
49
  `--source` is optional — pass it only to disambiguate a name that exists in
50
50
  more than one source, or to restrict the search.
@@ -161,16 +161,21 @@ publication-quality output.
161
161
 
162
162
  | Command | Description |
163
163
  |---------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
164
- | `scat` | Scatter plot; OLS/robust or LOWESS fit (`--fit lowess`, one per group with `-g`), hexagonal binning for large tables (`--hexbin`), bubble size (`--sizecol`), colour (`--colorcol`) |
164
+ | `scat` | Scatter plot; OLS/robust or LOWESS fit (`--fit lowess`, one per group with `-g`), hexagonal binning for large tables (`--hexbin`), bubble size (`--sizecol`), colour (`--colorcol`), error bars (`--xerr`/`--yerr`, `--errscale 1.96`), weighted fit (`--fit -w W`) |
165
165
  | `line` | Line plot; optional error bars (`--yerr`) or intervals (`--yci lo,hi`), `-ls none -m o` for points only, and fit overlay |
166
+ | `box` | Box or violin plot (`--kind violin`) of a value by category; `-g` boxes side by side, `--points` every point jittered on top, `--count` n under each category, `--order` |
166
167
  | `hist` | Histogram or KDE (`--kde`); normalisation, cumulative mode, mean±σ annotation (`--stats`) |
167
168
  | `chi` | Corner-resolved chi-plot: whether tail dependence sits in the lower or upper corner |
168
169
  | `heatmap` | Coloured grid of values from a long (`-x -y -v`) or wide (`-y`) table; correlograms from `corr --all`, `--annot`, `--lower` |
169
170
  | `pairs` | Scatter-plot matrix with KDEs (or histograms) on the diagonal; `-g` colours groups, `--upper corr` puts r in the upper triangle |
170
171
  | `qq` | QQ plot of p-values: observed against expected -log10(p), confidence band, genomic inflation λ; `-g` one curve and λ per group |
172
+ | `forest` | Forest plot: one row per estimate with its interval (`--se` or `--ci lo,hi`), `--exp` for odds/hazard ratios on a log axis, `--text`/`--textcol` numbers on the right, `-g` several series per row, `--section` headers |
173
+ | `phewas` | PheWAS plot: -log10(p) of each phenotype grouped by category (one colour each), ▲/▼ by the sign of `--betacol`, Bonferroni line, hits labelled |
171
174
  | `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` |
172
175
  | `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 |
173
176
 
177
+ `scat`, `line` and `hist` draw dashed reference lines with `--vline X` and `--hline Y`, each labelled when written `X:LABEL` (`--vline 412:carriers`); `forest` takes `--vline`.
178
+
174
179
  ### Utilities
175
180
 
176
181
  | Command | Description |
@@ -517,6 +522,27 @@ dftk dataset gwas -o | dftk query -q "Chr == '6' and pos > 31.6e6 and pos < 33.6
517
522
  | dftk locus --ldcol r2 -f locus.png
518
523
  ```
519
524
 
525
+ `phewas` draws a phenome-wide scan: -log10(p) of each phenotype, the phenotypes grouped by category along the x axis in one colour per category (columns `category`, `phenotype` and `Pval` unless named with `-c`, `-l` and the p-value options of `manhattan`). With `--betacol beta` the points are triangles pointing up or down with the sign of the effect. The significance line is Bonferroni (0.05 / number of tests) unless `--sig` gives a p-value, and the phenotypes above it are labelled, at most `--label N` (default 10). One row per phenotype: pick one genotype or mask with `query` first.
526
+
527
+ ```bash
528
+ dftk dataset phewas -o | dftk query -q "genotype == 'het'" -o | dftk phewas --betacol beta -f phewas.png
529
+ ```
530
+
531
+ `forest` draws one row per estimate: a point with its interval, labels down the left, top to bottom in file order (sort first to order them), and a reference line at 0. Give the interval as two columns (`--ci lo,hi`) or a standard error (`--se se`, ± 1.96 SE, `--level` to change). `--exp` turns log odds ratios (or any log-scale estimate) into ratios on a log axis with the reference at 1; `--text` writes `estimate [lo, hi]` to the right and `--textcol` adds columns such as the p-value or the number of carriers. `-g` puts several series on each row (het and hom carriers, two cohorts), `--section` groups rows under bold headers, `--weighted` sizes the markers by 1/SE². Coefficients from `fit`:
532
+
533
+ `dataset phewas` is a simulated phenome-wide scan of loss-of-function carriers (heterozygous and homozygous rows per phenotype, log odds ratios, five real effects) to try it on:
534
+
535
+ ```bash
536
+ dftk dataset phewas -o | dftk query -q "genotype == 'het' and Pval < 0.01" --sortasc Pval -o \
537
+ | dftk forest -y phenotype -x beta --se se --exp --text --textcol Pval -xl "odds ratio" -f top.png
538
+ ```
539
+
540
+ ```bash
541
+ dftk dataset tips -o \
542
+ | dftk fit -f "tip ~ total_bill + size + C(day) + C(smoker)" --postquery "marker != 'Intercept'" -o \
543
+ | dftk forest -y marker -x effect --ci cilo,cihi --text -f coef.png
544
+ ```
545
+
520
546
  ### Bootstrap confidence intervals
521
547
 
522
548
  Bootstrap mode repeats the full stat computation N times on resampled data
@@ -14,7 +14,7 @@ statistical modelling and publication-quality figures.
14
14
  small, real dataset, so you can copy-paste any of them and run them right
15
15
  now. Run `dftk dataset --list` to browse everything available (dozens of
16
16
  datasets from seaborn, statsmodels, and pydataset, plus `gwas`, a synthetic
17
- association scan made by dftk). `dftk dataset NAME` searches dftk, seaborn,
17
+ association scan, and `phewas`, a synthetic phenome-wide scan, both made by dftk). `dftk dataset NAME` searches dftk, seaborn,
18
18
  statsmodels and pydataset in that order and returns the first match, so
19
19
  `--source` is optional — pass it only to disambiguate a name that exists in
20
20
  more than one source, or to restrict the search.
@@ -131,16 +131,21 @@ publication-quality output.
131
131
 
132
132
  | Command | Description |
133
133
  |---------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
134
- | `scat` | Scatter plot; OLS/robust or LOWESS fit (`--fit lowess`, one per group with `-g`), hexagonal binning for large tables (`--hexbin`), bubble size (`--sizecol`), colour (`--colorcol`) |
134
+ | `scat` | Scatter plot; OLS/robust or LOWESS fit (`--fit lowess`, one per group with `-g`), hexagonal binning for large tables (`--hexbin`), bubble size (`--sizecol`), colour (`--colorcol`), error bars (`--xerr`/`--yerr`, `--errscale 1.96`), weighted fit (`--fit -w W`) |
135
135
  | `line` | Line plot; optional error bars (`--yerr`) or intervals (`--yci lo,hi`), `-ls none -m o` for points only, and fit overlay |
136
+ | `box` | Box or violin plot (`--kind violin`) of a value by category; `-g` boxes side by side, `--points` every point jittered on top, `--count` n under each category, `--order` |
136
137
  | `hist` | Histogram or KDE (`--kde`); normalisation, cumulative mode, mean±σ annotation (`--stats`) |
137
138
  | `chi` | Corner-resolved chi-plot: whether tail dependence sits in the lower or upper corner |
138
139
  | `heatmap` | Coloured grid of values from a long (`-x -y -v`) or wide (`-y`) table; correlograms from `corr --all`, `--annot`, `--lower` |
139
140
  | `pairs` | Scatter-plot matrix with KDEs (or histograms) on the diagonal; `-g` colours groups, `--upper corr` puts r in the upper triangle |
140
141
  | `qq` | QQ plot of p-values: observed against expected -log10(p), confidence band, genomic inflation λ; `-g` one curve and λ per group |
142
+ | `forest` | Forest plot: one row per estimate with its interval (`--se` or `--ci lo,hi`), `--exp` for odds/hazard ratios on a log axis, `--text`/`--textcol` numbers on the right, `-g` several series per row, `--section` headers |
143
+ | `phewas` | PheWAS plot: -log10(p) of each phenotype grouped by category (one colour each), ▲/▼ by the sign of `--betacol`, Bonferroni line, hits labelled |
141
144
  | `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` |
142
145
  | `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 |
143
146
 
147
+ `scat`, `line` and `hist` draw dashed reference lines with `--vline X` and `--hline Y`, each labelled when written `X:LABEL` (`--vline 412:carriers`); `forest` takes `--vline`.
148
+
144
149
  ### Utilities
145
150
 
146
151
  | Command | Description |
@@ -487,6 +492,27 @@ dftk dataset gwas -o | dftk query -q "Chr == '6' and pos > 31.6e6 and pos < 33.6
487
492
  | dftk locus --ldcol r2 -f locus.png
488
493
  ```
489
494
 
495
+ `phewas` draws a phenome-wide scan: -log10(p) of each phenotype, the phenotypes grouped by category along the x axis in one colour per category (columns `category`, `phenotype` and `Pval` unless named with `-c`, `-l` and the p-value options of `manhattan`). With `--betacol beta` the points are triangles pointing up or down with the sign of the effect. The significance line is Bonferroni (0.05 / number of tests) unless `--sig` gives a p-value, and the phenotypes above it are labelled, at most `--label N` (default 10). One row per phenotype: pick one genotype or mask with `query` first.
496
+
497
+ ```bash
498
+ dftk dataset phewas -o | dftk query -q "genotype == 'het'" -o | dftk phewas --betacol beta -f phewas.png
499
+ ```
500
+
501
+ `forest` draws one row per estimate: a point with its interval, labels down the left, top to bottom in file order (sort first to order them), and a reference line at 0. Give the interval as two columns (`--ci lo,hi`) or a standard error (`--se se`, ± 1.96 SE, `--level` to change). `--exp` turns log odds ratios (or any log-scale estimate) into ratios on a log axis with the reference at 1; `--text` writes `estimate [lo, hi]` to the right and `--textcol` adds columns such as the p-value or the number of carriers. `-g` puts several series on each row (het and hom carriers, two cohorts), `--section` groups rows under bold headers, `--weighted` sizes the markers by 1/SE². Coefficients from `fit`:
502
+
503
+ `dataset phewas` is a simulated phenome-wide scan of loss-of-function carriers (heterozygous and homozygous rows per phenotype, log odds ratios, five real effects) to try it on:
504
+
505
+ ```bash
506
+ dftk dataset phewas -o | dftk query -q "genotype == 'het' and Pval < 0.01" --sortasc Pval -o \
507
+ | dftk forest -y phenotype -x beta --se se --exp --text --textcol Pval -xl "odds ratio" -f top.png
508
+ ```
509
+
510
+ ```bash
511
+ dftk dataset tips -o \
512
+ | dftk fit -f "tip ~ total_bill + size + C(day) + C(smoker)" --postquery "marker != 'Intercept'" -o \
513
+ | dftk forest -y marker -x effect --ci cilo,cihi --text -f coef.png
514
+ ```
515
+
490
516
  ### Bootstrap confidence intervals
491
517
 
492
518
  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.22.1"
3
+ version = "0.24.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.22.1"
3
+ version = "0.24.0"
4
4
  description = "A command-line toolkit for DataFrame analysis and manipulation"
5
5
  readme = "README.md"
6
6
  authors = [
@@ -62,12 +62,15 @@ COMMAND_GROUPS: list[tuple[str, list[tuple[str, str]]]] = [
62
62
  ("scat", "scat_cmd:ScatCommand"),
63
63
  ("line", "line_cmd:LineCommand"),
64
64
  ("hist", "hist_cmd:HistCommand"),
65
+ ("box", "box_cmd:BoxCommand"),
65
66
  ("chi", "chi_cmd:ChiCommand"),
66
67
  ("heatmap", "heatmap_cmd:HeatmapCommand"),
67
68
  ("pairs", "pairs_cmd:PairsCommand"),
68
69
  ("manhattan", "manhattan_cmd:ManhattanCommand"),
69
70
  ("qq", "qq_cmd:QqCommand"),
70
71
  ("locus", "locus_cmd:LocusCommand"),
72
+ ("phewas", "phewas_cmd:PhewasCommand"),
73
+ ("forest", "forest_cmd:ForestCommand"),
71
74
  ],
72
75
  ),
73
76
  (
@@ -0,0 +1,326 @@
1
+ """
2
+ dftk.commands.box_cmd — dftk box subcommand.
3
+
4
+ Box plot (or violin plot) of a value by category, with the individual
5
+ points jittered on top if wanted: e.g. protein level by loss-of-function
6
+ genotype (0/1/2), tips by day. Drawn with seaborn, which is imported
7
+ only when the command runs.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import argparse
13
+ import logging
14
+
15
+ import pandas as pd
16
+
17
+ from dftk.commands.base import BaseCommand
18
+ from dftk.common.io import check_cols, io, option_columns
19
+ from dftk.common.plot import (
20
+ WONG_PALETTE,
21
+ add_figure_arguments,
22
+ apply_style,
23
+ make_figure,
24
+ save_or_show,
25
+ )
26
+
27
+ logger = logging.getLogger(__name__)
28
+
29
+ _BOX_COLOUR = WONG_PALETTE[1] # sky blue, without -g
30
+ _POINT_COLOUR = "0.15"
31
+
32
+ _EPILOG = """\
33
+ Input: one row per observation. -y is the value, -x the category (one
34
+ box each, in sorted order unless --order gives one; numbers such as a
35
+ genotype 0/1/2 are categories too). Without -x, a single box of all
36
+ rows. Rows without a value or category are left out.
37
+
38
+ The box spans the quartiles with a line at the median, and the whiskers
39
+ reach the furthest point within 1.5 times the box's height (Tukey);
40
+ points beyond them are drawn on their own, unless --points draws every
41
+ point anyway. --kind violin draws the distribution's density instead.
42
+
43
+ -g splits every box into one per group, side by side and in colour.
44
+
45
+ EXAMPLES
46
+ --------
47
+ Basic box plot of a value by category:
48
+
49
+ dftk box data.tsv -x genotype -y protein -f box.png
50
+
51
+ Tips by day, with every bill drawn on top, and how many there are:
52
+
53
+ dftk dataset tips -o | dftk box -x day -y tip --points --count \\
54
+ --order Thur Fri Sat Sun -f tips.png
55
+
56
+ Smokers and non-smokers side by side within each day:
57
+
58
+ dftk dataset tips -o | dftk box -x day -y tip -g smoker \\
59
+ --order Thur Fri Sat Sun -f tips_smoker.png
60
+
61
+ Violins of body mass by species, split by sex:
62
+
63
+ dftk dataset penguins -o | dftk box -x species -y body_mass_g -g sex \\
64
+ --kind violin -f penguins.png
65
+
66
+ A level by genotype (0, 1 or 2 copies of a loss-of-function allele), on
67
+ a log axis: a made-up level that halves with each copy (diamond prices
68
+ as the spread, genotypes drawn with randvar):
69
+
70
+ dftk dataset diamonds -o | dftk sample -n 2000 --randomseed 1 -o \\
71
+ | dftk randvar -d u --dist uniform --randomseed 2 -o \\
72
+ | dftk eval -f "dosage = (u > 0.6) * 1 + (u > 0.95) * 1" \\
73
+ -f "level = price / 2**dosage" -o \\
74
+ | dftk box -x dosage -y level --logy --points --count -f level.png
75
+ """
76
+
77
+
78
+ def _order(values: pd.Series, given: list[str] | None) -> list:
79
+ """Categories in sorted order (numbers numerically), or *given* first."""
80
+ found = list(pd.unique(values.dropna()))
81
+ try:
82
+ found = sorted(found)
83
+ except TypeError:
84
+ found = sorted(found, key=str)
85
+ if not given:
86
+ return found
87
+ by_text = {str(v): v for v in found}
88
+ missing = [g for g in given if g not in by_text]
89
+ if missing:
90
+ raise ValueError(
91
+ f"--order names values not in the data: {missing}; "
92
+ f"found {[str(v) for v in found]}."
93
+ )
94
+ listed = [by_text[g] for g in given]
95
+ return listed + [v for v in found if v not in listed]
96
+
97
+
98
+ class BoxCommand(BaseCommand):
99
+ name = "box"
100
+ help = "Box or violin plot of a value by category, points optional."
101
+
102
+ def add_arguments(self, parser: argparse.ArgumentParser) -> None:
103
+ parser.formatter_class = argparse.RawDescriptionHelpFormatter
104
+ parser.epilog = _EPILOG
105
+
106
+ self.add_read_arguments(parser)
107
+ c = parser.add_argument_group("columns")
108
+ c.add_argument(
109
+ "-y", "--ycol", required=True, metavar="COL", help="Value column."
110
+ )
111
+ c.add_argument(
112
+ "-x",
113
+ "--xcol",
114
+ metavar="COL",
115
+ help="Category column, one box each (default: one box of all rows).",
116
+ )
117
+ c.add_argument(
118
+ "-g",
119
+ "--groupcol",
120
+ metavar="COL",
121
+ help="Split each box into one per group, side by side, in colour.",
122
+ )
123
+ c.add_argument(
124
+ "--order",
125
+ nargs="+",
126
+ metavar="VAL",
127
+ help="Order of the -x categories (default: sorted); values not "
128
+ "listed follow.",
129
+ )
130
+ c.add_argument(
131
+ "--groupcolorder",
132
+ nargs="+",
133
+ metavar="VAL",
134
+ help="Order of the -g groups (default: sorted).",
135
+ )
136
+
137
+ b = parser.add_argument_group("box")
138
+ b.add_argument(
139
+ "--kind",
140
+ choices=["box", "violin"],
141
+ default="box",
142
+ help="box (quartiles and whiskers, the default) or violin (density).",
143
+ )
144
+ b.add_argument(
145
+ "--points",
146
+ action="store_true",
147
+ help="Draw every point on top, jittered sideways.",
148
+ )
149
+ b.add_argument(
150
+ "--count",
151
+ action="store_true",
152
+ help="Write the number of values under each category.",
153
+ )
154
+ b.add_argument(
155
+ "--markersize",
156
+ type=float,
157
+ default=3.0,
158
+ metavar="S",
159
+ help="Size of the --points (default: 3).",
160
+ )
161
+ b.add_argument(
162
+ "--alpha",
163
+ type=float,
164
+ default=0.5,
165
+ metavar="A",
166
+ help="Opacity of the --points, 0-1 (default: 0.5).",
167
+ )
168
+
169
+ a = parser.add_argument_group("axes")
170
+ a.add_argument("-xl", "--xlabel", metavar="TEXT", help="X-axis label.")
171
+ a.add_argument("-yl", "--ylabel", metavar="TEXT", help="Y-axis label.")
172
+ a.add_argument(
173
+ "-ym",
174
+ "--ylim",
175
+ nargs=2,
176
+ type=float,
177
+ metavar=("LO", "HI"),
178
+ help="Y-axis limits.",
179
+ )
180
+ a.add_argument("-ly", "--logy", action="store_true", help="Log y axis.")
181
+ a.add_argument(
182
+ "--legendloc",
183
+ nargs=2,
184
+ type=float,
185
+ metavar=("X", "Y"),
186
+ help="Position of the -g legend, in axes coordinates (default: best).",
187
+ )
188
+
189
+ add_figure_arguments(parser)
190
+ parser.set_defaults(size="7x4.5")
191
+
192
+ def execute(self, args: argparse.Namespace) -> None:
193
+ df = io.read(args, columns=option_columns(args))
194
+ check_cols(df, [args.ycol], "-y/--ycol")
195
+ if args.xcol:
196
+ check_cols(df, [args.xcol], "-x/--xcol")
197
+ if args.groupcol:
198
+ check_cols(df, [args.groupcol], "-g/--groupcol")
199
+ if args.order and not args.xcol:
200
+ raise ValueError("--order orders the -x categories; give -x.")
201
+ if args.groupcolorder and not args.groupcol:
202
+ raise ValueError("--groupcolorder orders the -g groups; give -g.")
203
+
204
+ data = df.copy()
205
+ values = pd.to_numeric(data[args.ycol], errors="coerce")
206
+ bad = values.isna() & data[args.ycol].notna()
207
+ if bad.any():
208
+ raise ValueError(
209
+ f"-y column {args.ycol!r} isn't numeric "
210
+ f"(e.g. {data.loc[bad, args.ycol].iloc[0]!r})."
211
+ )
212
+ data[args.ycol] = values
213
+ needed = [c for c in (args.ycol, args.xcol, args.groupcol) if c]
214
+ keep = data[needed].notna().all(axis=1)
215
+ if not keep.all():
216
+ logger.info(
217
+ "Left out %d of %d rows without %s",
218
+ int((~keep).sum()),
219
+ len(data),
220
+ " / ".join(needed),
221
+ )
222
+ data = data[keep]
223
+ if data.empty:
224
+ raise ValueError("No rows with a value to plot.")
225
+ if args.logy and (data[args.ycol] <= 0).any():
226
+ raise ValueError(f"--logy needs -y values above 0 ({args.ycol!r}).")
227
+
228
+ order = _order(data[args.xcol], args.order) if args.xcol else None
229
+ hue_order = (
230
+ _order(data[args.groupcol], args.groupcolorder) if args.groupcol else None
231
+ )
232
+
233
+ if args.file:
234
+ import matplotlib
235
+
236
+ matplotlib.use("Agg")
237
+ import matplotlib.pyplot as plt
238
+
239
+ if args.usetex:
240
+ plt.rc("text", usetex=True)
241
+ apply_style(args)
242
+ fig, axes = make_figure(args)
243
+ ax = axes[0][0]
244
+ draw(ax, data, args, order, hue_order)
245
+ ax.set_title(args.title or "")
246
+ fig.tight_layout()
247
+ save_or_show(fig, args)
248
+
249
+
250
+ def draw(ax, data: pd.DataFrame, args, order, hue_order) -> None:
251
+ import seaborn as sns
252
+
253
+ # matplotlib logs "Using categorical units ..." for numeric categories
254
+ logging.getLogger("matplotlib.category").setLevel(logging.WARNING)
255
+
256
+ common = dict(data=data, x=args.xcol, y=args.ycol, order=order, ax=ax)
257
+ if args.groupcol:
258
+ common.update(
259
+ hue=args.groupcol,
260
+ hue_order=hue_order,
261
+ palette=WONG_PALETTE[: len(hue_order)],
262
+ )
263
+ else:
264
+ common["color"] = _BOX_COLOUR
265
+ if args.kind == "box":
266
+ sns.boxplot(
267
+ **common,
268
+ showfliers=not args.points,
269
+ width=0.6,
270
+ linewidth=1,
271
+ log_scale=args.logy or None,
272
+ )
273
+ else:
274
+ sns.violinplot(
275
+ **common,
276
+ inner="quart" if not args.points else None,
277
+ cut=0,
278
+ linewidth=1,
279
+ log_scale=args.logy or None,
280
+ )
281
+ if args.points:
282
+ strip = dict(common)
283
+ strip.pop("palette", None)
284
+ strip.pop("hue_order", None)
285
+ strip.pop("color", None)
286
+ if args.groupcol:
287
+ strip.update(
288
+ hue_order=hue_order,
289
+ dodge=True,
290
+ palette=[_POINT_COLOUR] * len(hue_order),
291
+ )
292
+ sns.stripplot(
293
+ **strip,
294
+ color=_POINT_COLOUR if not args.groupcol else None,
295
+ size=args.markersize,
296
+ alpha=args.alpha,
297
+ jitter=0.2,
298
+ legend=False,
299
+ zorder=3,
300
+ )
301
+
302
+ if args.count and args.xcol:
303
+ counts = data.groupby(args.xcol, sort=False).size()
304
+ ax.set_xticks(ax.get_xticks())
305
+ ax.set_xticklabels(
306
+ [
307
+ f"{t.get_text()}\n(n={counts.get(v, 0)})"
308
+ for t, v in zip(ax.get_xticklabels(), order, strict=True)
309
+ ]
310
+ )
311
+ elif args.count:
312
+ ax.set_xticks([0])
313
+ ax.set_xticklabels([f"n={len(data)}"])
314
+
315
+ if args.groupcol and ax.get_legend() is not None:
316
+ ax.legend(
317
+ title=args.groupcol,
318
+ fontsize="small",
319
+ title_fontsize="small",
320
+ loc=tuple(args.legendloc) if args.legendloc else "best",
321
+ )
322
+ if args.ylim is not None:
323
+ ax.set_ylim(*args.ylim)
324
+ ax.spines[["top", "right"]].set_visible(False)
325
+ ax.set_xlabel(args.xlabel if args.xlabel is not None else (args.xcol or ""))
326
+ ax.set_ylabel(args.ylabel if args.ylabel is not None else args.ycol)
@@ -34,6 +34,11 @@ _DFTK_DATASETS = {
34
34
  "synthetic association scan: SNP, Chr, pos, Pval, Chisq, r2 "
35
35
  "(~121k variants, six peaks)"
36
36
  ),
37
+ "phewas": (
38
+ "synthetic PheWAS of loss-of-function carriers: category, phenotype, "
39
+ "prevalence, genotype (het/hom), n_carriers, beta (log OR), se, Pval "
40
+ "(74 phenotypes, five real effects)"
41
+ ),
37
42
  }
38
43
 
39
44
 
@@ -42,6 +47,10 @@ def _load_dftk(name: str) -> pd.DataFrame:
42
47
  from dftk.common.gwas import simulate_gwas
43
48
 
44
49
  return simulate_gwas()
50
+ if name == "phewas":
51
+ from dftk.common.gwas import simulate_phewas
52
+
53
+ return simulate_phewas()
45
54
  raise ValueError(f"dftk dataset {name!r} not found")
46
55
 
47
56