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,169 @@
1
+ """
2
+ engine/server.py
3
+ ----------------
4
+ `python -m PyATCLI serve`: the engine as a long-lived process that a window talks to over its standard input and output, one JSON
5
+ object per line, so the window never imports the numerical code and never freezes while it runs.
6
+
7
+ window -> engine {"id": 7, "method": "recording.open", "params": {"path": "D:/rats/Rat7"}}
8
+ {"cancel": 7} stop request 7 (at its next progress report, or before it starts)
9
+ {"method": "shutdown"} finish and exit (so does closing standard input)
10
+ engine -> window {"event": "ready", "protocol": 1, "library": "...", "pid": 1234, "data_dir": "...", "operations": [...]}
11
+ {"id": 7, "event": "progress", "fraction": 0.4, "message": "Reading and processing"}
12
+ {"id": 7, "event": "warning" | "note" | "state", ...}
13
+ {"id": 7, "event": "result", "ok": true, "result": {...}}
14
+ {"id": 7, "event": "error", "ok": false, "error": {"code", "message", "hint", "type"}}
15
+ {"event": "bye"}
16
+
17
+ Requests are done one at a time, in order; a second thread listens for `cancel` and `shutdown` while one runs. The methods are the operations
18
+ (ops/): `operations` lists them with their parameters. Bulk data — a recording's arrays, a big table — is written to files under `data_dir`
19
+ and named in the result, never sent through the pipe (see wire.py). Everything on standard output is protocol; anything a library prints on
20
+ its own is sent to standard error, where `--verbose` shows it.
21
+ """
22
+
23
+ import argparse
24
+ import json
25
+ import os
26
+ import queue
27
+ import sys
28
+ import threading
29
+ import traceback
30
+
31
+ from .. import ops, provenance
32
+ from ..ops import error_info, is_expected, to_jsonable
33
+ from ..progress import Cancelled
34
+ from .session import Session
35
+
36
+
37
+ class _Discard:
38
+ def write(self, text):
39
+ return len(text)
40
+
41
+ def flush(self):
42
+ pass
43
+
44
+
45
+ class _Gone(BaseException):
46
+ """The window's end of the pipe is closed: there is nobody left to answer. (A BaseException, like progress.Cancelled: an analysis that
47
+ is told its progress cannot be heard stops at the next report instead of computing for a window that is no longer there.)"""
48
+
49
+
50
+ def serve(stdin, stdout, stderr, data_dir=None, app=None, verbose=False):
51
+ """Runs the engine on the given streams until it is asked to stop, its input closes, or its output does (the window died: the engine
52
+ ends quietly, with no traceback — a frozen windowed program would show one in a dialog nobody can see). Returns 0."""
53
+ session = Session(data_dir=data_dir, app=app)
54
+ lock = threading.Lock()
55
+
56
+ def send(obj):
57
+ line = json.dumps(to_jsonable(obj), ensure_ascii=True)
58
+ try:
59
+ with lock:
60
+ stdout.write(line + "\n")
61
+ stdout.flush()
62
+ except (OSError, ValueError) as e: # a closed pipe is a BrokenPipeError / OSError; a closed file is a ValueError
63
+ raise _Gone() from e
64
+
65
+ jobs = queue.Queue()
66
+ cancelled = set()
67
+
68
+ def listen():
69
+ try:
70
+ _listen()
71
+ except _Gone: # an answer to a bad line could not be sent: the window is gone
72
+ jobs.put(None)
73
+
74
+ def _listen():
75
+ for raw in stdin:
76
+ line = raw.decode("utf-8", errors="replace") if isinstance(raw, bytes) else raw
77
+ if not line.strip():
78
+ continue
79
+ try:
80
+ message = json.loads(line)
81
+ if not isinstance(message, dict):
82
+ raise ValueError("a message is a JSON object")
83
+ except ValueError as e:
84
+ send({"id": None, "event": "error", "ok": False, "error": {"code": "invalid_input", "message": f"not a request: {e}", "hint": None, "type": "ValueError"}})
85
+ continue
86
+ if "cancel" in message:
87
+ cancelled.add(message["cancel"])
88
+ elif message.get("method") == "shutdown":
89
+ jobs.put(None)
90
+ return
91
+ else:
92
+ jobs.put(message)
93
+ jobs.put(None) # the window closed its end: finish
94
+
95
+ threading.Thread(target=listen, name="engine-listener", daemon=True).start()
96
+ try:
97
+ _serve_requests(session, send, jobs, cancelled, stderr)
98
+ except _Gone:
99
+ pass
100
+ finally:
101
+ session.close()
102
+ return 0
103
+
104
+
105
+ def _serve_requests(session, send, jobs, cancelled, stderr):
106
+ send({"event": "ready", "protocol": ops.PROTOCOL_VERSION, "library": provenance.library_version(), "pid": os.getpid(),
107
+ "data_dir": session.data_dir, "operations": ops.names()})
108
+ while True:
109
+ request = jobs.get()
110
+ if request is None:
111
+ break
112
+ rid = request.get("id")
113
+
114
+ def emit(event, _rid=rid, **fields):
115
+ send({"id": _rid, "event": event, **fields})
116
+
117
+ try:
118
+ if rid in cancelled:
119
+ raise Cancelled()
120
+ if not isinstance(request.get("method"), str):
121
+ raise ValueError("a request has a method")
122
+ result = session.handle(request["method"], request.get("params"), emit, lambda _rid=rid: _rid in cancelled)
123
+ send({"id": rid, "event": "result", "ok": True, "result": result})
124
+ except Cancelled:
125
+ send({"id": rid, "event": "error", "ok": False, "error": error_info(Cancelled())})
126
+ except Exception as e: # noqa: BLE001 — an error in one request is that request's answer, not the engine's end
127
+ if not is_expected(e):
128
+ print(traceback.format_exc(), file=stderr)
129
+ send({"id": rid, "event": "error", "ok": False, "error": error_info(e)})
130
+ finally:
131
+ cancelled.discard(rid)
132
+ send({"event": "bye"})
133
+
134
+
135
+ def main(argv=None):
136
+ p = argparse.ArgumentParser(prog="python -m PyATCLI serve", description=__doc__.split("\n\n")[0],
137
+ formatter_class=argparse.RawDescriptionHelpFormatter,
138
+ epilog="The protocol is described in PyATCLI/engine/server.py and API_REFERENCE.md (Engine).")
139
+ p.add_argument("--data-dir", metavar="DIR", help="where bulk results (arrays, big tables) are written (default: a temporary folder, removed on exit)")
140
+ p.add_argument("--app-name", default="PyATCLI engine", help="the program asking, for the provenance records the engine writes")
141
+ p.add_argument("--app-version", help="its version")
142
+ p.add_argument("--verbose", "-v", action="store_true", help="show what libraries print, and the tracebacks of bugs, on stderr")
143
+ args = p.parse_args(argv)
144
+ app = {"name": args.app_name}
145
+ if args.app_version:
146
+ app["version"] = args.app_version
147
+ protocol_out = sys.stdout
148
+ try:
149
+ protocol_out.reconfigure(newline="\n", encoding="utf-8") # one LF per message, whatever the platform's text mode
150
+ except (AttributeError, ValueError):
151
+ pass
152
+ sys.stdout = sys.stderr if args.verbose else _Discard() # a library that prints must not corrupt the protocol
153
+ try:
154
+ return serve(sys.stdin.buffer, protocol_out, sys.stderr, data_dir=args.data_dir, app=app, verbose=args.verbose)
155
+ except KeyboardInterrupt:
156
+ return 130
157
+ except Exception: # noqa: BLE001 — a bug in the engine: say so on stderr, and end (not a dialog)
158
+ traceback.print_exc(file=sys.stderr)
159
+ return 1
160
+ finally:
161
+ try:
162
+ protocol_out.flush()
163
+ except (OSError, ValueError): # the window is gone: Python's own flush at exit must not complain about it
164
+ protocol_out = _Discard()
165
+ sys.stdout = protocol_out
166
+
167
+
168
+ if __name__ == "__main__":
169
+ sys.exit(main())
@@ -0,0 +1,40 @@
1
+ """
2
+ engine/session.py
3
+ -----------------
4
+ One engine session: the recordings it holds open (store.py), the folder its bulk results are written to, and `handle`, which runs one
5
+ operation. The JSON-lines server (server.py) is a transport around this, and so is PyAT's in-process engine (used when no second process
6
+ is wanted: tests, debugging) — the operations see the same context either way.
7
+ """
8
+
9
+ import os
10
+ import shutil
11
+ import tempfile
12
+
13
+ from .. import ops
14
+ from ..ops import OpContext
15
+ from .store import RecordingStore
16
+
17
+
18
+ class Session:
19
+ def __init__(self, data_dir=None, app=None):
20
+ self._owns_dir = data_dir is None
21
+ self.data_dir = data_dir or tempfile.mkdtemp(prefix="pyatcli-engine-")
22
+ os.makedirs(self.data_dir, exist_ok=True)
23
+ self.store = RecordingStore(self.data_dir)
24
+ self.app = dict(app or {"name": "PyATCLI engine"})
25
+
26
+ def context(self, emit=None, cancelled=None):
27
+ return OpContext(emit=emit, cancelled=cancelled, store=self.store, data_dir=self.data_dir, app=self.app, wants_progress=emit is not None)
28
+
29
+ def handle(self, method, params=None, emit=None, cancelled=None):
30
+ """Runs operation `method` with `params` and returns its JSON-ready result. `emit(event, **fields)` hears progress, warnings, notes and
31
+ files written; `cancelled()` returning True stops the work at its next progress report (ops.Cancelled)."""
32
+ return ops.call(method, params, self.context(emit, cancelled))
33
+
34
+ def close(self):
35
+ """Lets go of every recording and, if the session made its own data folder, removes it (best effort: a file a window still has
36
+ mapped cannot be deleted on Windows, and is left for the system's temporary-file cleanup)."""
37
+ for entry_id in self.store.ids():
38
+ self.store.close(entry_id)
39
+ if self._owns_dir:
40
+ shutil.rmtree(self.data_dir, ignore_errors=True)
@@ -0,0 +1,222 @@
1
+ """
2
+ engine/store.py
3
+ ---------------
4
+ The recordings the engine holds between requests, so a window pays for opening one once (seconds: reading the tank, fitting the dF/F)
5
+ and every later request is a lookup.
6
+
7
+ A recording is held as the recording as recorded (`base`) and the variants of it a list of splices makes — a splice stacks on the ones
8
+ before it, each one re-fits the dF/F, and Ctrl+Z, removing a splice and Restore Full Recording are all just *which list* is asked for.
9
+ So a request names the recording and the splice list it wants, never "the current one": the engine keeps what it has worked out for each
10
+ list (the most recent few), and the same request twice, or after an undo, costs nothing.
11
+
12
+ ref = {"id": "r1", "splices": [{"mode": "cut_out", "start": 40, "end": 55}],
13
+ "markers": [...], "signal_labels": {"normalized": "GCaMP"}}
14
+
15
+ The markers, highlights, text boxes and signal names in a reference are the caller's own state, put on a shallow copy of the variant (the
16
+ arrays are shared): they decide what an analysis sees without the engine having to keep a second copy of a window's edits in step.
17
+ """
18
+
19
+ import json
20
+ import os
21
+ import shutil
22
+ from collections import OrderedDict
23
+
24
+ from ..splice import MODE_CUT_OUT, splice_cut_out, splice_keep_inside
25
+ from ..recording import (HIGHLIGHTS_FILE, TEXT_ANNOTATIONS_FILE, annotation_sidecar_path, apply_signal_labels, apply_splice,
26
+ legacy_marker_sidecar_path, load_recording, marker_sidecar_path, read_saved_signal_labels, spliced_store_name)
27
+ from ..ops import OpError
28
+ from .wire import ArrayFiles, encode
29
+
30
+ MAX_VARIANTS = 6 # spliced variants kept besides the recording as recorded
31
+
32
+
33
+ def splice_key(splices):
34
+ return tuple((s["mode"], float(s["start"]), float(s["end"])) for s in splices)
35
+
36
+
37
+ def _clean(splices):
38
+ return [{"mode": s["mode"], "start": float(s["start"]), "end": float(s["end"])} for s in splices]
39
+
40
+
41
+ def _saved_labels(path, cache):
42
+ """{signal key: name} the recording's saved state gave its signals ({} if none, or the file is unreadable: the load already warned)."""
43
+ signals = cache.get("signals") or {}
44
+ try:
45
+ saved = read_saved_signal_labels(path)
46
+ except Exception: # noqa: BLE001
47
+ return {}
48
+ return {k: v for k, v in saved.items() if k in signals and v}
49
+
50
+
51
+ def _restored(path, cache, splices):
52
+ """What the saved state put on the recording, for a window to tell the person: the number of splices replayed, and how many markers,
53
+ highlights and text boxes were read back (None where nothing was saved, so "restored 0" is never said of a file that is not there)."""
54
+ def exists(p):
55
+ return bool(p) and os.path.exists(p)
56
+
57
+ saved_markers = exists(marker_sidecar_path(path)) or exists(legacy_marker_sidecar_path(path))
58
+ out = {"splices": len(splices), "markers": len(cache.get("markers", [])) if saved_markers else None}
59
+ for key, filename in (("highlights", HIGHLIGHTS_FILE), ("text_annotations", TEXT_ANNOTATIONS_FILE)):
60
+ out[key] = len(cache.get(key, [])) if exists(annotation_sidecar_path(path, filename)) else None
61
+ return out
62
+
63
+
64
+ class Entry:
65
+ """One open recording: where it came from, how it was opened, the recording as recorded and the splice variants worked out so far."""
66
+
67
+ def __init__(self, entry_id, path, options, loaded, data_dir):
68
+ self.id, self.path, self.options = entry_id, path, options
69
+ self.base = loaded["original_cache"] if loaded["original_cache"] is not None else loaded["cache"]
70
+ self.initial_splices = _clean(loaded["splices"])
71
+ self.warnings = list(loaded["warnings"])
72
+ self.variants = OrderedDict()
73
+ self.variants[splice_key([])] = self.base
74
+ self.variants[splice_key(self.initial_splices)] = loaded["cache"]
75
+ self.files = ArrayFiles(os.path.join(data_dir, entry_id))
76
+ used_saved = options.get("use_saved", True)
77
+ self.saved_labels = _saved_labels(path, loaded["cache"]) if used_saved else {}
78
+ self.restored = _restored(path, loaded["cache"], self.initial_splices) if used_saved else {"splices": 0, "markers": None, "highlights": None, "text_annotations": None}
79
+
80
+ @property
81
+ def method(self):
82
+ return self.options.get("regression_method") or "ols"
83
+
84
+ def cache_for(self, splices, progress=None):
85
+ """The recording with `splices` applied (stacked, in order): from what is already worked out, or by applying the missing ones to
86
+ the longest prefix that is. ValueError if a splice leaves too little of the recording."""
87
+ splices = _clean(splices)
88
+ key = splice_key(splices)
89
+ if key in self.variants:
90
+ self.variants.move_to_end(key)
91
+ return self.variants[key]
92
+ have = max((n for n in range(len(splices) + 1) if splice_key(splices[:n]) in self.variants), default=0)
93
+ cache = self.variants[splice_key(splices[:have])]
94
+ todo = splices[have:]
95
+ for i, s in enumerate(todo):
96
+ sub = None if progress is None else (lambda f, m="", i=i: progress((i + f) / len(todo), m))
97
+ spliced = apply_splice(cache, s["mode"], s["start"], s["end"], regression_method=self.method, progress=sub)
98
+ if spliced is None:
99
+ raise OpError(f"a {s['mode']} of {s['start']:g}..{s['end']:g} s leaves too little of the recording (fewer than 2 samples)",
100
+ "invalid_input")
101
+ cache = spliced
102
+ cache['store'] = spliced_store_name(self.base['store'], splices[:have + i + 1])
103
+ self.variants[splice_key(splices[:have + i + 1])] = cache
104
+ self._trim()
105
+ return cache
106
+
107
+ def _trim(self):
108
+ keep = {splice_key([]), splice_key(self.initial_splices)}
109
+ extra = [k for k in self.variants if k not in keep]
110
+ for k in extra[:max(0, len(extra) - MAX_VARIANTS)]:
111
+ del self.variants[k] # its arrays are freed once nothing else holds them, and their files swept
112
+ self.files.sweep()
113
+
114
+ def move_markers(self, markers, splices, start=0):
115
+ """`markers` (dicts with a time) moved through the splices of the list, in order, the way each splice moves the markers of the
116
+ recording it is applied to — from the first splice (`start=0`: the markers are on the recording as recorded) or from splice number
117
+ `start` (they are on the timeline the first `start` splices leave). Returns the moved list: a marker in a stretch cut out is gone."""
118
+ splices = _clean(splices)
119
+ moved = list(markers)
120
+ for i in range(start, len(splices)):
121
+ s = splices[i]
122
+ before = self.cache_for(splices[:i])
123
+ fn = splice_cut_out if s["mode"] == MODE_CUT_OUT else splice_keep_inside
124
+ result = fn(before["x"], before["x"], before["x"], moved, [], s["start"], s["end"])
125
+ if result:
126
+ moved = result["markers"]
127
+ return moved
128
+
129
+ def set_signal_labels(self, labels):
130
+ """The names the recording's signals are given, on every variant held (and the recording as recorded)."""
131
+ for cache in {id(c): c for c in self.variants.values()}.values():
132
+ apply_signal_labels(cache, labels)
133
+
134
+ def resolve(self, ref=None, progress=None):
135
+ """The recording a reference names, as load_recording's dict: {"cache", "original_cache", "splices", "warnings"}."""
136
+ ref = ref or {}
137
+ splices = _clean(ref["splices"]) if ref.get("splices") is not None else self.initial_splices
138
+ cache = self.cache_for(splices, progress)
139
+ overrides = {k: ref[k] for k in ("markers", "highlights", "text_annotations") if ref.get(k) is not None}
140
+ if overrides or ref.get("signal_labels"):
141
+ cache = dict(cache)
142
+ cache.update(overrides)
143
+ if ref.get("signal_labels"):
144
+ apply_signal_labels(cache, ref["signal_labels"])
145
+ return {"cache": cache, "original_cache": self.base if splices else None, "splices": splices, "warnings": []}
146
+
147
+ def loaded(self):
148
+ return self.resolve({})
149
+
150
+ def wire(self, splices=None, progress=None):
151
+ """What a window needs to hold this recording: its structure as JSON and its arrays as .npy references (see wire.py)."""
152
+ splices = self.initial_splices if splices is None else _clean(splices)
153
+ cache = self.cache_for(splices, progress)
154
+ return {"id": self.id, "path": self.path, "splices": splices, "warnings": self.warnings,
155
+ "directory": self.files.directory, "cache": encode(cache, self.files)}
156
+
157
+
158
+ def opened(self, progress=None):
159
+ """wire(), plus what a window needs on opening: the recording as recorded when a saved splice was replayed (what Restore Full
160
+ Recording brings back), the names saved for its signals, and what the saved state restored."""
161
+ result = self.wire(progress=progress)
162
+ result.update(original_cache=encode(self.base, self.files) if self.initial_splices else None,
163
+ signal_labels=dict(self.saved_labels), restored=dict(self.restored), regression_method=self.method)
164
+ return result
165
+
166
+
167
+ class RecordingStore:
168
+ def __init__(self, data_dir):
169
+ self.data_dir = data_dir
170
+ self._entries = {}
171
+ self._by_key = {}
172
+ self._count = 0
173
+ self._leftovers = [] # data folders of closed recordings that could not be removed yet (a window still maps a file)
174
+
175
+ def open(self, path, options, progress=None, fresh=False):
176
+ """The entry for `path` opened with `options` — the one already open if there is one, else a fresh load. `fresh` reads the disk
177
+ again even if it is open (a window's Reload: the files may have changed since), letting go of the old entry."""
178
+ self.sweep()
179
+ key = (os.path.normcase(os.path.abspath(path)), json.dumps(options, sort_keys=True))
180
+ existing = self._by_key.get(key)
181
+ if existing is not None and fresh:
182
+ self.close(existing)
183
+ existing = None
184
+ if existing is not None:
185
+ return self._entries[existing]
186
+ loaded = load_recording(path, progress=progress, **options)
187
+ self._count += 1
188
+ entry = Entry(f"r{self._count}", path, dict(options), loaded, self.data_dir)
189
+ self._entries[entry.id] = entry
190
+ self._by_key[key] = entry.id
191
+ return entry
192
+
193
+ def get(self, entry_id):
194
+ try:
195
+ return self._entries[entry_id]
196
+ except KeyError:
197
+ raise OpError(f"the engine has no open recording {entry_id!r}", "no_recording",
198
+ hint="it was closed, or the engine was restarted: open it again") from None
199
+
200
+ def close(self, entry_id):
201
+ entry = self.get(entry_id)
202
+ del self._entries[entry_id]
203
+ self._by_key = {k: v for k, v in self._by_key.items() if v != entry_id}
204
+ entry.variants.clear()
205
+ entry.files.forget()
206
+ self._leftovers.append(entry.files.directory)
207
+ self.sweep()
208
+
209
+ def ids(self):
210
+ return list(self._entries)
211
+
212
+ def sweep(self):
213
+ """Removes the data folders of recordings that were closed. A file a window still maps cannot be removed on Windows: its folder
214
+ stays on the list and goes the next time (or at the end of the session)."""
215
+ left = []
216
+ for directory in self._leftovers:
217
+ shutil.rmtree(directory, ignore_errors=True)
218
+ if os.path.exists(directory):
219
+ left.append(directory)
220
+ self._leftovers = left
221
+ for entry in self._entries.values():
222
+ entry.files.sweep()
PyATCLI/engine/wire.py ADDED
@@ -0,0 +1,103 @@
1
+ """
2
+ engine/wire.py
3
+ --------------
4
+ How a recording crosses the process boundary. A recording (the cache dict of recording.py) is a few kilobytes of structure — names,
5
+ markers, sampling rate — and tens of megabytes of arrays (a 17-minute, 3-signal TDT recording is 34 MB). The structure travels as JSON;
6
+ every array is written once as an `.npy` file in the engine's data folder and replaced, in the structure, by a small reference:
7
+
8
+ {"__array__": "0003_signals.normalized.y.npy", "dtype": "float64", "shape": [1055744]}
9
+
10
+ The receiver maps those files (`numpy.load(..., mmap_mode="c")`: nothing is read until it is touched, and an edit stays in memory, never
11
+ in the file), so a window can plot a million samples without them ever passing through a pipe or being parsed. An array two places of the
12
+ cache point to (the normalized signal is also `corr`) is one file and, on the other side, one array.
13
+ """
14
+
15
+ import os
16
+ import weakref
17
+ from collections import deque
18
+
19
+ import numpy as np
20
+
21
+ ARRAY_KEY = "__array__"
22
+
23
+
24
+ class ArrayFiles:
25
+ """The `.npy` files of one data folder: writes each array the first time it is asked for and gives the same name after."""
26
+
27
+ def __init__(self, directory):
28
+ self.directory = directory
29
+ self._by_id = {} # id(array) -> (weak reference to the array, its file name)
30
+ self._orphans = deque() # files whose array has been freed, to remove when nothing maps them any more
31
+ self._count = 0
32
+
33
+ def name_for(self, array, hint=""):
34
+ key = id(array)
35
+ known = self._by_id.get(key)
36
+ if known is not None and known[0]() is array: # (an id can be reused once its array is freed: the weak reference says whose it is)
37
+ return known[1]
38
+ os.makedirs(self.directory, exist_ok=True)
39
+ self._count += 1
40
+ safe = "".join(c if c.isalnum() or c in "._-" else "_" for c in hint)[:60].strip("._") or "array"
41
+ name = f"{self._count:04d}_{safe}.npy"
42
+ np.save(os.path.join(self.directory, name), np.ascontiguousarray(array), allow_pickle=False)
43
+ # Weak: the files outlive the arrays only until the next sweep, and an engine that has worked out many splices holds the
44
+ # variants it keeps, not every array it ever wrote.
45
+ self._by_id[key] = (weakref.ref(array, lambda _ref, key=key, name=name: self._freed(key, name)), name)
46
+ return name
47
+
48
+ def _freed(self, key, name):
49
+ known = self._by_id.get(key)
50
+ if known is not None and known[1] == name:
51
+ del self._by_id[key]
52
+ self._orphans.append(name)
53
+
54
+ def sweep(self):
55
+ """Removes the files of arrays that have been freed. A file a window still maps cannot be removed on Windows: it stays on the list
56
+ for the next sweep."""
57
+ for _ in range(len(self._orphans)): # (a weak-reference callback may add one from another thread meanwhile)
58
+ name = self._orphans.popleft()
59
+ try:
60
+ os.remove(os.path.join(self.directory, name))
61
+ except FileNotFoundError:
62
+ pass
63
+ except OSError:
64
+ self._orphans.append(name)
65
+
66
+ def forget(self):
67
+ """Lets go of the arrays (not the files)."""
68
+ self._by_id.clear()
69
+
70
+
71
+ def encode(obj, files, hint=""):
72
+ """`obj` (a cache or any structure of dicts, lists, numbers, strings and arrays) as JSON-ready values, its arrays written by `files`."""
73
+ if isinstance(obj, np.ndarray):
74
+ if obj.dtype == object:
75
+ return [encode(v, files, hint) for v in obj.tolist()]
76
+ return {ARRAY_KEY: files.name_for(obj, hint), "dtype": str(obj.dtype), "shape": list(obj.shape)}
77
+ if isinstance(obj, dict):
78
+ return {str(k): encode(v, files, f"{hint}.{k}" if hint else str(k)) for k, v in obj.items()}
79
+ if isinstance(obj, (list, tuple)):
80
+ return [encode(v, files, hint) for v in obj]
81
+ if isinstance(obj, np.generic):
82
+ return encode(obj.item(), files, hint)
83
+ if isinstance(obj, float) and obj != obj:
84
+ return None
85
+ if obj is None or isinstance(obj, (bool, int, float, str)):
86
+ return obj
87
+ return str(obj)
88
+
89
+
90
+ def decode(obj, directory, mmap=True, _loaded=None):
91
+ """The structure `encode` made, with its arrays loaded back: mapped (copy-on-write) from the files in `directory`. The same file is
92
+ the same array object."""
93
+ loaded = {} if _loaded is None else _loaded
94
+ if isinstance(obj, dict):
95
+ if ARRAY_KEY in obj:
96
+ name = obj[ARRAY_KEY]
97
+ if name not in loaded:
98
+ loaded[name] = np.load(os.path.join(directory, name), mmap_mode="c" if mmap else None, allow_pickle=False)
99
+ return loaded[name]
100
+ return {k: decode(v, directory, mmap, loaded) for k, v in obj.items()}
101
+ if isinstance(obj, list):
102
+ return [decode(v, directory, mmap, loaded) for v in obj]
103
+ return obj
@@ -0,0 +1 @@
1
+ """The text-field study: the pipeline (study.py) and the statistical validation of its paired-similarity metric (validation.py)."""