dataframe-toolkit 0.27.0__tar.gz → 0.29.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.27.0 → dataframe_toolkit-0.29.0}/PKG-INFO +5 -3
  2. {dataframe_toolkit-0.27.0 → dataframe_toolkit-0.29.0}/README.md +4 -2
  3. {dataframe_toolkit-0.27.0 → dataframe_toolkit-0.29.0}/pyproject.toml +1 -1
  4. {dataframe_toolkit-0.27.0 → dataframe_toolkit-0.29.0}/pyproject.toml.orig +1 -1
  5. {dataframe_toolkit-0.27.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/box_cmd.py +1 -1
  6. {dataframe_toolkit-0.27.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/forest_cmd.py +0 -1
  7. {dataframe_toolkit-0.27.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/heatmap_cmd.py +17 -2
  8. {dataframe_toolkit-0.27.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/line_cmd.py +3 -1
  9. {dataframe_toolkit-0.27.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/locus_cmd.py +1 -1
  10. {dataframe_toolkit-0.27.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/manhattan_cmd.py +1 -3
  11. {dataframe_toolkit-0.27.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/pairs_cmd.py +1 -2
  12. {dataframe_toolkit-0.27.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/phewas_cmd.py +1 -1
  13. {dataframe_toolkit-0.27.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/qq_cmd.py +1 -1
  14. {dataframe_toolkit-0.27.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/scat_cmd.py +9 -1
  15. {dataframe_toolkit-0.27.0 → dataframe_toolkit-0.29.0}/src/dftk/common/io.py +107 -44
  16. {dataframe_toolkit-0.27.0 → dataframe_toolkit-0.29.0}/src/dftk/common/plot.py +103 -20
  17. {dataframe_toolkit-0.27.0 → dataframe_toolkit-0.29.0}/src/dftk/skills/dftk/SKILL.md +13 -2
  18. {dataframe_toolkit-0.27.0 → dataframe_toolkit-0.29.0}/src/dftk/__init__.py +0 -0
  19. {dataframe_toolkit-0.27.0 → dataframe_toolkit-0.29.0}/src/dftk/cli.py +0 -0
  20. {dataframe_toolkit-0.27.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/__init__.py +0 -0
  21. {dataframe_toolkit-0.27.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/annotate_cmd.py +0 -0
  22. {dataframe_toolkit-0.27.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/append_cmd.py +0 -0
  23. {dataframe_toolkit-0.27.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/base.py +0 -0
  24. {dataframe_toolkit-0.27.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/binx_cmd.py +0 -0
  25. {dataframe_toolkit-0.27.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/chi_cmd.py +0 -0
  26. {dataframe_toolkit-0.27.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/clean_cmd.py +0 -0
  27. {dataframe_toolkit-0.27.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/cleannames_cmd.py +0 -0
  28. {dataframe_toolkit-0.27.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/concat_cmd.py +0 -0
  29. {dataframe_toolkit-0.27.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/corr_cmd.py +0 -0
  30. {dataframe_toolkit-0.27.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/dataset_cmd.py +0 -0
  31. {dataframe_toolkit-0.27.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/describe_cmd.py +0 -0
  32. {dataframe_toolkit-0.27.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/eval_cmd.py +0 -0
  33. {dataframe_toolkit-0.27.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/explode_cmd.py +0 -0
  34. {dataframe_toolkit-0.27.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/fit_cmd.py +0 -0
  35. {dataframe_toolkit-0.27.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/func_cmd.py +0 -0
  36. {dataframe_toolkit-0.27.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/help.py +0 -0
  37. {dataframe_toolkit-0.27.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/hist_cmd.py +0 -0
  38. {dataframe_toolkit-0.27.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/implode_cmd.py +0 -0
  39. {dataframe_toolkit-0.27.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/info_cmd.py +0 -0
  40. {dataframe_toolkit-0.27.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/interp_cmd.py +0 -0
  41. {dataframe_toolkit-0.27.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/melt_cmd.py +0 -0
  42. {dataframe_toolkit-0.27.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/merge_cmd.py +0 -0
  43. {dataframe_toolkit-0.27.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/pivot_cmd.py +0 -0
  44. {dataframe_toolkit-0.27.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/print_cmd.py +0 -0
  45. {dataframe_toolkit-0.27.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/query_cmd.py +0 -0
  46. {dataframe_toolkit-0.27.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/randvar_cmd.py +0 -0
  47. {dataframe_toolkit-0.27.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/sample_cmd.py +0 -0
  48. {dataframe_toolkit-0.27.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/scale_cmd.py +0 -0
  49. {dataframe_toolkit-0.27.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/segid_cmd.py +0 -0
  50. {dataframe_toolkit-0.27.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/skill_cmd.py +0 -0
  51. {dataframe_toolkit-0.27.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/split_cmd.py +0 -0
  52. {dataframe_toolkit-0.27.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/stat_cmd.py +0 -0
  53. {dataframe_toolkit-0.27.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/test_cmd.py +0 -0
  54. {dataframe_toolkit-0.27.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/transpose_cmd.py +0 -0
  55. {dataframe_toolkit-0.27.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/wstat_cmd.py +0 -0
  56. {dataframe_toolkit-0.27.0 → dataframe_toolkit-0.29.0}/src/dftk/common/__init__.py +0 -0
  57. {dataframe_toolkit-0.27.0 → dataframe_toolkit-0.29.0}/src/dftk/common/copula.py +0 -0
  58. {dataframe_toolkit-0.27.0 → dataframe_toolkit-0.29.0}/src/dftk/common/docformats.py +0 -0
  59. {dataframe_toolkit-0.27.0 → dataframe_toolkit-0.29.0}/src/dftk/common/evalfuncs.py +0 -0
  60. {dataframe_toolkit-0.27.0 → dataframe_toolkit-0.29.0}/src/dftk/common/gwas.py +0 -0
  61. {dataframe_toolkit-0.27.0 → dataframe_toolkit-0.29.0}/src/dftk/common/seed.py +0 -0
  62. {dataframe_toolkit-0.27.0 → dataframe_toolkit-0.29.0}/src/dftk/common/seq.py +0 -0
  63. {dataframe_toolkit-0.27.0 → dataframe_toolkit-0.29.0}/src/dftk/common/stats.py +0 -0
  64. {dataframe_toolkit-0.27.0 → dataframe_toolkit-0.29.0}/src/dftk/io.py +0 -0
  65. {dataframe_toolkit-0.27.0 → dataframe_toolkit-0.29.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.27.0
3
+ Version: 0.29.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
@@ -174,7 +174,7 @@ publication-quality output.
174
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` |
175
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 |
176
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` and `box` `--hline`.
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` and `box` `--hline`. `scat` and `line` also draw sloped lines y = A + B*x with `--abline A:B[:LABEL]` (intercept, then slope, as in R; `--abline 0:0.15:15%`), across the whole panel without changing its limits; a bare `--abline` is the identity line y = x, and a negative intercept is written `--abline=-1:2`. On log axes the line is drawn as the curve it is. With `--subgraphcol` the same lines go on every panel.
178
178
 
179
179
  ### Utilities
180
180
 
@@ -713,7 +713,9 @@ dftk annotate iris2.parquet # source, species_col, and step all still present
713
713
  ## Figure options (plot commands)
714
714
 
715
715
  ```text
716
- --size single|double|full|WxH figure size (single ≈ 3.5", double ≈ 7.2")
716
+ --size single|double|full|WxH size of the whole figure, panels included (single ≈ 3.5",
717
+ double ≈ 7.2"); without it, each panel gets a default size
718
+ and the figure grows with them up to 16x10
717
719
  --fontsize screen|publication|presentation
718
720
  -f FILE save to file (PNG/PDF/SVG); omit to display
719
721
  --groupcol COL colour-code by this column
@@ -144,7 +144,7 @@ publication-quality output.
144
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` |
145
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 |
146
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` and `box` `--hline`.
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` and `box` `--hline`. `scat` and `line` also draw sloped lines y = A + B*x with `--abline A:B[:LABEL]` (intercept, then slope, as in R; `--abline 0:0.15:15%`), across the whole panel without changing its limits; a bare `--abline` is the identity line y = x, and a negative intercept is written `--abline=-1:2`. On log axes the line is drawn as the curve it is. With `--subgraphcol` the same lines go on every panel.
148
148
 
149
149
  ### Utilities
150
150
 
@@ -683,7 +683,9 @@ dftk annotate iris2.parquet # source, species_col, and step all still present
683
683
  ## Figure options (plot commands)
684
684
 
685
685
  ```text
686
- --size single|double|full|WxH figure size (single ≈ 3.5", double ≈ 7.2")
686
+ --size single|double|full|WxH size of the whole figure, panels included (single ≈ 3.5",
687
+ double ≈ 7.2"); without it, each panel gets a default size
688
+ and the figure grows with them up to 16x10
687
689
  --fontsize screen|publication|presentation
688
690
  -f FILE save to file (PNG/PDF/SVG); omit to display
689
691
  --groupcol COL colour-code by this column
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "dataframe-toolkit"
3
- version = "0.27.0"
3
+ version = "0.29.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.27.0"
3
+ version = "0.29.0"
4
4
  description = "A command-line toolkit for DataFrame analysis and manipulation"
5
5
  readme = "README.md"
6
6
  authors = [
@@ -195,7 +195,7 @@ class BoxCommand(BaseCommand):
195
195
 
196
196
  add_figure_arguments(parser)
197
197
  add_refline_arguments(parser, vertical=False)
198
- parser.set_defaults(size="7x4.5")
198
+ parser.set_defaults(default_size="7x4.5")
199
199
 
200
200
  def execute(self, args: argparse.Namespace) -> None:
201
201
  df = io.read(args, columns=option_columns(args))
@@ -597,7 +597,6 @@ class ForestCommand(BaseCommand):
597
597
 
598
598
  add_figure_arguments(parser)
599
599
  add_refline_arguments(parser, horizontal=False)
600
- parser.set_defaults(size=None)
601
600
 
602
601
  def execute(self, args: argparse.Namespace) -> None:
603
602
  if not 0 < args.level < 1:
@@ -145,6 +145,9 @@ def _heatmap(
145
145
  ax.set_aspect("equal" if args.square else "auto")
146
146
 
147
147
  if args.annot:
148
+ import matplotlib
149
+
150
+ size = args.annotsize or matplotlib.rcParams["xtick.labelsize"]
148
151
  for (i, j), v in np.ndenumerate(shown.filled(np.nan)):
149
152
  if np.isfinite(v):
150
153
  # Dark text on light cells, light text on dark cells
@@ -157,6 +160,7 @@ def _heatmap(
157
160
  ha="center",
158
161
  va="center",
159
162
  color="black" if light else "white",
163
+ fontsize=size,
160
164
  )
161
165
  return mesh
162
166
 
@@ -242,8 +246,9 @@ COLOURS AND NUMBERS
242
246
  -------------------
243
247
  --cmap takes any matplotlib colour map (viridis, magma, RdBu_r, coolwarm,
244
248
  ...). --annot writes each value in its cell, with --fmt as a Python format
245
- (.2f, .1%, g; default g for whole numbers, else .2f). Empty cells stay
246
- blank.
249
+ (.2f, .1%, g; default g for whole numbers, else .2f), as large as the
250
+ tick labels (--fontsize publication makes both smaller; --annotsize PT
251
+ sets the numbers alone). Empty cells stay blank.
247
252
 
248
253
  dftk dataset penguins -o | dftk pivot -i species -g island -v body_mass_g \\
249
254
  -f count -o \\
@@ -288,6 +293,14 @@ class HeatmapCommand(BaseCommand):
288
293
  help="Format of --annot values, e.g. .2f or .1%% (default: g for "
289
294
  "whole numbers, else .2f).",
290
295
  )
296
+ g.add_argument(
297
+ "--annotsize",
298
+ type=float,
299
+ default=None,
300
+ metavar="PT",
301
+ help="Font size of the --annot values in points (default: that of "
302
+ "the tick labels, set by --fontsize).",
303
+ )
291
304
  g.add_argument(
292
305
  "--cmap",
293
306
  default=None,
@@ -345,6 +358,8 @@ class HeatmapCommand(BaseCommand):
345
358
  add_figure_arguments(parser)
346
359
 
347
360
  def execute(self, args: argparse.Namespace) -> None:
361
+ if args.annotsize is not None and args.annotsize <= 0:
362
+ raise ValueError(f"--annotsize must be above 0, not {args.annotsize:g}.")
348
363
  df = io.read(args)
349
364
  if args.select:
350
365
  check_cols(df, args.select, "--select")
@@ -27,6 +27,7 @@ from dftk.common.plot import (
27
27
  add_legend_arguments,
28
28
  add_refline_arguments,
29
29
  add_xy_arguments,
30
+ apply_ablines,
30
31
  apply_labels,
31
32
  apply_limits,
32
33
  apply_reflines,
@@ -166,6 +167,7 @@ def _line_ax(ax, df, args, title_suffix: str = ""):
166
167
 
167
168
  apply_reflines(ax, args)
168
169
  apply_limits(ax, args)
170
+ apply_ablines(ax, args)
169
171
  apply_ticks(ax, args)
170
172
  apply_labels(ax, args, default_xlabel=xcol or "", default_ylabel=ycol or "")
171
173
  if title_suffix:
@@ -255,7 +257,7 @@ class LineCommand(BaseCommand):
255
257
  self.add_read_arguments(parser)
256
258
  add_xy_arguments(parser)
257
259
  add_figure_arguments(parser)
258
- add_refline_arguments(parser)
260
+ add_refline_arguments(parser, sloped=True)
259
261
  add_group_arguments(parser)
260
262
  add_legend_arguments(parser)
261
263
 
@@ -346,7 +346,7 @@ class LocusCommand(BaseCommand):
346
346
  )
347
347
 
348
348
  add_figure_arguments(parser)
349
- parser.set_defaults(size="7x4")
349
+ parser.set_defaults(default_size="7x4")
350
350
 
351
351
  def execute(self, args: argparse.Namespace) -> None:
352
352
  if args.logy is not None and args.logy <= 0:
@@ -607,7 +607,6 @@ class ManhattanCommand(BaseCommand):
607
607
  )
608
608
 
609
609
  add_figure_arguments(parser)
610
- parser.set_defaults(size=None)
611
610
  add_group_arguments(parser)
612
611
  add_legend_arguments(parser)
613
612
 
@@ -619,8 +618,7 @@ class ManhattanCommand(BaseCommand):
619
618
  raise ValueError("--miami and -g/--groupcol can't be combined.")
620
619
  if args.logy is not None and args.logy <= 0:
621
620
  raise ValueError(f"--logy must be above 0, not {args.logy:g}.")
622
- if args.size is None:
623
- args.size = "12x6" if args.miami else "12x4"
621
+ args.default_size = "12x6" if args.miami else "12x4"
624
622
  data = gwas_table(df, args)
625
623
  if args.miami:
626
624
  data, args.miami_names = miami_halves(data, args.miami)
@@ -15,7 +15,6 @@ import pandas as pd
15
15
  from dftk.commands.base import BaseCommand
16
16
  from dftk.common.io import check_cols, io
17
17
  from dftk.common.plot import (
18
- _DEFAULT_SIZE,
19
18
  WONG_PALETTE,
20
19
  add_figure_arguments,
21
20
  apply_style,
@@ -178,7 +177,7 @@ def _corr_text(ax, df, groups, xcol: str, ycol: str, method: str, cmap, colors):
178
177
 
179
178
 
180
179
  def _figsize(args: argparse.Namespace, k: int) -> tuple[float, float]:
181
- if args.size != _DEFAULT_SIZE:
180
+ if args.size is not None:
182
181
  return parse_figsize(args.size)
183
182
  side = min(_PANEL_INCHES * k, _MAX_INCHES)
184
183
  return side, side
@@ -609,7 +609,7 @@ class PhewasCommand(BaseCommand):
609
609
  )
610
610
 
611
611
  add_figure_arguments(parser)
612
- parser.set_defaults(size="8x4.5")
612
+ parser.set_defaults(default_size="8x4.5")
613
613
 
614
614
  def execute(self, args: argparse.Namespace) -> None:
615
615
  if args.logy is not None and args.logy <= 0:
@@ -264,7 +264,7 @@ class QqCommand(BaseCommand):
264
264
  )
265
265
 
266
266
  add_figure_arguments(parser)
267
- parser.set_defaults(size="5x5")
267
+ parser.set_defaults(default_size="5x5")
268
268
  add_group_arguments(parser)
269
269
  add_legend_arguments(parser)
270
270
 
@@ -32,6 +32,7 @@ from dftk.common.plot import (
32
32
  add_legend_arguments,
33
33
  add_refline_arguments,
34
34
  add_xy_arguments,
35
+ apply_ablines,
35
36
  apply_labels,
36
37
  apply_limits,
37
38
  apply_reflines,
@@ -283,6 +284,7 @@ def _scatter_ax(ax, df, args, title_suffix: str = ""):
283
284
 
284
285
  apply_reflines(ax, args)
285
286
  apply_limits(ax, args)
287
+ apply_ablines(ax, args)
286
288
  apply_ticks(ax, args)
287
289
  apply_labels(ax, args, default_xlabel=xcol or "", default_ylabel=ycol or "")
288
290
  if title_suffix:
@@ -324,6 +326,12 @@ can overshoot the data; a larger --frac or --xlim helps:
324
326
 
325
327
  dftk dataset tips -o | dftk scat -x total_bill -y tip --fit lowess
326
328
 
329
+ Lines y = A + B*x, here 15 % and 20 % tips, on every panel (bare --abline
330
+ is y = x; a negative intercept is written --abline=-1:2):
331
+
332
+ dftk dataset tips -o | dftk scat -x total_bill -y tip --subgraphcol time \\
333
+ --abline 0:0.15:15% 0:0.2:20%
334
+
327
335
  Hexagonal binning for large tables (54,000 diamonds), log colour scale and
328
336
  log axes; hexagons are binned on the log scale:
329
337
 
@@ -386,7 +394,7 @@ class ScatCommand(BaseCommand):
386
394
  self.add_read_arguments(parser)
387
395
  add_xy_arguments(parser)
388
396
  add_figure_arguments(parser)
389
- add_refline_arguments(parser)
397
+ add_refline_arguments(parser, sloped=True)
390
398
  add_group_arguments(parser)
391
399
  add_legend_arguments(parser)
392
400
 
@@ -66,8 +66,93 @@ _CAST_TYPES: dict[str, object] = {
66
66
  "bool": "bool",
67
67
  "datetime64": "datetime64[ns]",
68
68
  "category": "category",
69
+ "str": "string",
70
+ "string": "string",
69
71
  }
70
72
 
73
+
74
+ def _query(df: pd.DataFrame, query: str, option: str) -> pd.DataFrame:
75
+ """df.query for --prequery / --postquery; a bad expression is an input
76
+ error (pandas raises UndefinedVariableError, SyntaxError, ...)."""
77
+ try:
78
+ return df.query(query)
79
+ except Exception as exc:
80
+ raise ValueError(f"{option} {query!r}: {exc}") from None
81
+
82
+
83
+ def _round(df: pd.DataFrame, item: str) -> pd.DataFrame:
84
+ """Apply one --round COL:N (a glob rounds the numeric columns it matches)
85
+ or --round N (every float column). A malformed item, a literal column that
86
+ matches nothing or isn't numeric is an input error."""
87
+ col, sep, n = item.rpartition(":")
88
+ try:
89
+ ndigits = int(n)
90
+ except ValueError:
91
+ raise ValueError(f"--round expects COL:N or N, got {item!r}") from None
92
+ if not sep:
93
+ columns = [c for c in df.columns if df[c].dtype == np.float64]
94
+ elif not col:
95
+ raise ValueError(f"--round expects COL:N or N, got {item!r}")
96
+ elif frozenset("*?[") & set(col):
97
+ columns = [
98
+ c
99
+ for c in fnmatch.filter(df.columns, col)
100
+ if pd.api.types.is_numeric_dtype(df[c])
101
+ and not pd.api.types.is_bool_dtype(df[c])
102
+ ]
103
+ elif col not in df.columns:
104
+ raise ValueError(
105
+ f"--round {item!r}: no column {col!r} (available: {list(df.columns)})"
106
+ )
107
+ elif not pd.api.types.is_numeric_dtype(df[col]):
108
+ raise ValueError(f"--round {item!r}: {col} is not numeric ({df[col].dtype})")
109
+ else:
110
+ columns = [col]
111
+ for c in columns:
112
+ df[c] = df[c].round(ndigits)
113
+ return df
114
+
115
+
116
+ def _cast(df: pd.DataFrame, item: str) -> pd.DataFrame:
117
+ """Apply one --cast COL:TYPE. An unknown type, a literal column name that
118
+ matches nothing or a failed conversion is an input error."""
119
+ col, sep, coltype = item.rpartition(":")
120
+ if not sep or not col or not coltype:
121
+ raise ValueError(f"--cast expects COL:TYPE, got {item!r}")
122
+ # Case-sensitive: "int" is int64, "Int" is the nullable Int64
123
+ matches = [t for t in _CAST_TYPES if fnmatch.fnmatchcase(t, f"{coltype}*")]
124
+ if not matches:
125
+ raise ValueError(
126
+ f"--cast {item!r}: unknown type {coltype!r} "
127
+ f"(choose from {', '.join(_CAST_TYPES)})"
128
+ )
129
+ dtype = _CAST_TYPES[matches[0]]
130
+ columns = fnmatch.filter(df.columns, col)
131
+ if dtype in ("int64", "Int64"):
132
+ for c in columns:
133
+ if pd.api.types.is_float_dtype(df[c]):
134
+ values = df[c].dropna()
135
+ broken = values[values % 1 != 0]
136
+ if len(broken):
137
+ raise ValueError(
138
+ f"--cast {c}:{coltype}: {c} has non-whole numbers "
139
+ f"(e.g. {broken.iloc[0]}); use --round {c}:0 first"
140
+ )
141
+ if not columns and not (frozenset("*?[") & set(col)):
142
+ raise ValueError(
143
+ f"--cast {item!r}: no column {col!r} (available: {list(df.columns)})"
144
+ )
145
+ for c in columns:
146
+ try:
147
+ df[c] = df[c].astype(dtype)
148
+ except Exception as exc:
149
+ try: # e.g. "1.0" text to int: via float
150
+ df[c] = df[c].astype(float).astype(dtype)
151
+ except Exception:
152
+ raise ValueError(f"--cast {c}:{coltype}: {exc}") from None
153
+ return df
154
+
155
+
71
156
  DFTK_TMPDIR: str = os.environ.get(
72
157
  "DFTK_TMPDIR",
73
158
  os.path.join(tempfile.gettempdir(), "dftk"),
@@ -544,11 +629,7 @@ class io:
544
629
  # -- prequery ------------------------------------------------------
545
630
 
546
631
  for query in prequery:
547
- try:
548
- df = df.query(query)
549
- except Exception as exc:
550
- logging.error(f"--prequery failed ({query!r}): {exc}")
551
- raise
632
+ df = _query(df, query, "--prequery")
552
633
 
553
634
  return df
554
635
 
@@ -640,9 +721,12 @@ class io:
640
721
  "--cast",
641
722
  help=(
642
723
  "Cast column to dtype (COL:TYPE). TYPE is one of object, int64, "
643
- "Int64, float64, bool, datetime64, category (a prefix is enough, "
644
- "e.g. int, Int, cat). Int64 is an integer column that allows "
645
- "empty cells. Glob patterns supported."
724
+ "Int64, float64, bool, datetime64, category, str (a prefix is "
725
+ "enough, e.g. int, Int, cat). Int64 is an integer column that "
726
+ "allows empty cells; str is text (written to parquet as a "
727
+ "string column; empty cells stay empty). Casts apply in "
728
+ "order, so --cast c:Int64 c:str turns 1.0 into 1. Glob "
729
+ "patterns supported; a type that doesn't fit is an error."
646
730
  ),
647
731
  nargs="*",
648
732
  default=None,
@@ -651,8 +735,11 @@ class io:
651
735
  g.add_argument(
652
736
  "--round",
653
737
  help=(
654
- "Round columns to N decimal places (COL:N). "
655
- "A bare integer N rounds all float columns."
738
+ "Round columns to N decimal places (COL:N; a glob rounds "
739
+ "the numeric columns it matches). A bare integer N rounds all "
740
+ "float columns. Done before --cast, so --round x:0 --cast "
741
+ "x:int gives the nearest integer (halves go to the even "
742
+ "number: 2.5 to 2, 3.5 to 4)."
656
743
  ),
657
744
  nargs="*",
658
745
  default=None,
@@ -735,7 +822,9 @@ class io:
735
822
  help=(
736
823
  "Drop rows containing any NA value from the output. Applied "
737
824
  "after the command has run, so it does not change what the "
738
- "command sees (use --prequery for that)."
825
+ "command sees (use --prequery for that). For one column: "
826
+ "--postquery 'COL.notna()'; for 2 or missing: --postquery "
827
+ "'b == 2 or b.isna()' (b == 2 alone drops the missing rows)."
739
828
  ),
740
829
  action="store_true",
741
830
  )
@@ -789,27 +878,16 @@ class io:
789
878
 
790
879
  # Post-query filter
791
880
  for query in getattr(args, "postquery", []):
792
- try:
793
- df = df.query(query)
794
- except Exception as exc:
795
- logging.error(f"--postquery failed ({query!r}): {exc}")
796
- raise
881
+ df = _query(df, query, "--postquery")
882
+
883
+ # Round decimal places; before --cast, so --round x:0 --cast x:int
884
+ # gives the nearest integer
885
+ for item in getattr(args, "round", None) or []:
886
+ df = _round(df, item)
797
887
 
798
888
  # Cast columns
799
889
  for item in getattr(args, "cast", None) or []:
800
- try:
801
- col, coltype = item.split(":")
802
- # Case-sensitive: "int" is int64, "Int" is the nullable Int64
803
- pattern = f"{coltype}*"
804
- matches = [t for t in _CAST_TYPES if fnmatch.fnmatchcase(t, pattern)]
805
- dtype = _CAST_TYPES[matches[0]]
806
- for c in fnmatch.filter(df.columns, col):
807
- try:
808
- df[c] = df[c].astype(dtype)
809
- except Exception:
810
- df[c] = df[c].astype(float).astype(dtype)
811
- except Exception:
812
- logging.warning(f"--cast: failed for {item!r}")
890
+ df = _cast(df, item)
813
891
 
814
892
  # Sort; --sortasc or --sortdesc without names sorts by every column,
815
893
  # left to right
@@ -888,21 +966,6 @@ class io:
888
966
  except Exception as exc:
889
967
  logging.error(f"--select failed: {exc}")
890
968
 
891
- # Round decimal places
892
- for item in getattr(args, "round", None) or []:
893
- try:
894
- col, n = item.split(":")
895
- for c in fnmatch.filter(df.columns, col):
896
- df[c] = df[c].round(int(n))
897
- except Exception:
898
- try:
899
- n = int(item)
900
- for c in df.columns:
901
- if df[c].dtype == np.float64:
902
- df[c] = df[c].round(n)
903
- except Exception:
904
- pass
905
-
906
969
  # Deduplicate
907
970
  dedup = getattr(args, "deduplicate", None)
908
971
  if dedup is not None:
@@ -176,24 +176,14 @@ def make_figure(
176
176
  Returns (fig, axes) where axes is always a 2-D numpy array of shape
177
177
  (nrows, ncols) for uniform indexing even when nrows=ncols=1.
178
178
 
179
- For publication presets (single/double/full) the per-panel size is
180
- respected exactly. For freeform sizes (WxH, including the default)
181
- the total figure is capped at _MAX_SCREEN_W × _MAX_SCREEN_H so that
182
- large subplot grids remain at a comfortable screen size.
179
+ --size, when given (a preset or WxH), is the whole figure, exactly: the
180
+ panels share it. Without it, the command's default size
181
+ (``args.default_size``, else _DEFAULT_SIZE) is the size of one panel, and
182
+ the figure grows with the grid up to _MAX_SCREEN_W × _MAX_SCREEN_H.
183
183
  """
184
184
  import matplotlib.pyplot as plt
185
185
 
186
- size_str = getattr(args, "size", _DEFAULT_SIZE)
187
- w, h = parse_figsize(size_str)
188
-
189
- w_total = w * ncols
190
- h_total = h * nrows
191
-
192
- # Cap total size for freeform (non-preset) sizes so grids don't balloon.
193
- if size_str not in _SIZE_PRESETS:
194
- w_total = min(w_total, _MAX_SCREEN_W)
195
- h_total = min(h_total, _MAX_SCREEN_H)
196
-
186
+ w_total, h_total = figure_size(args, nrows, ncols)
197
187
  fig, axes = plt.subplots(
198
188
  nrows,
199
189
  ncols,
@@ -203,6 +193,18 @@ def make_figure(
203
193
  return fig, axes
204
194
 
205
195
 
196
+ def figure_size(
197
+ args: argparse.Namespace, nrows: int = 1, ncols: int = 1
198
+ ) -> tuple[float, float]:
199
+ """(width, height) in inches of a figure of nrows × ncols panels; see
200
+ make_figure."""
201
+ given = getattr(args, "size", None)
202
+ if given is not None:
203
+ return parse_figsize(given)
204
+ w, h = parse_figsize(getattr(args, "default_size", None) or _DEFAULT_SIZE)
205
+ return min(w * ncols, _MAX_SCREEN_W), min(h * nrows, _MAX_SCREEN_H)
206
+
207
+
206
208
  # ---------------------------------------------------------------------------
207
209
  # Subplot grid for --subgraphcol
208
210
  # ---------------------------------------------------------------------------
@@ -416,11 +418,90 @@ def apply_reflines(ax: matplotlib.axes.Axes, args: argparse.Namespace) -> None:
416
418
  )
417
419
 
418
420
 
421
+ def abline(value: str) -> tuple[float, float, str | None]:
422
+ """--abline value: INTERCEPT:SLOPE, or INTERCEPT:SLOPE:LABEL."""
423
+ a, sep, rest = value.partition(":")
424
+ b, _, label = rest.partition(":")
425
+ try:
426
+ if not sep:
427
+ raise ValueError
428
+ return float(a), float(b), (label or None)
429
+ except ValueError:
430
+ raise argparse.ArgumentTypeError(
431
+ f"expected INTERCEPT:SLOPE[:LABEL], not {value!r}"
432
+ ) from None
433
+
434
+
435
+ class _AblineAction(argparse.Action):
436
+ """--abline may be given more than once (a negative intercept needs
437
+ --abline=-1:2, one line per option); bare --abline adds y = x."""
438
+
439
+ def __call__(self, parser, namespace, values, option_string=None):
440
+ lines = list(getattr(namespace, self.dest, None) or [])
441
+ lines += values or [(0.0, 1.0, None)]
442
+ setattr(namespace, self.dest, lines)
443
+
444
+
445
+ def apply_ablines(ax: matplotlib.axes.Axes, args: argparse.Namespace) -> None:
446
+ """Draw --abline lines y = a + b*x across the whole panel, in the style of
447
+ --vline / --hline. Call after apply_limits: the line is drawn over the
448
+ final x range and leaves the limits as they are, so it never zooms the
449
+ plot out. On a log axis the line is a curve, drawn point by point."""
450
+ lines = getattr(args, "abline", None)
451
+ if not lines:
452
+ return
453
+ import numpy as np
454
+
455
+ xlim, ylim = ax.get_xlim(), ax.get_ylim()
456
+ logx = ax.get_xscale() == "log"
457
+ x = np.geomspace(*xlim, 512) if logx else np.linspace(*xlim, 512)
458
+ lo, hi = sorted(ylim)
459
+ for a, b, label in lines:
460
+ y = a + b * x
461
+ ax.plot(x, y, color=_REFLINE_COLOUR, ls="--", lw=0.9, zorder=1.5)
462
+ if label:
463
+ # at the right-most point inside the panel, along the line
464
+ inside = np.flatnonzero((y > lo) & (y < hi))
465
+ if len(inside):
466
+ i = max(inside[0], inside[-1] - 10)
467
+ ax.text(
468
+ x[i],
469
+ y[i],
470
+ f"{label} ",
471
+ ha="right",
472
+ va="bottom",
473
+ fontsize="small",
474
+ color=_REFLINE_COLOUR,
475
+ rotation=float(np.degrees(np.arctan(b))),
476
+ rotation_mode="anchor",
477
+ transform_rotates_text=True,
478
+ )
479
+ ax.set_xlim(xlim)
480
+ ax.set_ylim(ylim)
481
+
482
+
419
483
  def add_refline_arguments(
420
- parser: argparse.ArgumentParser, vertical: bool = True, horizontal: bool = True
484
+ parser: argparse.ArgumentParser,
485
+ vertical: bool = True,
486
+ horizontal: bool = True,
487
+ sloped: bool = False,
421
488
  ) -> None:
422
- """Add --vline / --hline (reference lines with optional labels)."""
489
+ """Add --vline / --hline (reference lines with optional labels), and
490
+ --abline with *sloped* (plots with a numeric x and y: scat, line)."""
423
491
  g = parser.add_argument_group("reference lines")
492
+ if sloped:
493
+ g.add_argument(
494
+ "--abline",
495
+ nargs="*",
496
+ type=abline,
497
+ action=_AblineAction,
498
+ default=None,
499
+ metavar="A:B[:LABEL]",
500
+ help="Dashed line(s) y = A + B*x (intercept, then slope, as in "
501
+ "R's abline), across the whole panel, labelled if :LABEL is "
502
+ "given. Bare --abline is the identity line y = x (0:1). A "
503
+ "negative intercept needs =: --abline=-1:2. Repeatable.",
504
+ )
424
505
  if vertical:
425
506
  g.add_argument(
426
507
  "--vline",
@@ -603,10 +684,12 @@ def add_figure_arguments(parser: argparse.ArgumentParser) -> None:
603
684
  g.add_argument("-t", "--title", default="", metavar="TEXT", help="Figure title.")
604
685
  g.add_argument(
605
686
  "--size",
606
- default=_DEFAULT_SIZE,
687
+ default=None,
607
688
  metavar="PRESET|WxH",
608
- help='Figure size: single (3.5" col), double (7.2" col), or WxH '
609
- f"in inches (default: {_DEFAULT_SIZE}).",
689
+ help='Size of the whole figure, panels included: single (3.5" '
690
+ 'journal column), double (7.2"), or WxH in inches (default: '
691
+ "a size per panel, growing with the panels up to "
692
+ f"{_MAX_SCREEN_W:g}x{_MAX_SCREEN_H:g}).",
610
693
  )
611
694
  g.add_argument(
612
695
  "--fontsize",
@@ -57,7 +57,8 @@ using a command for the first time.
57
57
  `cleannames`, which also fixes headers such as `Sample ID` or `GC %`:
58
58
  `dftk cleannames data.tsv --backend duckdb -o data.parquet`. Parquet keeps
59
59
  the types, so later steps need no option.
60
- For a column that is already float, `--cast COL:Int64` turns it back.
60
+ For a column that is already float, `--cast COL:Int64` turns it back;
61
+ `--cast COL:str` makes numbers text (e.g. cluster numbers as categories).
61
62
  `--digits N` writes such columns in exponent form (`2.49e+08`) and warns.
62
63
 
63
64
  ## Output modes (`-o`, on every data command)
@@ -88,6 +89,14 @@ right; give the file before them) / `--sort COL:a COL:d`,
88
89
  `--dropna`, `--na_rep VAL`, `--removeheader`, and
89
90
  `--meta KEY=VALUE` (provenance, see below).
90
91
 
92
+ Missing values in one column: `--dropna` drops rows with a gap in any column;
93
+ for one column filter instead, `--prequery 'a.notna()'` (before the command
94
+ runs) or `--postquery 'a.notna()'` (on the output). "2 or missing" is
95
+ `'b == 2 or b.isna()'`, or in SQL `b = 2 OR b IS NULL`: a comparison with a
96
+ missing value is false. Inequality differs: in a pandas expression `b != 3`
97
+ keeps the missing rows, in SQL `b <> 3` drops them. With `--backend duckdb`
98
+ only empty cells are missing; a column holding the text `NA` is read as text.
99
+
91
100
  Output format: TSV unless `-o FILE` ends in `.json` (array of records),
92
101
  `.jsonl`, `.md` (Markdown table) or `.tex` (bare booktabs tabular, for
93
102
  `\input` in a LaTeX table); `--format tsv|json|jsonl|md|tex` does the same
@@ -175,7 +184,9 @@ Bonferroni per panel),
175
184
  `--textcol Pval n` numbers on the right, `-g` series per row, `--section` headers;
176
185
  `fit -o | forest -y marker -x effect --ci cilo,cihi` plots coefficients). `-g COL`
177
186
  overlays groups, `--subgraphcol COL` makes panels. `scat`, `line`, `hist` take
178
- `--vline X[:LABEL]` / `--hline Y[:LABEL]` reference lines (`forest` takes `--vline`, `box` `--hline`).
187
+ `--vline X[:LABEL]` / `--hline Y[:LABEL]` reference lines (`forest` takes `--vline`, `box` `--hline`);
188
+ `scat`, `line` take `--abline A:B[:LABEL]` for y = A + B*x (bare: y = x; `--abline=-1:2` for a
189
+ negative intercept).
179
190
 
180
191
  Other: `dataset NAME` loads a bundled example table, `annotate FILE.parquet`
181
192
  reads and writes provenance metadata, `clean` removes leftover temp pipe