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
PyATCLI/reproduce.py ADDED
@@ -0,0 +1,278 @@
1
+ """
2
+ reproduce.py
3
+ ------------
4
+ Runs an analysis again from its provenance record — the file PyAT (or `python -m PyATCLI run`) writes
5
+ beside every export — and says whether the numbers come out the same.
6
+
7
+ rep = pl.reproduce_record("Event PETH_L1P_103522.provenance.json", out_dir="again",
8
+ compare=["Event PETH_L1P_103522.csv"])
9
+ rep.ok # True if every compared export matches
10
+ rep.warnings # the recording changed since, a different numpy, ...
11
+ rep.result.tables # the analysis's tables, as run now
12
+
13
+ What it does, in order: read the record; note whether the software differs from what produced it
14
+ (provenance.check_environment); find the recording (the path the record holds, or `recording=`) and check it
15
+ is the same one (its fingerprint's digest); rebuild it in exactly the state recorded — motion-correction
16
+ method, every splice, store renames — which is not necessarily the state its JSON saves/ folder is in now;
17
+ run the analysis with exactly the recorded parameters (for an event analysis that includes the event times
18
+ themselves, so the markers no longer matter); write the tables and a new record; and compare any exports
19
+ you name, column for column, to a tolerance (and, for an export written with rounded numbers, to the digits it kept).
20
+ """
21
+
22
+ import os
23
+ import re
24
+ from dataclasses import dataclass, field
25
+
26
+ import numpy as np
27
+ import pandas as pd
28
+
29
+ from . import provenance
30
+ from .analyses import AnalysisResult, GROUP_KIND, VIEW_KIND, kinds, run_analysis, run_group_from_spec, run_view
31
+ from .sources.load import load_dataset_file
32
+ from .sources.tables import load_any_file
33
+ from .sources.processing_TDT import process_tdt_folder
34
+ from .recording import apply_signal_labels, apply_splices, make_generic_cache, make_oxysoft_cache, make_tdt_cache
35
+
36
+ DEFAULT_TOLERANCE = 1e-4 # |a - b| <= tolerance * (1 + |b|): looser than the digits an export keeps, tighter than any real change
37
+
38
+
39
+ class ReproduceError(RuntimeError):
40
+ """A record cannot be replayed: not an analysis, no recording to run it on, or the wrong recording (strict)."""
41
+
42
+
43
+ @dataclass
44
+ class Reproduction:
45
+ record: dict
46
+ result: AnalysisResult
47
+ warnings: list = field(default_factory=list)
48
+ written: list = field(default_factory=list)
49
+ comparisons: list = field(default_factory=list)
50
+
51
+ @property
52
+ def ok(self):
53
+ """True if there was nothing compared, or everything compared matched."""
54
+ return all(c["ok"] for c in self.comparisons)
55
+
56
+
57
+ # ---------------------------------------------------------------------------
58
+ # The recording
59
+ # ---------------------------------------------------------------------------
60
+
61
+ def _fingerprint_differences(then, now):
62
+ """Which files of a recording differ from what a record saw (by name, size, hash)."""
63
+ old = {f["name"]: f for f in then.get("files", [])}
64
+ new = {f["name"]: f for f in now.get("files", [])}
65
+ out = [f"{n} is missing" for n in sorted(set(old) - set(new))]
66
+ out += [f"{n} is new" for n in sorted(set(new) - set(old))]
67
+ for n in sorted(set(old) & set(new)):
68
+ a, b = old[n], new[n]
69
+ if a["size"] != b["size"] or (a["sha256"] and b["sha256"] and a["sha256"] != b["sha256"]):
70
+ out.append(f"{n} changed")
71
+ return out
72
+
73
+
74
+ def check_recording(record, path):
75
+ """Sentences describing how the recording at `path` differs from the one the record saw ([] = identical)."""
76
+ then = record.get("source")
77
+ if not then or not then.get("digest"):
78
+ return []
79
+ now = provenance.file_fingerprint(path)
80
+ if now.get("kind") == "missing":
81
+ return [f"{path} does not exist"]
82
+ if now["digest"] == then["digest"]:
83
+ return []
84
+ diffs = _fingerprint_differences(then, now)
85
+ return ["The recording is not the one this record describes: " + ("; ".join(diffs[:5]) or "its files differ")]
86
+
87
+
88
+ def load_recording_for_record(record, path, progress=None):
89
+ """Rebuilds the recording a record describes, from its files, in the recorded state. Returns the cache
90
+ (see recording.py). The splices applied and the names the signals had are the record's own, not whatever
91
+ JSON saves/ holds now."""
92
+ state = record.get("recording") or {}
93
+ source_type = state.get("source_type")
94
+ method = state.get("regression_method") or "ols"
95
+ if source_type == "TDT":
96
+ cache = make_tdt_cache(path, process_tdt_folder(path, regression_method=method, progress=progress))
97
+ elif source_type == "Oxysoft":
98
+ cache = make_oxysoft_cache(path, load_dataset_file(path, progress=progress))
99
+ elif source_type == "Generic":
100
+ g = state.get("generic") or {}
101
+ tables = load_any_file(path, progress=progress)
102
+ table = next((t for t in tables if t.name == g.get("table")), None)
103
+ if table is None or g.get("x_column") not in table.headers:
104
+ raise ReproduceError(f"{os.path.basename(path)} no longer holds table {g.get('table')!r} with column {g.get('x_column')!r}")
105
+ missing = [c for c in g.get("y_columns", []) if c not in table.headers]
106
+ if missing:
107
+ raise ReproduceError(f"{os.path.basename(path)}: column(s) {missing} are gone from table {table.name!r}")
108
+ cache = make_generic_cache(path, table, table.headers.index(g["x_column"]), [table.headers.index(c) for c in g["y_columns"]])
109
+ else:
110
+ raise ReproduceError(f"Don't know how to rebuild a {source_type!r} recording")
111
+ splices = state.get("splices") or []
112
+ if splices:
113
+ cache, applied = apply_splices(cache, splices, regression_method=method)
114
+ if len(applied) != len(splices):
115
+ raise ReproduceError(f"{len(splices) - len(applied)} of the record's {len(splices)} splices cannot be applied to this recording")
116
+ return apply_signal_labels(cache, state.get("signal_labels"))
117
+
118
+
119
+ # ---------------------------------------------------------------------------
120
+ # Comparing an export
121
+ # ---------------------------------------------------------------------------
122
+
123
+ def _is_blank(v):
124
+ return v is None or (isinstance(v, float) and np.isnan(v)) or (isinstance(v, str) and v.strip() == "")
125
+
126
+
127
+ _NUMBER = re.compile(r"\s*[+-]?(\d*)(?:\.(\d*))?(?:[eE]([+-]?\d+))?\s*")
128
+
129
+
130
+ def _rounding_half_width(text):
131
+ """How far the number written as `text` can be from the value it was rounded from: half a unit in its last
132
+ digit ("13.8" -> 0.05, "1.5e-05" -> 5e-07). 0 for a number with no decimal point or exponent ("12"): a whole
133
+ number in an export (a trial number, a count) is exact, not rounded."""
134
+ m = _NUMBER.fullmatch(text)
135
+ if not m or (m.group(2) is None and m.group(3) is None):
136
+ return 0.0
137
+ return 0.5 * 10.0 ** (int(m.group(3) or 0) - len(m.group(2) or ""))
138
+
139
+
140
+ def compare_table(expected_path, table, tolerance=DEFAULT_TOLERANCE, rounded=False):
141
+ """Compares a CSV (an export) with a DataFrame (a result table) column for column. A number matches if it is
142
+ within `tolerance` (see DEFAULT_TOLERANCE); with `rounded=True` also if it is within the rounding its own text
143
+ shows — an export that wrote 13.8 for 13.846 agrees to the one decimal it kept, while a whole number in it
144
+ must still be exact. (`rounded` is for exports whose writer formats numbers to a fixed number of digits, as
145
+ PyAT does; for full-precision CSVs, like this library's own, "13.8" means exactly 13.8, so leave it off.)
146
+ Everything else is compared as text, ignoring case; blank and missing are the same.
147
+
148
+ Returns {"file", "ok", "message", "max_abs_diff", "cells"}."""
149
+ out = {"file": os.path.basename(expected_path), "ok": False, "message": "", "max_abs_diff": 0.0, "cells": 0}
150
+ expected = pd.read_csv(expected_path, dtype=object, keep_default_na=False, encoding="utf-8-sig")
151
+ if list(expected.columns) != list(table.columns):
152
+ out["message"] = f"columns differ: {list(expected.columns)} vs {list(table.columns)}"
153
+ return out
154
+ if len(expected) != len(table):
155
+ out["message"] = f"{len(expected)} rows in the export, {len(table)} in the result"
156
+ return out
157
+ worst = 0.0
158
+ for col in expected.columns:
159
+ for i, (a, b) in enumerate(zip(expected[col], table[col])):
160
+ out["cells"] += 1
161
+ if _is_blank(a) and _is_blank(b):
162
+ continue
163
+ try:
164
+ fa, fb = float(a), float(b)
165
+ except (TypeError, ValueError):
166
+ if str(a).strip().lower() != str(b).strip().lower():
167
+ out["message"] = f"row {i + 1}, {col!r}: {a!r} vs {b!r}"
168
+ return out
169
+ continue
170
+ diff = abs(fa - fb)
171
+ worst = max(worst, diff)
172
+ allowed = tolerance * (1.0 + abs(fb))
173
+ if rounded:
174
+ allowed = max(allowed, _rounding_half_width(str(a)) * 1.000001)
175
+ if not diff <= allowed:
176
+ out["message"] = f"row {i + 1}, {col!r}: {a} vs {fb:.6g} (difference {diff:.3g})"
177
+ return out
178
+ out.update(ok=True, max_abs_diff=worst, message="matches")
179
+ return out
180
+
181
+
182
+ def _compare(compare, result, tolerance, rounded=False):
183
+ out = []
184
+ for item in compare or ():
185
+ path, table_name = item if isinstance(item, (tuple, list)) else (item, None)
186
+ if table_name is None:
187
+ header = list(pd.read_csv(path, nrows=0, encoding="utf-8-sig").columns)
188
+ candidates = [n for n, t in result.tables.items() if list(t.columns) == header]
189
+ if not candidates:
190
+ out.append({"file": os.path.basename(path), "ok": False, "max_abs_diff": 0.0, "cells": 0,
191
+ "message": f"none of the result tables ({', '.join(result.tables)}) has these columns: {header}"})
192
+ continue
193
+ table_name = candidates[0]
194
+ c = compare_table(path, result.tables[table_name], tolerance, rounded)
195
+ c["table"] = table_name
196
+ out.append(c)
197
+ return out
198
+
199
+
200
+ # ---------------------------------------------------------------------------
201
+ # Reproduce
202
+ # ---------------------------------------------------------------------------
203
+
204
+ def safe_name(text):
205
+ return re.sub(r'[<>:"/\\|?*]+', "_", str(text)).strip() or "result"
206
+
207
+
208
+ def write_result(result, out_dir, stem=None):
209
+ """Writes each table of `result` as <out_dir>/<stem>_<table>.csv (UTF-8, full precision); returns the paths."""
210
+ os.makedirs(out_dir, exist_ok=True)
211
+ stem = safe_name(stem or result.kind)
212
+ paths = []
213
+ for name, table in result.tables.items():
214
+ path = os.path.join(out_dir, f"{stem}_{safe_name(name)}.csv")
215
+ table.to_csv(path, index=False, encoding="utf-8")
216
+ paths.append(path)
217
+ return paths
218
+
219
+
220
+ def reproduce(record, recording=None, out_dir=None, compare=(), tolerance=DEFAULT_TOLERANCE, strict=False, progress=None,
221
+ rounded=None):
222
+ """Runs the analysis a provenance record describes. `record` is the record (dict) or the path of its
223
+ .provenance.json. `recording` overrides the location the record holds (moved or renamed data).
224
+
225
+ If `out_dir` is given the result tables are written there as CSV, with a new provenance record beside them.
226
+ `compare` lists exports to check the result against: a path, or (path, table name); which table is found
227
+ from the CSV's own header when not named. `rounded` says whether the exports were written with numbers rounded
228
+ to a fixed number of digits (see compare_table): None decides from the record — PyAT's exports are, the
229
+ command line's are not. With `strict=True` a recording that differs from the recorded one (or a software
230
+ difference) raises ReproduceError instead of being reported in `warnings`.
231
+
232
+ Returns a Reproduction (`.ok`, `.warnings`, `.result`, `.written`, `.comparisons`)."""
233
+ if isinstance(record, (str, os.PathLike)):
234
+ record = provenance.read_record(os.fspath(record))
235
+ analysis = record.get("analysis") or {}
236
+ kind, params = analysis.get("type", record.get("kind")), dict(analysis.get("parameters") or {})
237
+ warnings = provenance.check_environment(record)
238
+ if rounded is None:
239
+ rounded = ((record.get("software") or {}).get("app") or {}).get("name") == "PyAT"
240
+
241
+ if kind == GROUP_KIND:
242
+ result, _ = run_group_from_spec(params, out_dir=out_dir, progress=progress)
243
+ files = list(result.summary.get("files", []))
244
+ return Reproduction(record, result, warnings, files, _compare(compare, result, tolerance, rounded))
245
+ if kind not in kinds() and kind != VIEW_KIND:
246
+ raise ReproduceError(f"A {kind!r} record describes something that is not an analysis, so there is nothing to "
247
+ f"run again; the analyses are: {', '.join(kinds())} (and a view's numbers)")
248
+
249
+ path = recording or (record.get("source") or {}).get("path")
250
+ if not path:
251
+ raise ReproduceError("The record does not say where the recording is (it was written without its path); "
252
+ "pass the recording's location")
253
+ if not os.path.exists(path):
254
+ raise ReproduceError(f"The recording is not at {path}; pass its current location")
255
+ mismatch = check_recording(record, path)
256
+ if mismatch and strict:
257
+ raise ReproduceError(mismatch[0])
258
+ if warnings and strict:
259
+ raise ReproduceError(warnings[0])
260
+ warnings += mismatch
261
+
262
+ cache = load_recording_for_record(record, path, progress=progress)
263
+ state = record.get("recording") or {}
264
+ if kind == VIEW_KIND: # a view's numbers: its data CSV
265
+ result = run_view(cache, params, store_labels=state.get("store_labels"))
266
+ else:
267
+ result = run_analysis(kind, cache, params, store_labels=state.get("store_labels"), progress=progress)
268
+
269
+ written = []
270
+ if out_dir:
271
+ stem = safe_name(os.path.basename(path.rstrip("/\\")) + "_" + kind)
272
+ written = write_result(result, out_dir, stem)
273
+ rec = provenance.build_record(
274
+ kind, result.parameters, source=provenance.file_fingerprint(path), recording=state,
275
+ pipeline=provenance.pipeline_parameters(state.get("regression_method") or "ols"),
276
+ outputs=written, notes=[f"reproduced from a record made {record.get('created', '?')}"] + warnings)
277
+ written.append(provenance.write_record(os.path.join(out_dir, f"{stem}.provenance.json"), rec))
278
+ return Reproduction(record, result, warnings, written, _compare(compare, result, tolerance, rounded))
PyATCLI/results.py ADDED
@@ -0,0 +1,106 @@
1
+ """
2
+ results.py
3
+ ----------
4
+ Reading back what the library, or a program driving it (PyAT), wrote: the numbers of a finished analysis, found from whatever the person names.
5
+
6
+ opened = open_results("out/Group Analysis/Sucrose") # a group analysis's folder: its settings say how it was run
7
+ opened = open_results("out/Rec_event_peth.provenance.json") # a record: the tables it lists
8
+ opened = open_results("out/Rec_event_peth_trials.csv") # one table file
9
+ opened = open_results("out") # a folder: its newest record, or else the tables in it
10
+
11
+ opened.kind what made them ("group_analysis", "event_peth", ... or None for a bare table file)
12
+ opened.parameters what it was asked (a group's settings as a dict)
13
+ opened.tables {name: DataFrame}; the group's folder is read by the names in analysis/group/report.py's TABLE_FILES
14
+ opened.notes what the analysis said ([{"level", "measure", "text"}], a group's), opened.software what it ran on
15
+ opened.files the files the tables were read from
16
+
17
+ No drawing happens here and no plotting library is needed: this is the data side of looking at a result. What a table is drawn as is the viewer's
18
+ business (PyAT's windows draw what this reads). The operation `results.open` is this for the engine.
19
+ """
20
+
21
+ import os
22
+ from dataclasses import dataclass, field
23
+
24
+ import pandas as pd
25
+
26
+ from . import provenance
27
+ from .analysis.group.report import TABLE_FILES, read_group_notes
28
+ from .analysis.group.run import GROUP_SETTINGS_FILENAME, read_group_settings
29
+
30
+
31
+ class NoResults(ValueError):
32
+ """What was named holds nothing that can be read as a result, or is not there."""
33
+
34
+
35
+ @dataclass
36
+ class OpenedResults:
37
+ path: str
38
+ directory: str
39
+ kind: object = None
40
+ parameters: dict = field(default_factory=dict)
41
+ tables: dict = field(default_factory=dict)
42
+ notes: list = field(default_factory=list)
43
+ software: dict = field(default_factory=dict)
44
+ files: list = field(default_factory=list)
45
+
46
+
47
+ def _read_tables(paths):
48
+ tables = {}
49
+ for p in paths:
50
+ if p.lower().endswith(".csv"):
51
+ if not os.path.isfile(p):
52
+ raise NoResults(f"{p} is not there any more")
53
+ # round_trip: the numbers read back exactly as they were written, so a plot of a file is a plot of the result
54
+ tables[os.path.splitext(os.path.basename(p))[0]] = pd.read_csv(p, encoding="utf-8-sig", float_precision="round_trip")
55
+ return tables
56
+
57
+
58
+ def _from_record(path):
59
+ record = provenance.read_record(path)
60
+ folder = os.path.dirname(os.path.abspath(path))
61
+ paths = [os.path.join(folder, o["name"]) for o in record.get("outputs", []) if str(o.get("name", "")).lower().endswith(".csv")]
62
+ tables = _read_tables(paths)
63
+ if not tables:
64
+ raise NoResults(f"{os.path.basename(path)} lists no table files (.csv) to plot")
65
+ return OpenedResults(os.path.abspath(path), folder, record.get("kind"), (record.get("analysis") or {}).get("parameters") or {},
66
+ tables, notes=[dict(n) for n in record.get("notes") or [] if isinstance(n, dict)], files=paths)
67
+
68
+
69
+ def _from_group_folder(folder):
70
+ """A group analysis's folder: its tables by name (trials, subject_means, ..., mean_traces), the settings it was run from, its notes."""
71
+ spec, _doc = read_group_settings(os.path.join(folder, GROUP_SETTINGS_FILENAME))
72
+ paths, tables = [], {}
73
+ for name, filename in TABLE_FILES.items():
74
+ path = os.path.join(folder, filename)
75
+ if os.path.isfile(path):
76
+ tables[name] = next(iter(_read_tables([path]).values()))
77
+ paths.append(path)
78
+ if not tables:
79
+ raise NoResults(f"{folder} holds the settings of a group analysis (*{GROUP_SETTINGS_FILENAME}) but none of its tables: it was not run, or its tables were moved")
80
+ notes, software = read_group_notes(folder)
81
+ return OpenedResults(os.path.abspath(folder), os.path.abspath(folder), "group_analysis", spec.to_dict(), tables, notes, software, paths)
82
+
83
+
84
+ def open_results(source):
85
+ """The OpenedResults for a folder, a provenance record, a group's analysis_settings.json or a .csv table. Raises NoResults if there is nothing
86
+ there to read."""
87
+ path = os.path.abspath(os.fspath(source))
88
+ if os.path.isdir(path):
89
+ if os.path.isfile(os.path.join(path, GROUP_SETTINGS_FILENAME)): # a group's folder, whatever else was exported into it since
90
+ return _from_group_folder(path)
91
+ names = sorted(os.listdir(path))
92
+ records = sorted((os.path.join(path, n) for n in names if n.endswith(provenance.SIDECAR_SUFFIX)), key=os.path.getmtime)
93
+ if records:
94
+ return _from_record(records[-1])
95
+ paths = [os.path.join(path, n) for n in names if n.lower().endswith(".csv")]
96
+ tables = _read_tables(paths)
97
+ if not tables: # no record, no tables: nothing here to read
98
+ raise NoResults(f"{path} holds no provenance record (*{provenance.SIDECAR_SUFFIX}) or table file (.csv) to plot")
99
+ return OpenedResults(path, path, tables=tables, files=paths)
100
+ if os.path.basename(path) == GROUP_SETTINGS_FILENAME and os.path.isfile(path):
101
+ return open_results(os.path.dirname(path))
102
+ if path.lower().endswith(".json"):
103
+ return _from_record(path)
104
+ if path.lower().endswith(".csv"):
105
+ return OpenedResults(path, os.path.dirname(path), tables=_read_tables([path]), files=[path])
106
+ raise NoResults(f"Don't know how to plot {path}: it can be a .csv table, a .provenance.json record or a folder of them")
PyATCLI/saved_state.py ADDED
@@ -0,0 +1,275 @@
1
+ """
2
+ saved_state.py
3
+ --------------
4
+ Writing the state PyAT's Save Changes writes next to a recording, so an edit made in a script is an edit made in the app: the
5
+ same files, in the same "JSON saves" folder, which either one reads back when it opens the recording (recording.py holds
6
+ where they live and the readers).
7
+
8
+ JSON saves/
9
+ markers.json the markers placed on the plot [{"time", "label", "color", "fontsize"}]
10
+ splice.json every splice stacked on the recording, in order [{"mode", "start", "end"}]
11
+ signal_labels.json the names given to its signals {signal key: name}
12
+ highlights.json shaded stretches [{"start", "end", "color"}]
13
+ text_annotations.json text boxes on the plot [{"x", "y", "text", "fontsize"}]
14
+
15
+ Two levels. The writers take what to write — `write_saved_markers(source, markers)` — and check that the app could read it
16
+ back. The edits take a recording's path and do what one action in the app does, to what is already saved:
17
+
18
+ pl.saved_state.add_marker("D:/rats/Rat7", 312.5, label="Lever") # Add Marker, then Save Changes
19
+ pl.saved_state.add_splice("D:/rats/Rat7", "cut_out", 40.0, 55.0) # Splice -> Cut Out, then Save Changes
20
+ pl.saved_state.rename_signals("D:/rats/Rat7", {"main_driver": "GCaMP"})
21
+ pl.saved_state.clear_saved_state("D:/rats/Rat7") # Undo All Changes, saved
22
+
23
+ An edit loads the recording the way the app does (saved splices replayed, so a new splice's times are on the time axis as it
24
+ now stands — a splice stacks on the ones before it), changes the one thing, and writes only that thing's file. Nothing is
25
+ written outside the recording's JSON saves folder. `python -m PyATCLI saved ...` runs the same functions.
26
+ """
27
+
28
+ import json
29
+ import numbers
30
+ import os
31
+
32
+ from .recording import (
33
+ HIGHLIGHTS_FILE, TEXT_ANNOTATIONS_FILE, annotation_sidecar_path, apply_splice, load_recording, marker_sidecar_path,
34
+ plan_signal_renames, read_saved_annotations, read_saved_markers, read_saved_signal_labels, read_saved_splices, saved_state_dir,
35
+ signal_labels_path, splice_sidecar_path,
36
+ )
37
+ from .splice import MODE_CUT_OUT, MODE_KEEP_INSIDE
38
+
39
+ # The five colours the Highlighter offers, and how see-through they are drawn.
40
+ HIGHLIGHT_COLORS = {
41
+ "Yellow": "#FFEB3B",
42
+ "Green": "#8BC34A",
43
+ "Pink": "#FF4D94",
44
+ "Orange": "#FF9800",
45
+ "Blue": "#29B6F6",
46
+ }
47
+ HIGHLIGHT_ALPHA = 0.35
48
+ DEFAULT_TEXT_FONT_SIZE = 10 # the Text tool's dialog opens on this
49
+ DEFAULT_MARKER = {"label": "Marker", "color": "green", "fontsize": 8} # what Add Marker stamps until it is configured
50
+ SPLICE_MODES = (MODE_CUT_OUT, MODE_KEEP_INSIDE)
51
+
52
+
53
+ # ---------------------------------------------------------------------------
54
+ # Writing
55
+ # ---------------------------------------------------------------------------
56
+
57
+ def _is_number(v):
58
+ return isinstance(v, numbers.Real) and not isinstance(v, bool) and v == v and abs(v) != float("inf")
59
+
60
+
61
+ def _dump(path, document, ensure_ascii=True):
62
+ os.makedirs(os.path.dirname(path), exist_ok=True)
63
+ with open(path, "w", encoding="utf-8") as f:
64
+ json.dump(document, f, indent=2, ensure_ascii=ensure_ascii)
65
+ return path
66
+
67
+
68
+ def _remove(path):
69
+ """Takes away a saved file that has nothing left to say (Save Changes never leaves behind an edit that was since undone).
70
+ Returns None."""
71
+ if os.path.exists(path):
72
+ os.remove(path)
73
+ return None
74
+
75
+
76
+ def write_saved_markers(source_path, markers):
77
+ """Writes `markers` (a list of dicts, each with a numeric "time" and a "label") as the recording's saved markers, replacing
78
+ what was saved. Returns the file's path."""
79
+ markers = list(markers)
80
+ for m in markers:
81
+ if not isinstance(m, dict) or not _is_number(m.get("time")):
82
+ raise ValueError(f"a marker is a dict with a numeric 'time' (seconds), not {m!r}")
83
+ return _dump(marker_sidecar_path(source_path), markers)
84
+
85
+
86
+ def _check_splice(s):
87
+ if not (isinstance(s, dict) and s.get("mode") in SPLICE_MODES and _is_number(s.get("start")) and _is_number(s.get("end"))
88
+ and s["start"] < s["end"]):
89
+ raise ValueError(f"a splice is {{'mode': {' or '.join(repr(m) for m in SPLICE_MODES)}, 'start', 'end'}} with start before end, not {s!r}")
90
+
91
+
92
+ def write_saved_splices(source_path, splices):
93
+ """Writes `splices` ([{"mode": "cut_out" or "keep_inside", "start", "end"}], in the order they were applied) as the
94
+ recording's saved splices, replacing what was saved; with none, the file is removed (returns None). Returns the path."""
95
+ splices = list(splices)
96
+ for s in splices:
97
+ _check_splice(s)
98
+ splices = [{"mode": s["mode"], "start": s["start"], "end": s["end"]} for s in splices]
99
+ path = splice_sidecar_path(source_path)
100
+ return _dump(path, splices) if splices else _remove(path)
101
+
102
+
103
+ def write_saved_signal_labels(source_path, labels):
104
+ """Writes `labels` ({signal key: the name it was given}) as the recording's saved signal names, replacing what was saved;
105
+ with none, the file is removed (returns None). Returns the path."""
106
+ labels = {str(k): str(v) for k, v in dict(labels).items() if str(v).strip()}
107
+ path = signal_labels_path(source_path)
108
+ return _dump(path, labels, ensure_ascii=False) if labels else _remove(path)
109
+
110
+
111
+ def write_saved_annotations(source_path, filename, items):
112
+ """Writes a list of dicts to its own file in the saved state (HIGHLIGHTS_FILE, TEXT_ANNOTATIONS_FILE), replacing what
113
+ was saved. Returns the path."""
114
+ items = list(items)
115
+ if not all(isinstance(i, dict) for i in items):
116
+ raise ValueError(f"{filename} holds a list of dicts")
117
+ return _dump(annotation_sidecar_path(source_path, filename), items)
118
+
119
+
120
+ def clear_saved_state(source_path):
121
+ """Undo All Changes, saved: deletes every file in the recording's JSON saves folder (not the folder, and nothing outside
122
+ it) so the recording opens as recorded. Returns the names of the files removed."""
123
+ folder = saved_state_dir(source_path)
124
+ if not os.path.isdir(folder):
125
+ return []
126
+ removed = []
127
+ for name in sorted(os.listdir(folder)):
128
+ entry = os.path.join(folder, name)
129
+ if os.path.isfile(entry):
130
+ os.remove(entry)
131
+ removed.append(name)
132
+ return removed
133
+
134
+
135
+ def saved_state_summary(source_path):
136
+ """What is saved for the recording: {"folder", "markers" [..], "splices" [..], "signal_labels" {..}, "highlights" [..],
137
+ "text_annotations" [..]}, each the list or dict that is saved ([] / {} for nothing). An unreadable file is an error that
138
+ says which."""
139
+ def read(what, fn, *args):
140
+ try:
141
+ return fn(source_path, *args)
142
+ except (OSError, ValueError, KeyError, TypeError) as e:
143
+ raise ValueError(f"The saved {what} of {source_path} cannot be read: {e}") from e
144
+
145
+ return {"folder": saved_state_dir(source_path),
146
+ "markers": read("markers", read_saved_markers),
147
+ "splices": read("splices", read_saved_splices),
148
+ "signal_labels": read("signal names", read_saved_signal_labels),
149
+ "highlights": read("highlights", read_saved_annotations, HIGHLIGHTS_FILE),
150
+ "text_annotations": read("text annotations", read_saved_annotations, TEXT_ANNOTATIONS_FILE)}
151
+
152
+
153
+ # ---------------------------------------------------------------------------
154
+ # What one action in the app makes
155
+ # ---------------------------------------------------------------------------
156
+
157
+ def new_marker(time, label=None, color=None, fontsize=None):
158
+ """A marker as Add Marker stamps it: {"time", "label", "color", "fontsize"}."""
159
+ if not _is_number(time):
160
+ raise ValueError(f"a marker's time is a number of seconds, not {time!r}")
161
+ return {"time": float(time), "label": label or DEFAULT_MARKER["label"], "color": color or DEFAULT_MARKER["color"],
162
+ "fontsize": fontsize if fontsize is not None else DEFAULT_MARKER["fontsize"]}
163
+
164
+
165
+ def new_highlight(start, end, color="Yellow"):
166
+ """A highlight as the Highlighter makes it: {"start", "end", "color"} with start before end. `color` is one of
167
+ HIGHLIGHT_COLORS' names (the app's five) or a colour of your own (a hex string)."""
168
+ if not (_is_number(start) and _is_number(end)) or start == end:
169
+ raise ValueError(f"a highlight runs between two different times in seconds, not {start!r} and {end!r}")
170
+ names = {k.lower(): v for k, v in HIGHLIGHT_COLORS.items()}
171
+ colour = names.get(str(color).lower(), str(color))
172
+ if colour not in HIGHLIGHT_COLORS.values() and not (colour.startswith("#") and len(colour) in (4, 7) and all(c in "0123456789abcdefABCDEF" for c in colour[1:])):
173
+ raise ValueError(f"{color!r} is not a highlight colour: use {', '.join(HIGHLIGHT_COLORS)} or a hex colour like #FFEB3B")
174
+ lo, hi = sorted((float(start), float(end)))
175
+ return {"start": lo, "end": hi, "color": colour}
176
+
177
+
178
+ def new_text_annotation(x, y, text, fontsize=DEFAULT_TEXT_FONT_SIZE):
179
+ """A text box as the Text tool places it: {"x", "y", "text", "fontsize"} (x in seconds, y in the plot's units)."""
180
+ if not (_is_number(x) and _is_number(y)):
181
+ raise ValueError(f"a text box is placed at numbers (x in seconds, y in the signal's units), not {x!r}, {y!r}")
182
+ if not str(text).strip():
183
+ raise ValueError("a text box has to say something")
184
+ if not (isinstance(fontsize, int) and 6 <= fontsize <= 72):
185
+ raise ValueError(f"a text box's font size is a whole number from 6 to 72, not {fontsize!r}")
186
+ return {"x": float(x), "y": float(y), "text": str(text).strip(), "fontsize": fontsize}
187
+
188
+
189
+ def _loaded(source_path, **load):
190
+ """The recording the way the app opens it: its saved splices replayed and its saved markers on top."""
191
+ loaded = load_recording(source_path, **load)
192
+ return loaded["cache"], loaded["splices"]
193
+
194
+
195
+ def add_marker(source_path, time, label=None, color=None, fontsize=None, **load):
196
+ """Add Marker + Save Changes: puts a marker at `time` (seconds on the time axis as the recording now stands, after its saved
197
+ splices) among the saved markers. Returns the marker. `load` is load_recording's own options (regression_method, ...)."""
198
+ marker = new_marker(time, label, color, fontsize)
199
+ cache, _ = _loaded(source_path, **load)
200
+ if not (cache["x"][0] <= marker["time"] <= cache["x"][-1]):
201
+ raise ValueError(f"{time} s is outside the recording, which runs from {cache['x'][0]:.3f} s to {cache['x'][-1]:.3f} s")
202
+ write_saved_markers(source_path, [*cache["markers"], marker])
203
+ return marker
204
+
205
+
206
+ def remove_markers(source_path, time, tolerance=0.05, label=None, **load):
207
+ """Deletes the saved markers within `tolerance` seconds of `time` (and named `label`, if given), and saves. Returns
208
+ the markers removed — [] if there were none, which is not an error here: the caller says what to make of it."""
209
+ cache, _ = _loaded(source_path, **load)
210
+ keep, removed = [], []
211
+ for m in cache["markers"]:
212
+ hit = abs(float(m["time"]) - float(time)) <= tolerance and (label is None or m.get("label") == label)
213
+ (removed if hit else keep).append(m)
214
+ if removed:
215
+ write_saved_markers(source_path, keep)
216
+ return removed
217
+
218
+
219
+ def add_splice(source_path, mode, start, end, **load):
220
+ """Splice + Save Changes: stacks a splice on the recording's saved ones — `mode` "cut_out" (remove start..end and close the
221
+ gap) or "keep_inside" (keep only start..end), `start` and `end` in seconds on the time axis as it now stands. The splice is
222
+ tried first: a range that leaves fewer than 2 samples is an error and nothing is written. Returns the saved splices."""
223
+ _check_splice({"mode": mode, "start": start, "end": end}) # before anything is loaded
224
+ cache, applied = _loaded(source_path, **load)
225
+ if apply_splice(cache, mode, float(start), float(end), regression_method=load.get("regression_method", "ols")) is None:
226
+ raise ValueError(f"a {mode} of {start}..{end} s leaves too little of the recording (fewer than 2 samples)")
227
+ splices = [*applied, {"mode": mode, "start": float(start), "end": float(end)}]
228
+ write_saved_splices(source_path, splices)
229
+ return splices
230
+
231
+
232
+ def remove_splice(source_path, number):
233
+ """Takes saved splice `number` (1 = the first applied) out of the stack and saves; the others stay in order and are
234
+ replayed on the full recording the next time it opens. Returns the splices left."""
235
+ splices = read_saved_splices(source_path)
236
+ if not 1 <= number <= len(splices):
237
+ raise ValueError(f"there is no saved splice {number}; the recording has {len(splices)}")
238
+ del splices[number - 1]
239
+ write_saved_splices(source_path, splices)
240
+ return splices
241
+
242
+
243
+ def rename_signals(source_path, names, **load):
244
+ """Plot -> rename a signal + Save Changes: `names` is {signal key: new name}; an empty name takes the rename away (the
245
+ signal goes back to its own). A key the recording does not have, or a name that two signals would share, is an error (the
246
+ latter as in the app). Returns the names saved."""
247
+ cache, _ = _loaded(source_path, **load)
248
+ signals = cache.get("signals") or {}
249
+ unknown = [k for k in names if k not in signals]
250
+ if unknown:
251
+ have = ", ".join(signals) or "none (this recording has no named signals)"
252
+ raise ValueError(f"no signal {', '.join(repr(k) for k in unknown)} in this recording; its signals are: {have}")
253
+ plan_signal_renames(cache, {k: v for k, v in names.items() if str(v).strip()}) # ValueError if two signals would share a name
254
+ saved = read_saved_signal_labels(source_path)
255
+ for key, name in names.items():
256
+ if str(name).strip():
257
+ saved[key] = str(name).strip()
258
+ else:
259
+ saved.pop(key, None)
260
+ write_saved_signal_labels(source_path, saved)
261
+ return saved
262
+
263
+
264
+ def add_highlight(source_path, start, end, color="Yellow"):
265
+ """Highlighter + Save Changes: shades start..end (seconds). Returns the highlight."""
266
+ item = new_highlight(start, end, color)
267
+ write_saved_annotations(source_path, HIGHLIGHTS_FILE, [*read_saved_annotations(source_path, HIGHLIGHTS_FILE), item])
268
+ return item
269
+
270
+
271
+ def add_text(source_path, x, y, text, fontsize=DEFAULT_TEXT_FONT_SIZE):
272
+ """Text tool + Save Changes: puts a text box at (x seconds, y in the signal's units). Returns it."""
273
+ item = new_text_annotation(x, y, text, fontsize)
274
+ write_saved_annotations(source_path, TEXT_ANNOTATIONS_FILE, [*read_saved_annotations(source_path, TEXT_ANNOTATIONS_FILE), item])
275
+ return item
@@ -0,0 +1 @@
1
+ """Reading a recording from disk: the formats (TDT, Oxysoft, generic tables, .pt2), the Dataset they produce, and load.py that ties them together."""