dataframe-toolkit 0.22.1__tar.gz → 0.23.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 (63) hide show
  1. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.23.0}/PKG-INFO +18 -2
  2. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.23.0}/README.md +17 -1
  3. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.23.0}/pyproject.toml +1 -1
  4. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.23.0}/pyproject.toml.orig +1 -1
  5. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.23.0}/src/dftk/commands/__init__.py +1 -0
  6. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.23.0}/src/dftk/commands/dataset_cmd.py +9 -0
  7. dataframe_toolkit-0.23.0/src/dftk/commands/forest_cmd.py +706 -0
  8. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.23.0}/src/dftk/common/gwas.py +102 -0
  9. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.23.0}/src/dftk/skills/dftk/SKILL.md +5 -1
  10. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.23.0}/src/dftk/__init__.py +0 -0
  11. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.23.0}/src/dftk/cli.py +0 -0
  12. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.23.0}/src/dftk/commands/annotate_cmd.py +0 -0
  13. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.23.0}/src/dftk/commands/append_cmd.py +0 -0
  14. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.23.0}/src/dftk/commands/base.py +0 -0
  15. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.23.0}/src/dftk/commands/binx_cmd.py +0 -0
  16. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.23.0}/src/dftk/commands/chi_cmd.py +0 -0
  17. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.23.0}/src/dftk/commands/clean_cmd.py +0 -0
  18. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.23.0}/src/dftk/commands/cleannames_cmd.py +0 -0
  19. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.23.0}/src/dftk/commands/concat_cmd.py +0 -0
  20. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.23.0}/src/dftk/commands/corr_cmd.py +0 -0
  21. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.23.0}/src/dftk/commands/describe_cmd.py +0 -0
  22. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.23.0}/src/dftk/commands/eval_cmd.py +0 -0
  23. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.23.0}/src/dftk/commands/explode_cmd.py +0 -0
  24. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.23.0}/src/dftk/commands/fit_cmd.py +0 -0
  25. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.23.0}/src/dftk/commands/func_cmd.py +0 -0
  26. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.23.0}/src/dftk/commands/heatmap_cmd.py +0 -0
  27. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.23.0}/src/dftk/commands/help.py +0 -0
  28. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.23.0}/src/dftk/commands/hist_cmd.py +0 -0
  29. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.23.0}/src/dftk/commands/implode_cmd.py +0 -0
  30. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.23.0}/src/dftk/commands/info_cmd.py +0 -0
  31. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.23.0}/src/dftk/commands/interp_cmd.py +0 -0
  32. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.23.0}/src/dftk/commands/line_cmd.py +0 -0
  33. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.23.0}/src/dftk/commands/locus_cmd.py +0 -0
  34. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.23.0}/src/dftk/commands/manhattan_cmd.py +0 -0
  35. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.23.0}/src/dftk/commands/melt_cmd.py +0 -0
  36. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.23.0}/src/dftk/commands/merge_cmd.py +0 -0
  37. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.23.0}/src/dftk/commands/pairs_cmd.py +0 -0
  38. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.23.0}/src/dftk/commands/pivot_cmd.py +0 -0
  39. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.23.0}/src/dftk/commands/print_cmd.py +0 -0
  40. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.23.0}/src/dftk/commands/qq_cmd.py +0 -0
  41. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.23.0}/src/dftk/commands/query_cmd.py +0 -0
  42. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.23.0}/src/dftk/commands/randvar_cmd.py +0 -0
  43. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.23.0}/src/dftk/commands/sample_cmd.py +0 -0
  44. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.23.0}/src/dftk/commands/scale_cmd.py +0 -0
  45. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.23.0}/src/dftk/commands/scat_cmd.py +0 -0
  46. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.23.0}/src/dftk/commands/segid_cmd.py +0 -0
  47. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.23.0}/src/dftk/commands/skill_cmd.py +0 -0
  48. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.23.0}/src/dftk/commands/split_cmd.py +0 -0
  49. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.23.0}/src/dftk/commands/stat_cmd.py +0 -0
  50. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.23.0}/src/dftk/commands/test_cmd.py +0 -0
  51. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.23.0}/src/dftk/commands/transpose_cmd.py +0 -0
  52. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.23.0}/src/dftk/commands/wstat_cmd.py +0 -0
  53. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.23.0}/src/dftk/common/__init__.py +0 -0
  54. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.23.0}/src/dftk/common/copula.py +0 -0
  55. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.23.0}/src/dftk/common/docformats.py +0 -0
  56. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.23.0}/src/dftk/common/evalfuncs.py +0 -0
  57. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.23.0}/src/dftk/common/io.py +0 -0
  58. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.23.0}/src/dftk/common/plot.py +0 -0
  59. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.23.0}/src/dftk/common/seed.py +0 -0
  60. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.23.0}/src/dftk/common/seq.py +0 -0
  61. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.23.0}/src/dftk/common/stats.py +0 -0
  62. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.23.0}/src/dftk/io.py +0 -0
  63. {dataframe_toolkit-0.22.1 → dataframe_toolkit-0.23.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.23.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.
@@ -168,6 +168,7 @@ publication-quality output.
168
168
  | `heatmap` | Coloured grid of values from a long (`-x -y -v`) or wide (`-y`) table; correlograms from `corr --all`, `--annot`, `--lower` |
169
169
  | `pairs` | Scatter-plot matrix with KDEs (or histograms) on the diagonal; `-g` colours groups, `--upper corr` puts r in the upper triangle |
170
170
  | `qq` | QQ plot of p-values: observed against expected -log10(p), confidence band, genomic inflation λ; `-g` one curve and λ per group |
171
+ | `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 |
171
172
  | `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
173
  | `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
174
 
@@ -517,6 +518,21 @@ dftk dataset gwas -o | dftk query -q "Chr == '6' and pos > 31.6e6 and pos < 33.6
517
518
  | dftk locus --ldcol r2 -f locus.png
518
519
  ```
519
520
 
521
+ `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`:
522
+
523
+ `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:
524
+
525
+ ```bash
526
+ dftk dataset phewas -o | dftk query -q "genotype == 'het' and Pval < 0.01" --sortasc Pval -o \
527
+ | dftk forest -y phenotype -x beta --se se --exp --text --textcol Pval -xl "odds ratio" -f top.png
528
+ ```
529
+
530
+ ```bash
531
+ dftk dataset tips -o \
532
+ | dftk fit -f "tip ~ total_bill + size + C(day) + C(smoker)" --postquery "marker != 'Intercept'" -o \
533
+ | dftk forest -y marker -x effect --ci cilo,cihi --text -f coef.png
534
+ ```
535
+
520
536
  ### Bootstrap confidence intervals
521
537
 
522
538
  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.
@@ -138,6 +138,7 @@ publication-quality output.
138
138
  | `heatmap` | Coloured grid of values from a long (`-x -y -v`) or wide (`-y`) table; correlograms from `corr --all`, `--annot`, `--lower` |
139
139
  | `pairs` | Scatter-plot matrix with KDEs (or histograms) on the diagonal; `-g` colours groups, `--upper corr` puts r in the upper triangle |
140
140
  | `qq` | QQ plot of p-values: observed against expected -log10(p), confidence band, genomic inflation λ; `-g` one curve and λ per group |
141
+ | `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 |
141
142
  | `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
143
  | `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
144
 
@@ -487,6 +488,21 @@ dftk dataset gwas -o | dftk query -q "Chr == '6' and pos > 31.6e6 and pos < 33.6
487
488
  | dftk locus --ldcol r2 -f locus.png
488
489
  ```
489
490
 
491
+ `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`:
492
+
493
+ `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:
494
+
495
+ ```bash
496
+ dftk dataset phewas -o | dftk query -q "genotype == 'het' and Pval < 0.01" --sortasc Pval -o \
497
+ | dftk forest -y phenotype -x beta --se se --exp --text --textcol Pval -xl "odds ratio" -f top.png
498
+ ```
499
+
500
+ ```bash
501
+ dftk dataset tips -o \
502
+ | dftk fit -f "tip ~ total_bill + size + C(day) + C(smoker)" --postquery "marker != 'Intercept'" -o \
503
+ | dftk forest -y marker -x effect --ci cilo,cihi --text -f coef.png
504
+ ```
505
+
490
506
  ### Bootstrap confidence intervals
491
507
 
492
508
  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.23.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.23.0"
4
4
  description = "A command-line toolkit for DataFrame analysis and manipulation"
5
5
  readme = "README.md"
6
6
  authors = [
@@ -68,6 +68,7 @@ COMMAND_GROUPS: list[tuple[str, list[tuple[str, str]]]] = [
68
68
  ("manhattan", "manhattan_cmd:ManhattanCommand"),
69
69
  ("qq", "qq_cmd:QqCommand"),
70
70
  ("locus", "locus_cmd:LocusCommand"),
71
+ ("forest", "forest_cmd:ForestCommand"),
71
72
  ],
72
73
  ),
73
74
  (
@@ -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
 
@@ -0,0 +1,706 @@
1
+ """
2
+ dftk.commands.forest_cmd — dftk forest subcommand.
3
+
4
+ Forest plot: one row per estimate, drawn as a point with a horizontal
5
+ confidence interval, labels down the left, a reference line at no effect
6
+ and, with --text, the numbers in columns on the right. For regression
7
+ coefficients (fit output), PheWAS or burden results, subgroup and
8
+ meta-analysis tables.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import argparse
14
+ import logging
15
+
16
+ import numpy as np
17
+ import pandas as pd
18
+
19
+ from dftk.commands.base import BaseCommand
20
+ from dftk.common.io import check_cols, io, option_columns
21
+ from dftk.common.plot import (
22
+ WONG_PALETTE,
23
+ add_figure_arguments,
24
+ apply_style,
25
+ make_figure,
26
+ parse_figsize,
27
+ save_or_show,
28
+ )
29
+
30
+ logger = logging.getLogger(__name__)
31
+
32
+ _POINT_COLOUR = "black"
33
+ _REF_COLOUR = "#888888"
34
+ _ROW_HEIGHT = 0.28 # inches per row when --size isn't given
35
+ _TEXT_GAP = 0.25 # inches between text columns (and the arrows)
36
+
37
+ _EPILOG = """\
38
+ Input: one row per estimate, with a label, the estimate and either the
39
+ two ends of its confidence interval (--ci LO,HI) or its standard error
40
+ (--se SE, interval estimate ± z·SE for --level). Rows are drawn top to
41
+ bottom in file order: sort first (--sortasc in the command before, or
42
+ query) to order them. Rows with no estimate keep their label and draw
43
+ nothing.
44
+
45
+ --exp draws exp() of estimate and interval on a log axis with the
46
+ reference line at 1: log odds ratios, log hazard ratios and coefficients
47
+ of a log-scale model become ratios. For a table that already holds
48
+ ratios, use --logx instead. --ref moves the reference line (default 0,
49
+ or 1 with --exp or --logx); --ref none removes it.
50
+
51
+ -g draws several series on each row, side by side and in colour (e.g.
52
+ heterozygous vs homozygous carriers, two cohorts, two masks); a label
53
+ must then appear once per series. --section puts rows under bold
54
+ headers (e.g. organ systems), in order of first appearance.
55
+
56
+ --text writes the estimate and interval to the right of the plot, and
57
+ --textcol adds columns as they are (p-value, number of carriers, ...).
58
+
59
+ EXAMPLES
60
+ --------
61
+ Basic forest plot of a results table (phenotype, beta, se):
62
+
63
+ dftk forest results.tsv -y phenotype -x beta --se se -f forest.png
64
+
65
+ Regression coefficients from fit, with their 95 % intervals:
66
+
67
+ dftk dataset tips -o \\
68
+ | dftk fit -f "tip ~ total_bill + size + C(day) + C(smoker)" \\
69
+ --postquery "marker != 'Intercept'" -o \\
70
+ | dftk forest -y marker -x effect --ci cilo,cihi -f coef.png
71
+
72
+ A log-scale model gives ratios: exp() of the coefficients, on a log
73
+ axis, with the numbers and p-values on the right:
74
+
75
+ dftk dataset diamonds -o \\
76
+ | dftk fit -f "np.log(price) ~ np.log(carat) + C(cut) + C(color)" \\
77
+ --postquery "marker.str.startswith('C(')" -o \\
78
+ | dftk forest -y marker -x effect --se stdev --exp --text --textcol pval \\
79
+ -xl "price ratio" -f ratios.png
80
+
81
+ The top hits of a phenome-wide scan of loss-of-function carriers
82
+ (dataset phewas is simulated), as odds ratios with their p-values:
83
+
84
+ dftk dataset phewas -o \\
85
+ | dftk query -q "genotype == 'het' and Pval < 0.01" --sortasc Pval -o \\
86
+ | dftk forest -y phenotype -x beta --se se --exp --text --textcol Pval \\
87
+ -xl "odds ratio" -f top.png
88
+
89
+ Heterozygous and homozygous carriers side by side, under category
90
+ headers; the few homozygotes give wide intervals, cut off at 0.1 and 20:
91
+
92
+ dftk dataset phewas -o \\
93
+ | dftk query -q "category in ['Cardiovascular', 'Haematology']" -o \\
94
+ | dftk forest -y phenotype -x beta --se se --exp -g genotype \\
95
+ --section category --text -xm 0.1 20 -xl "odds ratio" -f carriers.png
96
+
97
+ Under section headers, one series per sex (penguin body mass by species
98
+ and island, mean ± 1.96 SEM):
99
+
100
+ dftk dataset penguins -o \\
101
+ | dftk stat -c body_mass_g -g species island sex -o \\
102
+ | dftk forest -y island -x mean --se sem --section species -g sex \\
103
+ --ref none --text --digits 0 -f penguins.png
104
+ """
105
+
106
+
107
+ def _ci_columns(args) -> list[str]:
108
+ """The two column names of --ci LO,HI ([] without it)."""
109
+ if not args.ci:
110
+ return []
111
+ cols = [c.strip() for c in args.ci.split(",")]
112
+ if len(cols) != 2 or not all(cols):
113
+ raise ValueError(
114
+ f"--ci takes two column names separated by a comma, e.g. "
115
+ f"--ci cilo,cihi; not {args.ci!r}."
116
+ )
117
+ return cols
118
+
119
+
120
+ def _z(level: float) -> float:
121
+ from scipy.stats import norm
122
+
123
+ return float(norm.ppf(0.5 + level / 2))
124
+
125
+
126
+ def _numeric(df: pd.DataFrame, col: str, option: str) -> np.ndarray:
127
+ values = pd.to_numeric(df[col], errors="coerce")
128
+ bad = values.isna() & df[col].notna()
129
+ if bad.any():
130
+ example = df.loc[bad, col].iloc[0]
131
+ raise ValueError(f"{option} column {col!r} isn't numeric (e.g. {example!r}).")
132
+ return values.to_numpy(dtype=float)
133
+
134
+
135
+ def estimates(df: pd.DataFrame, args) -> pd.DataFrame:
136
+ """_est, _lo, _hi on the plotted scale, and _se (NaN without --se/--ci)."""
137
+ est = _numeric(df, args.xcol, "-x/--xcol")
138
+ if args.se:
139
+ se = _numeric(df, args.se, "--se")
140
+ if (se < 0).any():
141
+ raise ValueError(f"--se column {args.se!r} has negative values.")
142
+ z = _z(args.level)
143
+ lo, hi = est - z * se, est + z * se
144
+ elif args.ci:
145
+ lo_col, hi_col = _ci_columns(args)
146
+ lo = _numeric(df, lo_col, "--ci")
147
+ hi = _numeric(df, hi_col, "--ci")
148
+ # for --weighted: half the interval's width, in place of the SE
149
+ se = np.abs(hi - lo) / 2
150
+ else:
151
+ lo = hi = se = np.full(len(df), np.nan)
152
+ if args.exp:
153
+ est, lo, hi = np.exp(est), np.exp(lo), np.exp(hi)
154
+ return pd.DataFrame({"_est": est, "_lo": lo, "_hi": hi, "_se": se}, index=df.index)
155
+
156
+
157
+ def layout(df: pd.DataFrame, args) -> tuple[pd.Series, list[tuple[float, str, bool]]]:
158
+ """Y position of every row of *df*, and the (y, text, is_header) of
159
+ each label on the axis. Rows run 0, 1, ... from the top."""
160
+ label = df[args.ycol].astype(str).where(df[args.ycol].notna(), "")
161
+ section = (
162
+ df[args.section].astype(str).where(df[args.section].notna(), "")
163
+ if args.section
164
+ else pd.Series("", index=df.index)
165
+ )
166
+ sections = list(dict.fromkeys(section))
167
+ groups = _group_order(df, args)
168
+
169
+ ypos = pd.Series(np.nan, index=df.index)
170
+ ticks: list[tuple[float, str, bool]] = []
171
+ slot = 0
172
+ for sec in sections:
173
+ rows = df.index[section == sec]
174
+ if args.section:
175
+ ticks.append((slot, sec, True))
176
+ slot += 1
177
+ if not args.groupcol:
178
+ for row in rows:
179
+ ypos[row] = slot
180
+ ticks.append((slot, label[row], False))
181
+ slot += 1
182
+ continue
183
+ group = df.loc[rows, args.groupcol].astype(str)
184
+ dup = pd.DataFrame({"l": label[rows], "g": group}).duplicated()
185
+ if dup.any():
186
+ row = rows[dup.to_numpy()][0]
187
+ where = f" in section {sec!r}" if args.section else ""
188
+ raise ValueError(
189
+ f"Label {label[row]!r}{where} appears more than once for "
190
+ f"{args.groupcol} = {group[row]!r}; with -g each label needs "
191
+ f"one row per series."
192
+ )
193
+ offsets = _offsets(len(groups))
194
+ for lab in dict.fromkeys(label[rows]):
195
+ for row in rows[(label[rows] == lab).to_numpy()]:
196
+ ypos[row] = slot + offsets[groups.index(group[row])]
197
+ ticks.append((slot, lab, False))
198
+ slot += 1
199
+ return ypos, ticks
200
+
201
+
202
+ def _group_order(df: pd.DataFrame, args) -> list[str]:
203
+ if not args.groupcol:
204
+ return []
205
+ found = list(dict.fromkeys(df[args.groupcol].astype(str)))
206
+ if not args.groupcolorder:
207
+ return found
208
+ listed = [g for g in args.groupcolorder if g in found]
209
+ return listed + [g for g in found if g not in listed]
210
+
211
+
212
+ def _offsets(n: int) -> list[float]:
213
+ """Y offsets of n series within a row, the first at the top."""
214
+ if n <= 1:
215
+ return [0.0]
216
+ spread = {2: 0.3, 3: 0.5}.get(n, 0.6) # share of the row they take
217
+ step = spread / (n - 1)
218
+ return [-spread / 2 + i * step for i in range(n)]
219
+
220
+
221
+ def _fmt(x: float, digits: int) -> str:
222
+ if not np.isfinite(x):
223
+ return ""
224
+ return f"{x:.{digits}f}"
225
+
226
+
227
+ def ci_text(est: float, lo: float, hi: float, digits: int) -> str:
228
+ """'1.32 [1.05, 1.66]'; just the estimate without an interval."""
229
+ if not np.isfinite(est):
230
+ return ""
231
+ if not (np.isfinite(lo) and np.isfinite(hi)):
232
+ return _fmt(est, digits)
233
+ return f"{_fmt(est, digits)} [{_fmt(lo, digits)}, {_fmt(hi, digits)}]"
234
+
235
+
236
+ def cell_text(value) -> str:
237
+ """A --textcol value: integers as they are, other numbers to 3
238
+ significant digits, text unchanged, missing as empty."""
239
+ if isinstance(value, str):
240
+ return value
241
+ if pd.isna(value):
242
+ return ""
243
+ if isinstance(value, (bool, np.bool_)):
244
+ return str(value)
245
+ if isinstance(value, (int, np.integer)):
246
+ return str(value)
247
+ if isinstance(value, (float, np.floating)):
248
+ if float(value).is_integer() and abs(value) < 1e15:
249
+ return str(int(value))
250
+ return f"{value:.3g}"
251
+ return str(value)
252
+
253
+
254
+ def _est_header(args) -> str:
255
+ name = f"exp({args.xcol})" if args.exp else args.xcol
256
+ if args.se:
257
+ return f"{name} [{args.level * 100:g}% CI]"
258
+ if args.ci:
259
+ lo, hi = _ci_columns(args)
260
+ if args.exp:
261
+ lo, hi = f"exp({lo})", f"exp({hi})"
262
+ return f"{name} [{lo}, {hi}]"
263
+ return name
264
+
265
+
266
+ def _sizes(est: pd.DataFrame, args) -> np.ndarray:
267
+ base = args.markersize
268
+ if not args.weighted:
269
+ return np.full(len(est), base)
270
+ se = est["_se"].to_numpy(dtype=float)
271
+ with np.errstate(divide="ignore"):
272
+ w = 1.0 / se**2
273
+ w[~np.isfinite(w)] = np.nan
274
+ if np.isnan(w).all():
275
+ return np.full(len(est), base)
276
+ rel = np.clip(w / np.nanmax(w), 0.1, 1.0)
277
+ rel[np.isnan(rel)] = 0.1
278
+ return base * 3 * rel
279
+
280
+
281
+ def _draw(ax, df: pd.DataFrame, est: pd.DataFrame, ypos: pd.Series, args) -> None:
282
+ groups = _group_order(df, args)
283
+ colours = _colours(df, args)
284
+ sizes = pd.Series(_sizes(est, args), index=df.index)
285
+ xlim = _xlim(args)
286
+
287
+ series = (
288
+ [(g, df.index[(df[args.groupcol].astype(str) == g).to_numpy()]) for g in groups]
289
+ if groups
290
+ else [(None, df.index)]
291
+ )
292
+ for g, rows in series:
293
+ colour = colours.get(g, _POINT_COLOUR)
294
+ e = est.loc[rows]
295
+ y = ypos[rows].to_numpy()
296
+ lo, hi = e["_lo"].to_numpy(), e["_hi"].to_numpy()
297
+ has_ci = np.isfinite(lo) & np.isfinite(hi)
298
+ lo_c, hi_c = lo.copy(), hi.copy()
299
+ if xlim is not None:
300
+ lo_c = np.clip(lo_c, *xlim)
301
+ hi_c = np.clip(hi_c, *xlim)
302
+ ax.hlines(
303
+ y[has_ci],
304
+ lo_c[has_ci],
305
+ hi_c[has_ci],
306
+ color=colour,
307
+ lw=args.linewidth,
308
+ zorder=2,
309
+ )
310
+ if xlim is not None: # arrows where an interval runs off the axis
311
+ left = has_ci & (lo < xlim[0])
312
+ right = has_ci & (hi > xlim[1])
313
+ ax.scatter(
314
+ np.full(left.sum(), xlim[0]),
315
+ y[left],
316
+ marker="<",
317
+ s=20,
318
+ color=colour,
319
+ zorder=3,
320
+ clip_on=False,
321
+ )
322
+ ax.scatter(
323
+ np.full(right.sum(), xlim[1]),
324
+ y[right],
325
+ marker=">",
326
+ s=20,
327
+ color=colour,
328
+ zorder=3,
329
+ clip_on=False,
330
+ )
331
+ x = e["_est"].to_numpy()
332
+ show = np.isfinite(x)
333
+ if xlim is not None:
334
+ show &= (x >= xlim[0]) & (x <= xlim[1])
335
+ ax.scatter(
336
+ x[show],
337
+ y[show],
338
+ s=sizes[rows].to_numpy()[show],
339
+ marker=args.marker,
340
+ color=colour,
341
+ edgecolors="none",
342
+ zorder=4,
343
+ label=g if g is not None else None,
344
+ )
345
+
346
+
347
+ def _xlim(args) -> tuple[float, float] | None:
348
+ if args.xlim is None:
349
+ return None
350
+ lo, hi = (float(v) for v in args.xlim)
351
+ if lo >= hi:
352
+ raise ValueError(f"--xlim LO must be below HI, not {lo:g} {hi:g}.")
353
+ if (args.exp or args.logx) and lo <= 0:
354
+ raise ValueError("--xlim must be above 0 on a log axis (--exp, --logx).")
355
+ return lo, hi
356
+
357
+
358
+ def _ref(args) -> float | None:
359
+ if args.ref is None:
360
+ return 1.0 if (args.exp or args.logx) else 0.0
361
+ if args.ref.lower() == "none":
362
+ return None
363
+ try:
364
+ return float(args.ref)
365
+ except ValueError:
366
+ raise ValueError(f"--ref takes a number or none, not {args.ref!r}.") from None
367
+
368
+
369
+ def _text_columns(df, est, ypos, args) -> list:
370
+ """(header, [(y, text, colour), ...]) for each text column; with -g
371
+ each line is in its series' colour."""
372
+ colours = _colours(df, args)
373
+ colour = [
374
+ colours.get(g, _POINT_COLOUR)
375
+ for g in (df[args.groupcol].astype(str) if args.groupcol else [None] * len(df))
376
+ ]
377
+ cols = []
378
+ if args.text:
379
+ cells = [
380
+ (
381
+ ypos[row],
382
+ ci_text(*est.loc[row, ["_est", "_lo", "_hi"]], args.digits),
383
+ colour[i],
384
+ )
385
+ for i, row in enumerate(df.index)
386
+ ]
387
+ cols.append((_est_header(args), cells))
388
+ for col in args.textcol:
389
+ cells = [
390
+ (ypos[row], cell_text(df.at[row, col]), colour[i])
391
+ for i, row in enumerate(df.index)
392
+ ]
393
+ cols.append((col, cells))
394
+ return cols
395
+
396
+
397
+ def _colours(df: pd.DataFrame, args) -> dict[str, str]:
398
+ """Colour of each -g series ({} without -g)."""
399
+ return {
400
+ g: WONG_PALETTE[i % len(WONG_PALETTE)]
401
+ for i, g in enumerate(_group_order(df, args))
402
+ }
403
+
404
+
405
+ def _draw_text(fig, ax, columns, args) -> None:
406
+ """Write the text columns to the right of *ax*, each as wide as its
407
+ widest cell, and make room for them in the figure."""
408
+ if not columns:
409
+ return
410
+ from matplotlib.transforms import ScaledTranslation, blended_transform_factory
411
+
412
+ renderer = fig.canvas.get_renderer()
413
+ base = blended_transform_factory(ax.transAxes, ax.transData)
414
+ head = ax.transAxes
415
+ small = "small" if args.groupcol else None
416
+ offset = _TEXT_GAP
417
+ for header, cells in columns:
418
+ shift = ScaledTranslation(offset, 0, fig.dpi_scale_trans)
419
+ items = [
420
+ ax.text(
421
+ 1.0,
422
+ y,
423
+ s,
424
+ transform=base + shift,
425
+ va="center",
426
+ ha="left",
427
+ fontsize=small,
428
+ color=colour,
429
+ clip_on=False,
430
+ )
431
+ for y, s, colour in cells
432
+ if s
433
+ ]
434
+ items.append(
435
+ ax.text(
436
+ 1.0,
437
+ 1.0,
438
+ header,
439
+ transform=head + shift,
440
+ va="bottom",
441
+ ha="left",
442
+ fontweight="bold",
443
+ clip_on=False,
444
+ )
445
+ )
446
+ width = max(t.get_window_extent(renderer).width for t in items) / fig.dpi
447
+ offset += width + _TEXT_GAP
448
+ # the figure grows to the right by the text's width; the axes keep theirs
449
+ w, h = fig.get_size_inches()
450
+ fig.set_size_inches(w + offset, h)
451
+ fig.tight_layout(rect=(0, 0, w / (w + offset), 1))
452
+
453
+
454
+ class ForestCommand(BaseCommand):
455
+ name = "forest"
456
+ help = "Forest plot: estimates with confidence intervals, one row each."
457
+
458
+ def add_arguments(self, parser: argparse.ArgumentParser) -> None:
459
+ parser.formatter_class = argparse.RawDescriptionHelpFormatter
460
+ parser.epilog = _EPILOG
461
+
462
+ self.add_read_arguments(parser)
463
+ c = parser.add_argument_group("columns")
464
+ c.add_argument(
465
+ "-x", "--xcol", required=True, metavar="COL", help="Estimate column."
466
+ )
467
+ c.add_argument(
468
+ "-y",
469
+ "--ycol",
470
+ required=True,
471
+ metavar="COL",
472
+ help="Label column: the text down the left, one row each.",
473
+ )
474
+ ci = c.add_mutually_exclusive_group()
475
+ ci.add_argument(
476
+ "--ci",
477
+ metavar="LO,HI",
478
+ help="Interval columns, e.g. --ci cilo,cihi (on the estimate's scale).",
479
+ )
480
+ ci.add_argument(
481
+ "--se",
482
+ metavar="COL",
483
+ help="Standard-error column: interval estimate ± z·SE (see --level).",
484
+ )
485
+ c.add_argument(
486
+ "--level",
487
+ type=float,
488
+ default=0.95,
489
+ metavar="L",
490
+ help="Confidence level of the interval with --se (default: 0.95).",
491
+ )
492
+ c.add_argument(
493
+ "-g",
494
+ "--groupcol",
495
+ metavar="COL",
496
+ help="Several series per row, side by side, one colour each.",
497
+ )
498
+ c.add_argument(
499
+ "--groupcolorder",
500
+ nargs="+",
501
+ default=None,
502
+ metavar="VAL",
503
+ help="Series order for -g (top to bottom within a row).",
504
+ )
505
+ c.add_argument(
506
+ "--section",
507
+ metavar="COL",
508
+ help="Group rows under bold headers, in order of first appearance.",
509
+ )
510
+
511
+ f = parser.add_argument_group("forest")
512
+ f.add_argument(
513
+ "--exp",
514
+ action="store_true",
515
+ help="Draw exp() of the estimate and interval on a log axis, "
516
+ "reference at 1 (log odds ratios to odds ratios).",
517
+ )
518
+ f.add_argument(
519
+ "--ref",
520
+ metavar="V|none",
521
+ help="Reference line (default: 0, or 1 with --exp or --logx).",
522
+ )
523
+ f.add_argument(
524
+ "--text",
525
+ action="store_true",
526
+ help="Write 'estimate [lo, hi]' in a column right of the plot.",
527
+ )
528
+ f.add_argument(
529
+ "--textcol",
530
+ nargs="+",
531
+ default=[],
532
+ metavar="COL",
533
+ help="More columns to write on the right, as they are "
534
+ "(e.g. Pval n_carriers).",
535
+ )
536
+ f.add_argument(
537
+ "--digits",
538
+ type=int,
539
+ default=2,
540
+ metavar="N",
541
+ help="Decimals in the --text column (default: 2).",
542
+ )
543
+ f.add_argument(
544
+ "--weighted",
545
+ action="store_true",
546
+ help="Marker area by precision, 1/SE² (from --se, or the "
547
+ "interval's width with --ci).",
548
+ )
549
+ f.add_argument(
550
+ "-m",
551
+ "--marker",
552
+ default="s",
553
+ metavar="M",
554
+ help="Matplotlib marker (default: s, a square).",
555
+ )
556
+ f.add_argument(
557
+ "--markersize",
558
+ type=float,
559
+ default=25.0,
560
+ metavar="S",
561
+ help="Marker area in pt² (default: 25).",
562
+ )
563
+ f.add_argument(
564
+ "--linewidth",
565
+ type=float,
566
+ default=1.2,
567
+ metavar="W",
568
+ help="Interval line width (default: 1.2).",
569
+ )
570
+
571
+ a = parser.add_argument_group("axes")
572
+ a.add_argument(
573
+ "-xl", "--xlabel", metavar="TEXT", help="X-axis label (default: -x)."
574
+ )
575
+ a.add_argument(
576
+ "-xm",
577
+ "--xlim",
578
+ nargs=2,
579
+ metavar=("LO", "HI"),
580
+ help="X-axis limits; intervals beyond them end in an arrow.",
581
+ )
582
+ a.add_argument(
583
+ "-lx",
584
+ "--logx",
585
+ action="store_true",
586
+ help="Log x axis, for ratios already in the table (reference at 1).",
587
+ )
588
+ a.add_argument(
589
+ "--legendloc",
590
+ nargs=2,
591
+ type=float,
592
+ metavar=("X", "Y"),
593
+ help="Position of the -g legend, in axes coordinates (default: best).",
594
+ )
595
+
596
+ add_figure_arguments(parser)
597
+ parser.set_defaults(size=None)
598
+
599
+ def execute(self, args: argparse.Namespace) -> None:
600
+ if not 0 < args.level < 1:
601
+ raise ValueError(f"--level must be between 0 and 1, not {args.level:g}.")
602
+ if args.digits < 0:
603
+ raise ValueError(f"--digits must be 0 or more, not {args.digits}.")
604
+ if args.exp and args.logx:
605
+ raise ValueError("--exp already draws a log axis; leave out --logx.")
606
+ ci_cols = _ci_columns(args)
607
+ df = io.read(args, columns=option_columns(args, *ci_cols))
608
+ check_cols(df, [args.xcol], "-x/--xcol")
609
+ check_cols(df, [args.ycol], "-y/--ycol")
610
+ if args.se:
611
+ check_cols(df, [args.se], "--se")
612
+ if ci_cols:
613
+ check_cols(df, ci_cols, "--ci")
614
+ if args.groupcol:
615
+ check_cols(df, [args.groupcol], "-g/--groupcol")
616
+ if args.section:
617
+ check_cols(df, [args.section], "--section")
618
+ check_cols(df, args.textcol, "--textcol")
619
+ if df.empty:
620
+ raise ValueError("No rows to plot.")
621
+ df = df.reset_index(drop=True)
622
+ if args.weighted and not (args.se or args.ci):
623
+ raise ValueError("--weighted needs --se or --ci.")
624
+
625
+ est = estimates(df, args)
626
+ if (args.logx or args.exp) and ((est[["_est", "_lo", "_hi"]] <= 0).any().any()):
627
+ raise ValueError(
628
+ "--logx needs values above 0; for log ratios use --exp instead."
629
+ )
630
+ ypos, ticks = layout(df, args)
631
+ xlim = _xlim(args)
632
+ ref = _ref(args)
633
+
634
+ if args.file:
635
+ import matplotlib
636
+
637
+ matplotlib.use("Agg")
638
+ import matplotlib.pyplot as plt
639
+
640
+ if args.usetex:
641
+ plt.rc("text", usetex=True)
642
+ apply_style(args)
643
+ n_slots = len(ticks)
644
+ if args.size is None:
645
+ per_row = _ROW_HEIGHT * max(1.0, 0.6 * len(_group_order(df, args)))
646
+ args.size = f"7x{0.9 + per_row * n_slots:.2f}"
647
+ fig, ax = plt.subplots(figsize=parse_figsize(args.size))
648
+ else:
649
+ fig, axes = make_figure(args)
650
+ ax = axes[0][0]
651
+
652
+ _draw(ax, df, est, ypos, args)
653
+ if ref is not None:
654
+ ax.axvline(ref, color=_REF_COLOUR, lw=0.8, ls="--", zorder=1)
655
+ if args.exp or args.logx:
656
+ ax.set_xscale("log")
657
+ _log_ticks(ax, est, xlim, ref)
658
+ if xlim is not None:
659
+ ax.set_xlim(*xlim)
660
+ ax.set_ylim(n_slots - 0.5, -0.5) # first row at the top
661
+ ax.set_yticks([t[0] for t in ticks])
662
+ ax.set_yticklabels([t[1] for t in ticks])
663
+ for label, (_, _, header) in zip(ax.get_yticklabels(), ticks, strict=True):
664
+ if header:
665
+ label.set_fontweight("bold")
666
+ ax.tick_params(axis="y", length=0)
667
+ ax.spines[["top", "right", "left"]].set_visible(False)
668
+ ax.set_xlabel(
669
+ args.xlabel
670
+ if args.xlabel is not None
671
+ else (f"exp({args.xcol})" if args.exp else args.xcol)
672
+ )
673
+ if args.groupcol:
674
+ ax.legend(
675
+ title=args.groupcol,
676
+ fontsize="small",
677
+ title_fontsize="small",
678
+ loc=tuple(args.legendloc) if args.legendloc else "best",
679
+ )
680
+ ax.set_title(args.title or "")
681
+ fig.tight_layout()
682
+ _draw_text(fig, ax, _text_columns(df, est, ypos, args), args)
683
+ save_or_show(fig, args)
684
+
685
+
686
+ def _log_ticks(ax, est: pd.DataFrame, xlim, ref) -> None:
687
+ """Plain-number ticks on the log axis: 0.5, 1, 2 rather than 10^-0.3.
688
+
689
+ Within a decade, evenly spaced ticks (the log axis would label its
690
+ minor ticks on top of each other); over more, 1-2-5 steps."""
691
+ from matplotlib.ticker import LogLocator, MaxNLocator, NullFormatter
692
+
693
+ if xlim is not None:
694
+ lo, hi = xlim
695
+ else:
696
+ values = est[["_est", "_lo", "_hi"]].to_numpy(dtype=float).ravel()
697
+ values = values[np.isfinite(values)]
698
+ if ref is not None:
699
+ values = np.append(values, ref)
700
+ lo, hi = values.min(), values.max()
701
+ if hi / lo < 10:
702
+ ax.xaxis.set_major_locator(MaxNLocator(nbins=6))
703
+ else:
704
+ ax.xaxis.set_major_locator(LogLocator(base=10, subs=(1.0, 2.0, 5.0)))
705
+ ax.xaxis.set_major_formatter(lambda x, _pos: f"{x:g}")
706
+ ax.xaxis.set_minor_formatter(NullFormatter())
@@ -534,3 +534,105 @@ def _ld_z(z_lead: float, r2: np.ndarray, noise: np.ndarray) -> np.ndarray:
534
534
  # measured from the causal variant, so it should be the one on top).
535
535
  r = np.sqrt(r2)
536
536
  return np.clip(r * z_lead + np.sqrt(1 - r2) * noise, None, 0.98 * z_lead)
537
+
538
+
539
+ # Phenotypes of the simulated PheWAS, by category (top to bottom as listed)
540
+ _PHEWAS_PHENOTYPES = {
541
+ "Cardiovascular": (
542
+ "Atrial fibrillation", "Coronary artery disease", "Heart failure",
543
+ "Hypertension", "Stroke", "Venous thromboembolism", "Aortic stenosis",
544
+ "Peripheral artery disease", "Cardiomyopathy",
545
+ ),
546
+ "Metabolic": (
547
+ "Type 2 diabetes", "Obesity", "Gout", "Hypothyroidism", "Hyperlipidaemia",
548
+ "Osteoporosis", "Type 1 diabetes", "Hyperparathyroidism",
549
+ ),
550
+ "Haematology": (
551
+ "Anaemia", "Neutropenia", "Thrombocytopenia", "Iron deficiency",
552
+ "Lymphoma", "Myelodysplasia", "Leukaemia",
553
+ ),
554
+ "Immune and infection": (
555
+ "Asthma", "Rheumatoid arthritis", "Psoriasis", "Crohn's disease",
556
+ "Ulcerative colitis", "Pneumonia", "Sepsis", "Herpes zoster",
557
+ "Multiple sclerosis",
558
+ ),
559
+ "Neurological": (
560
+ "Migraine", "Epilepsy", "Parkinson's disease", "Alzheimer's disease",
561
+ "Peripheral neuropathy", "Sleep apnoea", "Essential tremor",
562
+ ),
563
+ "Psychiatric": (
564
+ "Depression", "Anxiety", "Bipolar disorder", "Schizophrenia", "ADHD",
565
+ "Alcohol use disorder",
566
+ ),
567
+ "Kidney and liver": (
568
+ "Chronic kidney disease", "Kidney stones", "Fatty liver disease",
569
+ "Cirrhosis", "Gallstones", "Pancreatitis",
570
+ ),
571
+ "Cancer": (
572
+ "Breast cancer", "Prostate cancer", "Colorectal cancer", "Lung cancer",
573
+ "Melanoma", "Bladder cancer", "Kidney cancer", "Pancreatic cancer",
574
+ ),
575
+ "Reproduction and development": (
576
+ "Infertility", "Miscarriage", "Pre-eclampsia", "Congenital heart defect",
577
+ "Endometriosis", "Cleft lip",
578
+ ),
579
+ "Musculoskeletal": (
580
+ "Osteoarthritis", "Back pain", "Fracture", "Carpal tunnel syndrome",
581
+ ),
582
+ "Eye and ear": (
583
+ "Cataract", "Glaucoma", "Macular degeneration", "Hearing loss",
584
+ ),
585
+ } # fmt: skip
586
+
587
+ # (true log odds ratio per loss-of-function allele, prevalence) of the
588
+ # phenotypes with an effect: heterozygotes have it once, homozygotes twice.
589
+ # Every other phenotype has none and a random prevalence.
590
+ _PHEWAS_EFFECTS = {
591
+ "Neutropenia": (0.8, 0.01),
592
+ "Cataract": (0.4, 0.15),
593
+ "Type 2 diabetes": (0.35, 0.08),
594
+ "Atrial fibrillation": (0.25, 0.1),
595
+ "Coronary artery disease": (-0.3, 0.08),
596
+ }
597
+
598
+
599
+ def simulate_phewas(
600
+ n_het: int = 4000, n_hom: int = 60, seed: int = 20261116
601
+ ) -> pd.DataFrame:
602
+ """A synthetic phenome-wide scan of loss-of-function carriers, for
603
+ examples: no real people, gene or results.
604
+
605
+ Columns: category, phenotype, prevalence, genotype (het, hom),
606
+ n_carriers, beta (log odds ratio against non-carriers), se, Pval.
607
+ One row per phenotype and genotype, in category order, het first.
608
+ Each phenotype gets a prevalence K (log-uniform, 0.3-20 %), and
609
+ SE(log OR) = 1 / sqrt(n K (1 - K)) for n carriers, so the few
610
+ homozygotes give wide intervals. Five phenotypes have a real effect
611
+ and a set prevalence (_PHEWAS_EFFECTS, doubled in homozygotes, one of
612
+ them protective; significant in heterozygotes, not in homozygotes); the
613
+ estimates are the true effect plus normal noise of that SE, and Pval is
614
+ two-sided. Deterministic for a given *seed*. numpy only (no scipy).
615
+ """
616
+ rng = np.random.default_rng(seed)
617
+ rows = []
618
+ for category, phenotypes in _PHEWAS_PHENOTYPES.items():
619
+ for phenotype in phenotypes:
620
+ prevalence = float(np.exp(rng.uniform(np.log(0.003), np.log(0.2))))
621
+ effect, prevalence = _PHEWAS_EFFECTS.get(phenotype, (0.0, prevalence))
622
+ for genotype, n, dose in (("het", n_het, 1), ("hom", n_hom, 2)):
623
+ se = 1 / math.sqrt(n * prevalence * (1 - prevalence))
624
+ beta = dose * effect + se * rng.standard_normal()
625
+ rows.append(
626
+ (
627
+ category, phenotype, round(prevalence, 4), genotype, n,
628
+ round(beta, 4), round(se, 4),
629
+ math.erfc(abs(beta / se) / math.sqrt(2)),
630
+ )
631
+ ) # fmt: skip
632
+ return pd.DataFrame(
633
+ rows,
634
+ columns=[
635
+ "category", "phenotype", "prevalence", "genotype", "n_carriers",
636
+ "beta", "se", "Pval",
637
+ ],
638
+ ) # fmt: skip
@@ -157,7 +157,11 @@ scale above 10, `--miami COL [UPPER LOWER]` two scans, the second upside
157
157
  down below it), `qq` (QQ plot of p-values with a 95 % band and the genomic inflation
158
158
  lambda; same p-value options, `-g` one curve and lambda per group, `--logy`),
159
159
  `locus` (one region, cut out with `query` first: -log10(p) by position, `--ldcol r2`
160
- colours by LD with the lead, `--lead`/`--label` take an ID or `chr6:32600000`). `-g COL`
160
+ colours by LD with the lead, `--lead`/`--label` take an ID or `chr6:32600000`),
161
+ `forest` (estimates with intervals, one row each, file order top to bottom:
162
+ `-y LABEL -x EST --se SE` or `--ci LO,HI`; `--exp` for log odds ratios, `--text`
163
+ `--textcol Pval n` numbers on the right, `-g` series per row, `--section` headers;
164
+ `fit -o | forest -y marker -x effect --ci cilo,cihi` plots coefficients). `-g COL`
161
165
  overlays groups, `--subgraphcol COL` makes panels.
162
166
 
163
167
  Other: `dataset NAME` loads a bundled example table, `annotate FILE.parquet`