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.
- PyATCLI/__init__.py +196 -0
- PyATCLI/__main__.py +7 -0
- PyATCLI/_version.py +47 -0
- PyATCLI/analyses.py +640 -0
- PyATCLI/analysis/__init__.py +81 -0
- PyATCLI/analysis/auc.py +79 -0
- PyATCLI/analysis/curve_fit.py +88 -0
- PyATCLI/analysis/event_peth.py +263 -0
- PyATCLI/analysis/fft.py +99 -0
- PyATCLI/analysis/group/__init__.py +318 -0
- PyATCLI/analysis/group/rebuild.py +59 -0
- PyATCLI/analysis/group/report.py +281 -0
- PyATCLI/analysis/group/run.py +164 -0
- PyATCLI/analysis/group/scan.py +92 -0
- PyATCLI/analysis/group/stats.py +451 -0
- PyATCLI/analysis/group/trials.py +188 -0
- PyATCLI/analysis/intervals.py +59 -0
- PyATCLI/analysis/peak_finder.py +155 -0
- PyATCLI/analysis/shared.py +100 -0
- PyATCLI/analysis/zscore_peth.py +107 -0
- PyATCLI/cli/__init__.py +105 -0
- PyATCLI/cli/commands.py +395 -0
- PyATCLI/cli/docs.py +246 -0
- PyATCLI/cli/parser.py +286 -0
- PyATCLI/cli/render.py +130 -0
- PyATCLI/engine/__init__.py +0 -0
- PyATCLI/engine/contract.py +124 -0
- PyATCLI/engine/server.py +169 -0
- PyATCLI/engine/session.py +40 -0
- PyATCLI/engine/store.py +222 -0
- PyATCLI/engine/wire.py +103 -0
- PyATCLI/fieldstudy/__init__.py +1 -0
- PyATCLI/fieldstudy/study.py +440 -0
- PyATCLI/fieldstudy/validation.py +443 -0
- PyATCLI/markers.py +71 -0
- PyATCLI/models.py +102 -0
- PyATCLI/numeric.py +35 -0
- PyATCLI/ops/__init__.py +274 -0
- PyATCLI/ops/analysis.py +136 -0
- PyATCLI/ops/common.py +93 -0
- PyATCLI/ops/compute.py +94 -0
- PyATCLI/ops/fieldstudy.py +52 -0
- PyATCLI/ops/files.py +42 -0
- PyATCLI/ops/group.py +144 -0
- PyATCLI/ops/recording.py +90 -0
- PyATCLI/ops/records.py +63 -0
- PyATCLI/ops/results.py +27 -0
- PyATCLI/ops/saved.py +98 -0
- PyATCLI/ops/system.py +31 -0
- PyATCLI/outputs.py +165 -0
- PyATCLI/progress.py +227 -0
- PyATCLI/provenance.py +336 -0
- PyATCLI/recording.py +602 -0
- PyATCLI/reproduce.py +278 -0
- PyATCLI/results.py +106 -0
- PyATCLI/saved_state.py +275 -0
- PyATCLI/sources/__init__.py +1 -0
- PyATCLI/sources/dataset.py +110 -0
- PyATCLI/sources/load.py +169 -0
- PyATCLI/sources/processing_TDT.py +810 -0
- PyATCLI/sources/processing_oxysoft.py +259 -0
- PyATCLI/sources/pt2.py +46 -0
- PyATCLI/sources/tables.py +306 -0
- PyATCLI/splice.py +196 -0
- PyATCLI/viewplan.py +181 -0
- pyatcli-2026.10.10.dist-info/METADATA +296 -0
- pyatcli-2026.10.10.dist-info/RECORD +71 -0
- pyatcli-2026.10.10.dist-info/WHEEL +5 -0
- pyatcli-2026.10.10.dist-info/entry_points.txt +2 -0
- pyatcli-2026.10.10.dist-info/licenses/LICENSE +661 -0
- pyatcli-2026.10.10.dist-info/top_level.txt +1 -0
PyATCLI/cli/parser.py
ADDED
|
@@ -0,0 +1,286 @@
|
|
|
1
|
+
"""
|
|
2
|
+
cli/parser.py
|
|
3
|
+
-------------
|
|
4
|
+
The argument parser: every command, its flags, its help and its examples.
|
|
5
|
+
|
|
6
|
+
Every command takes the same global flags — `--json`, `--plain`, `-q/--quiet`, `-v/--verbose`, `-d/--debug`, `--no-input`, `--events`,
|
|
7
|
+
`--progress/--no-progress` — before or after the command name, so they can be given wherever they come to mind.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import argparse
|
|
11
|
+
|
|
12
|
+
from .. import provenance, saved_state
|
|
13
|
+
from ..analyses import kinds
|
|
14
|
+
from ..analysis import group as group_design
|
|
15
|
+
from ..sources.processing_TDT import REGRESSION_METHODS
|
|
16
|
+
from . import commands as C
|
|
17
|
+
|
|
18
|
+
PROG = "python -m PyATCLI"
|
|
19
|
+
|
|
20
|
+
CONCISE = """\
|
|
21
|
+
PyATCLI {version} — analyse fibre-photometry, NIRS and tabular recordings from a script or the shell.
|
|
22
|
+
|
|
23
|
+
usage: {prog} <command> [options]
|
|
24
|
+
|
|
25
|
+
commands:
|
|
26
|
+
run run one analysis on a recording
|
|
27
|
+
reproduce run an analysis again from its provenance record and check the numbers
|
|
28
|
+
batch many analyses over many recordings
|
|
29
|
+
group group analysis: `group setup` (the wizard), `group run`
|
|
30
|
+
saved what the app's Save Changes saves: markers, splices, signal names, highlights, text
|
|
31
|
+
kinds the analyses and every parameter of each
|
|
32
|
+
info versions of this library, Python and the packages
|
|
33
|
+
serve the engine: these operations as JSON lines on stdin/stdout, with recordings kept open (what PyAT's window talks to)
|
|
34
|
+
docs this command line's reference: markdown, or a man page
|
|
35
|
+
|
|
36
|
+
examples:
|
|
37
|
+
{prog} run event_peth "D:/rats/Rat7" -p event="L1P¹" -p pre_s=10 -p post_s=20 --out out
|
|
38
|
+
{prog} batch jobs.json --out batch-out
|
|
39
|
+
{prog} run zscore_window "D:/rats/Rat7" -p center_s=312.5 --json | jq .result.summary
|
|
40
|
+
|
|
41
|
+
`{prog} <command> --help` lists a command's options; `--help` shows everything. Every command takes --json and --plain.
|
|
42
|
+
"""
|
|
43
|
+
|
|
44
|
+
EPILOGS = {
|
|
45
|
+
"info": f"""examples:
|
|
46
|
+
{PROG} info
|
|
47
|
+
{PROG} info --json
|
|
48
|
+
""",
|
|
49
|
+
"serve": f"""examples:
|
|
50
|
+
{PROG} serve # then one JSON request per line on stdin, one JSON answer per line on stdout
|
|
51
|
+
echo '{{"id": 1, "method": "kinds"}}' | {PROG} serve
|
|
52
|
+
{PROG} serve --data-dir ./engine-data -v
|
|
53
|
+
""",
|
|
54
|
+
"docs": f"""examples:
|
|
55
|
+
{PROG} docs --format man --out pyatcli.1 && man ./pyatcli.1
|
|
56
|
+
{PROG} docs --format markdown --out CLI_REFERENCE.md
|
|
57
|
+
""",
|
|
58
|
+
"kinds": f"""examples:
|
|
59
|
+
{PROG} kinds every analysis and its parameters
|
|
60
|
+
{PROG} kinds event_peth just one
|
|
61
|
+
{PROG} kinds --plain | cut -f1,2 tab-separated: kind, parameter
|
|
62
|
+
""",
|
|
63
|
+
"run": f"""examples:
|
|
64
|
+
{PROG} run event_peth "D:/rats/Rat7-250101" --param event="L1P¹" --param pre_s=10 --param post_s=20 --out out
|
|
65
|
+
{PROG} run zscore_window "D:/rats/Rat7-250101" --param center_s=312.5 --param signal=main_driver --json
|
|
66
|
+
{PROG} run auc_window recording.txt -p center_s=30 --output-folder Output # Output/Oxysoft/recording (Analysis)/
|
|
67
|
+
""",
|
|
68
|
+
"reproduce": f"""examples:
|
|
69
|
+
{PROG} reproduce "out/Rat7_event_peth.provenance.json" --compare "out/Event PETH.csv"
|
|
70
|
+
{PROG} reproduce record.provenance.json --recording "E:/moved/Rat7" --strict
|
|
71
|
+
""",
|
|
72
|
+
"batch": f"""examples:
|
|
73
|
+
{PROG} batch jobs.json --out batch-out
|
|
74
|
+
{PROG} batch jobs.json --output-folder Output
|
|
75
|
+
cat jobs.json | {PROG} batch - --out batch-out
|
|
76
|
+
""",
|
|
77
|
+
"group": f"""examples:
|
|
78
|
+
{PROG} group setup "D:/cohort" --name Sucrose # lists the markers the recordings share
|
|
79
|
+
{PROG} group setup "D:/cohort" --name Sucrose --marker "L1P¹" --marker "L2P¹" --output-folder Output
|
|
80
|
+
{PROG} group run "Output/Group Analysis/Sucrose"
|
|
81
|
+
""",
|
|
82
|
+
"group setup": f"""examples:
|
|
83
|
+
{PROG} group setup "D:/cohort" --name Sucrose
|
|
84
|
+
{PROG} group setup "D:/cohort" --name Sucrose --marker "L1P¹" --marker "L2P¹" --output-folder Output --run
|
|
85
|
+
""",
|
|
86
|
+
"group run": f"""examples:
|
|
87
|
+
{PROG} group run "Output/Group Analysis/Sucrose"
|
|
88
|
+
{PROG} group run analysis_settings.json --out results
|
|
89
|
+
""",
|
|
90
|
+
"saved": f"""examples:
|
|
91
|
+
{PROG} saved show "D:/rats/Rat7"
|
|
92
|
+
{PROG} saved marker "D:/rats/Rat7" --time 312.5 --label Lever
|
|
93
|
+
{PROG} saved splice "D:/rats/Rat7" --mode cut_out --start 40 --end 55
|
|
94
|
+
{PROG} saved clear "D:/rats/Rat7" # asks first; --yes to go ahead without asking
|
|
95
|
+
""",
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def concise_help():
|
|
100
|
+
return CONCISE.format(version=provenance.library_version(), prog=PROG)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def add_global(parser, top):
|
|
104
|
+
"""The flags every command takes. On a command's own parser their defaults are suppressed, so a flag given before the command is not
|
|
105
|
+
overwritten by the command's absence of it."""
|
|
106
|
+
d = (lambda value: value) if top else (lambda value: argparse.SUPPRESS)
|
|
107
|
+
g = parser.add_argument_group("global options (accepted before or after the command)")
|
|
108
|
+
shape = g.add_mutually_exclusive_group()
|
|
109
|
+
shape.add_argument("--json", action="store_true", default=d(False), help="print the result as one JSON document on stdout")
|
|
110
|
+
shape.add_argument("--plain", action="store_true", default=d(False), help="print tab-separated rows on stdout, nothing else (for cut, awk, spreadsheets)")
|
|
111
|
+
g.add_argument("--quiet", "-q", action="store_true", default=d(False), help="print nothing but errors")
|
|
112
|
+
g.add_argument("--verbose", "-v", action="count", default=d(0), help="say more on stderr (and show what libraries print)")
|
|
113
|
+
g.add_argument("--debug", "-d", action="store_true", default=d(False), help="show the full traceback of an error (also set by DEBUG=1)")
|
|
114
|
+
g.add_argument("--no-input", action="store_true", default=d(False), help="never ask a question (an action that needs a yes fails instead)")
|
|
115
|
+
g.add_argument("--events", action="store_true", default=d(False),
|
|
116
|
+
help="report progress, warnings and notes as JSON lines on stderr (for a program driving this one)")
|
|
117
|
+
g.add_argument("--progress", dest="progress", action="store_true", default=d(None), help="always show a progress bar on stderr for slow steps")
|
|
118
|
+
g.add_argument("--no-progress", dest="progress", action="store_false", default=d(None),
|
|
119
|
+
help="never show a progress bar (the default shows one when stderr is a terminal)")
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _load_flags(sp):
|
|
123
|
+
sp.add_argument("--regression", default="ols", choices=REGRESSION_METHODS, help="motion-correction method for TDT (default ols)")
|
|
124
|
+
sp.add_argument("--no-saved", action="store_true", help="ignore the recording's saved splices and markers (JSON saves/)")
|
|
125
|
+
sp.add_argument("--table", help="generic file: which table to open")
|
|
126
|
+
sp.add_argument("--x", help="generic file: the x column (default the first)")
|
|
127
|
+
sp.add_argument("--y", nargs="+", help="generic file: the trace columns (default all the others)")
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _where_to(sp, default, what, group=False):
|
|
131
|
+
"""--out DIR (the results exactly there), or --output-folder DIR (PyAT's layout under an Output folder)."""
|
|
132
|
+
choice = sp.add_mutually_exclusive_group()
|
|
133
|
+
choice.add_argument("--out", "-o", metavar="DIR", help=f"folder for {what}" + (f" (default {default})" if default else ""))
|
|
134
|
+
choice.add_argument("--output-folder", metavar="DIR",
|
|
135
|
+
help="an Output folder, laid out as PyAT's exports are: " + (
|
|
136
|
+
"<DIR>/Group Analysis/<group name>, a new folder if the name was used before" if group else
|
|
137
|
+
"<DIR>/<data type>/<recording> (Analysis)/, and a repeat run never overwrites an earlier one"))
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def build_parser():
|
|
141
|
+
top = argparse.ArgumentParser(
|
|
142
|
+
prog=PROG, formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
143
|
+
description="Run PyATCLI analyses from the command line, and run them again from a provenance record.",
|
|
144
|
+
epilog="""exit status: 0 done; 1 something failed (the message is on stderr); 2 bad usage; 3 `reproduce` ran but an export did not match; 130 interrupted.
|
|
145
|
+
Standard output is only ever the result (--json for a program, --plain for rows); everything else goes to standard error.
|
|
146
|
+
Environment: DEBUG=1 (same as --debug).
|
|
147
|
+
""" + "\n" + EPILOGS["run"])
|
|
148
|
+
top.add_argument("--version", "-V", action="version", version=f"PyATCLI {provenance.library_version()}")
|
|
149
|
+
add_global(top, True)
|
|
150
|
+
sub = top.add_subparsers(dest="command", metavar="<command>")
|
|
151
|
+
|
|
152
|
+
def command(name, help_text, fn, epilog_key=None, description=None, parent=sub):
|
|
153
|
+
sp = parent.add_parser(name, help=help_text, description=description or help_text, formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
154
|
+
epilog=EPILOGS.get(epilog_key or name), add_help=True)
|
|
155
|
+
sp.set_defaults(fn=fn)
|
|
156
|
+
add_global(sp, False)
|
|
157
|
+
return sp
|
|
158
|
+
|
|
159
|
+
command("info", "versions of this library, Python and the numerical packages", C.cmd_info)
|
|
160
|
+
|
|
161
|
+
sp = command("serve", "the engine: these operations as JSON lines on stdin/stdout, with recordings kept open", C.cmd_serve, description=(
|
|
162
|
+
"Runs the engine: the operations of the other commands as a long-lived process that speaks one JSON object per line on standard input "
|
|
163
|
+
"and output, and keeps recordings open between requests. It is what PyAT's window talks to. Requests: "
|
|
164
|
+
'{"id": 7, "method": "recording.open", "params": {...}}; {"cancel": 7} stops one; {"method": "shutdown"} ends the process. '
|
|
165
|
+
"Arrays travel as .npy files in the data folder, never through the pipe."))
|
|
166
|
+
sp.add_argument("--data-dir", metavar="DIR", help="where bulk results (arrays, big tables) are written (default: a temporary folder, removed on exit)")
|
|
167
|
+
sp.add_argument("--app-name", default="PyATCLI engine", metavar="NAME", help="the program asking, for the provenance records the engine writes")
|
|
168
|
+
sp.add_argument("--app-version", metavar="VERSION", help="its version")
|
|
169
|
+
|
|
170
|
+
sp = command("docs", "print this command line's reference: markdown, or a man page (or the engine's contract)", C.cmd_docs)
|
|
171
|
+
sp.add_argument("--format", "-f", choices=["markdown", "man", "contract"], default="markdown",
|
|
172
|
+
help="markdown (CLI_REFERENCE.md), man (pyatcli.1), or contract (ENGINE_CONTRACT.json: what the engine's callers can count on)")
|
|
173
|
+
sp.add_argument("--out", "-o", metavar="FILE", help="write it to this file instead of standard output (- is standard output)")
|
|
174
|
+
|
|
175
|
+
sp = command("kinds", "list the analyses and their parameters", C.cmd_kinds)
|
|
176
|
+
sp.add_argument("kind", nargs="?", help="describe just this one")
|
|
177
|
+
|
|
178
|
+
sp = command("run", "run one analysis on a recording", C.cmd_run)
|
|
179
|
+
sp.add_argument("kind", choices=kinds(), help="the analysis (see `kinds`)")
|
|
180
|
+
sp.add_argument("recording", help="a TDT folder, an Oxysoft .txt export, or a generic table file")
|
|
181
|
+
sp.add_argument("--param", "-p", action="append", metavar="NAME=VALUE", help="an analysis parameter; repeat for several")
|
|
182
|
+
sp.add_argument("--params", metavar="FILE.json", help="parameters from a JSON file, or - for standard input (--param overrides it)")
|
|
183
|
+
_where_to(sp, "pyatcli-output", "the CSV tables and the provenance record")
|
|
184
|
+
_load_flags(sp)
|
|
185
|
+
|
|
186
|
+
sp = command("reproduce", "run an analysis again from its provenance record and check the numbers", C.cmd_reproduce)
|
|
187
|
+
sp.add_argument("record", help="a .provenance.json written beside an export, or - for standard input")
|
|
188
|
+
sp.add_argument("--recording", help="where the recording is now, if it is not where the record says")
|
|
189
|
+
sp.add_argument("--compare", "-c", nargs="+", metavar="EXPORT.csv", help="exports to check the result against")
|
|
190
|
+
sp.add_argument("--tolerance", type=float, default=1e-4, help="|a-b| <= tolerance*(1+|b|) counts as equal (default 1e-4)")
|
|
191
|
+
sp.add_argument("--strict", action="store_true", help="fail if the recording or the software differs from the record's")
|
|
192
|
+
rounding = sp.add_mutually_exclusive_group()
|
|
193
|
+
rounding.add_argument("--rounded", action="store_true", help="the exports hold rounded numbers: accept the digits they show (the default for PyAT's exports)")
|
|
194
|
+
rounding.add_argument("--exact", action="store_true", help="compare to the tolerance only, whoever wrote the exports")
|
|
195
|
+
sp.add_argument("--out", "-o", metavar="DIR", help="write the result tables and a new record here")
|
|
196
|
+
|
|
197
|
+
sp = command("batch", "run many analyses over many recordings", C.cmd_batch)
|
|
198
|
+
sp.add_argument("jobs", help='JSON: {"defaults": {...}, "jobs": [{"kind", "recording", "parameters"}, ...]}, or - for standard input')
|
|
199
|
+
_where_to(sp, "pyatcli-batch", "the results, a folder per job and recording")
|
|
200
|
+
_load_flags(sp)
|
|
201
|
+
|
|
202
|
+
# -- group: setup, run
|
|
203
|
+
group = command("group", "group analysis across recordings: `setup` (the wizard) and `run`", None, description=(
|
|
204
|
+
"Group analysis (Hypothesis Testing): `group setup` finds the recordings, lists the markers they share and writes analysis_settings.json; "
|
|
205
|
+
"`group run` runs it."))
|
|
206
|
+
group.set_defaults(fn=lambda args, out: group.print_help(out.stdout) or C.EXIT_USAGE)
|
|
207
|
+
gsub = group.add_subparsers(dest="group_command", metavar="<setup|run>")
|
|
208
|
+
|
|
209
|
+
sp = command("setup", "set up a group analysis as the wizard does, and write its analysis_settings.json", C.cmd_group_setup, "group setup",
|
|
210
|
+
description="Finds the recordings (a cohort folder is searched, at any depth), lists the markers they share, takes the choices the "
|
|
211
|
+
"wizard asks for, checks the design and writes analysis_settings.json. Without --marker it only lists the markers. "
|
|
212
|
+
"The defaults are the wizard's.", parent=gsub)
|
|
213
|
+
sp.add_argument("folders", nargs="+", help="a cohort folder to search, or recordings (TDT blocks)")
|
|
214
|
+
sp.add_argument("--name", required=True, help="the group's name (its folder and its figures' titles)")
|
|
215
|
+
sp.add_argument("--marker", "-m", action="append", default=[], metavar="NAME", help="a marker to compare, as `group setup` lists it; repeat for each")
|
|
216
|
+
sp.add_argument("--exclude", action="append", default=[], metavar="RECORDING", help="leave a recording out, by its subject name; repeat")
|
|
217
|
+
sp.add_argument("--store-label", action="append", default=[], metavar="ID=NAME", help="show an event store under another name (what Edit Attributes does); repeat")
|
|
218
|
+
sp.add_argument("--pre", type=float, default=group_design.DEFAULT_PRE, help="seconds before each event (default %(default)g)")
|
|
219
|
+
sp.add_argument("--post", type=float, default=group_design.DEFAULT_POST, help="seconds after each event (default %(default)g)")
|
|
220
|
+
sp.add_argument("--baseline", type=float, nargs=2, default=group_design.DEFAULT_BASELINE, metavar=("START", "END"),
|
|
221
|
+
help="the baseline window, seconds from the event (default %(default)s)")
|
|
222
|
+
sp.add_argument("--response", type=float, nargs=2, default=group_design.DEFAULT_RESPONSE, metavar=("START", "END"),
|
|
223
|
+
help="the response window, seconds from the event (default %(default)s)")
|
|
224
|
+
sp.add_argument("--signal", choices=group_design.SIGNALS, default="dff", help="dff, or zscore (also divide by the baseline's SD)")
|
|
225
|
+
sp.add_argument("--smooth", type=float, default=0.5, help="moving-average smoothing before slicing, seconds; 0 for none (default 0.5)")
|
|
226
|
+
sp.add_argument("--measure", action="append", choices=group_design.METRICS, help="a measure to compute and test; repeat (default: all five)")
|
|
227
|
+
sp.add_argument("--peak-direction", choices=group_design.PEAK_DIRECTIONS, default="absolute", help="default absolute")
|
|
228
|
+
sp.add_argument("--decay-fraction", type=float, default=0.5, help="how far the trace must fall for the decay time, as a fraction of the peak (default 0.5)")
|
|
229
|
+
sp.add_argument("--correction", choices=group_design.CORRECTIONS, default="holm", help="multiple-comparison correction (default holm)")
|
|
230
|
+
sp.add_argument("--alpha", type=float, default=0.05, help="significance level (default 0.05)")
|
|
231
|
+
sp.add_argument("--regression", default="ols", choices=REGRESSION_METHODS, help="motion-correction method for every recording (default ols)")
|
|
232
|
+
_where_to(sp, None, "the settings (and, with --run, the results)", group=True)
|
|
233
|
+
sp.add_argument("--run", action="store_true", help="run the analysis right after, as the wizard's Run Analysis does")
|
|
234
|
+
|
|
235
|
+
sp = command("run", "run a group analysis from its analysis_settings.json", C.cmd_group_run, "group run", parent=gsub)
|
|
236
|
+
sp.add_argument("settings", help="analysis_settings.json, or the folder holding it")
|
|
237
|
+
_where_to(sp, None, "the tables and the report", group=True)
|
|
238
|
+
|
|
239
|
+
# -- saved
|
|
240
|
+
saved = command("saved", "edit what the app's Save Changes saves (markers, splices, signal names, highlights, text)", None, description=(
|
|
241
|
+
"Writes the files PyAT writes in a recording's JSON saves folder, so what is done here is what was done in the app: either reads it "
|
|
242
|
+
"back when it opens the recording."))
|
|
243
|
+
saved.set_defaults(fn=lambda args, out: saved.print_help(out.stdout) or C.EXIT_USAGE)
|
|
244
|
+
actions = saved.add_subparsers(dest="action", metavar="<action>")
|
|
245
|
+
|
|
246
|
+
def action(name, help_text, fn, load=False):
|
|
247
|
+
sp = command(name, help_text, fn, "saved", parent=actions)
|
|
248
|
+
sp.add_argument("recording", help="a TDT folder, an Oxysoft .txt export, or a generic table file")
|
|
249
|
+
if load:
|
|
250
|
+
sp.add_argument("--regression", default="ols", choices=REGRESSION_METHODS, help="motion-correction method for TDT (default ols)")
|
|
251
|
+
sp.add_argument("--table", help="generic file: which table to open")
|
|
252
|
+
sp.add_argument("--x", help="generic file: the x column (default the first)")
|
|
253
|
+
sp.add_argument("--y", nargs="+", help="generic file: the trace columns (default all the others)")
|
|
254
|
+
return sp
|
|
255
|
+
|
|
256
|
+
action("show", "list what is saved for a recording", C.cmd_saved_show)
|
|
257
|
+
sp = action("marker", "Add Marker + Save Changes: put a marker at a time (seconds, on the time axis as the recording now stands)", C.cmd_saved_marker, load=True)
|
|
258
|
+
sp.add_argument("--time", "-t", type=float, required=True, help="seconds")
|
|
259
|
+
sp.add_argument("--label", help="what the marker says (default Marker)")
|
|
260
|
+
sp.add_argument("--color", help="its colour (default green)")
|
|
261
|
+
sp.add_argument("--fontsize", type=int, help="its text size (default 8)")
|
|
262
|
+
sp = action("unmark", "delete the saved markers near a time", C.cmd_saved_unmark, load=True)
|
|
263
|
+
sp.add_argument("--time", "-t", type=float, required=True, help="seconds")
|
|
264
|
+
sp.add_argument("--tolerance", type=float, default=0.05, help="how near counts, in seconds (default 0.05)")
|
|
265
|
+
sp.add_argument("--label", help="only markers with this name")
|
|
266
|
+
sp = action("splice", "Splice + Save Changes: stack a splice on the saved ones (it is replayed whenever the recording opens)", C.cmd_saved_splice, load=True)
|
|
267
|
+
sp.add_argument("--mode", required=True, choices=saved_state.SPLICE_MODES, help="cut_out removes start..end and closes the gap; keep_inside keeps only start..end")
|
|
268
|
+
sp.add_argument("--start", type=float, required=True, help="seconds, on the time axis as the recording now stands (after the saved splices)")
|
|
269
|
+
sp.add_argument("--end", type=float, required=True, help="seconds")
|
|
270
|
+
sp = action("unsplice", "take one saved splice out of the stack", C.cmd_saved_unsplice)
|
|
271
|
+
sp.add_argument("number", type=int, help="which one: 1 is the first applied (see `saved show`)")
|
|
272
|
+
sp = action("rename", "give signals names of your own, kept with the recording", C.cmd_saved_rename, load=True)
|
|
273
|
+
sp.add_argument("names", nargs="+", metavar="KEY=NAME", help="the signal's key (main_driver, isosbestic, normalized, ...) and its name; empty NAME takes the rename away")
|
|
274
|
+
sp = action("highlight", "Highlighter + Save Changes: shade a stretch of the recording", C.cmd_saved_highlight)
|
|
275
|
+
sp.add_argument("--start", type=float, required=True, help="seconds")
|
|
276
|
+
sp.add_argument("--end", type=float, required=True, help="seconds")
|
|
277
|
+
sp.add_argument("--color", default="Yellow", help="Yellow, Green, Pink, Orange or Blue (the app's five), or a hex colour (default Yellow)")
|
|
278
|
+
sp = action("text", "Text tool + Save Changes: put a text box on the plot", C.cmd_saved_text)
|
|
279
|
+
sp.add_argument("--x", type=float, required=True, help="seconds")
|
|
280
|
+
sp.add_argument("--y", type=float, required=True, help="in the signal's units")
|
|
281
|
+
sp.add_argument("--text", required=True, help="what it says")
|
|
282
|
+
sp.add_argument("--fontsize", type=int, default=saved_state.DEFAULT_TEXT_FONT_SIZE, help="6 to 72 (default 10)")
|
|
283
|
+
sp = action("clear", "Undo All Changes, saved: delete every file in the recording's JSON saves folder (asks first)", C.cmd_saved_clear)
|
|
284
|
+
sp.add_argument("--yes", "-y", action="store_true", help="go ahead without asking")
|
|
285
|
+
|
|
286
|
+
return top
|
PyATCLI/cli/render.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
"""
|
|
2
|
+
cli/render.py
|
|
3
|
+
-------------
|
|
4
|
+
How a command's result reaches the person (or the program) that ran it. One `Output` per run:
|
|
5
|
+
|
|
6
|
+
human the default: short lines on stdout saying what was done, aligned tables, "wrote ..." for every file written
|
|
7
|
+
--plain tab-separated rows and nothing else on stdout: for `cut`, `awk`, a spreadsheet
|
|
8
|
+
--json one JSON document on stdout — {"schema": 1, "ok": true, "command": ..., "result": {...}, "warnings": [...]} — and nothing else
|
|
9
|
+
|
|
10
|
+
Whatever the mode, stdout is only ever the result: warnings, errors, progress and anything a library prints on its own go to stderr (or are
|
|
11
|
+
dropped), so `pyatcli run ... --json | jq` always sees valid JSON. Colour is never used, so NO_COLOR has nothing to turn off.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
import json
|
|
15
|
+
import sys
|
|
16
|
+
|
|
17
|
+
from ..ops import to_jsonable
|
|
18
|
+
|
|
19
|
+
SCHEMA = 1
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class Output:
|
|
23
|
+
def __init__(self, args, stdout, stderr):
|
|
24
|
+
self.json = bool(getattr(args, "json", False))
|
|
25
|
+
self.plain = bool(getattr(args, "plain", False))
|
|
26
|
+
self.quiet = bool(getattr(args, "quiet", False))
|
|
27
|
+
self.verbose = int(getattr(args, "verbose", 0) or 0)
|
|
28
|
+
self.debug = bool(getattr(args, "debug", False))
|
|
29
|
+
self.no_input = bool(getattr(args, "no_input", False))
|
|
30
|
+
self.stdout, self.stderr = stdout, stderr
|
|
31
|
+
self.warnings = []
|
|
32
|
+
|
|
33
|
+
# ---- what the person reads ---------------------------------------------------------------------------------------------------------
|
|
34
|
+
|
|
35
|
+
@property
|
|
36
|
+
def human(self):
|
|
37
|
+
return not (self.json or self.plain)
|
|
38
|
+
|
|
39
|
+
def say(self, text=""):
|
|
40
|
+
"""A line of prose: stdout, in human mode, unless --quiet."""
|
|
41
|
+
if self.human and not self.quiet:
|
|
42
|
+
print(text, file=self.stdout)
|
|
43
|
+
|
|
44
|
+
def detail(self, text):
|
|
45
|
+
"""A line only --verbose wants (stderr, so it never mixes with the result)."""
|
|
46
|
+
if self.verbose:
|
|
47
|
+
print(text, file=self.stderr)
|
|
48
|
+
|
|
49
|
+
def table(self, header, rows, indent=" "):
|
|
50
|
+
"""Rows under a header. Human: aligned columns. --plain: tab-separated, no header. --json: nothing (the result carries the data)."""
|
|
51
|
+
rows = [[("" if v is None else str(v)) for v in row] for row in rows]
|
|
52
|
+
if self.plain:
|
|
53
|
+
for row in rows:
|
|
54
|
+
print("\t".join(row), file=self.stdout)
|
|
55
|
+
elif self.human and not self.quiet:
|
|
56
|
+
widths = [max(len(str(h)), *(len(r[i]) for r in rows)) if rows else len(str(h)) for i, h in enumerate(header)]
|
|
57
|
+
print(indent + " ".join(str(h).ljust(w) for h, w in zip(header, widths)).rstrip(), file=self.stdout)
|
|
58
|
+
for row in rows:
|
|
59
|
+
print(indent + " ".join(v.ljust(w) for v, w in zip(row, widths)).rstrip(), file=self.stdout)
|
|
60
|
+
|
|
61
|
+
def files(self, paths, directory=None):
|
|
62
|
+
"""The files a command wrote — a change of state the person is always told about (even with --plain; --quiet says nothing)."""
|
|
63
|
+
if not paths:
|
|
64
|
+
return
|
|
65
|
+
if self.plain:
|
|
66
|
+
for p in paths:
|
|
67
|
+
print(p, file=self.stdout)
|
|
68
|
+
else:
|
|
69
|
+
self.say(f"wrote {len(paths)} files to {directory}" if directory else "\n".join(f"wrote {p}" for p in paths))
|
|
70
|
+
|
|
71
|
+
def warn(self, text):
|
|
72
|
+
self.warnings.append(str(text))
|
|
73
|
+
print(f"warning: {text}", file=self.stderr)
|
|
74
|
+
|
|
75
|
+
def error(self, message, hint=None):
|
|
76
|
+
print(f"error: {message}", file=self.stderr)
|
|
77
|
+
if hint:
|
|
78
|
+
print(f" {hint}", file=self.stderr)
|
|
79
|
+
|
|
80
|
+
def fail(self, info):
|
|
81
|
+
"""Prints an error_info dict: as `error: ...` (and the hint), or, with --json, as {"ok": false, "error": {...}} on stderr."""
|
|
82
|
+
if self.json:
|
|
83
|
+
print(json.dumps({"schema": SCHEMA, "ok": False, "error": to_jsonable(info)}, ensure_ascii=False), file=self.stderr)
|
|
84
|
+
else:
|
|
85
|
+
self.error(info["message"], info.get("hint"))
|
|
86
|
+
|
|
87
|
+
# ---- what a program reads ----------------------------------------------------------------------------------------------------------
|
|
88
|
+
|
|
89
|
+
def result(self, command, result):
|
|
90
|
+
"""With --json: the one document on stdout."""
|
|
91
|
+
if self.json:
|
|
92
|
+
doc = {"schema": SCHEMA, "ok": True, "command": command, "result": to_jsonable(result), "warnings": list(self.warnings)}
|
|
93
|
+
print(json.dumps(doc, indent=2, ensure_ascii=False), file=self.stdout)
|
|
94
|
+
|
|
95
|
+
def event(self, name, **fields):
|
|
96
|
+
"""--events: one JSON line on stderr per event (progress, warning, note, state)."""
|
|
97
|
+
print(json.dumps({"event": name, **to_jsonable(fields)}, ensure_ascii=False), file=self.stderr, flush=True)
|
|
98
|
+
|
|
99
|
+
# ---- asking -------------------------------------------------------------------------------------------------------------------------
|
|
100
|
+
|
|
101
|
+
def interactive(self):
|
|
102
|
+
"""True if a person is there to ask: stdin is a terminal and --no-input was not given."""
|
|
103
|
+
try:
|
|
104
|
+
return not self.no_input and sys.stdin is not None and sys.stdin.isatty() and self.stderr.isatty()
|
|
105
|
+
except (AttributeError, ValueError):
|
|
106
|
+
return False
|
|
107
|
+
|
|
108
|
+
def confirm(self, question):
|
|
109
|
+
"""Asks `question` on stderr and reads yes/no from stdin; False without asking when nobody is there to answer."""
|
|
110
|
+
if not self.interactive():
|
|
111
|
+
return False
|
|
112
|
+
print(f"{question} [y/N] ", end="", file=self.stderr, flush=True)
|
|
113
|
+
try:
|
|
114
|
+
return sys.stdin.readline().strip().lower() in ("y", "yes")
|
|
115
|
+
except (KeyboardInterrupt, EOFError):
|
|
116
|
+
return False
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
class Discard:
|
|
120
|
+
"""What sys.stdout is while a command runs: anything a library prints on its own (the TDT SDK reports every block it opens) must not mix
|
|
121
|
+
into a result."""
|
|
122
|
+
|
|
123
|
+
def write(self, text):
|
|
124
|
+
return len(text)
|
|
125
|
+
|
|
126
|
+
def flush(self):
|
|
127
|
+
pass
|
|
128
|
+
|
|
129
|
+
def isatty(self):
|
|
130
|
+
return False
|
|
File without changes
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
"""
|
|
2
|
+
engine/contract.py
|
|
3
|
+
------------------
|
|
4
|
+
What a program that talks to the engine (`python -m PyATCLI serve`) can count on, written down so a change that would break it is noticed:
|
|
5
|
+
|
|
6
|
+
build() the contract as it is now: the protocol version, every operation with its parameters, and every analysis with
|
|
7
|
+
its parameters and the tables it returns with the columns that are always there, and the tables written
|
|
8
|
+
besides ("outputs": a group analysis's folder with the file of each table, an Export View's data). ENGINE_CONTRACT.json in the
|
|
9
|
+
repository is this, generated (`python -m PyATCLI docs --format contract --out ENGINE_CONTRACT.json`)
|
|
10
|
+
breaking_changes(old, new) what `new` no longer offers of what `old` did: a caller written against `old` would break
|
|
11
|
+
|
|
12
|
+
Adding is never breaking: a new operation, an optional parameter, a new table or column. These are:
|
|
13
|
+
|
|
14
|
+
an operation, or one of its parameters, that is gone; a parameter that must now be given (it was optional, or did not exist)
|
|
15
|
+
a key of an operation's result that was always there and no longer is; a key of the loaded recording (`recording.CACHE_KEYS`) likewise
|
|
16
|
+
an analysis, one of its parameters, or a choice of one, that is gone; a parameter that must now be given or has another type
|
|
17
|
+
a table of an analysis that is gone, or a column that is always there and no longer is; likewise for the outputs, and a file of a group's
|
|
18
|
+
folder that is gone or has another name
|
|
19
|
+
a protocol version that went down
|
|
20
|
+
|
|
21
|
+
A breaking change means a new `ops.PROTOCOL_VERSION`. tests/contracts/protocol_N.json is the contract as it was when protocol N began, and
|
|
22
|
+
tests/test_engine_contract.py checks that the engine still honours the one of its own protocol: change something it lists and the test fails
|
|
23
|
+
until the protocol is raised (and the new baseline added), which is also what tells a window running an older engine to say so (the app
|
|
24
|
+
compares the protocol in the engine's `ready` message with the ones it speaks).
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
from .. import ops
|
|
28
|
+
from ..analyses import describe_kinds, describe_outputs
|
|
29
|
+
from ..recording import CACHE_KEYS
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def build():
|
|
33
|
+
"""The contract as the code has it now (JSON-ready)."""
|
|
34
|
+
operations = {name: {"summary": op["summary"], "parameters": [dict(p) for p in op["parameters"]], "result": list(op["result"])}
|
|
35
|
+
for name, op in ops.describe().items()}
|
|
36
|
+
analyses = {kind: {"summary": a["summary"],
|
|
37
|
+
"parameters": [{k: p[k] for k in ("name", "type", "required", "default", "choices")} for p in a["parameters"]],
|
|
38
|
+
"tables": {name: list(cols) for name, cols in a["tables"].items()}}
|
|
39
|
+
for kind, a in describe_kinds().items()}
|
|
40
|
+
outputs = {name: {"summary": o["summary"], "tables": {t: list(cols) for t, cols in o["tables"].items()}, "files": dict(o["files"])}
|
|
41
|
+
for name, o in describe_outputs().items()}
|
|
42
|
+
return {"protocol": ops.PROTOCOL_VERSION, "operations": operations, "analyses": analyses, "outputs": outputs,
|
|
43
|
+
"recording_cache": {source: list(keys) for source, keys in CACHE_KEYS.items()}}
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _params(items):
|
|
47
|
+
return {p["name"]: p for p in items}
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _newly_required(old_p, new_p):
|
|
51
|
+
return bool(new_p.get("required")) and not (old_p is not None and old_p.get("required"))
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def breaking_changes(old, new):
|
|
55
|
+
"""[a sentence for each thing `old` offered that `new` does not] — empty if a caller written against `old` still works against `new`."""
|
|
56
|
+
problems = []
|
|
57
|
+
if new.get("protocol", 0) < old.get("protocol", 0):
|
|
58
|
+
problems.append(f"the protocol went down, from {old['protocol']} to {new['protocol']}")
|
|
59
|
+
for name, op in old.get("operations", {}).items():
|
|
60
|
+
now = new.get("operations", {}).get(name)
|
|
61
|
+
if now is None:
|
|
62
|
+
problems.append(f"operation {name!r} is gone")
|
|
63
|
+
continue
|
|
64
|
+
before, after = _params(op["parameters"]), _params(now["parameters"])
|
|
65
|
+
for p in before:
|
|
66
|
+
if p not in after:
|
|
67
|
+
problems.append(f"operation {name!r}: parameter {p!r} is gone")
|
|
68
|
+
for p, spec in after.items():
|
|
69
|
+
if _newly_required(before.get(p), spec):
|
|
70
|
+
problems.append(f"operation {name!r}: parameter {p!r} must now be given")
|
|
71
|
+
for key in op.get("result", []):
|
|
72
|
+
if key not in now.get("result", []):
|
|
73
|
+
problems.append(f"operation {name!r}: its result no longer always has {key!r}")
|
|
74
|
+
for kind, a in old.get("analyses", {}).items():
|
|
75
|
+
now = new.get("analyses", {}).get(kind)
|
|
76
|
+
if now is None:
|
|
77
|
+
problems.append(f"analysis {kind!r} is gone")
|
|
78
|
+
continue
|
|
79
|
+
before, after = _params(a["parameters"]), _params(now["parameters"])
|
|
80
|
+
for p, spec in before.items():
|
|
81
|
+
if p not in after:
|
|
82
|
+
problems.append(f"analysis {kind!r}: parameter {p!r} is gone")
|
|
83
|
+
continue
|
|
84
|
+
if after[p].get("type") != spec.get("type"):
|
|
85
|
+
problems.append(f"analysis {kind!r}: parameter {p!r} changed type, from {spec.get('type')} to {after[p].get('type')}")
|
|
86
|
+
for choice in spec.get("choices") or []:
|
|
87
|
+
if choice not in (after[p].get("choices") or []):
|
|
88
|
+
problems.append(f"analysis {kind!r}: parameter {p!r} no longer accepts {choice!r}")
|
|
89
|
+
for p, spec in after.items():
|
|
90
|
+
if _newly_required(before.get(p), spec):
|
|
91
|
+
problems.append(f"analysis {kind!r}: parameter {p!r} must now be given")
|
|
92
|
+
for table, columns in a.get("tables", {}).items():
|
|
93
|
+
have = now.get("tables", {}).get(table)
|
|
94
|
+
if have is None:
|
|
95
|
+
problems.append(f"analysis {kind!r}: table {table!r} is gone")
|
|
96
|
+
continue
|
|
97
|
+
for column in columns:
|
|
98
|
+
if column not in have:
|
|
99
|
+
problems.append(f"analysis {kind!r}: table {table!r} has no column {column!r} any more")
|
|
100
|
+
for name, o in old.get("outputs", {}).items():
|
|
101
|
+
now = new.get("outputs", {}).get(name)
|
|
102
|
+
if now is None:
|
|
103
|
+
problems.append(f"output {name!r} is gone")
|
|
104
|
+
continue
|
|
105
|
+
for table, columns in o.get("tables", {}).items():
|
|
106
|
+
have = now.get("tables", {}).get(table)
|
|
107
|
+
if have is None:
|
|
108
|
+
problems.append(f"output {name!r}: table {table!r} is gone")
|
|
109
|
+
continue
|
|
110
|
+
for column in columns:
|
|
111
|
+
if column not in have:
|
|
112
|
+
problems.append(f"output {name!r}: table {table!r} has no column {column!r} any more")
|
|
113
|
+
for role, filename in o.get("files", {}).items():
|
|
114
|
+
if now.get("files", {}).get(role) != filename:
|
|
115
|
+
problems.append(f"output {name!r}: {role!r} is no longer written to {filename!r}")
|
|
116
|
+
for source, keys in old.get("recording_cache", {}).items():
|
|
117
|
+
have = new.get("recording_cache", {}).get(source)
|
|
118
|
+
if have is None:
|
|
119
|
+
problems.append(f"the loaded recording: no keys are promised for {source!r} any more")
|
|
120
|
+
continue
|
|
121
|
+
for key in keys:
|
|
122
|
+
if key not in have:
|
|
123
|
+
problems.append(f"the loaded recording ({source}) no longer always has {key!r}")
|
|
124
|
+
return problems
|