ephys-mcp 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,123 @@
1
+ Metadata-Version: 2.4
2
+ Name: ephys-mcp
3
+ Version: 0.1.0
4
+ Summary: MCP server for read-only analysis of intracortical (spike-level) brain-computer-interface recordings
5
+ Keywords: mcp,bci,electrophysiology,neuroscience,spikes,nwb,dandi
6
+ Author: happyc0der
7
+ Author-email: happyc0der <Keshav.Rajput4@gmail.com>
8
+ License-Expression: CC0-1.0
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Intended Audience :: Science/Research
11
+ Classifier: License :: CC0 1.0 Universal (CC0 1.0) Public Domain Dedication
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Topic :: Scientific/Engineering
14
+ Requires-Dist: h5py>=3.16.0
15
+ Requires-Dist: httpx>=0.28.1
16
+ Requires-Dist: matplotlib>=3.11.2
17
+ Requires-Dist: mcp[cli]>=2.2.0
18
+ Requires-Dist: numpy>=2.5.3
19
+ Requires-Dist: pynwb>=4.2.0
20
+ Requires-Dist: remfile>=0.1.14
21
+ Requires-Dist: scipy>=1.18.1
22
+ Requires-Python: >=3.12
23
+ Project-URL: Homepage, https://github.com/happyc0der/ephys-mcp
24
+ Project-URL: Repository, https://github.com/happyc0der/ephys-mcp
25
+ Project-URL: Issues, https://github.com/happyc0der/ephys-mcp/issues
26
+ Description-Content-Type: text/markdown
27
+
28
+ # ephys-mcp
29
+
30
+ An [MCP](https://modelcontextprotocol.io) server that lets an LLM analyse **intracortical (spike-level) brain-computer-interface recordings**: signal quality, spike detection, firing rates, and cursor-velocity decoding.
31
+
32
+ Existing BCI MCP servers target scalp EEG. This one targets the kind of data a high-channel-count implant produces, and defines a read-only adapter contract so a live device backend can be added when a vendor publishes an API.
33
+
34
+ > Research and education software. **Not a medical device. Not for clinical use.**
35
+ > Not affiliated with or endorsed by Neuralink Corp. or any other implant manufacturer.
36
+
37
+ ## Status
38
+
39
+ v0.1, early. Working today: local NWB files, local broadband WAV recordings, streaming from the DANDI Archive, a synthetic motor-cortex source with ground truth, spike detection, quality metrics, ridge and Kalman decoders, trial-aligned PSTHs, and figures. Planned: PyPI release and registry listings.
40
+
41
+ ## Install and run
42
+
43
+ Needs [uv](https://docs.astral.sh/uv/). No install step: `uvx ephys-mcp` fetches the package and starts the server on stdio.
44
+
45
+ Claude Code:
46
+
47
+ ```bash
48
+ claude mcp add ephys -- uvx ephys-mcp
49
+ ```
50
+
51
+ Claude Desktop (`claude_desktop_config.json`):
52
+
53
+ ```json
54
+ { "mcpServers": { "ephys": { "command": "uvx", "args": ["ephys-mcp"] } } }
55
+ ```
56
+
57
+ From a checkout, use `uv run ephys-mcp` instead, or `uv --directory /path/to/ephys-mcp run ephys-mcp` in the configs above.
58
+
59
+ Then ask, for real data: *"Find a small motor cortex dataset on DANDI, open it, and tell me how well hand velocity can be decoded."*
60
+ Or offline: *"Open a synthetic session, check signal quality, fit a Kalman decoder and show me a decoded window."*
61
+
62
+ ## Data sources
63
+
64
+ | Source | What it opens |
65
+ | --- | --- |
66
+ | `synthetic` | Simulated units tuned to cursor velocity, with broadband signal and ground truth |
67
+ | `nwb` | A local `.nwb` file (`params.path`) |
68
+ | `wav_dir` | Local broadband WAV (`params.path`): a folder of mono clips, one channel each, or one multi-channel file |
69
+ | `dandi` | An NWB file streamed from the [DANDI Archive](https://dandiarchive.org) by HTTP range requests; nothing is mirrored |
70
+ | `n1_stub` | Not implemented. Documents the contract for a live implant adapter |
71
+
72
+ Dataset licence and citation come from the archive and are returned by `open_session`, so the model can attribute the data. Many datasets record only during trials; the server tracks those spans (`recorded_fraction`) and leaves the gaps out of rates and decoding instead of reading them as silence.
73
+
74
+ WAV samples carry no physical unit, so amplitudes are reported as ADC counts unless you pass `uv_per_count`; every amplitude result names its unit. Clips in a folder are separate recordings, so the server says that timing across those channels is not meaningful. Spike times from WAV are threshold crossings, not sorted units.
75
+
76
+ Reference result on MC_Maze_Small (DANDI 000140, 142 units, last 20% held out, 50 ms bins): ridge R² 0.50, Kalman R² 0.34 for hand velocity. These are simple causal linear baselines, not state of the art.
77
+
78
+ ## Tools
79
+
80
+ | Tool | Purpose |
81
+ | --- | --- |
82
+ | `list_sources` | Source types and their parameters |
83
+ | `search_datasets` | Search DANDI, or list curated intracortical datasets |
84
+ | `list_dataset_files` | Licence, citation and NWB files of a DANDI dataset |
85
+ | `open_session` / `close_session` | Session lifecycle |
86
+ | `get_session_info` | Channels, rates, behaviour signals, licence, citation |
87
+ | `get_signal_quality` | Noise, SNR, dead/noisy channels |
88
+ | `detect_spikes` | Threshold crossings; precision/recall when truth exists |
89
+ | `get_firing_rates` | Population rate summary |
90
+ | `fit_decoder` | Ridge or Kalman, scored on held-out data; hyperparameters chosen inside the training split |
91
+ | `decode_window` | Decoded-vs-true preview for a window |
92
+ | `get_psth` | Firing aligned to a trial event, optionally grouped by a trial column or limited to some units |
93
+ | `plot_psth` | Figure: PSTH per group with SEM, above a unit-by-time heatmap of change from baseline |
94
+ | `plot_raster` | Figure: spike raster, unrecorded spans shaded |
95
+ | `plot_decoding` | Figure: decoded against actual behaviour, one panel per dimension |
96
+
97
+ Resource: `ephys://sessions`. Prompt: `analyze_session`.
98
+
99
+ Tools return summaries, never raw arrays, so results fit in a model's context.
100
+
101
+ Plot tools return the PNG inline, so a vision-capable model can read the figure, and also save it under `~/.cache/ephys-mcp/plots` (override with `EPHYS_MCP_OUTPUT_DIR`). Figures use a categorical palette checked for colour-blind separation, with direct labels so identity never rests on colour alone.
102
+
103
+ ## Design rules
104
+
105
+ - **Read-only.** The `NeuralSource` contract has no write, stimulate or configure method. None will be added without a separate safety design.
106
+ - **Local by default.** stdio transport, no telemetry. Neural data is sensitive.
107
+ - **No bundled third-party data.** See [DATA_LICENSES.md](DATA_LICENSES.md).
108
+
109
+ ## Writing a source adapter
110
+
111
+ Subclass `ephys_mcp.sources.base.NeuralSource` (`info`, `read_raw`, `spike_times`, `behavior`) and register it in `ephys_mcp/sources/__init__.py`. `sources/n1_stub.py` documents what a live implant adapter would need.
112
+
113
+ ## Development
114
+
115
+ ```bash
116
+ uv run pytest # offline
117
+ uv run pytest -m network # also streams a real file from DANDI
118
+ uv run ruff check .
119
+ ```
120
+
121
+ ## Licence
122
+
123
+ [CC0 1.0 Universal](LICENSE). The authors waive all copyright and related rights to the extent the law allows. Use it for anything, no attribution required. CC0 does not grant patent or trademark rights.
@@ -0,0 +1,96 @@
1
+ # ephys-mcp
2
+
3
+ An [MCP](https://modelcontextprotocol.io) server that lets an LLM analyse **intracortical (spike-level) brain-computer-interface recordings**: signal quality, spike detection, firing rates, and cursor-velocity decoding.
4
+
5
+ Existing BCI MCP servers target scalp EEG. This one targets the kind of data a high-channel-count implant produces, and defines a read-only adapter contract so a live device backend can be added when a vendor publishes an API.
6
+
7
+ > Research and education software. **Not a medical device. Not for clinical use.**
8
+ > Not affiliated with or endorsed by Neuralink Corp. or any other implant manufacturer.
9
+
10
+ ## Status
11
+
12
+ v0.1, early. Working today: local NWB files, local broadband WAV recordings, streaming from the DANDI Archive, a synthetic motor-cortex source with ground truth, spike detection, quality metrics, ridge and Kalman decoders, trial-aligned PSTHs, and figures. Planned: PyPI release and registry listings.
13
+
14
+ ## Install and run
15
+
16
+ Needs [uv](https://docs.astral.sh/uv/). No install step: `uvx ephys-mcp` fetches the package and starts the server on stdio.
17
+
18
+ Claude Code:
19
+
20
+ ```bash
21
+ claude mcp add ephys -- uvx ephys-mcp
22
+ ```
23
+
24
+ Claude Desktop (`claude_desktop_config.json`):
25
+
26
+ ```json
27
+ { "mcpServers": { "ephys": { "command": "uvx", "args": ["ephys-mcp"] } } }
28
+ ```
29
+
30
+ From a checkout, use `uv run ephys-mcp` instead, or `uv --directory /path/to/ephys-mcp run ephys-mcp` in the configs above.
31
+
32
+ Then ask, for real data: *"Find a small motor cortex dataset on DANDI, open it, and tell me how well hand velocity can be decoded."*
33
+ Or offline: *"Open a synthetic session, check signal quality, fit a Kalman decoder and show me a decoded window."*
34
+
35
+ ## Data sources
36
+
37
+ | Source | What it opens |
38
+ | --- | --- |
39
+ | `synthetic` | Simulated units tuned to cursor velocity, with broadband signal and ground truth |
40
+ | `nwb` | A local `.nwb` file (`params.path`) |
41
+ | `wav_dir` | Local broadband WAV (`params.path`): a folder of mono clips, one channel each, or one multi-channel file |
42
+ | `dandi` | An NWB file streamed from the [DANDI Archive](https://dandiarchive.org) by HTTP range requests; nothing is mirrored |
43
+ | `n1_stub` | Not implemented. Documents the contract for a live implant adapter |
44
+
45
+ Dataset licence and citation come from the archive and are returned by `open_session`, so the model can attribute the data. Many datasets record only during trials; the server tracks those spans (`recorded_fraction`) and leaves the gaps out of rates and decoding instead of reading them as silence.
46
+
47
+ WAV samples carry no physical unit, so amplitudes are reported as ADC counts unless you pass `uv_per_count`; every amplitude result names its unit. Clips in a folder are separate recordings, so the server says that timing across those channels is not meaningful. Spike times from WAV are threshold crossings, not sorted units.
48
+
49
+ Reference result on MC_Maze_Small (DANDI 000140, 142 units, last 20% held out, 50 ms bins): ridge R² 0.50, Kalman R² 0.34 for hand velocity. These are simple causal linear baselines, not state of the art.
50
+
51
+ ## Tools
52
+
53
+ | Tool | Purpose |
54
+ | --- | --- |
55
+ | `list_sources` | Source types and their parameters |
56
+ | `search_datasets` | Search DANDI, or list curated intracortical datasets |
57
+ | `list_dataset_files` | Licence, citation and NWB files of a DANDI dataset |
58
+ | `open_session` / `close_session` | Session lifecycle |
59
+ | `get_session_info` | Channels, rates, behaviour signals, licence, citation |
60
+ | `get_signal_quality` | Noise, SNR, dead/noisy channels |
61
+ | `detect_spikes` | Threshold crossings; precision/recall when truth exists |
62
+ | `get_firing_rates` | Population rate summary |
63
+ | `fit_decoder` | Ridge or Kalman, scored on held-out data; hyperparameters chosen inside the training split |
64
+ | `decode_window` | Decoded-vs-true preview for a window |
65
+ | `get_psth` | Firing aligned to a trial event, optionally grouped by a trial column or limited to some units |
66
+ | `plot_psth` | Figure: PSTH per group with SEM, above a unit-by-time heatmap of change from baseline |
67
+ | `plot_raster` | Figure: spike raster, unrecorded spans shaded |
68
+ | `plot_decoding` | Figure: decoded against actual behaviour, one panel per dimension |
69
+
70
+ Resource: `ephys://sessions`. Prompt: `analyze_session`.
71
+
72
+ Tools return summaries, never raw arrays, so results fit in a model's context.
73
+
74
+ Plot tools return the PNG inline, so a vision-capable model can read the figure, and also save it under `~/.cache/ephys-mcp/plots` (override with `EPHYS_MCP_OUTPUT_DIR`). Figures use a categorical palette checked for colour-blind separation, with direct labels so identity never rests on colour alone.
75
+
76
+ ## Design rules
77
+
78
+ - **Read-only.** The `NeuralSource` contract has no write, stimulate or configure method. None will be added without a separate safety design.
79
+ - **Local by default.** stdio transport, no telemetry. Neural data is sensitive.
80
+ - **No bundled third-party data.** See [DATA_LICENSES.md](DATA_LICENSES.md).
81
+
82
+ ## Writing a source adapter
83
+
84
+ Subclass `ephys_mcp.sources.base.NeuralSource` (`info`, `read_raw`, `spike_times`, `behavior`) and register it in `ephys_mcp/sources/__init__.py`. `sources/n1_stub.py` documents what a live implant adapter would need.
85
+
86
+ ## Development
87
+
88
+ ```bash
89
+ uv run pytest # offline
90
+ uv run pytest -m network # also streams a real file from DANDI
91
+ uv run ruff check .
92
+ ```
93
+
94
+ ## Licence
95
+
96
+ [CC0 1.0 Universal](LICENSE). The authors waive all copyright and related rights to the extent the law allows. Use it for anything, no attribution required. CC0 does not grant patent or trademark rights.
@@ -0,0 +1,68 @@
1
+ [project]
2
+ name = "ephys-mcp"
3
+ version = "0.1.0"
4
+ description = "MCP server for read-only analysis of intracortical (spike-level) brain-computer-interface recordings"
5
+ license = "CC0-1.0"
6
+ keywords = [
7
+ "mcp",
8
+ "bci",
9
+ "electrophysiology",
10
+ "neuroscience",
11
+ "spikes",
12
+ "nwb",
13
+ "dandi",
14
+ ]
15
+ classifiers = [
16
+ "Development Status :: 3 - Alpha",
17
+ "Intended Audience :: Science/Research",
18
+ "License :: CC0 1.0 Universal (CC0 1.0) Public Domain Dedication",
19
+ "Programming Language :: Python :: 3",
20
+ "Topic :: Scientific/Engineering",
21
+ ]
22
+ readme = "README.md"
23
+ requires-python = ">=3.12"
24
+ dependencies = [
25
+ "h5py>=3.16.0",
26
+ "httpx>=0.28.1",
27
+ "matplotlib>=3.11.2",
28
+ "mcp[cli]>=2.2.0",
29
+ "numpy>=2.5.3",
30
+ "pynwb>=4.2.0",
31
+ "remfile>=0.1.14",
32
+ "scipy>=1.18.1",
33
+ ]
34
+
35
+ [[project.authors]]
36
+ name = "happyc0der"
37
+ email = "Keshav.Rajput4@gmail.com"
38
+
39
+ [project.urls]
40
+ Homepage = "https://github.com/happyc0der/ephys-mcp"
41
+ Repository = "https://github.com/happyc0der/ephys-mcp"
42
+ Issues = "https://github.com/happyc0der/ephys-mcp/issues"
43
+
44
+ [project.scripts]
45
+ ephys-mcp = "ephys_mcp.server:main"
46
+
47
+ [build-system]
48
+ requires = ["uv_build>=0.12.10,<0.13.0"]
49
+ build-backend = "uv_build"
50
+
51
+ [dependency-groups]
52
+ dev = [
53
+ "pytest>=9.1.1",
54
+ "pytest-asyncio>=1.4.0",
55
+ "ruff>=0.16.8",
56
+ ]
57
+
58
+ [tool.ruff]
59
+ line-length = 120
60
+
61
+ [tool.pytest.ini_options]
62
+ asyncio_mode = "auto"
63
+ markers = ["network: needs internet access to the DANDI Archive"]
64
+ addopts = "-m 'not network'"
65
+ filterwarnings = [
66
+ "ignore::UserWarning:hdmf",
67
+ "ignore::UserWarning:pynwb",
68
+ ]
@@ -0,0 +1,56 @@
1
+ [project]
2
+ name = "ephys-mcp"
3
+ version = "0.1.0"
4
+ description = "MCP server for read-only analysis of intracortical (spike-level) brain-computer-interface recordings"
5
+ license = "CC0-1.0"
6
+ keywords = ["mcp", "bci", "electrophysiology", "neuroscience", "spikes", "nwb", "dandi"]
7
+ classifiers = [
8
+ "Development Status :: 3 - Alpha",
9
+ "Intended Audience :: Science/Research",
10
+ "License :: CC0 1.0 Universal (CC0 1.0) Public Domain Dedication",
11
+ "Programming Language :: Python :: 3",
12
+ "Topic :: Scientific/Engineering",
13
+ ]
14
+ readme = "README.md"
15
+ authors = [
16
+ { name = "happyc0der", email = "Keshav.Rajput4@gmail.com" }
17
+ ]
18
+ requires-python = ">=3.12"
19
+ dependencies = [
20
+ "h5py>=3.16.0",
21
+ "httpx>=0.28.1",
22
+ "matplotlib>=3.11.2",
23
+ "mcp[cli]>=2.2.0",
24
+ "numpy>=2.5.3",
25
+ "pynwb>=4.2.0",
26
+ "remfile>=0.1.14",
27
+ "scipy>=1.18.1",
28
+ ]
29
+
30
+ [project.urls]
31
+ Homepage = "https://github.com/happyc0der/ephys-mcp"
32
+ Repository = "https://github.com/happyc0der/ephys-mcp"
33
+ Issues = "https://github.com/happyc0der/ephys-mcp/issues"
34
+
35
+ [project.scripts]
36
+ ephys-mcp = "ephys_mcp.server:main"
37
+
38
+ [build-system]
39
+ requires = ["uv_build>=0.12.10,<0.13.0"]
40
+ build-backend = "uv_build"
41
+
42
+ [dependency-groups]
43
+ dev = [
44
+ "pytest>=9.1.1",
45
+ "pytest-asyncio>=1.4.0",
46
+ "ruff>=0.16.8",
47
+ ]
48
+
49
+ [tool.ruff]
50
+ line-length = 120
51
+
52
+ [tool.pytest.ini_options]
53
+ asyncio_mode = "auto"
54
+ markers = ["network: needs internet access to the DANDI Archive"]
55
+ addopts = "-m 'not network'"
56
+ filterwarnings = ["ignore::UserWarning:hdmf", "ignore::UserWarning:pynwb"]
@@ -0,0 +1,2 @@
1
+ def hello() -> str:
2
+ return "Hello from ephys-mcp!"
@@ -0,0 +1,188 @@
1
+ """Static figures, saved as PNG. Colour is assigned by job: categorical hues in a
2
+ fixed order for groups, a blue-gray-red diverging map for signed change, ink for
3
+ single series. The categorical set is validated for colour-blind separation."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import os
8
+ import re
9
+ import time
10
+ from pathlib import Path
11
+
12
+ import matplotlib
13
+
14
+ matplotlib.use("Agg")
15
+ import matplotlib.pyplot as plt
16
+ import numpy as np
17
+ from matplotlib.colors import LinearSegmentedColormap
18
+
19
+ CATEGORICAL = ["#2a78d6", "#eb6834", "#1baf7a", "#eda100", "#e87ba4", "#008300", "#4a3aa7", "#e34948"]
20
+ DIVERGING = LinearSegmentedColormap.from_list("blue_gray_red", ["#184f95", "#86b6ef", "#f0efec", "#ec835a", "#a82a2a"])
21
+ SURFACE, INK, INK_2, MUTED, GRID, AXIS = "#fcfcfb", "#0b0b0b", "#52514e", "#898781", "#e1e0d9", "#c3c2b7"
22
+ UNRECORDED = "#d5d3c8"
23
+ MAX_DIRECT_LABELS = 4
24
+
25
+ plt.rcParams.update(
26
+ {
27
+ "figure.facecolor": SURFACE,
28
+ "axes.facecolor": SURFACE,
29
+ "savefig.facecolor": SURFACE,
30
+ "axes.edgecolor": AXIS,
31
+ "axes.labelcolor": INK_2,
32
+ "axes.titlecolor": INK,
33
+ "axes.titlesize": 11,
34
+ "axes.titleweight": "bold",
35
+ "axes.titlelocation": "left",
36
+ "axes.labelsize": 9,
37
+ "axes.spines.top": False,
38
+ "axes.spines.right": False,
39
+ "xtick.color": MUTED,
40
+ "ytick.color": MUTED,
41
+ "xtick.labelsize": 8,
42
+ "ytick.labelsize": 8,
43
+ "grid.color": GRID,
44
+ "grid.linewidth": 0.6,
45
+ "legend.frameon": False,
46
+ "legend.fontsize": 8,
47
+ "legend.labelcolor": INK_2,
48
+ "lines.linewidth": 2.0,
49
+ "font.family": "sans-serif",
50
+ }
51
+ )
52
+
53
+
54
+ def output_dir() -> Path:
55
+ d = Path(os.environ.get("EPHYS_MCP_OUTPUT_DIR", Path.home() / ".cache" / "ephys-mcp" / "plots")).expanduser()
56
+ d.mkdir(parents=True, exist_ok=True)
57
+ return d
58
+
59
+
60
+ def _save(fig, stem: str) -> Path:
61
+ safe = re.sub(r"[^A-Za-z0-9_-]+", "-", stem)
62
+ path = output_dir() / f"{safe}-{int(time.time() * 1000) % 10**9}.png"
63
+ fig.savefig(path, dpi=150, bbox_inches="tight")
64
+ plt.close(fig)
65
+ return path
66
+
67
+
68
+ def _event_line(ax):
69
+ ax.axvline(0, color=INK_2, linewidth=1.0, linestyle=(0, (3, 3)), zorder=1)
70
+
71
+
72
+ def _title_and_legend(ax, title: str, legend_cols: int):
73
+ """Title on top, legend in its own band beneath it, so neither ever covers data."""
74
+ if legend_cols:
75
+ legend = ax.legend(
76
+ loc="lower left",
77
+ bbox_to_anchor=(0, 1.0),
78
+ ncols=legend_cols,
79
+ handlelength=1.4,
80
+ columnspacing=1.2,
81
+ borderpad=0,
82
+ )
83
+ rows = -(-len(legend.get_texts()) // legend_cols)
84
+ ax.set_title(title, pad=10 + 15 * rows)
85
+ else:
86
+ ax.set_title(title)
87
+
88
+
89
+ def plot_psth(
90
+ stem: str, title: str, event: str, t, groups: dict[str, tuple], unit_z: np.ndarray, rate_label: str
91
+ ) -> Path:
92
+ """groups: label -> (mean, sem, n) of the population rate. unit_z: (n_units, n_bins) baseline z-scores."""
93
+ heatmap = len(unit_z) > 1 # a one-row heatmap says nothing the curve above does not
94
+ if heatmap:
95
+ fig, (top, bottom) = plt.subplots(
96
+ 2, 1, figsize=(7.2, 6.4), sharex=True, gridspec_kw={"height_ratios": [1, 1.25], "hspace": 0.16}
97
+ )
98
+ else:
99
+ fig, top = plt.subplots(figsize=(7.2, 3.6))
100
+ for (label, (mean, sem, n)), colour in zip(groups.items(), CATEGORICAL):
101
+ top.fill_between(t, mean - sem, mean + sem, color=colour, alpha=0.16, linewidth=0)
102
+ top.plot(t, mean, color=colour, label=f"{label} (n={n})", solid_capstyle="round")
103
+ if 1 < len(groups) <= MAX_DIRECT_LABELS:
104
+ ends = sorted(groups.items(), key=lambda kv: kv[1][0][-1])
105
+ gap = 0.075 * (top.get_ylim()[1] - top.get_ylim()[0])
106
+ y_prev = -np.inf
107
+ for label, (mean, _, _) in ends: # nudge labels apart so they never collide
108
+ y = max(mean[-1], y_prev + gap)
109
+ top.annotate(
110
+ label, (t[-1], y), xytext=(5, 0), textcoords="offset points", va="center", fontsize=8, color=INK_2
111
+ )
112
+ y_prev = y
113
+ _event_line(top)
114
+ top.grid(axis="y")
115
+ top.set_ylabel(rate_label)
116
+ _title_and_legend(top, title, min(len(groups), 4) if len(groups) > 1 else 0)
117
+ top.margins(x=0)
118
+ if not heatmap:
119
+ top.set_xlabel(f"Time from {event} (s)")
120
+ return _save(fig, stem)
121
+
122
+ order = np.argsort(np.abs(unit_z).argmax(axis=1))
123
+ lim = max(2.0, float(np.percentile(np.abs(unit_z), 99)))
124
+ step = t[1] - t[0]
125
+ im = bottom.imshow(
126
+ unit_z[order],
127
+ aspect="auto",
128
+ cmap=DIVERGING,
129
+ vmin=-lim,
130
+ vmax=lim,
131
+ extent=(t[0] - step / 2, t[-1] + step / 2, len(order), 0),
132
+ interpolation="nearest",
133
+ )
134
+ _event_line(bottom)
135
+ bottom.set_ylabel("Units, sorted by time of peak change")
136
+ bottom.set_xlabel(f"Time from {event} (s)")
137
+ bar = fig.colorbar(im, ax=[top, bottom], fraction=0.035, pad=0.09, shrink=0.5, anchor=(0, 0.1))
138
+ bar.outline.set_visible(False)
139
+ bar.set_label("Change from baseline (SD)", color=INK_2, fontsize=8)
140
+ return _save(fig, stem)
141
+
142
+
143
+ def plot_raster(stem: str, title: str, spikes: list[np.ndarray], t0: float, t1: float, valid: np.ndarray) -> Path:
144
+ fig, ax = plt.subplots(figsize=(7.2, 4.6))
145
+ edges = np.concatenate([[t0], np.clip(valid, t0, t1).ravel(), [t1]])
146
+ for a, b in edges.reshape(-1, 2): # spans between recorded intervals
147
+ if b > a:
148
+ ax.axvspan(a, b, color=UNRECORDED, linewidth=0, zorder=0)
149
+ ax.eventplot(spikes, colors=INK, linewidths=0.6, linelengths=0.8, lineoffsets=np.arange(len(spikes)) + 0.5)
150
+ ax.set_xlim(t0, t1)
151
+ ax.set_ylim(len(spikes), 0)
152
+ ax.set_xlabel("Time (s)")
153
+ ax.set_ylabel("Unit")
154
+ ax.set_title(title)
155
+ if (np.diff(edges.reshape(-1, 2), axis=1) > 0).any():
156
+ ax.annotate(
157
+ "shaded = not recorded",
158
+ (1, 1.01),
159
+ xycoords="axes fraction",
160
+ ha="right",
161
+ va="bottom",
162
+ fontsize=8,
163
+ color=MUTED,
164
+ )
165
+ return _save(fig, stem)
166
+
167
+
168
+ def plot_decode(stem: str, title: str, t, true: np.ndarray, decoded: np.ndarray, unit: str, r2: np.ndarray) -> Path:
169
+ dims = true.shape[1]
170
+ fig, axes = plt.subplots(dims, 1, figsize=(7.2, 1.6 + 1.9 * dims), sharex=True, squeeze=False)
171
+ names = ["x", "y", "z"] if dims <= 3 else [str(i) for i in range(dims)]
172
+ gaps = np.flatnonzero(np.diff(t) > 1.5 * np.median(np.diff(t))) + 1 # break lines across unrecorded spans
173
+ for i, ax in enumerate(axes[:, 0]):
174
+ for series, colour, label in (
175
+ (true[:, i], CATEGORICAL[0], "Actual"),
176
+ (decoded[:, i], CATEGORICAL[1], "Decoded"),
177
+ ):
178
+ ax.plot(np.insert(t, gaps, np.nan), np.insert(series, gaps, np.nan), color=colour, label=label)
179
+ ax.axhline(0, color=AXIS, linewidth=0.8, zorder=0)
180
+ ax.grid(axis="y")
181
+ ax.margins(x=0)
182
+ ax.set_ylabel(f"{names[i]} ({unit})" if unit else names[i])
183
+ ax.annotate(
184
+ f"R² {r2[i]:.2f}", (1, 1.03), xycoords="axes fraction", ha="right", va="bottom", fontsize=8, color=INK_2
185
+ )
186
+ _title_and_legend(axes[0, 0], title, 2)
187
+ axes[-1, 0].set_xlabel("Time (s)")
188
+ return _save(fig, stem)
File without changes
@@ -0,0 +1,121 @@
1
+ """Linear decoders from binned spike counts to a continuous behavioural signal.
2
+
3
+ Both decoders are causal: the estimate at bin t uses counts up to bin t only.
4
+ Hyperparameters left as None are chosen on the tail of the training data, so
5
+ the caller's test split is never touched.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import numpy as np
11
+
12
+ VALIDATION_FRACTION = 0.2
13
+ ALPHAS = (1.0, 10.0, 100.0, 1000.0)
14
+ LEADS = (0, 1, 2, 3) # bins by which neural activity leads behaviour
15
+
16
+
17
+ def r2_score(y: np.ndarray, yhat: np.ndarray) -> np.ndarray:
18
+ ss_res = ((y - yhat) ** 2).sum(axis=0)
19
+ ss_tot = ((y - y.mean(axis=0)) ** 2).sum(axis=0)
20
+ return 1.0 - ss_res / np.where(ss_tot == 0, 1.0, ss_tot)
21
+
22
+
23
+ def _select(make, candidates, counts: np.ndarray, y: np.ndarray):
24
+ """Best candidate by R² on the tail of the training data."""
25
+ cut = int(len(y) * (1 - VALIDATION_FRACTION))
26
+ scores = [r2_score(y[cut:], make(c)._fit(counts[:cut], y[:cut]).predict(counts[cut:])).mean() for c in candidates]
27
+ return candidates[int(np.argmax(scores))]
28
+
29
+
30
+ class RidgeDecoder:
31
+ """Ridge regression on a short history of spike counts."""
32
+
33
+ kind = "ridge"
34
+
35
+ def __init__(self, n_lags: int = 10, alpha: float | None = None):
36
+ self.n_lags, self.alpha = n_lags, alpha
37
+
38
+ @property
39
+ def params(self) -> dict:
40
+ return {"history_bins": self.n_lags, "alpha": self.alpha}
41
+
42
+ def _design(self, counts: np.ndarray) -> np.ndarray:
43
+ lagged = [np.roll(counts, k, axis=0) for k in range(self.n_lags)]
44
+ X = np.concatenate(lagged, axis=1)
45
+ X[: self.n_lags] = 0.0
46
+ return np.concatenate([X, np.ones((X.shape[0], 1))], axis=1)
47
+
48
+ def _fit(self, counts: np.ndarray, y: np.ndarray) -> RidgeDecoder:
49
+ X = self._design(counts)
50
+ reg = self.alpha * np.eye(X.shape[1])
51
+ reg[-1, -1] = 0.0
52
+ self.W = np.linalg.solve(X.T @ X + reg, X.T @ y)
53
+ return self
54
+
55
+ def fit(self, counts: np.ndarray, y: np.ndarray) -> RidgeDecoder:
56
+ if self.alpha is None:
57
+ self.alpha = _select(lambda a: RidgeDecoder(self.n_lags, a), ALPHAS, counts, y)
58
+ return self._fit(counts, y)
59
+
60
+ def predict(self, counts: np.ndarray) -> np.ndarray:
61
+ return self._design(counts) @ self.W
62
+
63
+
64
+ class KalmanDecoder:
65
+ """Kalman filter (Wu et al. 2006): x_t = A x_{t-1} + w, z_t = H x_t + q.
66
+
67
+ The state holds the target at the current and previous bin, which gives the
68
+ smooth second-order dynamics real movements have. `lead_bins` models motor
69
+ cortex firing ahead of the movement it drives.
70
+ """
71
+
72
+ kind = "kalman"
73
+
74
+ def __init__(self, lead_bins: int | None = None):
75
+ self.lead_bins = lead_bins
76
+
77
+ @property
78
+ def params(self) -> dict:
79
+ return {"lead_bins": self.lead_bins, "state": "target at t and t-1"}
80
+
81
+ def _fit(self, counts: np.ndarray, y: np.ndarray) -> KalmanDecoder:
82
+ k = self.lead_bins
83
+ self.d = y.shape[1]
84
+ if k:
85
+ counts, y = counts[:-k], y[k:]
86
+ counts, y = counts[1:], np.hstack([y[1:], y[:-1]])
87
+ self.z_mean, self.x_mean = counts.mean(axis=0), y.mean(axis=0)
88
+ Z, X = counts - self.z_mean, y - self.x_mean
89
+ X0, X1 = X[:-1], X[1:]
90
+ self.A = np.linalg.lstsq(X0, X1, rcond=None)[0].T
91
+ self.W = np.cov((X1 - X0 @ self.A.T).T) + 1e-9 * np.eye(X.shape[1])
92
+ self.H = np.linalg.lstsq(X, Z, rcond=None)[0].T
93
+ self.Q = np.cov((Z - X @ self.H.T).T) + 1e-6 * np.eye(Z.shape[1])
94
+ return self
95
+
96
+ def fit(self, counts: np.ndarray, y: np.ndarray) -> KalmanDecoder:
97
+ if self.lead_bins is None:
98
+ self.lead_bins = _select(KalmanDecoder, LEADS, counts, y)
99
+ return self._fit(counts, y)
100
+
101
+ def predict(self, counts: np.ndarray) -> np.ndarray:
102
+ Z = counts - self.z_mean
103
+ n = self.A.shape[0]
104
+ x, P = np.zeros(n), np.eye(n)
105
+ HtQinv = self.H.T @ np.linalg.inv(self.Q)
106
+ HtQinvH = HtQinv @ self.H
107
+ out = np.empty((Z.shape[0], n))
108
+ for t in range(Z.shape[0]):
109
+ x = self.A @ x
110
+ P = self.A @ P @ self.A.T + self.W
111
+ P = np.linalg.inv(np.linalg.inv(P) + HtQinvH) # information form: small inverse only
112
+ x = x + P @ HtQinv @ (Z[t] - self.H @ x)
113
+ out[t] = x
114
+ est = (out + self.x_mean)[:, : self.d]
115
+ k = self.lead_bins
116
+ if k: # counts at bin t describe behaviour at t + k; realign to the input bins
117
+ est = np.vstack([np.repeat(est[:1], k, axis=0), est[:-k]])
118
+ return est
119
+
120
+
121
+ DECODERS = {"ridge": RidgeDecoder, "kalman": KalmanDecoder}