dataframe-toolkit 0.26.0__tar.gz → 0.27.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.26.0 → dataframe_toolkit-0.27.0}/PKG-INFO +22 -7
  2. {dataframe_toolkit-0.26.0 → dataframe_toolkit-0.27.0}/README.md +21 -6
  3. {dataframe_toolkit-0.26.0 → dataframe_toolkit-0.27.0}/pyproject.toml +1 -1
  4. {dataframe_toolkit-0.26.0 → dataframe_toolkit-0.27.0}/pyproject.toml.orig +1 -1
  5. {dataframe_toolkit-0.26.0 → dataframe_toolkit-0.27.0}/src/dftk/commands/phewas_cmd.py +190 -57
  6. {dataframe_toolkit-0.26.0 → dataframe_toolkit-0.27.0}/src/dftk/commands/query_cmd.py +8 -5
  7. {dataframe_toolkit-0.26.0 → dataframe_toolkit-0.27.0}/src/dftk/skills/dftk/SKILL.md +5 -1
  8. {dataframe_toolkit-0.26.0 → dataframe_toolkit-0.27.0}/src/dftk/__init__.py +0 -0
  9. {dataframe_toolkit-0.26.0 → dataframe_toolkit-0.27.0}/src/dftk/cli.py +0 -0
  10. {dataframe_toolkit-0.26.0 → dataframe_toolkit-0.27.0}/src/dftk/commands/__init__.py +0 -0
  11. {dataframe_toolkit-0.26.0 → dataframe_toolkit-0.27.0}/src/dftk/commands/annotate_cmd.py +0 -0
  12. {dataframe_toolkit-0.26.0 → dataframe_toolkit-0.27.0}/src/dftk/commands/append_cmd.py +0 -0
  13. {dataframe_toolkit-0.26.0 → dataframe_toolkit-0.27.0}/src/dftk/commands/base.py +0 -0
  14. {dataframe_toolkit-0.26.0 → dataframe_toolkit-0.27.0}/src/dftk/commands/binx_cmd.py +0 -0
  15. {dataframe_toolkit-0.26.0 → dataframe_toolkit-0.27.0}/src/dftk/commands/box_cmd.py +0 -0
  16. {dataframe_toolkit-0.26.0 → dataframe_toolkit-0.27.0}/src/dftk/commands/chi_cmd.py +0 -0
  17. {dataframe_toolkit-0.26.0 → dataframe_toolkit-0.27.0}/src/dftk/commands/clean_cmd.py +0 -0
  18. {dataframe_toolkit-0.26.0 → dataframe_toolkit-0.27.0}/src/dftk/commands/cleannames_cmd.py +0 -0
  19. {dataframe_toolkit-0.26.0 → dataframe_toolkit-0.27.0}/src/dftk/commands/concat_cmd.py +0 -0
  20. {dataframe_toolkit-0.26.0 → dataframe_toolkit-0.27.0}/src/dftk/commands/corr_cmd.py +0 -0
  21. {dataframe_toolkit-0.26.0 → dataframe_toolkit-0.27.0}/src/dftk/commands/dataset_cmd.py +0 -0
  22. {dataframe_toolkit-0.26.0 → dataframe_toolkit-0.27.0}/src/dftk/commands/describe_cmd.py +0 -0
  23. {dataframe_toolkit-0.26.0 → dataframe_toolkit-0.27.0}/src/dftk/commands/eval_cmd.py +0 -0
  24. {dataframe_toolkit-0.26.0 → dataframe_toolkit-0.27.0}/src/dftk/commands/explode_cmd.py +0 -0
  25. {dataframe_toolkit-0.26.0 → dataframe_toolkit-0.27.0}/src/dftk/commands/fit_cmd.py +0 -0
  26. {dataframe_toolkit-0.26.0 → dataframe_toolkit-0.27.0}/src/dftk/commands/forest_cmd.py +0 -0
  27. {dataframe_toolkit-0.26.0 → dataframe_toolkit-0.27.0}/src/dftk/commands/func_cmd.py +0 -0
  28. {dataframe_toolkit-0.26.0 → dataframe_toolkit-0.27.0}/src/dftk/commands/heatmap_cmd.py +0 -0
  29. {dataframe_toolkit-0.26.0 → dataframe_toolkit-0.27.0}/src/dftk/commands/help.py +0 -0
  30. {dataframe_toolkit-0.26.0 → dataframe_toolkit-0.27.0}/src/dftk/commands/hist_cmd.py +0 -0
  31. {dataframe_toolkit-0.26.0 → dataframe_toolkit-0.27.0}/src/dftk/commands/implode_cmd.py +0 -0
  32. {dataframe_toolkit-0.26.0 → dataframe_toolkit-0.27.0}/src/dftk/commands/info_cmd.py +0 -0
  33. {dataframe_toolkit-0.26.0 → dataframe_toolkit-0.27.0}/src/dftk/commands/interp_cmd.py +0 -0
  34. {dataframe_toolkit-0.26.0 → dataframe_toolkit-0.27.0}/src/dftk/commands/line_cmd.py +0 -0
  35. {dataframe_toolkit-0.26.0 → dataframe_toolkit-0.27.0}/src/dftk/commands/locus_cmd.py +0 -0
  36. {dataframe_toolkit-0.26.0 → dataframe_toolkit-0.27.0}/src/dftk/commands/manhattan_cmd.py +0 -0
  37. {dataframe_toolkit-0.26.0 → dataframe_toolkit-0.27.0}/src/dftk/commands/melt_cmd.py +0 -0
  38. {dataframe_toolkit-0.26.0 → dataframe_toolkit-0.27.0}/src/dftk/commands/merge_cmd.py +0 -0
  39. {dataframe_toolkit-0.26.0 → dataframe_toolkit-0.27.0}/src/dftk/commands/pairs_cmd.py +0 -0
  40. {dataframe_toolkit-0.26.0 → dataframe_toolkit-0.27.0}/src/dftk/commands/pivot_cmd.py +0 -0
  41. {dataframe_toolkit-0.26.0 → dataframe_toolkit-0.27.0}/src/dftk/commands/print_cmd.py +0 -0
  42. {dataframe_toolkit-0.26.0 → dataframe_toolkit-0.27.0}/src/dftk/commands/qq_cmd.py +0 -0
  43. {dataframe_toolkit-0.26.0 → dataframe_toolkit-0.27.0}/src/dftk/commands/randvar_cmd.py +0 -0
  44. {dataframe_toolkit-0.26.0 → dataframe_toolkit-0.27.0}/src/dftk/commands/sample_cmd.py +0 -0
  45. {dataframe_toolkit-0.26.0 → dataframe_toolkit-0.27.0}/src/dftk/commands/scale_cmd.py +0 -0
  46. {dataframe_toolkit-0.26.0 → dataframe_toolkit-0.27.0}/src/dftk/commands/scat_cmd.py +0 -0
  47. {dataframe_toolkit-0.26.0 → dataframe_toolkit-0.27.0}/src/dftk/commands/segid_cmd.py +0 -0
  48. {dataframe_toolkit-0.26.0 → dataframe_toolkit-0.27.0}/src/dftk/commands/skill_cmd.py +0 -0
  49. {dataframe_toolkit-0.26.0 → dataframe_toolkit-0.27.0}/src/dftk/commands/split_cmd.py +0 -0
  50. {dataframe_toolkit-0.26.0 → dataframe_toolkit-0.27.0}/src/dftk/commands/stat_cmd.py +0 -0
  51. {dataframe_toolkit-0.26.0 → dataframe_toolkit-0.27.0}/src/dftk/commands/test_cmd.py +0 -0
  52. {dataframe_toolkit-0.26.0 → dataframe_toolkit-0.27.0}/src/dftk/commands/transpose_cmd.py +0 -0
  53. {dataframe_toolkit-0.26.0 → dataframe_toolkit-0.27.0}/src/dftk/commands/wstat_cmd.py +0 -0
  54. {dataframe_toolkit-0.26.0 → dataframe_toolkit-0.27.0}/src/dftk/common/__init__.py +0 -0
  55. {dataframe_toolkit-0.26.0 → dataframe_toolkit-0.27.0}/src/dftk/common/copula.py +0 -0
  56. {dataframe_toolkit-0.26.0 → dataframe_toolkit-0.27.0}/src/dftk/common/docformats.py +0 -0
  57. {dataframe_toolkit-0.26.0 → dataframe_toolkit-0.27.0}/src/dftk/common/evalfuncs.py +0 -0
  58. {dataframe_toolkit-0.26.0 → dataframe_toolkit-0.27.0}/src/dftk/common/gwas.py +0 -0
  59. {dataframe_toolkit-0.26.0 → dataframe_toolkit-0.27.0}/src/dftk/common/io.py +0 -0
  60. {dataframe_toolkit-0.26.0 → dataframe_toolkit-0.27.0}/src/dftk/common/plot.py +0 -0
  61. {dataframe_toolkit-0.26.0 → dataframe_toolkit-0.27.0}/src/dftk/common/seed.py +0 -0
  62. {dataframe_toolkit-0.26.0 → dataframe_toolkit-0.27.0}/src/dftk/common/seq.py +0 -0
  63. {dataframe_toolkit-0.26.0 → dataframe_toolkit-0.27.0}/src/dftk/common/stats.py +0 -0
  64. {dataframe_toolkit-0.26.0 → dataframe_toolkit-0.27.0}/src/dftk/io.py +0 -0
  65. {dataframe_toolkit-0.26.0 → dataframe_toolkit-0.27.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.26.0
3
+ Version: 0.27.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
@@ -245,15 +245,28 @@ dftk query --sql "
245
245
  # ATXN7 chr3:30-42
246
246
  ```
247
247
 
248
- To get JSON back, write `-o FILE.json` or `.jsonl`, or `--format json` for stdout (see [Output formats](#output-formats)). Nested values and mixed fields are written as JSON again; a key missing from a record is written as `null`:
248
+ dftk reads JSON as a table, and a table has every column in every row: a record without a key gets an empty cell, and JSON output (`-o FILE.json`, `.jsonl`, `--format json`; see [Output formats](#output-formats)) writes that cell as `null`. So dftk is the tool for getting a table out of JSON, not for filtering JSON and keeping it JSON. With a third record `{"locus": "ATXN8"}` in `catalog.jsonl`:
249
249
 
250
250
  ```bash
251
- dftk query --sql "SELECT * FROM 'catalog.jsonl' WHERE locus LIKE 'ATXN%'" --format json
252
- # [
253
- # {"locus": "ATXN7", "region": ["chr3:1-30", "chr3:30-42"]}
254
- # ]
251
+ dftk query --sql "SELECT * FROM 'catalog.jsonl' WHERE locus LIKE 'ATXN%'" --format jsonl
252
+ # {"locus": "ATXN7", "region": ["chr3:1-30", "chr3:30-42"]}
253
+ # {"locus": "ATXN8", "region": null}
254
+ ```
255
+
256
+ [jq](https://jqlang.org/) filters records without making a table, so each comes out as it went in, and can also write TSV for a dftk pipeline:
257
+
258
+ ```bash
259
+ jq -c 'select(.locus | startswith("ATXN"))' catalog.jsonl
260
+ # {"locus":"ATXN7","region":["chr3:1-30","chr3:30-42"]}
261
+ # {"locus":"ATXN8"}
262
+ jq -r '[.locus, (.region // "" | tostring)] | @tsv' catalog.jsonl
263
+ # AFF2 chrX:1-60
264
+ # ATXN7 ["chr3:1-30","chr3:30-42"]
265
+ # ATXN8
255
266
  ```
256
267
 
268
+ JSON output is for tables: results, small records (`append`, below), input for tools that want JSON. Nested values and mixed fields are written as JSON again.
269
+
257
270
  ### One row: status logs and small records
258
271
 
259
272
  `append` adds one row from `-c COL=VALUE` values; columns not given stay empty. Numbers and `true`/`false` are typed, a quoted value (`'"007"'`) stays text and `note=` is empty. Without input it makes a one-row table, a quick way to write a small JSON record:
@@ -530,10 +543,12 @@ dftk dataset gwas -o | dftk query -q "Chr == '6' and pos > 31.6e6 and pos < 33.6
530
543
  | dftk locus --ldcol r2 -f locus.png
531
544
  ```
532
545
 
533
- `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, or draw one panel each with `--subgraphcol`.
546
+ `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). `--labelpercat 1` labels only the strongest hit of each category, and `--labelnumbers` writes numbers instead of names, left to right, with the key on stdout for a caption. Every category is as wide on the x axis (`--catwidth count` makes a category as wide as its number of phenotypes). One row per phenotype: pick one genotype or mask with `query` first, or draw one panel each with `--subgraphcol`.
534
547
 
535
548
  ```bash
536
549
  dftk dataset phewas -o | dftk query -q "genotype == 'het'" -o | dftk phewas --betacol beta -f phewas.png
550
+ dftk dataset phewas -o | dftk query -q "genotype == 'het'" -o \
551
+ | dftk phewas --betacol beta --labelpercat 1 --labelnumbers -f phewas.png > phewas_key.tsv
537
552
  ```
538
553
 
539
554
  `--subgraphcol COL` stacks one PheWAS per value of a column: burden models of one gene, genes within one model, or genotypes. A phenotype stands at the same x in every panel and the panels share one y axis. The Bonferroni line counts each panel's own tests; `--sig P` draws one line at P in all of them:
@@ -215,15 +215,28 @@ dftk query --sql "
215
215
  # ATXN7 chr3:30-42
216
216
  ```
217
217
 
218
- To get JSON back, write `-o FILE.json` or `.jsonl`, or `--format json` for stdout (see [Output formats](#output-formats)). Nested values and mixed fields are written as JSON again; a key missing from a record is written as `null`:
218
+ dftk reads JSON as a table, and a table has every column in every row: a record without a key gets an empty cell, and JSON output (`-o FILE.json`, `.jsonl`, `--format json`; see [Output formats](#output-formats)) writes that cell as `null`. So dftk is the tool for getting a table out of JSON, not for filtering JSON and keeping it JSON. With a third record `{"locus": "ATXN8"}` in `catalog.jsonl`:
219
219
 
220
220
  ```bash
221
- dftk query --sql "SELECT * FROM 'catalog.jsonl' WHERE locus LIKE 'ATXN%'" --format json
222
- # [
223
- # {"locus": "ATXN7", "region": ["chr3:1-30", "chr3:30-42"]}
224
- # ]
221
+ dftk query --sql "SELECT * FROM 'catalog.jsonl' WHERE locus LIKE 'ATXN%'" --format jsonl
222
+ # {"locus": "ATXN7", "region": ["chr3:1-30", "chr3:30-42"]}
223
+ # {"locus": "ATXN8", "region": null}
224
+ ```
225
+
226
+ [jq](https://jqlang.org/) filters records without making a table, so each comes out as it went in, and can also write TSV for a dftk pipeline:
227
+
228
+ ```bash
229
+ jq -c 'select(.locus | startswith("ATXN"))' catalog.jsonl
230
+ # {"locus":"ATXN7","region":["chr3:1-30","chr3:30-42"]}
231
+ # {"locus":"ATXN8"}
232
+ jq -r '[.locus, (.region // "" | tostring)] | @tsv' catalog.jsonl
233
+ # AFF2 chrX:1-60
234
+ # ATXN7 ["chr3:1-30","chr3:30-42"]
235
+ # ATXN8
225
236
  ```
226
237
 
238
+ JSON output is for tables: results, small records (`append`, below), input for tools that want JSON. Nested values and mixed fields are written as JSON again.
239
+
227
240
  ### One row: status logs and small records
228
241
 
229
242
  `append` adds one row from `-c COL=VALUE` values; columns not given stay empty. Numbers and `true`/`false` are typed, a quoted value (`'"007"'`) stays text and `note=` is empty. Without input it makes a one-row table, a quick way to write a small JSON record:
@@ -500,10 +513,12 @@ dftk dataset gwas -o | dftk query -q "Chr == '6' and pos > 31.6e6 and pos < 33.6
500
513
  | dftk locus --ldcol r2 -f locus.png
501
514
  ```
502
515
 
503
- `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, or draw one panel each with `--subgraphcol`.
516
+ `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). `--labelpercat 1` labels only the strongest hit of each category, and `--labelnumbers` writes numbers instead of names, left to right, with the key on stdout for a caption. Every category is as wide on the x axis (`--catwidth count` makes a category as wide as its number of phenotypes). One row per phenotype: pick one genotype or mask with `query` first, or draw one panel each with `--subgraphcol`.
504
517
 
505
518
  ```bash
506
519
  dftk dataset phewas -o | dftk query -q "genotype == 'het'" -o | dftk phewas --betacol beta -f phewas.png
520
+ dftk dataset phewas -o | dftk query -q "genotype == 'het'" -o \
521
+ | dftk phewas --betacol beta --labelpercat 1 --labelnumbers -f phewas.png > phewas_key.tsv
507
522
  ```
508
523
 
509
524
  `--subgraphcol COL` stacks one PheWAS per value of a column: burden models of one gene, genes within one model, or genotypes. A phenotype stands at the same x in every panel and the panels share one y axis. The Bonferroni line counts each panel's own tests; `--sig P` draws one line at P in all of them:
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "dataframe-toolkit"
3
- version = "0.26.0"
3
+ version = "0.27.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.26.0"
3
+ version = "0.27.0"
4
4
  description = "A command-line toolkit for DataFrame analysis and manipulation"
5
5
  readme = "README.md"
6
6
  authors = [
@@ -53,7 +53,9 @@ _CATEGORY_COLOURS = (
53
53
  "#8C564B",
54
54
  "#80BA5A",
55
55
  )
56
- _GAP = 2.0 # x gap between categories, in phenotype widths
56
+ _GAP = 1.0 # --catwidth count: gap between categories, in phenotype widths
57
+ _BAND = 1.0 # --catwidth equal: width of every category
58
+ _BAND_GAP = 0.15 # --catwidth equal: gap between categories
57
59
 
58
60
  _EPILOG = """\
59
61
  Input: one row per test (phenotype), with a category, a phenotype name
@@ -61,7 +63,10 @@ and a p-value (columns category, phenotype and Pval unless named; the
61
63
  p-value as in manhattan: --pcol, --mlogpcol or --chi2col, common spellings
62
64
  found ignoring case). Categories are drawn left to right in order of
63
65
  first appearance, each in its own colour, and the phenotypes in file
64
- order within them: sort first to order them differently.
66
+ order within them: sort first to order them differently. Every category
67
+ is as wide, its phenotypes spread evenly across it; --catwidth count
68
+ makes each phenotype one unit wide instead, so a category is as wide as
69
+ its number of phenotypes.
65
70
 
66
71
  --betacol names a signed effect (beta, log odds ratio): points become
67
72
  triangles pointing up where it is above 0 and down where it is below.
@@ -71,7 +76,11 @@ The significance line is at 0.05 divided by the number of tests
71
76
  (Bonferroni) unless --sig gives a p-value; --sig none removes it. The
72
77
  phenotypes above it are labelled, the strongest first, at most --label N
73
78
  of them (default 10; 0 for none); labels that would overlap are moved
74
- down.
79
+ down. --labelpercat K labels at most K per category, so several strong
80
+ hits in one category (variations of one phenotype) don't take every
81
+ label. --labelnumbers writes numbers, 1, 2, ... left to right, instead of
82
+ long names, and the key (number, category, phenotype, Pval, and the
83
+ --betacol and --subgraphcol values) on stdout as TSV, for a caption.
75
84
 
76
85
  One row per phenotype: several tests of a phenotype (e.g. heterozygous and
77
86
  homozygous carriers) would stand side by side; pick one with query, or
@@ -99,6 +108,13 @@ Heterozygous and homozygous carriers, one panel each:
99
108
  dftk dataset phewas -o | dftk phewas --betacol beta \\
100
109
  --subgraphcol genotype -f phewas_by_genotype.png
101
110
 
111
+ The strongest hit of each category, numbered, the key saved for the
112
+ caption:
113
+
114
+ dftk dataset phewas -o | dftk query -q "genotype == 'het'" -o \\
115
+ | dftk phewas --betacol beta --labelpercat 1 --labelnumbers \\
116
+ -f phewas.png > phewas_key.tsv
117
+
102
118
  Fixed threshold, a suggestive line, more room for the labels:
103
119
 
104
120
  dftk dataset phewas -o | dftk query -q "genotype == 'het'" -o \\
@@ -161,9 +177,14 @@ def phewas_table(df: pd.DataFrame, args) -> pd.DataFrame:
161
177
  return out
162
178
 
163
179
 
164
- def layout(data: pd.DataFrame) -> tuple[np.ndarray, list[tuple[str, float, float]]]:
165
- """x of every row, and (category, first x, last x) of each category:
166
- categories in order of first appearance, rows in file order within."""
180
+ def layout(
181
+ data: pd.DataFrame, equal: bool = True
182
+ ) -> tuple[np.ndarray, list[tuple[str, float, float]]]:
183
+ """x of every row, and (category, left edge, right edge) of each
184
+ category's band: categories in order of first appearance, rows in file
185
+ order within. *equal*: every band is as wide (the phenotypes spread
186
+ evenly across it); otherwise each phenotype is one unit wide, so a band
187
+ is as wide as its count."""
167
188
  cats = list(dict.fromkeys(data["_cat"]))
168
189
  x = np.empty(len(data))
169
190
  spans = []
@@ -171,20 +192,22 @@ def layout(data: pd.DataFrame) -> tuple[np.ndarray, list[tuple[str, float, float
171
192
  codes = data["_cat"].to_numpy()
172
193
  for cat in cats:
173
194
  idx = np.flatnonzero(codes == cat)
174
- x[idx] = start + np.arange(len(idx))
175
- spans.append((cat, start, start + len(idx) - 1))
176
- start += len(idx) - 1 + _GAP
195
+ n = len(idx)
196
+ width = _BAND if equal else float(n)
197
+ x[idx] = start + (np.arange(n) + 0.5) * width / n
198
+ spans.append((cat, start, start + width))
199
+ start += width + (_BAND_GAP if equal else _GAP)
177
200
  return x, spans
178
201
 
179
202
 
180
203
  def shared_layout(
181
- panels: list[pd.DataFrame],
204
+ panels: list[pd.DataFrame], equal: bool = True
182
205
  ) -> tuple[list[np.ndarray], list[tuple[str, float, float]]]:
183
206
  """x of every row of every panel, and the category spans: one x per
184
207
  phenotype (category and label) across all panels, so that a phenotype
185
208
  stands at the same place in each; one missing from a panel leaves a gap."""
186
209
  keys = pd.concat([p[["_cat", "_label"]] for p in panels]).drop_duplicates()
187
- x, spans = layout(keys.reset_index(drop=True))
210
+ x, spans = layout(keys.reset_index(drop=True), equal)
188
211
  at = dict(zip(zip(keys["_cat"], keys["_label"], strict=True), x, strict=True))
189
212
  xs = [
190
213
  np.array([at[k] for k in zip(p["_cat"], p["_label"], strict=True)], dtype=float)
@@ -193,6 +216,77 @@ def shared_layout(
193
216
  return xs, spans
194
217
 
195
218
 
219
+ def pick_labels(data: pd.DataFrame, args, panel: str = "") -> list[int]:
220
+ """Rows to label: above the significance line, strongest first, at most
221
+ --labelpercat per category and --label in all."""
222
+ sig = significance(args, len(data))
223
+ if sig is None or args.label == 0:
224
+ return []
225
+ y = data["_y"].to_numpy()
226
+ cats = data["_cat"].to_numpy()
227
+ above = np.flatnonzero(y >= -np.log10(sig))
228
+ picked: list[int] = []
229
+ per_cat: dict[str, int] = {}
230
+ for i in above[np.argsort(-y[above], kind="stable")]:
231
+ if len(picked) == args.label:
232
+ break
233
+ if args.labelpercat is not None and per_cat.get(cats[i], 0) >= args.labelpercat:
234
+ continue
235
+ per_cat[cats[i]] = per_cat.get(cats[i], 0) + 1
236
+ picked.append(int(i))
237
+ if len(above) > len(picked):
238
+ limits = [f"--label {args.label}"]
239
+ if args.labelpercat is not None:
240
+ limits.append(f"--labelpercat {args.labelpercat}")
241
+ logger.info(
242
+ "%sLabelled %d of %d phenotypes above the line (%s)",
243
+ f"{panel}: " if panel else "",
244
+ len(picked),
245
+ len(above),
246
+ ", ".join(limits),
247
+ )
248
+ return picked
249
+
250
+
251
+ def number_labels(
252
+ panels: list[pd.DataFrame], xs: list[np.ndarray], picks: list[list[int]]
253
+ ) -> dict[float, int]:
254
+ """--labelnumbers: 1, 2, ... for the labelled phenotypes, left to right;
255
+ a phenotype labelled in several panels keeps one number."""
256
+ at = sorted({float(x[i]) for x, pick in zip(xs, picks, strict=True) for i in pick})
257
+ return {x: n for n, x in enumerate(at, start=1)}
258
+
259
+
260
+ def write_key(
261
+ panels: list[pd.DataFrame],
262
+ xs: list[np.ndarray],
263
+ picks: list[list[int]],
264
+ numbers: dict[float, int],
265
+ args,
266
+ ) -> None:
267
+ """The --labelnumbers key on stdout: number, panel columns, category,
268
+ phenotype, Pval (and --betacol), in number order."""
269
+ import sys
270
+
271
+ rows = []
272
+ for panel, x, pick in zip(panels, xs, picks, strict=True):
273
+ for i in pick:
274
+ row = {"number": numbers[float(x[i])]}
275
+ for col in args.subgraphcol or []:
276
+ row[col] = panel[col].iloc[i]
277
+ row[args.catcol] = panel["_cat"].iloc[i]
278
+ row[args.labelcol] = panel["_label"].iloc[i]
279
+ row["Pval"] = f"{10 ** -panel['_y'].iloc[i]:.3g}"
280
+ if args.betacol:
281
+ row[args.betacol] = panel[args.betacol].iloc[i]
282
+ rows.append(row)
283
+ if not rows:
284
+ logger.info("--labelnumbers: no phenotype above the line to number")
285
+ return
286
+ key = pd.DataFrame(rows).sort_values("number", kind="stable")
287
+ key.to_csv(sys.stdout, sep="\t", index=False)
288
+
289
+
196
290
  def significance(args, n: int) -> float | None:
197
291
  if args.sig == "bonferroni":
198
292
  return 0.05 / n
@@ -224,6 +318,8 @@ def _draw(
224
318
  legend: bool = True,
225
319
  categories: bool = True,
226
320
  ylabel: bool = True,
321
+ labels: list[int] = (),
322
+ numbers: dict[float, int] | None = None,
227
323
  ) -> None:
228
324
  y = data["_y"].to_numpy()
229
325
  sign = data["_sign"].to_numpy()
@@ -261,14 +357,16 @@ def _draw(
261
357
  zorder=1,
262
358
  )
263
359
 
264
- if sig is not None and args.label > 0:
265
- above = np.flatnonzero(y >= -np.log10(sig))
266
- top = above[np.argsort(-y[above], kind="stable")][: args.label]
360
+ if len(labels):
267
361
  right = x.max() - 0.15 * (x.max() - x.min())
268
- for i in top:
362
+ for i in labels:
269
363
  near_edge = x[i] > right # label to the left, inside the axes
364
+ text = (
365
+ str(numbers[float(x[i])]) if numbers is not None
366
+ else data["_label"].iloc[i]
367
+ ) # fmt: skip
270
368
  ax.annotate(
271
- data["_label"].iloc[i],
369
+ text,
272
370
  (x[i], min(y[i], hi)),
273
371
  xytext=(-4 if near_edge else 4, 4),
274
372
  textcoords="offset points",
@@ -278,13 +376,6 @@ def _draw(
278
376
  zorder=5,
279
377
  annotation_clip=False,
280
378
  )
281
- if len(above) > len(top):
282
- logger.info(
283
- "Labelled the %d strongest of %d phenotypes above the line "
284
- "(--label N for more)",
285
- len(top),
286
- len(above),
287
- )
288
379
 
289
380
  if legend and args.betacol and (sign != 0).any():
290
381
  from matplotlib.lines import Line2D
@@ -303,6 +394,7 @@ def _draw(
303
394
  )
304
395
 
305
396
  ax.set_xticks([(a + b) / 2 for _, a, b in spans])
397
+ margin = _BAND_GAP if args.catwidth == "equal" else _GAP
306
398
  if categories:
307
399
  ax.set_xticklabels([c for c, _, _ in spans], rotation=45, ha="right")
308
400
  for label, (cat, _, _) in zip(ax.get_xticklabels(), spans, strict=True):
@@ -310,7 +402,7 @@ def _draw(
310
402
  else:
311
403
  ax.set_xticklabels([])
312
404
  ax.tick_params(axis="x", length=0)
313
- ax.set_xlim(-_GAP / 2 - 0.5, spans[-1][2] + _GAP / 2 + 0.5)
405
+ ax.set_xlim(spans[0][1] - margin, spans[-1][2] + margin)
314
406
  ax.set_ylim(lo, hi)
315
407
  if args.logy is not None:
316
408
  log_yaxis(ax, args.logy, lo, hi)
@@ -417,6 +509,29 @@ class PhewasCommand(BaseCommand):
417
509
  help="Label at most N phenotypes above the significance line, "
418
510
  "strongest first (default: 10; 0 for none).",
419
511
  )
512
+ g.add_argument(
513
+ "--labelpercat",
514
+ type=int,
515
+ default=None,
516
+ metavar="K",
517
+ help="Label at most K phenotypes per category (per panel), so the "
518
+ "hits of one category don't take every label (default: no limit).",
519
+ )
520
+ g.add_argument(
521
+ "--labelnumbers",
522
+ action="store_true",
523
+ help="Label with numbers, 1, 2, ... left to right, and write the "
524
+ "key (number, category, phenotype, Pval) to stdout as TSV, for a "
525
+ "caption.",
526
+ )
527
+ g.add_argument(
528
+ "--catwidth",
529
+ choices=["equal", "count"],
530
+ default="equal",
531
+ help="equal: every category as wide, its phenotypes spread across "
532
+ "it (default); count: each phenotype one unit, so a category is as "
533
+ "wide as its number of phenotypes.",
534
+ )
420
535
  g.add_argument(
421
536
  "--logy",
422
537
  nargs="?",
@@ -501,6 +616,10 @@ class PhewasCommand(BaseCommand):
501
616
  raise ValueError(f"--logy must be above 0, not {args.logy:g}.")
502
617
  if args.label < 0:
503
618
  raise ValueError(f"--label must be 0 or more, not {args.label}.")
619
+ if args.labelpercat is not None and args.labelpercat < 1:
620
+ raise ValueError(
621
+ f"--labelpercat must be 1 or more, not {args.labelpercat}."
622
+ )
504
623
  df = io.read(args, columns=_columns(args))
505
624
  check_cols(df, [args.catcol], "-c/--catcol")
506
625
  check_cols(df, [args.labelcol], "-l/--labelcol")
@@ -517,44 +636,58 @@ class PhewasCommand(BaseCommand):
517
636
  if args.usetex:
518
637
  plt.rc("text", usetex=True)
519
638
  apply_style(args)
639
+ equal = args.catwidth == "equal"
640
+ if args.subgraphcol:
641
+ titles, panels = _panels(data, args)
642
+ xs, spans = shared_layout(panels, equal)
643
+ else:
644
+ titles, panels = [args.title or ""], [data]
645
+ x, spans = layout(data, equal)
646
+ xs = [x]
647
+ picks = [
648
+ pick_labels(p, args, t if args.subgraphcol else "")
649
+ for t, p in zip(titles, panels, strict=True)
650
+ ]
651
+ numbers = number_labels(panels, xs, picks) if args.labelnumbers else None
652
+ ylim = _ylim(panels, args)
653
+
520
654
  if not args.subgraphcol:
521
655
  fig, axes = make_figure(args)
522
656
  ax = axes[0][0]
523
- x, spans = layout(data)
524
- _draw(ax, data, args, x, spans, _ylim([data], args))
525
- ax.set_title(args.title or "")
657
+ _draw(ax, data, args, x, spans, ylim, labels=picks[0], numbers=numbers)
658
+ ax.set_title(titles[0])
526
659
  fig.tight_layout()
527
660
  spread_labels(fig, ax)
528
- save_or_show(fig, args)
529
- return
530
-
531
- titles, panels = _panels(data, args)
532
- xs, spans = shared_layout(panels)
533
- ylim = _ylim(panels, args)
534
- nrows, ncols = subgraph_layout(len(panels), args.ncols)
535
- fig, axes = make_figure(args, nrows=nrows, ncols=ncols)
536
- used = []
537
- for idx, (title, panel, x) in enumerate(zip(titles, panels, xs, strict=True)):
538
- row, col = divmod(idx, ncols)
539
- ax = axes[row][col]
540
- # Category names under the lowest panel of each column only
541
- lowest = idx + ncols >= len(panels)
542
- _draw(
543
- ax, panel, args, x, spans, ylim,
544
- legend=idx == 0, categories=lowest, ylabel=col == 0,
545
- ) # fmt: skip
546
- ax.set_title(title)
547
- if lowest and row < nrows - 1:
548
- # An empty grid cell below: its labels hang into that space
549
- ax.xaxis.set_in_layout(False)
550
- used.append(ax)
551
- for idx in range(len(panels), nrows * ncols):
552
- axes[idx // ncols][idx % ncols].set_visible(False)
553
- if args.title:
554
- fig.suptitle(args.title)
555
- fig.tight_layout()
556
- for ax in used:
557
- spread_labels(fig, ax)
661
+ else:
662
+ nrows, ncols = subgraph_layout(len(panels), args.ncols)
663
+ fig, axes = make_figure(args, nrows=nrows, ncols=ncols)
664
+ used = []
665
+ for idx, (title, panel, x, pick) in enumerate(
666
+ zip(titles, panels, xs, picks, strict=True)
667
+ ):
668
+ row, col = divmod(idx, ncols)
669
+ ax = axes[row][col]
670
+ # Category names under the lowest panel of each column only
671
+ lowest = idx + ncols >= len(panels)
672
+ _draw(
673
+ ax, panel, args, x, spans, ylim,
674
+ legend=idx == 0, categories=lowest, ylabel=col == 0,
675
+ labels=pick, numbers=numbers,
676
+ ) # fmt: skip
677
+ ax.set_title(title)
678
+ if lowest and row < nrows - 1:
679
+ # An empty grid cell below: its labels hang into that space
680
+ ax.xaxis.set_in_layout(False)
681
+ used.append(ax)
682
+ for idx in range(len(panels), nrows * ncols):
683
+ axes[idx // ncols][idx % ncols].set_visible(False)
684
+ if args.title:
685
+ fig.suptitle(args.title)
686
+ fig.tight_layout()
687
+ for ax in used:
688
+ spread_labels(fig, ax)
689
+ if numbers is not None:
690
+ write_key(panels, xs, picks, numbers, args)
558
691
  save_or_show(fig, args)
559
692
 
560
693
 
@@ -264,12 +264,15 @@ column of each field, len() counts a list, unnest() gives a row per item:
264
264
  In TSV output a list or object that is left nested is shown as one line
265
265
  of JSON (["x","y"]). A field that is a string in some records and a list
266
266
  in others gets DuckDB type JSON; its plain strings are shown without
267
- quotes. To get JSON back, give -o FILE.json (or .jsonl) or --format json;
268
- nested values, and such mixed fields, are written as JSON again, and a key
269
- missing from a record is written as null:
267
+ quotes.
268
+
269
+ The JSON becomes a table, with every column in every row: a record
270
+ without a key gets an empty cell, and JSON output (-o FILE.json, .jsonl,
271
+ --format json) writes it as null. To filter JSON and keep each record as
272
+ it was, use jq (jq -c 'select(.pos.chr == "1")' records.jsonl); jq -r
273
+ '[.id, .pos.chr] | @tsv' gives TSV for a dftk pipeline. JSON output of a
274
+ table writes nested values, and such mixed fields, as JSON again:
270
275
 
271
- dftk query --sql "SELECT * FROM 'records.jsonl' WHERE pos.chr = '1'" \\
272
- --format json
273
276
  dftk query --sql "SELECT id, tags FROM 'records.jsonl'" -o ids.jsonl
274
277
 
275
278
  OUT-OF-CORE LARGE FILES
@@ -92,7 +92,9 @@ Output format: TSV unless `-o FILE` ends in `.json` (array of records),
92
92
  `.jsonl`, `.md` (Markdown table) or `.tex` (bare booktabs tabular, for
93
93
  `\input` in a LaTeX table); `--format tsv|json|jsonl|md|tex` does the same
94
94
  on stdout. Lists and nested values are one line of JSON in TSV and stay
95
- nested in JSON output.
95
+ nested in JSON output. JSON read by `query` becomes a table, so JSON output
96
+ writes a key missing from a record as `null`: to filter JSON and keep it
97
+ JSON, use jq, not dftk.
96
98
 
97
99
  ## Choosing a command
98
100
 
@@ -164,6 +166,8 @@ lambda; same p-value options, `-g` one curve and lambda per group, `--logy`),
164
166
  colours by LD with the lead, `--lead`/`--label` take an ID or `chr6:32600000`),
165
167
  `phewas` (-log10(p) per phenotype grouped by `category`, labels from `phenotype`;
166
168
  `--betacol beta` triangles up/down by sign, Bonferroni line by default, hits labelled;
169
+ `--labelpercat 1` one label per category, `--labelnumbers` numbers with the key on
170
+ stdout (`> key.tsv`); categories equally wide unless `--catwidth count`;
167
171
  `--subgraphcol MODEL` stacks one panel per burden model or gene, same x, one y axis,
168
172
  Bonferroni per panel),
169
173
  `forest` (estimates with intervals, one row each, file order top to bottom: