PyATCLI 2026.10.10__py3-none-any.whl

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 (71) hide show
  1. PyATCLI/__init__.py +196 -0
  2. PyATCLI/__main__.py +7 -0
  3. PyATCLI/_version.py +47 -0
  4. PyATCLI/analyses.py +640 -0
  5. PyATCLI/analysis/__init__.py +81 -0
  6. PyATCLI/analysis/auc.py +79 -0
  7. PyATCLI/analysis/curve_fit.py +88 -0
  8. PyATCLI/analysis/event_peth.py +263 -0
  9. PyATCLI/analysis/fft.py +99 -0
  10. PyATCLI/analysis/group/__init__.py +318 -0
  11. PyATCLI/analysis/group/rebuild.py +59 -0
  12. PyATCLI/analysis/group/report.py +281 -0
  13. PyATCLI/analysis/group/run.py +164 -0
  14. PyATCLI/analysis/group/scan.py +92 -0
  15. PyATCLI/analysis/group/stats.py +451 -0
  16. PyATCLI/analysis/group/trials.py +188 -0
  17. PyATCLI/analysis/intervals.py +59 -0
  18. PyATCLI/analysis/peak_finder.py +155 -0
  19. PyATCLI/analysis/shared.py +100 -0
  20. PyATCLI/analysis/zscore_peth.py +107 -0
  21. PyATCLI/cli/__init__.py +105 -0
  22. PyATCLI/cli/commands.py +395 -0
  23. PyATCLI/cli/docs.py +246 -0
  24. PyATCLI/cli/parser.py +286 -0
  25. PyATCLI/cli/render.py +130 -0
  26. PyATCLI/engine/__init__.py +0 -0
  27. PyATCLI/engine/contract.py +124 -0
  28. PyATCLI/engine/server.py +169 -0
  29. PyATCLI/engine/session.py +40 -0
  30. PyATCLI/engine/store.py +222 -0
  31. PyATCLI/engine/wire.py +103 -0
  32. PyATCLI/fieldstudy/__init__.py +1 -0
  33. PyATCLI/fieldstudy/study.py +440 -0
  34. PyATCLI/fieldstudy/validation.py +443 -0
  35. PyATCLI/markers.py +71 -0
  36. PyATCLI/models.py +102 -0
  37. PyATCLI/numeric.py +35 -0
  38. PyATCLI/ops/__init__.py +274 -0
  39. PyATCLI/ops/analysis.py +136 -0
  40. PyATCLI/ops/common.py +93 -0
  41. PyATCLI/ops/compute.py +94 -0
  42. PyATCLI/ops/fieldstudy.py +52 -0
  43. PyATCLI/ops/files.py +42 -0
  44. PyATCLI/ops/group.py +144 -0
  45. PyATCLI/ops/recording.py +90 -0
  46. PyATCLI/ops/records.py +63 -0
  47. PyATCLI/ops/results.py +27 -0
  48. PyATCLI/ops/saved.py +98 -0
  49. PyATCLI/ops/system.py +31 -0
  50. PyATCLI/outputs.py +165 -0
  51. PyATCLI/progress.py +227 -0
  52. PyATCLI/provenance.py +336 -0
  53. PyATCLI/recording.py +602 -0
  54. PyATCLI/reproduce.py +278 -0
  55. PyATCLI/results.py +106 -0
  56. PyATCLI/saved_state.py +275 -0
  57. PyATCLI/sources/__init__.py +1 -0
  58. PyATCLI/sources/dataset.py +110 -0
  59. PyATCLI/sources/load.py +169 -0
  60. PyATCLI/sources/processing_TDT.py +810 -0
  61. PyATCLI/sources/processing_oxysoft.py +259 -0
  62. PyATCLI/sources/pt2.py +46 -0
  63. PyATCLI/sources/tables.py +306 -0
  64. PyATCLI/splice.py +196 -0
  65. PyATCLI/viewplan.py +181 -0
  66. pyatcli-2026.10.10.dist-info/METADATA +296 -0
  67. pyatcli-2026.10.10.dist-info/RECORD +71 -0
  68. pyatcli-2026.10.10.dist-info/WHEEL +5 -0
  69. pyatcli-2026.10.10.dist-info/entry_points.txt +2 -0
  70. pyatcli-2026.10.10.dist-info/licenses/LICENSE +661 -0
  71. pyatcli-2026.10.10.dist-info/top_level.txt +1 -0
@@ -0,0 +1,395 @@
1
+ """
2
+ cli/commands.py
3
+ ---------------
4
+ One function per command: it turns the arguments into an operation's parameters (ops/), calls the operation, and has the result shown
5
+ (render.py). No analysis, file or figure logic lives here — that is in the operations, which the engine calls too.
6
+ """
7
+
8
+ import json
9
+ import sys
10
+
11
+ from .. import ops
12
+ from ..analyses import ParameterError
13
+ from ..ops import OpContext, OpError
14
+ from ..ops.common import recording_name # noqa: F401 — also this module's public name (cli/__init__.py)
15
+ from ..progress import coerce
16
+
17
+ EXIT_OK, EXIT_ERROR, EXIT_USAGE, EXIT_MISMATCH = 0, 1, 2, 3
18
+ APP = {"name": "PyATCLI command line"}
19
+
20
+
21
+ # ---------------------------------------------------------------------------
22
+ # helpers
23
+ # ---------------------------------------------------------------------------
24
+
25
+ def parse_value(text):
26
+ """A command-line value: JSON if it is JSON (10, 2.5, true, [1, 2]), otherwise the text itself."""
27
+ try:
28
+ return json.loads(text)
29
+ except ValueError:
30
+ return text
31
+
32
+
33
+ def read_json(path):
34
+ """A JSON document from a file — or from standard input when `path` is "-"."""
35
+ if path == "-":
36
+ return json.load(sys.stdin)
37
+ with open(path, "r", encoding="utf-8") as f:
38
+ return json.load(f)
39
+
40
+
41
+ def collect_parameters(param_args, params_file=None):
42
+ """{name: value} from an optional JSON file ("-" is stdin) and then each K=V argument (which wins)."""
43
+ out = {}
44
+ if params_file:
45
+ loaded = read_json(params_file)
46
+ out.update(loaded.get("parameters", loaded) if isinstance(loaded, dict) else {})
47
+ for item in param_args or []:
48
+ if "=" not in item:
49
+ raise ParameterError(f"--param expects NAME=VALUE, got {item!r}")
50
+ k, v = item.split("=", 1)
51
+ out[k.strip()] = parse_value(v)
52
+ return out
53
+
54
+
55
+ def pair(text, what):
56
+ """(left, right) from "LEFT=RIGHT"."""
57
+ left, sep, right = text.partition("=")
58
+ if not sep or not left:
59
+ raise ValueError(what)
60
+ return left, right
61
+
62
+
63
+ def name_pair(text):
64
+ return pair(text, f"a rename is KEY=NAME (the signal's key, and what to call it; NAME empty to take the rename away), not {text!r}")
65
+
66
+
67
+ def load_from_flags(args):
68
+ """The `load` parameter of an operation from the load flags (--regression, --no-saved, --table, --x, --y)."""
69
+ load = {}
70
+ if getattr(args, "regression", None):
71
+ load["regression_method"] = args.regression
72
+ if getattr(args, "no_saved", False):
73
+ load["use_saved"] = False
74
+ if getattr(args, "table", None):
75
+ load["table"] = args.table
76
+ if getattr(args, "x", None):
77
+ load["x_column"] = args.x
78
+ if getattr(args, "y", None):
79
+ load["y_columns"] = args.y
80
+ return load
81
+
82
+
83
+ def make_context(args, out):
84
+ """The OpContext for a run: what the operation reports goes to the person (a progress bar when stderr is a terminal, --progress to
85
+ force it, --events for JSON lines), never into the result."""
86
+ events = bool(getattr(args, "events", False))
87
+ mode = getattr(args, "progress", None)
88
+ bar = not events and not out.quiet and (mode is True or (mode is None and _is_tty(out.stderr)))
89
+ state = {"sink": None}
90
+
91
+ def emit(event, **fields):
92
+ if events:
93
+ out.event(event, **fields)
94
+ if event == "progress" and bar:
95
+ if state["sink"] is None:
96
+ state["sink"] = coerce(True)
97
+ state["sink"](fields["fraction"], fields.get("message", ""))
98
+ if fields["fraction"] >= 1.0:
99
+ state["sink"] = None
100
+ elif event == "warning":
101
+ if events:
102
+ out.warnings.append(fields["text"])
103
+ else:
104
+ out.warn(fields["text"])
105
+ elif event == "note" and not events:
106
+ out.say(fields["text"])
107
+
108
+ return OpContext(emit=emit, wants_progress=events or bar, app=APP)
109
+
110
+
111
+ def _is_tty(stream):
112
+ try:
113
+ return stream.isatty()
114
+ except (AttributeError, ValueError):
115
+ return False
116
+
117
+
118
+ def call(args, out, name, params):
119
+ """Runs operation `name` for a command and returns its result (errors propagate to main, which shows them)."""
120
+ return ops.call(name, params, make_context(args, out))
121
+
122
+
123
+
124
+ def _tables_lines(out, tables):
125
+ """What tables a result has: a line each in human mode, rows in --plain."""
126
+ if out.plain:
127
+ out.table([], [[name, t["rows"], len(t["columns"])] for name, t in tables.items()])
128
+ for name, t in tables.items():
129
+ out.say(f" {name}: {t['rows']} rows x {len(t['columns'])} columns")
130
+
131
+
132
+ def _out_dir(args, default):
133
+ """The folder `--out` names (or `default`) — or None when `--output-folder` is given instead (each recording's results then go in its
134
+ own folder under it)."""
135
+ return None if args.output_folder else (args.out or default)
136
+
137
+
138
+ # ---------------------------------------------------------------------------
139
+ # info, kinds
140
+ # ---------------------------------------------------------------------------
141
+
142
+ def cmd_info(args, out):
143
+ result = call(args, out, "info", {})
144
+ if out.plain:
145
+ out.table([], [["library", result["library"]], ["python", result["python"]], ["platform", result["platform"]]]
146
+ + [[name, v] for name, v in result["packages"].items()])
147
+ else:
148
+ out.say(f"PyATCLI {result['library']}")
149
+ out.say(f"Python {result['python']} ({result['implementation']}, {result['bits']}-bit) on {result['platform']}")
150
+ for name, v in result["packages"].items():
151
+ out.say(f" {name} {v}")
152
+ out.result("info", result)
153
+ return EXIT_OK
154
+
155
+
156
+ def cmd_serve(args, out):
157
+ """`serve` is routed before argument parsing (cli.main); this is only here so that parsing it by itself does the same."""
158
+ from ..engine.server import main as serve_main
159
+
160
+ argv = ["--app-name", args.app_name]
161
+ argv += ["--data-dir", args.data_dir] if args.data_dir else []
162
+ argv += ["--app-version", args.app_version] if args.app_version else []
163
+ return serve_main(argv + (["--verbose"] if out.verbose else []))
164
+
165
+
166
+ def cmd_docs(args, out):
167
+ from . import docs
168
+
169
+ text = docs.FORMATS[args.format]()
170
+ if args.out and args.out != "-":
171
+ with open(args.out, "w", encoding="utf-8", newline=chr(10)) as f:
172
+ f.write(text if text.endswith(chr(10)) else text + chr(10))
173
+ out.files([args.out])
174
+ out.result("docs", {"format": args.format, "file": args.out})
175
+ elif out.json:
176
+ out.result("docs", {"format": args.format, "text": text})
177
+ else:
178
+ print(text, file=out.stdout)
179
+ return EXIT_OK
180
+
181
+
182
+ def cmd_kinds(args, out):
183
+ result = call(args, out, "kinds", {"kind": args.kind})
184
+ if out.plain:
185
+ out.table([], [[k, p["name"], p["type"], "required" if p["required"] else p["default"], p["doc"]]
186
+ for k, a in result["analyses"].items() for p in a["parameters"]])
187
+ else:
188
+ for k, a in result["analyses"].items():
189
+ out.say(f"{k}\n {a['summary']}")
190
+ for p in a["parameters"]:
191
+ default = "required" if p["required"] else f"default {p['default']!r}"
192
+ choices = f" one of {', '.join(p['choices'])};" if p["choices"] else ""
193
+ out.say(f" {p['name']:<16} {p['type']:<8}{choices} {default}. {p['doc']}")
194
+ if "group_analysis" in result:
195
+ out.say(f"\n{result['group_analysis']['kind']}\n {result['group_analysis']['summary']}")
196
+ out.result("kinds", result)
197
+ return EXIT_OK
198
+
199
+
200
+ # ---------------------------------------------------------------------------
201
+ # run, reproduce, batch
202
+ # ---------------------------------------------------------------------------
203
+
204
+ def cmd_run(args, out):
205
+ parameters = collect_parameters(args.param, args.params)
206
+ result = call(args, out, "run", {"kind": args.kind, "recording": args.recording, "parameters": parameters, "load": load_from_flags(args),
207
+ "out": _out_dir(args, "pyatcli-output"), "output_folder": args.output_folder})
208
+ out.say(f"{args.kind} on {recording_name(args.recording)}")
209
+ _tables_lines(out, result["tables"])
210
+ for n in result["notes"]:
211
+ out.say(f" note: {n}")
212
+ out.files(result["files"], result["directory"])
213
+ out.result("run", result)
214
+ return EXIT_OK
215
+
216
+
217
+ def cmd_reproduce(args, out):
218
+ rounded = True if args.rounded else (False if args.exact else None)
219
+ record = read_json("-") if args.record == "-" else args.record
220
+ result = call(args, out, "reproduce", {"record": record, "recording": args.recording, "out": args.out, "compare": args.compare or [],
221
+ "tolerance": args.tolerance, "strict": args.strict, "rounded": rounded})
222
+ _tables_lines(out, result["tables"])
223
+ rows = []
224
+ for c in result["comparisons"]:
225
+ verdict = "MATCH" if c["ok"] else "MISMATCH"
226
+ detail = c["message"] + (f" (largest difference {c['max_abs_diff']:.3g} over {c['cells']} cells)" if c["ok"] else "")
227
+ rows.append([verdict, c["file"], c.get("table", "?"), detail])
228
+ out.say(f"{'MATCH ' if c['ok'] else 'MISMATCH'} {c['file']} vs {c.get('table', '?')}: {detail}")
229
+ if out.plain:
230
+ out.table([], rows)
231
+ out.files(result["files"], args.out)
232
+ out.result("reproduce", result)
233
+ return EXIT_OK if result["ok"] else EXIT_MISMATCH
234
+
235
+
236
+ def cmd_batch(args, out):
237
+ jobs = read_json("-") if args.jobs == "-" else args.jobs
238
+ result = call(args, out, "batch", {"jobs": jobs, "out": None if args.output_folder else (args.out or "pyatcli-batch"),
239
+ "output_folder": args.output_folder, "load": load_from_flags(args)})
240
+ for f in result["failed"]:
241
+ out.error(f"job {f['job']} ({f['kind']}) on {f['recording']}: {f['error']}")
242
+ out.result("batch", result)
243
+ return EXIT_OK if result["ok"] else EXIT_ERROR
244
+
245
+
246
+ # ---------------------------------------------------------------------------
247
+ # groups
248
+ # ---------------------------------------------------------------------------
249
+
250
+ def cmd_group_run(args, out):
251
+ result = call(args, out, "group.run", {"settings": args.settings, "out": args.out, "output_folder": args.output_folder})
252
+ out.say(f"group analysis {result['name']!r}: {result['tables']} tables")
253
+ for n in result["notes"]:
254
+ out.say(f" note: {n}")
255
+ if result["directory"]:
256
+ out.say(f"wrote {len(result['files'])} files to {result['directory']}")
257
+ out.result("group.run", result)
258
+ return EXIT_OK
259
+
260
+
261
+ def cmd_group_setup(args, out):
262
+ result = call(args, out, "group.setup", {
263
+ "folders": args.folders, "name": args.name, "markers": args.marker, "exclude": args.exclude,
264
+ "store_labels": dict(name_pair(t) for t in args.store_label), "pre": args.pre, "post": args.post, "baseline": list(args.baseline),
265
+ "response": list(args.response), "signal": args.signal, "smooth": args.smooth, "measures": args.measure,
266
+ "peak_direction": args.peak_direction, "decay_fraction": args.decay_fraction, "correction": args.correction, "alpha": args.alpha,
267
+ "regression": args.regression, "out": args.out, "output_folder": args.output_folder, "run": args.run})
268
+ if result["stage"] == "markers":
269
+ out.say(f"{len(result['recordings'])} recordings under {result['base']}; the markers they have:")
270
+ n = len(result["recordings"])
271
+ out.table(["marker (* = in every one)", "recordings", "events"],
272
+ [[("* " if m["shared"] else " ") + m["name"], f"{m['recordings']} of {n}", m["events"]] for m in result["markers"]])
273
+ out.result("group.setup", result)
274
+ out.error("say which markers to compare with --marker NAME (repeat it for each)")
275
+ return EXIT_USAGE
276
+ for w in result["design_warnings"]:
277
+ out.say(f"{w['level']}: {w['text']}")
278
+ out.say(f"settings for {result['subjects']} recordings and {len(result['marker_names'])} markers saved: {result['settings']}")
279
+ if result["ran"]:
280
+ for n in result["run"]["notes"]:
281
+ out.say(f" note: {n}")
282
+ out.say(f"wrote {len(result['run']['files'])} files to {result['directory']}")
283
+ else:
284
+ out.say(f"run it with: python -m PyATCLI group run \"{result['directory']}\"")
285
+ out.result("group.setup", result)
286
+ return EXIT_OK
287
+
288
+
289
+ # ---------------------------------------------------------------------------
290
+ # saved
291
+ # ---------------------------------------------------------------------------
292
+
293
+ def cmd_saved_show(args, out):
294
+ result = call(args, out, "saved.show", {"recording": args.recording})
295
+ kinds_saved = ("markers", "splices", "signal_labels", "highlights", "text_annotations")
296
+ out.say(f"saved state of {result['name']} ({result['folder']})")
297
+ if not any(result[k] for k in kinds_saved):
298
+ out.say(" nothing saved")
299
+ rows = []
300
+ for m in result["markers"]:
301
+ rows.append(["marker", f"{m['time']:.3f}", m.get("label", ""), m.get("color", "")])
302
+ out.say(f" marker {m['time']:.3f} s {m.get('label', '')} ({m.get('color', '')})")
303
+ for i, s in enumerate(result["splices"], 1):
304
+ rows.append(["splice", i, s["mode"], f"{s['start']:.3f}..{s['end']:.3f}"])
305
+ out.say(f" splice {i} {s['mode']} {s['start']:.3f}..{s['end']:.3f} s")
306
+ for key, name in result["signal_labels"].items():
307
+ rows.append(["signal_name", key, name, ""])
308
+ out.say(f" signal name {key} -> {name}")
309
+ for h in result["highlights"]:
310
+ rows.append(["highlight", f"{h['start']:.3f}..{h['end']:.3f}", h["color"], ""])
311
+ out.say(f" highlight {h['start']:.3f}..{h['end']:.3f} s {h['color']}")
312
+ for t in result["text_annotations"]:
313
+ rows.append(["text", f"{t['x']:.3f}", f"{t['y']:g}", t["text"]])
314
+ out.say(f" text ({t['x']:.3f} s, {t['y']:g}) {t['text']}")
315
+ if out.plain:
316
+ out.table([], rows)
317
+ out.result("saved.show", result)
318
+ return EXIT_OK
319
+
320
+
321
+ def cmd_saved_marker(args, out):
322
+ result = call(args, out, "saved.marker", {"recording": args.recording, "time": args.time, "label": args.label, "color": args.color,
323
+ "fontsize": args.fontsize, "load": load_from_flags(args)})
324
+ m = result["marker"]
325
+ out.say(f"marker {m['label']!r} saved at {m['time']:.3f} s")
326
+ out.result("saved.marker", result)
327
+ return EXIT_OK
328
+
329
+
330
+ def cmd_saved_unmark(args, out):
331
+ result = call(args, out, "saved.unmark", {"recording": args.recording, "time": args.time, "tolerance": args.tolerance,
332
+ "label": args.label, "load": load_from_flags(args)})
333
+ if not result["removed"]:
334
+ out.error(f"no saved marker within {args.tolerance:g} s of {args.time:g} s" + (f" named {args.label!r}" if args.label else ""))
335
+ return EXIT_ERROR
336
+ n = len(result["removed"])
337
+ out.say(f"removed {n} marker{'s' if n != 1 else ''}")
338
+ out.result("saved.unmark", result)
339
+ return EXIT_OK
340
+
341
+
342
+ def cmd_saved_splice(args, out):
343
+ result = call(args, out, "saved.splice", {"recording": args.recording, "mode": args.mode, "start": args.start, "end": args.end,
344
+ "load": load_from_flags(args)})
345
+ out.say(f"splice saved ({len(result['splices'])} stacked): {args.mode} {args.start:g}..{args.end:g} s")
346
+ out.result("saved.splice", result)
347
+ return EXIT_OK
348
+
349
+
350
+ def cmd_saved_unsplice(args, out):
351
+ result = call(args, out, "saved.unsplice", {"recording": args.recording, "number": args.number})
352
+ out.say(f"splice {args.number} removed ({len(result['splices'])} left)")
353
+ out.result("saved.unsplice", result)
354
+ return EXIT_OK
355
+
356
+
357
+ def cmd_saved_rename(args, out):
358
+ result = call(args, out, "saved.rename", {"recording": args.recording, "names": dict(name_pair(t) for t in args.names),
359
+ "load": load_from_flags(args)})
360
+ n = len(result["names"])
361
+ out.say(f"{n} signal name{'s' if n != 1 else ''} saved")
362
+ out.result("saved.rename", result)
363
+ return EXIT_OK
364
+
365
+
366
+ def cmd_saved_highlight(args, out):
367
+ result = call(args, out, "saved.highlight", {"recording": args.recording, "start": args.start, "end": args.end, "color": args.color})
368
+ out.say(f"highlight saved: {result['highlight']['start']:g}..{result['highlight']['end']:g} s")
369
+ out.result("saved.highlight", result)
370
+ return EXIT_OK
371
+
372
+
373
+ def cmd_saved_text(args, out):
374
+ result = call(args, out, "saved.text", {"recording": args.recording, "x": args.x, "y": args.y, "text": args.text, "fontsize": args.fontsize})
375
+ t = result["text"]
376
+ out.say(f"text box saved at ({t['x']:g} s, {t['y']:g})")
377
+ out.result("saved.text", result)
378
+ return EXIT_OK
379
+
380
+
381
+ def cmd_saved_clear(args, out):
382
+ params = {"recording": args.recording, "yes": args.yes}
383
+ try:
384
+ result = call(args, out, "saved.clear", params)
385
+ except OpError as e:
386
+ if e.code != "confirmation_required":
387
+ raise
388
+ if not out.confirm(f"{e}. Delete them?"):
389
+ out.error(str(e), "say --yes to do it")
390
+ return EXIT_USAGE
391
+ result = call(args, out, "saved.clear", {**params, "yes": True})
392
+ n = len(result["removed"])
393
+ out.say(f"removed {n} file{'s' if n != 1 else ''}" + (": " + ", ".join(result["removed"]) if result["removed"] else ""))
394
+ out.result("saved.clear", result)
395
+ return EXIT_OK
PyATCLI/cli/docs.py ADDED
@@ -0,0 +1,246 @@
1
+ """
2
+ cli/docs.py
3
+ -----------
4
+ The command line's reference documentation, generated from the parser itself so it cannot drift from what the program accepts:
5
+
6
+ python -m PyATCLI docs --format markdown the web reference (CLI_REFERENCE.md in the repository)
7
+ python -m PyATCLI docs --format man the manual page (pyatcli.1; `man ./pyatcli.1`)
8
+ python -m PyATCLI docs --format contract what a program using the engine can count on (ENGINE_CONTRACT.json; engine/contract.py)
9
+
10
+ Both walk the argparse tree — every command and subcommand, its arguments and options with their help text, its examples — and add the
11
+ parts that are the same for every command (the global options, the exit status, the environment variables, the engine's protocol).
12
+ `tests/test_cli_docs.py` regenerates both and compares them with the files committed beside the code, so a changed flag fails the tests
13
+ until the documents are regenerated (`python -m PyATCLI docs --format markdown --out CLI_REFERENCE.md`).
14
+ """
15
+
16
+ import argparse
17
+ import re
18
+
19
+ from .. import provenance
20
+ from .parser import PROG, build_parser
21
+
22
+ EXIT_STATUS = [
23
+ ("0", "done"),
24
+ ("1", "something failed; the message is on standard error (with `--json`, a JSON error record: code, message, hint)"),
25
+ ("2", "bad usage: an unknown flag, a missing argument, an action that needs a yes and was not given one"),
26
+ ("3", "`reproduce` ran, but an export did not match the result"),
27
+ ("130", "interrupted (Ctrl-C)"),
28
+ ]
29
+
30
+ ENVIRONMENT = [
31
+ ("DEBUG", "set to anything but 0/false/no/off: the same as `--debug` (a bug's full traceback)"),
32
+ ("NO_COLOR", "accepted and unused: the command line never uses colour"),
33
+ ]
34
+
35
+ ENGINE = (
36
+ "`serve` runs the same operations as the other commands as a long-lived process, speaking one JSON object per line on standard input and "
37
+ "output, and keeps recordings open between requests; it is what PyAT's window talks to. A request is "
38
+ '`{"id": 7, "method": "recording.open", "params": {"path": "D:/rats/Rat7"}}`; it answers with `progress` events and one `result` or `error` '
39
+ '(`{"id": 7, "event": "result", "ok": true, "result": {...}}`); `{"cancel": 7}` stops a request at its next progress report and '
40
+ '`{"method": "shutdown"}` ends the process. Large arrays are never sent through the pipe: they are written as `.npy` files in the engine\'s '
41
+ "data folder and named in the result. The protocol is described at the top of `PyATCLI/engine/server.py`."
42
+ )
43
+
44
+
45
+ # ---------------------------------------------------------------------------
46
+ # Walking the parser
47
+ # ---------------------------------------------------------------------------
48
+
49
+ class Node:
50
+ """One command: its name ("group setup"), help, usage line, the arguments it takes, its options, its examples and its subcommands."""
51
+
52
+ def __init__(self, parser, name, summary=""):
53
+ self.name = name
54
+ self.summary = summary
55
+ self.parser = parser
56
+ self.description = (parser.description or "").strip()
57
+ self.epilog = (parser.epilog or "").strip()
58
+ self.arguments, self.options, self.children = [], [], []
59
+ formatter = parser._get_formatter()
60
+ for action in parser._actions:
61
+ if isinstance(action, argparse._SubParsersAction):
62
+ for child_name, child in action.choices.items():
63
+ helps = {a.dest: a.help for a in action._choices_actions}
64
+ self.children.append(Node(child, f"{name} {child_name}".strip(), helps.get(child_name) or ""))
65
+ continue
66
+ if isinstance(action, (argparse._HelpAction, argparse._VersionAction)) or action.help == argparse.SUPPRESS:
67
+ continue
68
+ row = (action, formatter._expand_help(action) if action.help else "")
69
+ (self.options if action.option_strings else self.arguments).append(row)
70
+
71
+ def usage(self):
72
+ """`python -m PyATCLI run [options] kind recording`: the arguments in order, the options as one word."""
73
+ if self.children:
74
+ return f"{PROG} {self.name} <{'|'.join(c.name.split()[-1] for c in self.children)}> [options]"
75
+ parts = [PROG, self.name, "[options]"] if self.name else [PROG, "<command>", "[options]"]
76
+ for action, _ in self.arguments:
77
+ label = _argument_label(action)
78
+ if action.nargs == "?":
79
+ parts.append(f"[{label}]")
80
+ elif action.nargs == "*":
81
+ parts.append(f"[{label} ...]")
82
+ elif action.nargs == "+":
83
+ parts.append(f"{label} ...")
84
+ else:
85
+ parts.append(label)
86
+ return " ".join(parts)
87
+
88
+ def is_global(self, action):
89
+ return any(s in ("--json", "--plain", "--quiet", "--verbose", "--debug", "--no-input", "--events", "--progress", "--no-progress")
90
+ for s in action.option_strings)
91
+
92
+ def own_options(self):
93
+ return [(a, h) for a, h in self.options if not self.is_global(a)]
94
+
95
+ def walk(self):
96
+ yield self
97
+ for child in self.children:
98
+ yield from child.walk()
99
+
100
+
101
+ def tree():
102
+ top = Node(build_parser(), "")
103
+ return top
104
+
105
+
106
+ def _option_label(action):
107
+ names = ", ".join(action.option_strings)
108
+ if action.nargs == 0 or isinstance(action, (argparse._StoreTrueAction, argparse._StoreFalseAction, argparse._CountAction)):
109
+ return names
110
+ metavar = action.metavar or action.dest.upper()
111
+ if isinstance(metavar, tuple):
112
+ metavar = " ".join(metavar)
113
+ if action.nargs in ("+", "*"):
114
+ metavar += " ..."
115
+ return f"{names} {metavar}"
116
+
117
+
118
+ def _argument_label(action):
119
+ return action.metavar or action.dest
120
+
121
+
122
+ def _examples(node):
123
+ """The commands in a node's epilog, one per line, without the leading prose and the common indentation."""
124
+ lines = []
125
+ for line in node.epilog.splitlines():
126
+ if line.strip().startswith(("examples:", "exit status", "Standard output", "Environment")):
127
+ continue
128
+ if line.strip():
129
+ lines.append(line.rstrip())
130
+ margin = min((len(l) - len(l.lstrip()) for l in lines), default=0)
131
+ return [l[margin:] for l in lines]
132
+
133
+
134
+ ORDER = ["run", "reproduce", "batch", "group", "saved", "kinds", "info", "serve", "docs"]
135
+
136
+
137
+ def _commands_of(node):
138
+ """Every command and subcommand, the top-level ones in the order --help lists them."""
139
+ ranked = sorted(node.children, key=lambda c: ORDER.index(c.name) if c.name in ORDER else len(ORDER))
140
+ out = []
141
+ for child in ranked:
142
+ out += [n for n in child.walk() if n.name]
143
+ return out
144
+
145
+
146
+ # ---------------------------------------------------------------------------
147
+ # Markdown
148
+ # ---------------------------------------------------------------------------
149
+
150
+ def _md_escape(text):
151
+ return text.replace("|", "\\|")
152
+
153
+
154
+ def markdown():
155
+ top = tree()
156
+ out = ["# PyATCLI command line", "", f"`{PROG}` (or `pyatcli`) — version {provenance.library_version()}.", "",
157
+ "This page is generated from the program (`python -m PyATCLI docs --format markdown`); the same text is in `--help`.", ""]
158
+ out += ["## Commands", ""]
159
+ for n in _commands_of(top):
160
+ if " " not in n.name:
161
+ out.append(f"- [`{n.name}`](#{n.name}) — {n.summary}")
162
+ out += ["", "## Options every command takes", "", "Before or after the command name:", ""]
163
+ for action, help_text in top.options:
164
+ if top.is_global(action):
165
+ out.append(f"- `{_option_label(action)}` — {help_text}")
166
+ out += ["", "`--version`, `-V` print the version; `--help`, `-h` print a command's options and examples.", ""]
167
+ for n in _commands_of(top):
168
+ level = "##" if " " not in n.name else "###"
169
+ out += [f"{level} {n.name}", "", n.description or n.summary, "", "```", n.usage(), "```", ""]
170
+ if n.arguments:
171
+ out += ["| argument | |", "|---|---|"]
172
+ out += [f"| `{_argument_label(a)}` | {_md_escape(h)} |" for a, h in n.arguments]
173
+ out.append("")
174
+ own = n.own_options()
175
+ if own:
176
+ out += ["| option | |", "|---|---|"]
177
+ out += [f"| `{_option_label(a)}` | {_md_escape(h)} |" for a, h in own]
178
+ out.append("")
179
+ examples = _examples(n)
180
+ if examples:
181
+ out += ["Examples:", "", "```bash"] + examples + ["```", ""]
182
+ out += ["## Exit status", ""] + [f"- `{code}` — {text}" for code, text in EXIT_STATUS] + [""]
183
+ out += ["## Environment", ""] + [f"- `{name}` — {text}" for name, text in ENVIRONMENT] + [""]
184
+ out += ["## The engine", "", ENGINE, ""]
185
+ return "\n".join(out)
186
+
187
+
188
+ # ---------------------------------------------------------------------------
189
+ # roff (man page)
190
+ # ---------------------------------------------------------------------------
191
+
192
+ def _roff(text):
193
+ """Text as roff: backslashes and a leading dot or apostrophe made safe, markdown backticks dropped."""
194
+ text = text.replace("`", "")
195
+ text = text.replace("\\", "\\e").replace("-", "\\-")
196
+ return re.sub(r"(?m)^([.'])", r"\\&\1", text)
197
+
198
+
199
+ def man():
200
+ top = tree()
201
+ version = provenance.library_version()
202
+ out = [f'.TH PYATCLI 1 "" "PyATCLI {version}" "PyATCLI"',
203
+ ".SH NAME", "pyatcli \\- analyse fibre-photometry, NIRS and tabular recordings from a script or the shell",
204
+ ".SH SYNOPSIS", ".B pyatcli", ".I command", ".RI [ options ]", ".br", ".B python \\-m PyATCLI", ".I command", ".RI [ options ]",
205
+ ".SH DESCRIPTION",
206
+ _roff("Runs the analyses of PyAT (Python Analysis Tool) on a recording without the app, writes their tables and a provenance record, "
207
+ "and runs an analysis again from its record to check the numbers. Standard output is only ever the result (--json for a program, "
208
+ "--plain for tab-separated rows); warnings, errors and progress go to standard error."),
209
+ ".SH COMMANDS"]
210
+ for n in _commands_of(top):
211
+ out += [".TP", f".B {_roff(n.name)}", _roff(n.summary or n.description)]
212
+ out += [".SH GLOBAL OPTIONS", _roff("Accepted before or after the command name.")]
213
+ for action, help_text in top.options:
214
+ if top.is_global(action):
215
+ out += [".TP", f".B {_roff(_option_label(action))}", _roff(help_text)]
216
+ for n in _commands_of(top):
217
+ out += [f".SH {_roff(n.name.upper())}", _roff(n.description or n.summary), ".PP", ".B " + _roff(n.usage())]
218
+ for a, h in n.arguments:
219
+ out += [".TP", f".I {_roff(_argument_label(a))}", _roff(h)]
220
+ for a, h in n.own_options():
221
+ out += [".TP", f".B {_roff(_option_label(a))}", _roff(h)]
222
+ examples = _examples(n)
223
+ if examples:
224
+ out += [".PP", "Examples:", ".nf"] + [_roff(line) for line in examples] + [".fi"]
225
+ out += [".SH EXIT STATUS"]
226
+ for code, text in EXIT_STATUS:
227
+ out += [".TP", f".B {code}", _roff(text)]
228
+ out += [".SH ENVIRONMENT"]
229
+ for name, text in ENVIRONMENT:
230
+ out += [".TP", f".B {name}", _roff(text)]
231
+ out += [".SH THE ENGINE", _roff(ENGINE),
232
+ ".SH SEE ALSO", _roff("API_REFERENCE.md and CLI_REFERENCE.md in the repository; https://github.com/zakgm2/PyATCLI"),
233
+ ""]
234
+ return "\n".join(out)
235
+
236
+
237
+ def contract():
238
+ """What a program that talks to the engine can count on (ENGINE_CONTRACT.json in the repository): see engine/contract.py."""
239
+ import json
240
+
241
+ from ..engine import contract as engine_contract
242
+
243
+ return json.dumps(engine_contract.build(), indent=2, ensure_ascii=False) + "\n"
244
+
245
+
246
+ FORMATS = {"markdown": markdown, "man": man, "contract": contract}