diff --git a/.binder/dendrinet_binder.py b/.binder/dendrinet_binder.py
new file mode 100644
index 00000000..d5a10bcb
--- /dev/null
+++ b/.binder/dendrinet_binder.py
@@ -0,0 +1,52 @@
+"""Open the local Studio belonging to this personal Jupyter server."""
+
+import threading
+from pathlib import Path
+
+from jupyter_server.auth.decorator import authorized
+from jupyter_server.base.handlers import JupyterHandler
+from jupyter_server.extension.application import ExtensionApp
+from jupyter_server.utils import url_path_join
+from tornado import web
+
+
+class OpenStudio(JupyterHandler):
+ def initialize(self, studio):
+ self.studio = studio
+
+ @web.authenticated
+ @authorized(action="execute", resource="kernels")
+ def get(self):
+ server = self.studio.start_for(self.request.host_name)
+ # The fragment reaches the editor. It is never sent to the proxy as a query.
+ base = url_path_join(self.base_url, "proxy", str(server.server_port))
+ self.set_header("Cache-Control", "no-store")
+ self.set_header("Referrer-Policy", "no-referrer")
+ self.redirect(f"{base}/#{server.studio_token}")
+
+
+class StudioSession(ExtensionApp):
+ name = "dendrinet_binder"
+ server = None
+
+ def initialize_handlers(self):
+ self.handlers.append((r"/open-studio/?", OpenStudio, {"studio": self}))
+
+ def start_for(self, host):
+ if self.server is None:
+ from dendrinet_studio.server import make_server
+
+ root = Path(self.serverapp.root_dir) / "studio-runs"
+ self.server = make_server(root, port=0, threads=1, allowed_hosts=(host,))
+ threading.Thread(target=self.server.serve_forever, daemon=True).start()
+ return self.server
+
+ async def stop_extension(self):
+ if self.server is not None:
+ self.server.studio_runs.close()
+ self.server.shutdown()
+ self.server.server_close()
+
+
+def _jupyter_server_extension_points():
+ return [{"module": __name__, "app": StudioSession}]
diff --git a/.binder/environment.yml b/.binder/environment.yml
new file mode 100644
index 00000000..8b3d1576
--- /dev/null
+++ b/.binder/environment.yml
@@ -0,0 +1,9 @@
+name: dendrinet-studio
+channels:
+ - conda-forge
+dependencies:
+ - python=3.11
+ - pip
+ - jupyter_server>=2,<3
+ - pip:
+ - jupyter-server-proxy==4.6.1
diff --git a/.binder/postBuild b/.binder/postBuild
new file mode 100755
index 00000000..fb790ce8
--- /dev/null
+++ b/.binder/postBuild
@@ -0,0 +1,8 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+# Install CPU wheels before resolving the two packages from the selected Git revision.
+python -m pip install --index-url https://download.pytorch.org/whl/cpu torch==2.9.1 torchvision==0.24.1
+python -m pip install . ./apps/studio
+
+python .binder/register_studio.py
diff --git a/.binder/register_studio.py b/.binder/register_studio.py
new file mode 100644
index 00000000..f4d3adbe
--- /dev/null
+++ b/.binder/register_studio.py
@@ -0,0 +1,15 @@
+"""Register the personal launcher in the Python environment running Jupyter."""
+
+import json
+import shutil
+import sys
+import sysconfig
+from pathlib import Path
+
+if __name__ == "__main__":
+ module = Path(__file__).with_name("dendrinet_binder.py")
+ shutil.copyfile(module, Path(sysconfig.get_path("purelib")) / module.name)
+ config = Path(sys.prefix) / "etc/jupyter/jupyter_server_config.d"
+ config.mkdir(parents=True, exist_ok=True)
+ settings = {"ServerApp": {"jpserver_extensions": {"dendrinet_binder": True}}}
+ (config / "dendrinet_binder.json").write_text(json.dumps(settings) + "\n")
diff --git a/.binder/test_session.py b/.binder/test_session.py
new file mode 100644
index 00000000..87a90948
--- /dev/null
+++ b/.binder/test_session.py
@@ -0,0 +1,122 @@
+"""Exercise the browser launch through an authenticated, path-prefixed Jupyter proxy."""
+
+import csv
+import json
+import math
+import os
+import secrets
+import subprocess
+import sys
+import time
+from contextlib import contextmanager
+from urllib.parse import urljoin, urlsplit
+
+import yaml
+from playwright.sync_api import expect, sync_playwright
+
+
+@contextmanager
+def personal_server(root):
+ root.mkdir()
+ runtime = root / "runtime"
+ token = secrets.token_urlsafe()
+ env = {
+ **os.environ,
+ "JUPYTER_CONFIG_DIR": str(root / "config"),
+ "JUPYTER_RUNTIME_DIR": str(runtime),
+ "JUPYTER_TOKEN": token,
+ }
+ with (root / "server.log").open("w") as log:
+ proc = subprocess.Popen(
+ [
+ sys.executable,
+ "-m",
+ "jupyter_server",
+ "--no-browser",
+ "--ServerApp.base_url=/user/visitor/",
+ ],
+ cwd=root,
+ env=env,
+ stdout=log,
+ stderr=subprocess.STDOUT,
+ )
+ try:
+ info = runtime / f"jpserver-{proc.pid}.json"
+ for _ in range(300):
+ if info.exists() and info.stat().st_size:
+ break
+ if proc.poll() is not None:
+ raise RuntimeError("Personal Jupyter server exited during startup")
+ time.sleep(0.1)
+ base = json.loads(info.read_text())["url"]
+ yield urljoin(base, "open-studio"), token
+ finally:
+ proc.terminate()
+ proc.wait(timeout=30)
+
+
+def test_personal_session_training_and_exports(tmp_path):
+ with personal_server(tmp_path / "first") as (entry, token):
+ with sync_playwright() as engine:
+ browser = engine.chromium.launch()
+ page = browser.new_page(accept_downloads=True)
+ response = page.request.get(entry, max_redirects=0)
+ assert response.status in (302, 403)
+ assert "/proxy/" not in response.headers.get("location", "")
+ page.goto(f"{entry}?token={token}", timeout=90_000)
+ page.locator("svg.network .card").first.wait_for()
+ address = urlsplit(page.url)
+ assert address.path.startswith("/user/visitor/proxy/")
+ first_secret = address.fragment.split("&")[0]
+ assert first_secret
+
+ page.get_by_role("tab", name="Training").click()
+ epochs = page.locator('[data-key="training.main.common.epochs"]')
+ epochs.fill("1")
+ epochs.press("Enter")
+ keys = page.evaluate("Object.keys(localStorage)")
+ assert f"dendrinet-studio-draft-v1:{address.path}" in keys
+ page.get_by_role("button", name="Train").click()
+ run_name = page.locator("dialog.dialog input")
+ run_name.fill("Personal example")
+ run_name.press("Enter")
+ card = page.locator(".run-card", has_text="Personal example")
+ expect(card.locator(".status")).to_contain_text(
+ "Completed", timeout=180_000
+ )
+ card.locator("input[type=checkbox]").check()
+ with page.expect_download() as curves:
+ page.get_by_role("button", name="Curves (CSV)").click()
+ with curves.value.path().open() as f:
+ rows = list(csv.DictReader(f))
+ assert len(rows) == 1 and rows[0]["epoch"] == "1"
+ for split in ("train", "validation"):
+ assert math.isfinite(float(rows[0][f"Personal example {split}"]))
+ page.get_by_role("tab", name="YAML").click()
+ with page.expect_download() as config:
+ page.get_by_role("button", name="Export").click()
+ raw = yaml.safe_load(config.value.path().read_text())
+ assert raw["training"]["main"]["common"]["epochs"] == 1
+ assert raw["data"]["dataset_name"] == "linear_separable"
+ reopened = page.request.get(entry, max_redirects=0)
+ assert urlsplit(reopened.headers["location"]).fragment == first_secret
+ browser.close()
+
+ with (
+ personal_server(tmp_path / "second") as (entry, token),
+ sync_playwright() as engine,
+ ):
+ client = engine.request.new_context()
+ reply = client.get(f"{entry}?token={token}", max_redirects=0, timeout=90_000)
+ assert reply.status == 302
+ address = urlsplit(urljoin(entry, reply.headers["location"]))
+ assert address.fragment and address.fragment != first_secret
+ runs = address._replace(path=address.path + "api/runs", fragment="").geturl()
+ assert client.get(runs, headers={"X-Studio-Token": first_secret}).status == 403
+ assert (
+ client.get(runs, headers={"X-Studio-Token": address.fragment}).json()[
+ "runs"
+ ]
+ == []
+ )
+ client.dispose()
diff --git a/.github/workflows/package.yml b/.github/workflows/package.yml
index 9315d94f..2115e7ac 100644
--- a/.github/workflows/package.yml
+++ b/.github/workflows/package.yml
@@ -70,6 +70,9 @@ jobs:
python "$GITHUB_WORKSPACE/setup/check_installed.py"
python "$GITHUB_WORKSPACE/setup/check_installed_sweep.py"
python -m pytest "$GITHUB_WORKSPACE/apps/studio/tests" -q
+ python -m pip install jupyter-server-proxy==4.6.1
+ python "$GITHUB_WORKSPACE/.binder/register_studio.py"
+ python -m pytest "$GITHUB_WORKSPACE/.binder/test_session.py" -q
- uses: actions/upload-artifact@v4
with:
name: qualified-core
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d3a05ee0..fb373f7d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,15 +1,63 @@
# Changelog
-## Unreleased
+## 0.6.0
- The installation guides start with the published core and Studio packages
and show how to run the synthetic tutorial outside a source checkout.
+ The Studio guide also covers optional GPU training in a cluster allocation.
- Release maintainers can select a project-scoped upload token when their
package index does not support the enterprise identity issuer. Promotion
checks the staging tag, upload job and file hashes. Trusted Publishing
remains the default.
- Update the Black development formatter and pre-commit hook to 26.10.1.
+### Core library 0.6.0
+
+- Set a population projection's travel time with `delay_steps` or
+ `delay_steps_by_level`. Delayed projections default to one update.
+ Longer delays carry source outputs across sequence chunks and support
+ backpropagation through those outputs. A zero-probability route keeps
+ its source columns without storing earlier samples.
+
+### DendriNet Studio 0.2.0
+
+- Add a compact contextual-remapping template on EMNIST Balanced. Explore
+ how a cue changes a character's target in a two-layer E/I network, or
+ export its configuration with `dendritic-example contextual_remapping_population`.
+
+- Show and edit the receiving compartment's response time at each depth.
+ Add multiple same-step excitatory sources from the receiving population
+ and see which sources share its contact budget.
+- Set a shared or depth-specific travel delay in the connection editor. The
+ diagram labels delayed routes and the inspector shows travel steps beside
+ each receiving depth's response time.
+- Open Studio from the documentation in a personal Binder session, train
+ the two-class example on a CPU and download the configuration and curves.
+- Connect two populations from the diagram or choose both endpoints and the
+ projection timing before applying an edit. Surface the receiving E/I budget
+ and validate route changes with DendriNet before saving them.
+- Add feedforward and recurrent layers in one population network. Preserve
+ explicit readouts and per-level contact settings when extending a design.
+ Copy a local inhibitory projection only when the receiver has eligible
+ inhibitory contacts. Stepped layers require exact gradient credit.
+- Apply successive inspector edits in order. Morphology and routing edits
+ use the latest validated time constants and depth-specific contact counts.
+ Resetting to uniform counts and then editing one depth preserves both edits.
+ Studio reports a missing source if a depth-restricted pathway leaves
+ contacts at an unreachable receiving depth.
+ The inspector can repair that error by adding the depth to a connection.
+ The connection editor can also add a source at an uncovered depth.
+ A confirmed removal can repair an invalid population or layer. Removing
+ the implicit readout layer preserves a compatible population override on
+ the preceding layer and clears one that no longer applies.
+ Renames and per-depth time edits use the current draft, including after Undo
+ or Redo. Editing an inactive route preserves the shared contact count.
+ Model checks, training, export and copy wait for pending connection edits.
+ YAML Export and Copy use the current design during preview refresh and
+ preserve any unapplied edits in the text editor.
+- Align populations in a column per layer, label layer dynamics, and identify
+ inhibitory feedback with both a dashed line and a bar.
+
## 0.5.0
### Core library
diff --git a/INSTALL.md b/INSTALL.md
index eb0a2f8c..01563f58 100644
--- a/INSTALL.md
+++ b/INSTALL.md
@@ -2,7 +2,7 @@
In a fresh Python 3.10 or later environment, install the library with
`python -m pip install dendritic-modeling==0.5.0`. To use the graphical
-editor, run `python -m pip install dendrinet-studio==0.1.0` and
+editor, run `python -m pip install --upgrade dendrinet-studio` and
`dendrinet-studio --workspace my-runs`. Studio installs the compatible core.
The installation guide covers virtual environments, PyTorch CPU and CUDA
diff --git a/README.md b/README.md
index bc9d2367..41a938ce 100644
--- a/README.md
+++ b/README.md
@@ -28,19 +28,37 @@ For the Python library and command-line tools, install the core from PyPI
in a Python 3.10 or later environment.
```bash
-python -m pip install dendritic-modeling==0.5.0
+python -m pip install --upgrade dendritic-modeling
```
The import name is `dendritic_modeling`. The examples run on a CPU.
The installation guide covers virtual environments, CPU and CUDA builds
of PyTorch, optional dependencies and editable installs for contributors.
-[PyPI release](https://pypi.org/project/dendritic-modeling/0.5.0/) ·
+[Core on PyPI](https://pypi.org/project/dendritic-modeling/) ·
[Installation guide](docs/installation.rst)
## DendriNet Studio
Studio lets you draw feedforward and recurrent networks, inspect a neuron's
-dendrites and compare runs in your browser. Open a terminal on your laptop.
+dendrites and compare runs in your browser.
+
+**[Open Studio 0.2.0 online](https://mybinder.org/v2/gh/KempnerInstitute/DendriNet/studio-v0.2.0?urlpath=open-studio)**
+to try the editor in a personal CPU session. No account or local installation is
+required. In **Training**, set **Epochs** to `1` and select **Train** to try the
+two-class example. Download your YAML and loss curves before the session expires.
+Before 0.2.0 is tagged, use the **Try it** link in [PR #404](https://github.com/KempnerInstitute/DendriNet/pull/404).
+
+For GPU training, start Studio on an allocated compute node and choose
+**GPU if available** beside **Train**. You can open it through Open OnDemand,
+Cursor or SSH. [Cluster GPU instructions](docs/studio.rst#train-on-a-cluster-gpu)
+
+With Studio 0.2.0 and DendriNet 0.6.x, select a population to add an
+incoming source, or select a delayed connection to set its travel time at
+each dendritic depth. The laptop commands below install the latest
+compatible pair published on PyPI. Check your installed versions with
+`python -m pip show dendrinet-studio dendritic-modeling`.
+
+To keep runs on your own computer, open a terminal on your laptop.
On an Apple silicon Mac or a Linux laptop with Python 3.10 or later, run
these commands the first time. Installing Studio also installs DendriNet and
PyTorch. On a Mac, use the arm64 build of Python.
@@ -48,7 +66,7 @@ PyTorch. On a Mac, use the arm64 build of Python.
```bash
python3 -m venv ~/dendrinet-env
source ~/dendrinet-env/bin/activate
-python -m pip install dendrinet-studio==0.1.0
+python -m pip install --upgrade dendrinet-studio
dendrinet-studio --workspace ~/dendrinet-runs
```
@@ -70,7 +88,7 @@ Press **Ctrl+C** in the terminal to stop Studio. Next time, activate the
same environment and repeat the `dendrinet-studio --workspace` command above
to see your saved runs. The editor also exports YAML for `dendritic-train`.
[Illustrated Studio guide](https://kempnerinstitute.github.io/DendriNet/studio.html#studio-first-run) ·
-[Studio on PyPI](https://pypi.org/project/dendrinet-studio/0.1.0/)
+[Studio on PyPI](https://pypi.org/project/dendrinet-studio/)
## First steps
diff --git a/README_PYPI.md b/README_PYPI.md
index f94be7eb..d3e82cad 100644
--- a/README_PYPI.md
+++ b/README_PYPI.md
@@ -7,7 +7,7 @@ shunting and additive integration, population networks, training and analysis.
## Install and train a first model
```bash
-python -m pip install dendritic-modeling==0.5.0
+python -m pip install dendritic-modeling
dendritic-example synthetic_population --output demo.yaml
dendritic-train demo.yaml --epochs 1
```
@@ -22,12 +22,13 @@ reproduction requires the study's recorded dependencies, source and settings.
## Graphical model editor
-Install the companion distribution with `python -m pip install dendrinet-studio==0.1.0` to draw dendritic
+Install the companion distribution with `python -m pip install --upgrade dendrinet-studio` to draw dendritic
populations, trace incoming E and I connections, and compare training runs on
your computer. Launch it with `dendrinet-studio --workspace my-runs`. Designs
export as YAML that the core training command accepts. The
[Studio guide](https://kempnerinstitute.github.io/DendriNet/studio.html)
-includes a first run with generated data and a worked synapse-count example.
+includes a first run with generated data, a worked synapse-count example,
+and [instructions for training on a cluster GPU](https://kempnerinstitute.github.io/DendriNet/studio.html#studio-cluster-gpu).
- [Documentation](https://kempnerinstitute.github.io/DendriNet/)
- [Source and examples](https://github.com/KempnerInstitute/DendriNet)
diff --git a/apps/studio/README.md b/apps/studio/README.md
index 28d8bb42..11ddbddd 100644
--- a/apps/studio/README.md
+++ b/apps/studio/README.md
@@ -1,11 +1,35 @@
# DendriNet Studio
Design, check, train and compare [DendriNet](https://github.com/KempnerInstitute/DendriNet)
-models on your computer. Select a neuron population to trace the external
+models in a browser. Select a neuron population to trace the external
and local sources of its excitatory and inhibitory contacts. Inspect the
contact count at each dendritic level, build the network, or train and compare
two designs. Each design exports as an ordinary DendriNet experiment YAML.
+In Studio 0.2.0, choose **Connect** above the network, or select a population,
+choose **Connect from this population** and select the receiving population
+on the diagram. A same-step route carries current activity. A delayed route
+carries earlier activity and can return from a later layer. The guide walks
+through a recurrent decision circuit with a feedforward readout. Use **Add
+input source** on a receiving population to connect multiple excitatory
+populations. In **Edit connection → Travel delay**, choose a uniform delay
+or enter whole steps at each depth. The connection inspector shows these
+arrival times beside the compartment response times (τ). Studio 0.2.0 requires
+DendriNet 0.6.x. Installing Studio from PyPI selects a compatible core
+automatically. Check your versions with
+`python -m pip show dendrinet-studio dendritic-modeling`.
+[Connect populations and mix layer dynamics](https://kempnerinstitute.github.io/DendriNet/studio.html#studio-connect)
+
+## Open a personal session online
+
+[Open Studio 0.2.0 on Binder](https://mybinder.org/v2/gh/KempnerInstitute/DendriNet/studio-v0.2.0?urlpath=open-studio)
+to design a network and train the two-class example on a CPU. Set **Epochs**
+to `1` in **Training**, then select **Train**. In **Runs**, select the finished
+run and download **Curves (CSV)**. Use **YAML → Export** to keep your design.
+Binder starts a temporary workspace for each visitor. The first launch for a
+new Git revision can take several minutes.
+Before 0.2.0 is tagged, the **Try it** link in [PR #404](https://github.com/KempnerInstitute/DendriNet/pull/404) opens the review version.
+
## Install and open Studio on your laptop
Open a local terminal. Studio runs on your computer and opens in your browser.
@@ -21,7 +45,7 @@ Run these commands the first time on macOS or Linux.
```bash
python3 -m venv ~/dendrinet-env
source ~/dendrinet-env/bin/activate
-python -m pip install dendrinet-studio==0.1.0
+python -m pip install --upgrade dendrinet-studio
dendrinet-studio --workspace ~/dendrinet-runs
```
@@ -36,7 +60,7 @@ also starts Studio on later visits.
```powershell
py -3.11 -m venv "$HOME\dendrinet-env"
-& "$HOME\dendrinet-env\Scripts\python.exe" -m pip install dendrinet-studio==0.1.0
+& "$HOME\dendrinet-env\Scripts\python.exe" -m pip install --upgrade dendrinet-studio
& "$HOME\dendrinet-env\Scripts\dendrinet-studio.exe" --workspace "$HOME\dendrinet-runs"
```
@@ -59,12 +83,18 @@ Press **Ctrl+C** in the terminal when finished. The commands above keep
your runs in the `dendrinet-runs` folder in your home directory. Launch
Studio with that workspace again to reopen them.
+To try the empirical paper's cue-dependent task, choose **Model → Start from
+→ Contextual remapping on EMNIST**. The first run downloads EMNIST. A 32-way
+cue changes the target for the same image in a compact two-layer E/I network.
+The full paper configurations and calibration instructions are in the
+[empirical project](https://github.com/KempnerInstitute/DendriNet/tree/v0.5.0/projects/empirical#build-a-network).
+
## What you can do
- **Design population networks visually**: layers, excitatory and inhibitory
populations, neuron counts, dendritic branching, contacts per compartment
and per level, shunting or additive integration, dendritic gates, time
- constants, and connections that act in the same step or one step later
+ constants, and connections that act in the same step or after a configurable delay
(recurrent networks).
- **Configure other model families** using typed forms and the YAML editor,
including structured dendritic trees, GRU, LSTM and vanilla RNN baselines,
@@ -83,15 +113,15 @@ trains in seconds with no download, the same task with structured dendritic
trees, a recurrent decision network, a GRU regression baseline and an MNIST
network.
-## Remote machines
-
-```bash
-dendrinet-studio --workspace ~/studio-runs --no-browser # on the remote machine
-ssh -L 8765:127.0.0.1:8765 user@remote-host # on your computer
-```
+## Remote machines and cluster GPUs
-Open the printed address on your computer. `--no-execution` turns a machine
-into design-and-export only.
+Start `dendrinet-studio --no-browser` on your workstation or inside a GPU
+allocation. In an Open OnDemand remote desktop, paste the full printed URL
+into that desktop's browser. From a laptop, forward the printed port with
+Cursor or SSH to the host running Studio and keep the `#` token in the URL.
+Choose **GPU if available** beside **Train**, or select **CPU**. After training,
+`model_resources.json` records the device used. Use `--no-execution` for
+design and export only. [Cluster GPU instructions](https://kempnerinstitute.github.io/DendriNet/studio.html#studio-cluster-gpu)
## Privacy
diff --git a/apps/studio/pyproject.toml b/apps/studio/pyproject.toml
index ecfd2c0c..89d3b860 100644
--- a/apps/studio/pyproject.toml
+++ b/apps/studio/pyproject.toml
@@ -4,12 +4,12 @@ build-backend = "setuptools.build_meta"
[project]
name = "dendrinet-studio"
-version = "0.1.0"
+version = "0.2.0"
description = "Design, check, train and compare DendriNet models in the browser"
readme = "README.md"
requires-python = ">=3.10"
license = "MIT"
-dependencies = ["dendritic_modeling>=0.5.0,<0.6", "PyYAML>=6"]
+dependencies = ["dendritic_modeling>=0.6.0,<0.7", "PyYAML>=6"]
[project.urls]
Documentation = "https://kempnerinstitute.github.io/DendriNet/studio.html"
diff --git a/apps/studio/src/dendrinet_studio/__init__.py b/apps/studio/src/dendrinet_studio/__init__.py
index fd253977..7a95aae5 100644
--- a/apps/studio/src/dendrinet_studio/__init__.py
+++ b/apps/studio/src/dendrinet_studio/__init__.py
@@ -1,3 +1,3 @@
"""Optional local visual editor for DendriNet configurations."""
-__version__ = "0.1.0"
+__version__ = "0.2.0"
diff --git a/apps/studio/src/dendrinet_studio/model.py b/apps/studio/src/dendrinet_studio/model.py
index 41b886e0..753a08ed 100644
--- a/apps/studio/src/dendrinet_studio/model.py
+++ b/apps/studio/src/dendrinet_studio/model.py
@@ -18,12 +18,16 @@
from dendritic_modeling import __version__ as core_version
from dendritic_modeling.config import config_from_mapping
-from dendritic_modeling.config.conversion import to_plain_dict
+from dendritic_modeling.config.conversion import (
+ has_enabled_synapse_types,
+ to_plain_dict,
+)
from dendritic_modeling.config.keys import config_from_payload
from dendritic_modeling.config.population_routing import (
INPUT_POLARITIES,
canonical_input_source,
population_readout,
+ projection_delays,
projection_pathway,
)
from dendritic_modeling.config.recurrence import is_recurrent_core_config
@@ -35,6 +39,8 @@
as_population_definition_config,
population_config_from_definition,
population_level_dims,
+ population_requires_temporal_state,
+ validate_stepped_credit_modes,
)
from dendritic_modeling.networks.architectures.recurrent.population_configs import (
PopulationLayerConfig,
@@ -111,6 +117,7 @@ def _example_header(text: str) -> tuple[str, str]:
"recurrent_decision_population",
"adding_problem_gru",
"mnist_population",
+ "contextual_remapping_population",
)
@@ -126,6 +133,9 @@ def example_catalog() -> list[dict[str, Any]]:
for name in example_names():
text = example_text(name)
raw = yaml.safe_load(text) or {}
+ data = raw.get("data", {}) or {}
+ dataset = data.get("dataset_name", "")
+ params = (data.get("dataset_params") or {}).get(dataset) or {}
model = raw.get("model", {}) or {}
core = model.get("core", {}) or {}
title, description = _example_header(text)
@@ -136,10 +146,9 @@ def example_catalog() -> list[dict[str, Any]]:
"description": description,
"family": core.get("type", ""),
"task": model.get("task", "classification"),
- "dataset": (raw.get("data", {}) or {}).get("dataset_name", ""),
+ "dataset": dataset,
"recurrent": bool(is_recurrent_core_config(core)),
- "download": (raw.get("data", {}) or {}).get("dataset_name")
- in downloads,
+ "download": params.get("download", dataset in downloads),
}
)
rank = {name: index for index, name in enumerate(EXAMPLE_ORDER)}
@@ -155,7 +164,9 @@ def _levels_soma_first(branch_factors: list[int]) -> list[int]:
return list(reversed(population_level_dims(1, branch_factors)))
-def _population_graph(network: dict[str, Any]) -> dict[str, Any]:
+def _population_graph(
+ network: dict[str, Any], *, require_contact_coverage: bool = True
+) -> dict[str, Any]:
nodes, edges, layers = [], [], []
signs = dict(INPUT_POLARITIES)
definitions = [
@@ -172,6 +183,7 @@ def _population_graph(network: dict[str, Any]) -> dict[str, Any]:
settings: dict[str, Any] = {}
for li, layer in enumerate(definitions):
polarities = {}
+ steps_through_time = bool(layer.recurrent)
for pi, item in enumerate(layer.populations):
definition = as_population_definition_config(item)
population = population_config_from_definition(
@@ -181,6 +193,12 @@ def _population_graph(network: dict[str, Any]) -> dict[str, Any]:
network_layer_idx=li,
)
levels = _levels_soma_first(population.branch_factors)
+ steps_through_time |= population_requires_temporal_state(population)
+ if population.level_taus and len(population.level_taus) != len(levels):
+ raise ValueError(
+ f"{layer.name}.{definition.name}: level_taus needs {len(levels)} "
+ "values from the most distal level to the soma"
+ )
per_level = {}
for stream in STREAMS:
field = stream + "_synapses"
@@ -208,6 +226,9 @@ def _population_graph(network: dict[str, Any]) -> dict[str, Any]:
"branch_factors": list(definition.branch_factors),
"levels_including_soma": levels,
"compartments_per_neuron": sum(levels),
+ "has_receptor_traces": has_enabled_synapse_types(
+ population.synapse_types
+ ),
"configured_per_level": per_level,
"overridden": sorted(override),
"settings": dataclasses.asdict(population),
@@ -215,6 +236,11 @@ def _population_graph(network: dict[str, Any]) -> dict[str, Any]:
)
if "excitatory" not in polarities.values():
raise ValueError(f"Layer {layer.name!r} requires an excitatory population")
+ if steps_through_time:
+ validate_stepped_credit_modes(
+ layer.name,
+ {name: settings[f"{layer.name}.{name}"] for name in polarities},
+ )
override = (
network.get("readout_population") if layer.name == selected_layer else None
)
@@ -234,6 +260,7 @@ def _population_graph(network: dict[str, Any]) -> dict[str, Any]:
"name": layer.name,
"readout": readout,
"recurrent": bool(layer.recurrent),
+ "steps_through_time": steps_through_time,
"dt": layer.dt,
"is_readout_layer": layer.name == selected_layer,
}
@@ -241,6 +268,7 @@ def _population_graph(network: dict[str, Any]) -> dict[str, Any]:
# Resolve qualified delayed sources after all populations are known.
reached: dict[str, dict[str, set[int] | None]] = {}
+ restricted: set[tuple[str, str]] = set()
for li, layer in enumerate(definitions):
for item in layer.connections:
projection = as_population_projection_config(item)
@@ -270,12 +298,18 @@ def _population_graph(network: dict[str, Any]) -> dict[str, Any]:
f"in layer {layer.name!r}"
)
timing = str(connection.get("timing") or "same_step").lower()
+ if external and timing == "delayed":
+ raise ValueError(
+ f"Delayed source {declared!r} must name a population output"
+ )
pathway = projection_pathway(
timing, signs[origin], str(connection.get("pathway") or "").lower()
)
n_levels = len(_levels_soma_first(settings[target_id].branch_factors))
depths = projection.target_depths(n_levels)
- if connection.get("enabled", True):
+ if projection.enabled and depths is not None:
+ restricted.add((target_id, pathway))
+ if projection.enabled and projection.probability != 0:
current = reached.setdefault(target_id, {}).get(pathway, set())
if depths is None or current is None:
reached[target_id][pathway] = None
@@ -290,6 +324,16 @@ def _population_graph(network: dict[str, Any]) -> dict[str, Any]:
"source_id": origin,
"target_id": target_id,
"timing": timing,
+ "arrival_steps": list(
+ reversed(
+ projection_delays(
+ timing,
+ projection.delay_steps,
+ projection.delay_steps_by_level,
+ n_levels,
+ )
+ )
+ ),
"pathway": pathway,
"target_depths": sorted(depths) if depths is not None else None,
}
@@ -308,6 +352,18 @@ def _population_graph(network: dict[str, Any]) -> dict[str, Any]:
ok = allowed is None or depth in allowed
if depth == 0 and not population.somatic_synapses:
ok = False
+ elif (
+ require_contact_coverage
+ and count
+ and not ok
+ and (node["id"], stream) in restricted
+ ):
+ raise ValueError(
+ f"{node['id']} has {count} {stream} contacts per compartment "
+ f"at depth {depth}, but no active source reaches that depth. "
+ "Set its contact count to zero or include that depth on an "
+ "enabled connection with positive probability."
+ )
counts.append(count if ok else 0)
received[stream] = counts
node["received_per_level"] = received
@@ -328,6 +384,20 @@ def _population_graph(network: dict[str, Any]) -> dict[str, Any]:
}
+def inspect_wiring(raw: dict[str, Any]) -> dict[str, Any]:
+ """Describe the current endpoints and budgets so a user can repair coverage."""
+ if not isinstance(raw, dict):
+ raise ValueError("A configuration must be a mapping")
+ cfg = config_from_mapping(copy.deepcopy(raw))
+ core = to_plain_dict(cfg.model.core)
+ if core["type"] != "population_network":
+ raise ValueError("The connection editor requires a population network")
+ return {
+ "biological_neuron": core.get("biological_neuron"),
+ **_population_graph(core["population_network"], require_contact_coverage=False),
+ }
+
+
def _structured_overview(core: dict[str, Any]) -> dict[str, Any]:
"""Morphology of the structured dendritic family, read from its sections."""
architecture = core.get("architecture", {}) or {}
diff --git a/apps/studio/src/dendrinet_studio/runs.py b/apps/studio/src/dendrinet_studio/runs.py
index 717e90e7..94c0c6b7 100644
--- a/apps/studio/src/dendrinet_studio/runs.py
+++ b/apps/studio/src/dendrinet_studio/runs.py
@@ -30,10 +30,9 @@
KINDS = {"inspect": "Model check", "train": "Training"}
DEVICES = {"cpu", "auto"}
LOG_TAIL_BYTES = 40_000
-# Trainer progress lines, e.g. "epoch=10/30, train_loss=0.68 (...), valid_loss=0.71".
-_PROGRESS = re.compile(
- r"epoch=(\d+)/(\d+),\s*train_loss=([^\s,(]+).*?valid_loss=([^\s,(]+)"
-)
+# Standard and presentation-stream trainers both log the epoch and training loss.
+_PROGRESS = re.compile(r"\bepoch=(\d+)/(\d+),?[ \t]+train_loss=([^\s,(]+)([^\r\n]*)")
+_VALID_LOSS = re.compile(r"\bvalid_loss=([^\s,(]+)")
def json_values(value: Any) -> Any:
@@ -131,11 +130,12 @@ def progress_from_log(text: str) -> dict | None:
epochs = None
for match in _PROGRESS.finditer(text):
epoch, total = int(match.group(1)), int(match.group(2))
+ validation = _VALID_LOSS.search(match.group(4))
epochs = total
points[epoch] = {
"epoch": epoch,
"train_loss": _number(match.group(3)),
- "valid_loss": _number(match.group(4)),
+ "valid_loss": _number(validation.group(1)) if validation else None,
}
if not points:
return None
diff --git a/apps/studio/src/dendrinet_studio/server.py b/apps/studio/src/dendrinet_studio/server.py
index d12fe777..db7e43e1 100644
--- a/apps/studio/src/dendrinet_studio/server.py
+++ b/apps/studio/src/dendrinet_studio/server.py
@@ -73,6 +73,7 @@ def make_server(
example,
example_catalog,
inspect_document,
+ inspect_wiring,
parse_document,
parse_value,
)
@@ -195,6 +196,8 @@ def do_POST(self):
path = urlsplit(self.path).path
if path == "/api/preview":
self.json_reply(preview(data))
+ elif path == "/api/wiring":
+ self.json_reply(inspect_wiring(data["config"]))
elif path == "/api/parse":
self.json_reply({"value": parse_value(str(data["yaml"]))})
elif path == "/api/dump":
diff --git a/apps/studio/src/dendrinet_studio/web/js/afferents.js b/apps/studio/src/dendrinet_studio/web/js/afferents.js
index 6ae341dd..dbc4eb8b 100644
--- a/apps/studio/src/dendrinet_studio/web/js/afferents.js
+++ b/apps/studio/src/dendrinet_studio/web/js/afferents.js
@@ -13,7 +13,7 @@ const modes = {
split: "Separate groups of input channels",
};
-function afferentMode(net) {
+export function afferentMode(net) {
if (!net.use_transfer) return "shared";
if (net.transfer_params?.independent_pathways) return "split";
return net.transfer_params?.input_source_identity === "paired_afferents" ? "paired" : "shared";
diff --git a/apps/studio/src/dendrinet_studio/web/js/app.js b/apps/studio/src/dendrinet_studio/web/js/app.js
index a0fc8018..0829abf4 100644
--- a/apps/studio/src/dendrinet_studio/web/js/app.js
+++ b/apps/studio/src/dendrinet_studio/web/js/app.js
@@ -1,7 +1,7 @@
// DendriNet Studio: application shell, views, runs polling and actions.
import { h, s, icon } from "./dom.js";
-import { state, api, on, adopt, undo, redo, readDraft, clearDraft, configKey } from "./store.js";
+import { state, api, on, adopt, undo, redo, readDraft, clearDraft, configKey, modelReady } from "./store.js";
import { mountModel, renderModel, currentCheck } from "./design.js";
import { mountData, renderData, mountTraining, renderTraining, mountOptions, renderOptions } from "./forms.js";
import { mountYaml, refreshYaml } from "./yamlview.js";
@@ -184,10 +184,11 @@ function device() {
}
async function checkModel() {
- if (state.error) return toast(`Fix the configuration first: ${state.error}`, { kind: "error" });
try {
+ await modelReady();
+ const key = configKey();
const run = await api("run", { config: state.config, kind: "inspect", device: device(), name: `Model check · ${state.docName}` });
- state.modelCheck = { key: configKey(), runId: run.id };
+ state.modelCheck = { key, runId: run.id };
toast("Building the model to count its parameters and synapses…", { kind: "info" });
renderViews();
refreshRuns();
@@ -197,19 +198,20 @@ async function checkModel() {
}
async function train() {
- if (state.error) return toast(`Fix the configuration first: ${state.error}`, { kind: "error" });
- const p = state.preview;
- const stem = (state.docName || "model").replace(/\.(ya?ml)$/i, "");
- const epochs = p.resolved_config.training?.main?.common?.epochs;
- const name = await promptDialog({
- title: "Train this model",
- label: "Run name",
- value: `${stem}${epochs ? ` · ${epochs} epochs` : ""}`,
- confirm: "Start training",
- help: `Runs on ${device() === "cpu" ? "the CPU" : "a GPU if one is available, else the CPU"} with ${state.runs?.threads ?? state.schema.threads} threads. The dataset ${p.dataset} is prepared (or downloaded) first. Everything is saved under ${state.runs?.workspace || state.schema.workspace}.`,
- });
- if (name === null) return;
try {
+ await modelReady();
+ const p = state.preview;
+ const stem = (state.docName || "model").replace(/\.(ya?ml)$/i, "");
+ const epochs = p.resolved_config.training?.main?.common?.epochs;
+ const name = await promptDialog({
+ title: "Train this model",
+ label: "Run name",
+ value: `${stem}${epochs ? ` · ${epochs} epochs` : ""}`,
+ confirm: "Start training",
+ help: `Runs on ${device() === "cpu" ? "the CPU" : "a GPU if one is available, else the CPU"} with ${state.runs?.threads ?? state.schema.threads} threads. The dataset ${p.dataset} is prepared (or downloaded) first. Everything is saved under ${state.runs?.workspace || state.schema.workspace}.`,
+ });
+ if (name === null) return;
+ await modelReady();
const run = await api("run", { config: state.config, kind: "train", device: device(), name });
state.focusRun = run.id;
showView("runs");
diff --git a/apps/studio/src/dendrinet_studio/web/js/design.js b/apps/studio/src/dendrinet_studio/web/js/design.js
index 11ea1101..87652dac 100644
--- a/apps/studio/src/dendrinet_studio/web/js/design.js
+++ b/apps/studio/src/dendrinet_studio/web/js/design.js
@@ -6,14 +6,20 @@
// diagram of encoder, core and decoder.
import { h, s, icon, fmt, polarityGlyph, download } from "./dom.js";
-import { state, api, edit, select, adopt, emit, getPath, deletePath, isPopulationNetwork, layers, nodeView, configKey } from "./store.js";
+import { state, api, edit, editTopology, topologyReady, validationRevision, select, adopt, emit, getPath, deletePath, isPopulationNetwork, layers, layerView, nodeView, configKey } from "./store.js";
import { field, textInput, numberInput, stepper, selectInput, switchInput, segmented, mappingInput, factorEditor, sectionForm, disclosure, humanize, controlFor, describeCount, rebuildKeepingFocus } from "./fields.js";
import { drawNetwork, drawOverview, layoutNetwork, svgForExport } from "./graph.js";
import { externalControls, sourcesTable, structuredInputGuide } from "./afferents.js";
-import { compartmentLevels, drawNeuron, levelTable, neuronLegend } from "./morphology.js";
-import { toast, confirmDialog } from "./ui.js";
+import { compartmentLevels, drawNeuron, levelName, levelTable, neuronLegend, targetDepths } from "./morphology.js";
+import { toast, confirmDialog, dialog } from "./ui.js";
+import { connectionEditor as showConnectionDialog } from "./wiring.js";
+import { travelLabel, travelRange } from "./travel.js";
const NET = "model.core.population_network";
+const connectionEditor = topologyDialog(showConnectionDialog, { allowRepair: true });
+const addLayer = topologyDialog(newLayerDialog);
+const removePopulation = topologyDialog(confirmRemovePopulation, { allowRepair: true });
+const removeLayer = topologyDialog(confirmRemoveLayer, { allowRepair: true });
const STREAMS = [
["ff_excitatory", "Excitatory", "same step"],
["ff_inhibitory", "Inhibitory", "same step"],
@@ -32,10 +38,11 @@ const CURATED = new Set([...Object.values(POP_GROUPS).flat(), ...STREAMS.flatMap
let els = null;
let zoom = 1;
-let zoomMode = "fit";
+let zoomMode = "readable";
let lastWidth = 0;
let natural = { width: 800, height: 300 };
let showCounts = true;
+let connectingFrom = null;
export const familyLabel = type => {
const known = { population_network: "Population network", gru: "GRU", lstm: "LSTM", vanilla_rnn: "Vanilla RNN", rnn: "Vanilla RNN", heterogeneous_leak_ctrnn: "Multi-timescale CTRNN", legendre_memory: "Legendre memory", unified_ei: "Unified E/I network", mlp: "MLP" };
@@ -133,6 +140,7 @@ function decoderText() {
function populationOutline() {
const p = state.preview;
+ const nodesById = new Map(p.nodes.map(node => [node.id, node]));
const sel = state.selection;
const tree = h("div", { class: "tree" });
const width = getPath(p.resolved_config, NET).input_dim;
@@ -142,7 +150,7 @@ function populationOutline() {
treeRow({ cls: "layer-row", current: sel.kind === "layer" && sel.layer === li, onclick: () => select({ kind: "layer", layer: li }) }, [
icon("layers"),
h("span", { class: "grow", text: layer.name }),
- h("span", { class: "meta", text: [layer.recurrent ? "recurrent" : null, `readout ${layer.readout}`].filter(Boolean).join(" · ") }),
+ h("span", { class: "meta", text: [layer.recurrent ? "recurrent" : layer.steps_through_time ? "stateful" : null, `readout ${layer.readout}`].filter(Boolean).join(" · ") }),
])
);
for (const node of p.nodes.filter(n => n.layer === li)) {
@@ -155,13 +163,21 @@ function populationOutline() {
])
);
}
- const count = (layers()[li].connections || []).length;
- tree.append(
- treeRow({ cls: "conn-row", current: sel.kind === "connection" && sel.layer === li, onclick: () => (count ? select({ kind: "connection", layer: li, index: 0 }) : addConnection(li)) }, [
- h("span", { class: "indent" }),
- h("span", { class: "grow", text: count ? describeCount(count, "connection") : "Add a connection" }),
- ])
- );
+ const group = h("details", { class: "route-list" });
+ const edges = p.edges.filter(e => e.layer === li);
+ group.open = sel.kind === "connection" && sel.layer === li;
+ group.append(h("summary", { text: describeCount(edges.length, "connection") }));
+ edges.forEach((edge, index) => {
+ const range = edge.timing === "delayed" ? travelRange(edge, nodesById.get(edge.target_id)) : null;
+ const labels = [edge.pathway.endsWith("inhibitory") ? "I" : "E"];
+ if (range) labels.push(travelLabel(range));
+ if (edge.enabled === false) labels.push("off");
+ group.append(treeRow({ cls: "route-row", current: group.open && sel.index === index,
+ onclick: () => select({ kind: "connection", layer: li, index }) },
+ [h("span", { class: "grow", text: edge.source + " → " + edge.target }),
+ h("span", { class: "meta", text: labels.join(" · ") })]));
+ });
+ tree.append(group);
});
tree.append(treeRow({ current: sel.kind === "decoder", onclick: () => select({ kind: "decoder" }) }, [icon("sliders"), h("span", { class: "grow", text: decoderText() })]));
const target = targetLayer();
@@ -171,7 +187,7 @@ function populationOutline() {
h("div", { class: "add-row" }, [
h("button", { type: "button", class: "btn small", onclick: () => addPopulation(target, "excitatory") }, [icon("plus"), "E population"]),
h("button", { type: "button", class: "btn small", onclick: () => addPopulation(target, "inhibitory") }, [icon("plus"), "I population"]),
- h("button", { type: "button", class: "btn small", onclick: () => addConnection(target) }, [icon("plus"), "Connection"]),
+ h("button", { type: "button", class: "btn small", onclick: () => connectionEditor(target) }, [icon("plus"), "Connection"]),
h("button", { type: "button", class: "btn small", onclick: addLayer }, [icon("plus"), "Layer"]),
]),
h("p", { class: "help", text: `New populations and connections go into ${state.preview.layers[target]?.name}.` }),
@@ -237,26 +253,34 @@ function buildCanvasPanel() {
});
els.svg = s("svg", { class: "network", role: "group", "aria-label": "Network diagram" });
els.scroller = h("div", { class: "canvas-scroll" }, [els.svg]);
+ els.scroller.addEventListener("keydown", event => {
+ if (event.key === "Escape" && connectingFrom) {
+ connectingFrom = null;
+ renderCanvas();
+ }
+ });
els.canvasTitle = h("h3", { text: "Network" });
els.canvasSub = h("span", { class: "sub" });
els.canvasTools = h("div", { class: "tools" }, [
+ h("button", { type: "button", class: "btn small", onclick: () => connectionEditor(targetLayer()) }, [icon("plus"), "Connect"]),
h("label", { class: "check", for: "show-counts" }, [counts, "Contact counts"]),
iconButton("zoomOut", "Zoom out", () => setZoom(zoom / 1.2)),
iconButton("zoomIn", "Zoom in", () => setZoom(zoom * 1.2)),
iconButton("fit", "Fit to the panel", fitZoom),
iconButton("download", "Export the diagram (SVG)", exportSvg),
]);
+ els.pickTarget = h("div", { class: "pick-target", hidden: true });
els.legend = h("div", { class: "legend" });
if (window.ResizeObserver) {
new ResizeObserver(() => {
const width = els.scroller.clientWidth;
- if (zoomMode === "fit" && Math.abs(width - lastWidth) > 8 && state.preview?.family === "population_network") {
+ if (zoomMode !== "manual" && Math.abs(width - lastWidth) > 8 && state.preview?.family === "population_network") {
lastWidth = width;
renderCanvas();
}
}).observe(els.scroller);
}
- els.canvas.replaceChildren(h("div", { class: "panel-head" }, [els.canvasTitle, els.canvasSub, h("span", { class: "spacer" }), els.canvasTools]), els.scroller, els.legend);
+ els.canvas.replaceChildren(h("div", { class: "panel-head" }, [els.canvasTitle, els.canvasSub, h("span", { class: "spacer" }), els.canvasTools]), els.pickTarget, els.scroller, els.legend);
}
function setZoom(value) {
@@ -273,7 +297,7 @@ function fitZoom() {
// In fit mode the network fills the panel's width (never enlarged past 110%).
function fittedZoom(width) {
const available = els.scroller.clientWidth - 12;
- return available > 120 ? Math.min(1.1, Math.max(0.35, available / width)) : zoom;
+ return available > 120 ? Math.min(1.1, Math.max(zoomMode === "fit" ? 0.05 : 0.72, available / width)) : zoom;
}
function exportSvg() {
@@ -281,18 +305,37 @@ function exportSvg() {
download(`${name}_network.svg`, svgForExport(els.svg), "image/svg+xml");
}
+function pickTarget(node) {
+ connectingFrom = { id: node.id, revision: validationRevision };
+ renderCanvas();
+ els.scroller.scrollIntoView({ block: "nearest" });
+ els.svg.querySelector(".card.selected")?.focus({ preventScroll: true });
+}
+
function renderCanvas() {
const p = state.preview;
+ if (connectingFrom?.revision !== validationRevision) connectingFrom = null;
+ els.pickTarget.hidden = !connectingFrom;
+ if (connectingFrom) els.pickTarget.replaceChildren(
+ h("span", { role: "status", text: "Select the receiving population for " + connectingFrom.id + "." }),
+ h("button", { type: "button", class: "btn small", text: "Cancel", onclick: () => { connectingFrom = null; renderCanvas(); } })
+ );
if (p.family === "population_network") {
els.canvasTitle.textContent = "Network";
- els.canvasSub.textContent = "configured pathways between populations, not individual synapses";
+ els.canvasSub.textContent = "";
els.canvasTools.hidden = false;
- if (zoomMode === "fit") zoom = fittedZoom(layoutNetwork(p).width);
+ if (zoomMode !== "manual") zoom = fittedZoom(layoutNetwork(p).width);
natural = drawNetwork(els.svg, p, {
selection: state.selection,
showCounts,
zoom,
- onSelectPopulation: (layer, population) => select({ kind: "population", layer, population }),
+ onSelectPopulation: (layer, population) => {
+ if (!connectingFrom) return select({ kind: "population", layer, population });
+ const from = connectingFrom.id;
+ connectingFrom = null;
+ renderCanvas();
+ connectionEditor(layer, { from, to: nodeView(layer, population).id });
+ },
onSelectConnection: (layer, index) => select({ kind: "connection", layer, index }),
onSelectLayer: layer => select({ kind: "layer", layer }),
});
@@ -316,7 +359,7 @@ function networkLegend() {
h("span", { class: "legend-item" }, [polarityGlyph("inhibitory"), "I population"]),
legendItem([s("path", { d: "M2 7H19", class: "edge exc" }), s("path", { d: "M18 3L25 7L18 11Z", class: "marker-exc" })], "excitation (arrow)"),
legendItem([s("path", { d: "M2 7H22", class: "edge inh" }), s("path", { d: "M23 1V13", class: "marker-inh" })], "inhibition (bar end)"),
- legendItem([s("path", { d: "M2 7H24", class: "edge exc delayed" })], "delayed one step (Δt)"),
+ legendItem([s("path", { d: "M2 7H24", class: "edge exc delayed" })], "travel delay (steps of Δt)"),
legendItem([s("path", { d: "M2 7H24", class: "edge exc disabled" })], "switched off"),
];
}
@@ -487,8 +530,16 @@ function group(title, children, note) {
return h("section", { class: "group" }, [h("h3", { class: "eyebrow", text: title }), note ? h("p", { class: "help", text: note }) : null, ...[].concat(children).filter(Boolean)]);
}
+function selectionNotice() {
+ return h("p", { class: "help", role: "status", text: state.validating ? "Updating the selection…" : "Select an item in the current design." });
+}
+
// Contexts that read and write per-population options --------------------------------
+function populationSetting(layer, item, name) {
+ return item.population?.[name] ?? layer.population_defaults?.[name] ?? popSpec(name)?.default;
+}
+
function populationContext(li, pi) {
const layer = layers()[li];
const item = layer.populations[pi];
@@ -496,6 +547,10 @@ function populationContext(li, pi) {
const node = nodeView(li, pi);
return {
keyOf: name => `${itemPath}.population.${name}`,
+ current: name => {
+ const current = layers()[li];
+ return populationSetting(current, current.populations[pi], name);
+ },
ownOf: name => item.population?.[name],
inheritedOf: name =>
layer.population_defaults?.[name] !== undefined ? { value: layer.population_defaults[name], source: "layer default" } : { value: node?.settings?.[name] ?? popSpec(name)?.default, source: "default" },
@@ -540,7 +595,7 @@ function optionField(ctx, name, overrides = {}) {
const key = ctx.keyOf(name);
return field({
label: overrides.label || humanize(name),
- control: controlFor(spec, shown, value => ctx.write(name, value)),
+ control: controlFor(spec, shown, value => ctx.write(name, value), overrides.label),
key,
inherited: own === undefined ? inherited.source : false,
onReset: own !== undefined ? () => ctx.remove(name) : null,
@@ -608,9 +663,12 @@ function perLevelEditor(ctx, node, recurrentRelevant) {
for (const [key, label] of streams) {
const current = node.configured_per_level[key][depth];
const input = numberInput(current, value => {
- const list = [...node.configured_per_level[key]];
- list[depth] = value;
- ctx.write(`${key}_synapses_by_level`, list.reverse());
+ const field = key + "_synapses_by_level";
+ // A reset or another depth edit can be newer than the last preview.
+ const old = ctx.current(field);
+ const list = old?.length ? [...old] : Array(levels).fill(ctx.current(key + "_synapses"));
+ list[levels - depth - 1] = value;
+ ctx.write(field, list);
}, { integer: true, min: 0 });
input.setAttribute("aria-label", `${label} contacts at level ${names(depth)}`);
input.dataset.key = `${ctx.keyOf(`${key}_synapses_by_level`)}.${depth}`;
@@ -620,7 +678,17 @@ function perLevelEditor(ctx, node, recurrentRelevant) {
}
table.append(body);
const clearButton = h("button", { type: "button", class: "btn small", onclick: () => {
- for (const [key] of STREAMS) if (ctx.ownOf(`${key}_synapses_by_level`) !== undefined) ctx.remove(`${key}_synapses_by_level`);
+ edit(cfg => {
+ const layer = getPath(cfg, NET).layers[node.layer];
+ for (const [key] of STREAMS) {
+ const path = ctx.keyOf(key + "_synapses_by_level");
+ const inherited = layer.population_defaults?.[key + "_synapses_by_level"];
+ if (inherited?.length) {
+ const item = layer.populations[node.population];
+ (item.population ||= {})[key + "_synapses_by_level"] = [];
+ } else deletePath(cfg, path);
+ }
+ }, { structural: true });
} }, ["Use one count for all levels"]);
return h("div", {}, [table, h("p", { class: "help", text: "Saved as *_synapses_by_level lists, which run from the most distal level to the soma." }), clearButton]);
}
@@ -629,6 +697,65 @@ function groupedOptions(ctx, groupName) {
return POP_GROUPS[groupName].map(name => optionField(ctx, name));
}
+function tauAtDepth(settings, depth) {
+ return settings.level_taus?.at(-1 - depth) ?? settings.tau_base * settings.tau_ratio ** depth;
+}
+
+function depthTimeTable(node, { ctx, edge } = {}) {
+ const deepest = node.branch_factors.length;
+ const rows = [];
+ for (let depth = 0; depth <= deepest; depth++) {
+ if (edge && (edge.enabled === false || edge.probability === 0 || !node.received_per_level[edge.pathway][depth] ||
+ (edge.target_depths && !edge.target_depths.includes(depth)))) continue;
+ const label = levelName(depth, deepest);
+ const value = tauAtDepth(node.settings, depth);
+ let cell = String(value);
+ if (ctx) {
+ cell = numberInput(value, next => {
+ // Resolve the latest edits, including changes made before the previous preview arrived.
+ const timing = { level_taus: ctx.current("level_taus"), tau_base: ctx.current("tau_base"), tau_ratio: ctx.current("tau_ratio") };
+ const list = Array.from({ length: deepest + 1 }, (_, i) => tauAtDepth(timing, deepest - i));
+ list[deepest - depth] = next;
+ ctx.write("level_taus", list);
+ }, { positive: true });
+ cell.setAttribute("aria-label", "Response time at " + label);
+ cell.dataset.key = ctx.keyOf("level_taus") + "." + (deepest - depth);
+ }
+ rows.push(h("tr", {}, [h("th", { scope: "row", text: label }),
+ edge ? h("td", { text: String(edge.arrival_steps[depth]) }) : null, h("td", {}, [cell])]));
+ }
+ if (!rows.length) return h("p", { class: "help", text: "This route has no active contacts at the selected depths." });
+ const columns = ["Receiving depth", ...(edge ? ["Travel steps"] : []), node.settings.learnable_tau ? "Initial τ (learned)" : "Response τ (fixed)"];
+ return h("table", { class: "levels" + (ctx ? " editable" : ""), "aria-label": "Response times by depth" }, [
+ h("thead", {}, [h("tr", {}, columns.map(text => h("th", { scope: "col", text })))]), h("tbody", {}, rows),
+ ]);
+}
+
+function timeConstantsGroup(ctx, node) {
+ const fields = [
+ optionField(ctx, "tau_base", { label: "Soma time constant (base)" }),
+ optionField(ctx, "tau_ratio", { label: "Ratio per outward depth" }),
+ optionField(ctx, "learnable_tau", { label: "Learn one time constant per depth" }),
+ ];
+ if (node) {
+ fields.push(depthTimeTable(node, { ctx }));
+ const inherited = layers()[node.layer].population_defaults?.level_taus;
+ if (node.settings.level_taus.length) {
+ fields.push(h("button", { type: "button", class: "btn small",
+ onclick: () => layers()[node.layer].population_defaults?.level_taus?.length ? ctx.write("level_taus", []) : ctx.remove("level_taus"),
+ text: "Use base and ratio" }));
+ }
+ if (inherited?.length && ctx.ownOf("level_taus") !== undefined) {
+ fields.push(h("button", { type: "button", class: "btn small",
+ onclick: () => ctx.remove("level_taus"), text: "Restore layer time constants" }));
+ }
+ } else {
+ fields.push(optionField(ctx, "level_taus", { label: "Explicit times, distal to soma", help: "Include one value per depth, including the soma. An empty list uses the base and ratio." }));
+ }
+ return group("Time constants", fields, "Larger τ makes the receiving compartment respond more slowly. " +
+ (node ? "Editing a depth sets an explicit time for every row." : "These defaults apply to each population in this layer."));
+}
+
function allOptions(ctx, idPrefix) {
return disclosure(`${idPrefix}-all`, "All population options", () => {
const box = h("div");
@@ -653,21 +780,27 @@ function populationInspector(sel) {
const li = sel.layer;
const pi = sel.population;
const layer = layers()[li];
- const item = layer.populations[pi];
+ const item = layer?.populations?.[pi];
const node = nodeView(li, pi);
+ if (!item || !node) return selectionNotice();
+ const name = item.name ?? node.name;
+ const layerName = layer.name ?? node.layer_name;
+ if (state.validating && (name !== node.name || layerName !== node.layer_name)) return selectionNotice();
const itemPath = `${NET}.layers.${li}.populations.${pi}`;
const ctx = populationContext(li, pi);
const polarity = item.polarity || node?.polarity || "excitatory";
- const recurrentRelevant = Boolean(layer.recurrent) || state.preview.edges.some(e => e.target_id === `${layer.name}.${item.name}` && e.timing === "delayed");
- const setItem = (key, value, structural = false) => edit(cfg => (getPath(cfg, itemPath)[key] = value), { path: `${itemPath}.${key}`, structural });
- const factors = item.branch_factors || [];
+ const recurrentRelevant = state.preview.layers[li].steps_through_time;
+ const setItem = (key, value, structural = false) => structural
+ ? safeTopology(cfg => { getPath(cfg, itemPath)[key] = value; })
+ : edit(cfg => (getPath(cfg, itemPath)[key] = value), { path: `${itemPath}.${key}` });
+ const factors = node?.branch_factors || item.branch_factors || [];
const levels = factors.length + 1;
return [
- head(polarityGlyph(polarity, 18), `${polarity === "inhibitory" ? "Inhibitory" : "Excitatory"} population · ${item.name}`, `in ${layer.name}${node ? ` · ${fmt(node.synapses_per_neuron)} contacts per neuron` : ""}`),
+ head(polarityGlyph(polarity, 18), `${polarity === "inhibitory" ? "Inhibitory" : "Excitatory"} population · ${name}`, `in ${layerName} · ${fmt(node.synapses_per_neuron)} contacts per neuron`),
group("Population", [
- field({ label: "Name", control: textInput(item.name, v => renamePopulation(li, pi, v.trim())), key: `${itemPath}.name` }),
+ field({ label: "Name", control: textInput(item.name ?? node.name, v => renamePopulation(li, pi, v.trim())), key: `${itemPath}.name` }),
field({ label: "Cell type", control: segmented(polarity, [["excitatory", "Excitatory", "exc"], ["inhibitory", "Inhibitory", "inh"]], v => setItem("polarity", v, true), "Cell type"), key: `${itemPath}.polarity`, help: "Excitatory populations send excitation; inhibitory populations send inhibition." }),
- field({ label: "Neurons", control: stepper(item.n_neurons, v => setItem("n_neurons", v), { min: 1, label: "neurons" }), key: `${itemPath}.n_neurons`, error: state.errorPath === `${itemPath}.n_neurons` ? state.error : null }),
+ field({ label: "Neurons", control: stepper(item.n_neurons ?? node?.neurons, v => setItem("n_neurons", v), { min: 1, label: "neurons" }), key: `${itemPath}.n_neurons`, error: state.errorPath === `${itemPath}.n_neurons` ? state.error : null }),
]),
group(
"Morphology",
@@ -675,14 +808,18 @@ function populationInspector(sel) {
field({ label: "Branching per level (soma → distal)", control: factorEditor(factors, v => setFactors(li, pi, v)), key: `${itemPath}.branch_factors`, help: `${levels} ${levels === 1 ? "level" : "levels"} · ${fmt(node?.compartments_per_neuron ?? 1)} compartments per neuron` }),
]
),
+ node ? h("div", { class: "add-row" }, [
+ h("button", { type: "button", class: "btn small", onclick: () => connectionEditor(li, { to: node.id }) }, [icon("plus"), "Add input source"]),
+ h("button", { type: "button", class: "btn small", onclick: () => pickTarget(node) }, [icon("plus"), "Connect from this population"]),
+ ]) : null,
li === 0 && node ? group("External input to this population", externalControls(node), "Choose the incoming synapse signs for this population. Connections from other populations are set separately.") : null,
synapseGroup(ctx, { node, recurrentRelevant }),
integrationGroup(ctx, null),
group("Dendritic gate", groupedOptions(ctx, "Dendritic gate")),
group("Initialization", groupedOptions(ctx, "Initialization"), "How synaptic weights, couplings and gates start."),
- recurrentRelevant ? group("Time constants", groupedOptions(ctx, "Time constants")) : null,
+ recurrentRelevant ? timeConstantsGroup(ctx, node) : null,
allOptions(ctx, `pop-${li}-${pi}`),
- h("div", { class: "danger-zone" }, [h("button", { type: "button", class: "btn danger small", onclick: () => removePopulation(li, pi) }, [icon("trash"), "Remove population"])]),
+ h("div", { class: "danger-zone" }, [h("button", { type: "button", class: "btn danger small", onclick: () => removePopulation(li, pi, layerName, name) }, [icon("trash"), "Remove population"])]),
].filter(Boolean);
}
@@ -691,25 +828,20 @@ function populationInspector(sel) {
function connectionInspector(sel) {
const li = sel.layer;
const layer = layers()[li];
- const list = layer.connections || [];
+ const list = layer?.connections || [];
const conn = list[sel.index];
const path = `${NET}.layers.${li}.connections.${sel.index}`;
- const edge = state.preview.edges.filter(e => e.layer === li)[sel.index];
- const target = edge ? state.preview.nodes.find(n => n.id === edge.target_id) : null;
- const set = (name, value, structural = false) =>
- edit(cfg => {
+ const edge = state.preview?.edges?.filter(e => e.layer === li)[sel.index];
+ if (!conn || !edge) return selectionNotice();
+ const target = state.preview.nodes.find(n => n.id === edge.target_id);
+ const set = (name, value) =>
+ safeTopology(cfg => {
const c = getPath(cfg, path);
if (value === null || value === undefined || value === "") delete c[name];
else c[name] = value;
- }, { path: `${path}.${name}`, structural });
- const local = layer.populations.map(p => p.name);
- const sources = { Input: li === 0 ? ["input", "input_e", "input_i"] : ["input"], [`Populations in ${layer.name}`]: local };
- const others = layers().flatMap((l, i) => (i === li ? [] : l.populations.map(p => `${l.name}.${p.name}`)));
- if (others.length) sources["Populations of other layers"] = others;
- const sourceLabels = { input: li === 0 ? "input (all features)" : `input (readout of ${layers()[li - 1].name})`, input_e: "input_e (excitatory channels)", input_i: "input_i (inhibitory channels)" };
- const derived = edge ? edge.pathway : "";
+ });
+ const derived = edge.pathway;
const levels = target ? target.levels_including_soma.length : 1;
- const levelName = depth => (depth === 0 ? "soma" : depth === levels - 1 ? "distal" : depth === 1 ? "primary" : `level ${depth}`);
const allLevels = conn.target_levels === undefined || conn.target_levels === null;
const levelBoxes = h("div", { class: "level-checks" });
for (let depth = levels - 1; depth >= 0; depth--) {
@@ -717,10 +849,17 @@ function connectionInspector(sel) {
box.checked = !allLevels && (edge?.target_depths || []).includes(depth);
box.disabled = allLevels;
box.addEventListener("change", () => {
- const chosen = [...levelBoxes.querySelectorAll("input")].filter(b => b.checked).map(b => Number(b.id.slice(4)));
- set("target_levels", chosen.length ? chosen.sort((a, b) => a - b) : null, true);
+ const checked = box.checked;
+ safeTopology(cfg => {
+ const route = getPath(cfg, path);
+ const chosen = new Set(targetDepths(route.target_levels, levels) ?? Array.from({ length: levels }, (_, i) => i));
+ if (checked) chosen.add(depth);
+ else chosen.delete(depth);
+ if (chosen.size) route.target_levels = [...chosen].sort((a, b) => a - b);
+ else delete route.target_levels;
+ });
});
- levelBoxes.append(h("label", { class: "check", for: `lvl-${depth}` }, [box, `${depth} · ${levelName(depth)}`]));
+ levelBoxes.append(h("label", { class: "check", for: `lvl-${depth}` }, [box, levelName(depth, levels - 1)]));
}
const nav = h("div", { class: "nav-row" }, [
h("button", { type: "button", class: "btn small", disabled: sel.index === 0, onclick: () => select({ kind: "connection", layer: li, index: sel.index - 1 }) }, ["Previous"]),
@@ -728,20 +867,23 @@ function connectionInspector(sel) {
h("button", { type: "button", class: "btn small", disabled: sel.index >= list.length - 1, onclick: () => select({ kind: "connection", layer: li, index: sel.index + 1 }) }, ["Next"]),
]);
const inhibitory = derived.endsWith("inhibitory");
+ const travel = edge && target ? travelRange(edge, target) : null;
return [
- head(icon(inhibitory ? "minus" : "chevron"), `Connection · ${conn.source} → ${conn.target}`, edge ? `${derived.replace("_", " ")} · ${edge.timing === "delayed" ? "delayed one step" : "same step"}` : ""),
+ head(icon(inhibitory ? "minus" : "chevron"), `Connection · ${edge?.source ?? "input"} → ${conn.target}`, edge ? `${derived.replace("_", " ")} · ${edge.timing === "delayed" ? "delayed" : "same step"}` : ""),
nav,
group("Route", [
- field({ label: "From", control: selectInput(conn.source, [], v => set("source", v, true), { groups: sources, labels: sourceLabels }), key: `${path}.source` }),
- field({ label: "To", control: selectInput(conn.target, local, v => set("target", v, true), { allowCustom: false }), key: `${path}.target` }),
- field({ label: "Timing", control: segmented(conn.timing || "same_step", [["same_step", "Same step"], ["delayed", "Delayed (Δt)"]], v => set("timing", v === "same_step" ? null : v, true), "Timing"), key: `${path}.timing`, help: "Delayed connections carry the source's previous state; they make the network recurrent." }),
- field({
- label: "Pathway",
- control: selectInput(conn.pathway || "", ["", "ff_excitatory", "ff_inhibitory", "rec_excitatory", "rec_inhibitory"], v => set("pathway", v || null, true), { allowCustom: false, labels: { "": `automatic (${edge && !conn.pathway ? derived : "from source and timing"})` } }),
- key: `${path}.pathway`,
- help: "Automatic uses the source's cell type and the timing. The pathway decides which synapse count of the target applies.",
- }),
+ h("p", { text: (edge?.source_id || "input") + " → " + edge?.target_id }),
+ h("button", { type: "button", class: "btn small", onclick: () => connectionEditor(li, { index: sel.index }) }, ["Edit connection"]),
]),
+ edge && target ? group("Connection timing", [
+ travel === null ? null : h("p", { text: `Source delay: ${travel} ${travel === "1" ? "step" : "steps"}.` }),
+ state.preview.layers[li].steps_through_time ? [
+ h("p", { class: "help", text: `Compartment τ uses the same time units as the layer step (dt = ${state.preview.layers[li].dt}).` +
+ (target.has_receptor_traces ? " This target also has receptor-specific synaptic time constants." : "") }),
+ depthTimeTable(target, { edge }),
+ h("button", { type: "button", class: "btn small", onclick: () => select({ kind: "population", layer: li, population: target.population }), text: "Edit receiving population" }),
+ ] : h("p", { class: "help", text: "This feedforward layer computes its response directly at each step." }),
+ ].flat()) : null,
group("Placement", [
field({ label: "All levels of the target", control: switchInput(allLevels, v => set("target_levels", v ? null : Array.from({ length: levels }, (_, i) => i), true), "All levels"), key: `${path}.target_levels`, help: allLevels ? null : "Untick the levels this connection should not reach (0 = soma)." }),
allLevels ? null : levelBoxes,
@@ -760,7 +902,9 @@ function layerInspector(sel) {
const li = sel.layer;
const layer = layers()[li];
const path = `${NET}.layers.${li}`;
- const view = state.preview.layers[li];
+ const view = layerView(li);
+ if (!layer || !view || (state.validating && (layer.name ?? view.name) !== view.name)) return selectionNotice();
+ const name = layer.name ?? view.name;
const set = (name, value, structural = false) =>
edit(cfg => {
const l = getPath(cfg, path);
@@ -768,14 +912,23 @@ function layerInspector(sel) {
else l[name] = value;
}, { path: `${path}.${name}`, structural });
const ctx = layerDefaultsContext(li);
- const recurrentRelevant = Boolean(layer.recurrent) || (layer.connections || []).some(c => c.timing === "delayed");
+ const recurrentRelevant = view.steps_through_time;
return [
- head(icon("layers"), `Layer · ${layer.name}`, `${describeCount(layer.populations.length, "population")} · ${describeCount((layer.connections || []).length, "connection")}`),
+ head(icon("layers"), `Layer · ${view.name}`, `${describeCount(layer.populations.length, "population")} · ${describeCount((layer.connections || []).length, "connection")}`),
group("Layer", [
- field({ label: "Name", control: textInput(layer.name, v => renameLayer(li, v.trim())), key: `${path}.name` }),
- field({ label: "Readout population", control: selectInput(layer.readout_population || "", ["", ...layer.populations.filter(p => p.polarity !== "inhibitory").map(p => p.name)], v => set("readout_population", v || null, true), { allowCustom: false, labels: { "": `first excitatory (${view?.readout || "?"})` } }), key: `${path}.readout_population`, help: "Its activity is what the next layer or the decoder reads." }),
- field({ label: "Recurrent", control: switchInput(Boolean(layer.recurrent), v => set("recurrent", v || null, true), "Recurrent"), key: `${path}.recurrent`, help: "Integrate the layer over time steps; required for delayed connections within the layer." }),
- layer.recurrent ? field({ label: "Time step dt", control: numberInput(layer.dt ?? 1, v => set("dt", v), { min: 0 }), key: `${path}.dt` }) : null,
+ field({ label: "Name", control: textInput(layer.name ?? view.name, v => renameLayer(li, v.trim())), key: `${path}.name` }),
+ field({ label: "Readout population", control: selectInput(layer.readout_population || "", ["", ...state.preview.nodes.filter(n => n.layer === li).map(n => n.name)], v => safeTopology(cfg => {
+ const net = getPath(cfg, NET);
+ const row = net.layers[li];
+ if (v) row.readout_population = v;
+ else delete row.readout_population;
+ if (view.is_readout_layer && net.readout_population) {
+ if (v) net.readout_population = v;
+ else delete net.readout_population;
+ }
+ }), { allowCustom: false, labels: { "": "First excitatory population" } }), key: `${path}.readout_population`, help: "The next layer's input route and the selected decoder readout use this population. Connect additional populations by name." }),
+ field({ label: "Recurrent", control: switchInput(Boolean(layer.recurrent), v => safeTopology(cfg => { getPath(cfg, path).recurrent = v; }), "Recurrent"), key: `${path}.recurrent`, help: "Receives current and delayed population activity. Remove or retime delayed connections before switching off." }),
+ recurrentRelevant ? field({ label: "Time step dt", control: numberInput(layer.dt ?? 1, v => set("dt", v), { min: 0, positive: true }), key: `${path}.dt` }) : null,
field({ label: "Connection seed", control: numberInput(layer.connection_seed ?? null, v => set("connection_seed", v), { integer: true, optional: true }), key: `${path}.connection_seed` }),
]),
h("p", { class: "help lead", text: "Defaults for every population in this layer. A population's own setting overrides them." }),
@@ -783,14 +936,14 @@ function layerInspector(sel) {
integrationGroup(ctx, null),
group("Dendritic gate", groupedOptions(ctx, "Dendritic gate")),
group("Initialization", groupedOptions(ctx, "Initialization")),
- recurrentRelevant ? group("Time constants", groupedOptions(ctx, "Time constants")) : null,
+ recurrentRelevant ? timeConstantsGroup(ctx, null) : null,
allOptions(ctx, `layer-${li}`),
h("div", { class: "add-row" }, [
h("button", { type: "button", class: "btn small", onclick: () => addPopulation(li, "excitatory") }, [icon("plus"), "E population"]),
h("button", { type: "button", class: "btn small", onclick: () => addPopulation(li, "inhibitory") }, [icon("plus"), "I population"]),
- h("button", { type: "button", class: "btn small", onclick: () => addConnection(li) }, [icon("plus"), "Connection"]),
+ h("button", { type: "button", class: "btn small", onclick: () => connectionEditor(li) }, [icon("plus"), "Connection"]),
]),
- layers().length > 1 ? h("div", { class: "danger-zone" }, [h("button", { type: "button", class: "btn danger small", onclick: () => removeLayer(li) }, [icon("trash"), "Remove layer"])]) : null,
+ layers().length > 1 ? h("div", { class: "danger-zone" }, [h("button", { type: "button", class: "btn danger small", onclick: () => removeLayer(li, name) }, [icon("trash"), "Remove layer"])]) : null,
].filter(Boolean);
}
@@ -902,91 +1055,161 @@ function uniqueName(existing, stem) {
return name;
}
+function hasContacts(node, pathway) {
+ return node.configured_per_level[pathway].some((count, depth) =>
+ count > 0 && (depth > 0 || node.settings.somatic_synapses));
+}
+
+function reportTopologyError(error) {
+ toast(error.message, { kind: "error" });
+ renderModel();
+}
+
+function topologyDialog(open, options) {
+ return (...args) => topologyReady(options).then(() => open(...args)).catch(reportTopologyError);
+}
+
+function safeTopology(mutate, options) {
+ return editTopology(mutate, options).catch(reportTopologyError);
+}
+
function addPopulation(li, polarity) {
- const layer = layers()[li];
- const names = layer.populations.map(p => p.name);
- const name = uniqueName(names, polarity === "inhibitory" ? "i" : "e");
- const readout = state.preview.layers[li]?.readout;
- edit(cfg => {
- const l = getPath(cfg, `${NET}.layers.${li}`);
- l.populations.push({ name, polarity, n_neurons: 8, branch_factors: polarity === "inhibitory" ? [1] : [2] });
- l.connections = l.connections || [];
- l.connections.push({ source: "input", target: name });
- if (polarity === "inhibitory" && readout) l.connections.push({ source: name, target: readout });
- }, { structural: true }).then(() => select({ kind: "population", layer: li, population: names.length }));
+ return safeTopology(cfg => {
+ const layer = getPath(cfg, NET).layers[li];
+ const nodes = state.preview.nodes.filter(n => n.layer === li);
+ const template = nodes.find(n => n.polarity === polarity) || nodes[0];
+ const readout = state.preview.layers[li].readout;
+ const name = uniqueName(nodes.map(p => p.name), polarity === "inhibitory" ? "i" : "e");
+ const previous = state.preview.layers[li - 1];
+ const prevNode = previous && state.preview.nodes.find(n => n.layer === li - 1 && n.name === previous.readout);
+ const source = prevNode?.polarity === "inhibitory"
+ ? state.preview.nodes.find(n => n.layer === li - 1 && n.polarity === "excitatory").id : "input";
+ const item = structuredClone(layer.populations[template.population]);
+ Object.assign(item, { name, polarity, n_neurons: 8 });
+ const index = layer.populations.push(item) - 1;
+ (layer.connections ||= []).push({ source, target: name });
+ if (polarity === "inhibitory" && hasContacts(nodes.find(n => n.name === readout), "ff_inhibitory"))
+ layer.connections.push({ source: name, target: readout });
+ return { kind: "population", layer: li, population: index };
+ });
}
-function addConnection(li) {
- const layer = layers()[li];
- const target = state.preview.layers[li]?.readout || layer.populations[0]?.name;
- const index = (layer.connections || []).length;
- edit(cfg => {
- const l = getPath(cfg, `${NET}.layers.${li}`);
- l.connections = l.connections || [];
- l.connections.push({ source: "input", target });
- }, { structural: true }).then(() => select({ kind: "connection", layer: li, index }));
-}
-
-function addLayer() {
- const all = layers();
- const last = all.at(-1);
- // Read the new layer's index now: `all` is the live list the edit extends.
- const index = all.length;
- const name = uniqueName(all.map(l => l.name), `layer${index}`);
- edit(cfg => {
- const net = getPath(cfg, NET);
- net.layers.push({
- name,
- ...(last?.population_defaults ? { population_defaults: structuredClone(last.population_defaults) } : {}),
- populations: [
- { name: "i", polarity: "inhibitory", n_neurons: 8, branch_factors: [1] },
- { name: "e", polarity: "excitatory", n_neurons: 16, branch_factors: [2, 2] },
- ],
- connections: [{ source: "input", target: "i" }, { source: "input", target: "e" }, { source: "i", target: "e" }],
- });
- if (net.readout_layer === last?.name) delete net.readout_layer;
- }, { structural: true }).then(() => select({ kind: "layer", layer: index }));
+function newLayerDialog() {
+ const index = layers().length;
+ const last = layers()[index - 1];
+ const previous = state.preview.layers[index - 1];
+ const nodes = state.preview.nodes.filter(n => n.layer === index - 1);
+ const pyr = nodes.find(n => n.polarity === "excitatory" && n.name === previous.readout) || nodes.find(n => n.polarity === "excitatory");
+ const inh = nodes.find(n => n.polarity === "inhibitory");
+ const localInhibition = hasContacts(pyr, "ff_inhibitory");
+ const revision = validationRevision;
+ const name = h("input", { class: "input", value: uniqueName(state.preview.layers.map(l => l.name), "layer" + index), required: true });
+ const mode = selectInput("feedforward", ["feedforward", "recurrent"], () => {}, { labels: { feedforward: "Feedforward", recurrent: "Recurrent" }, allowCustom: false });
+ const info = h("p", { class: "help" });
+ function describe() {
+ const route = mode.value === "recurrent" ? " It also starts with a one-step excitatory feedback loop." : "";
+ const inhibition = localInhibition ? "The I population inhibits the E population."
+ : "The copied E population has no eligible inhibitory contacts. Add an inhibitory connection later to set its contact budget.";
+ info.textContent = "The new E and I populations receive excitation from " + pyr.id + ". " + inhibition + route;
+ }
+ mode.addEventListener("change", describe);
+ describe();
+ return dialog({ title: "Add layer", body: [field({ label: "Layer name", control: name }), field({ label: "Layer dynamics", control: mode }), info],
+ actions: [{ label: "Cancel", submit: false }, { label: "Add layer", value: true, primary: true }],
+ onConfirm: signal => editTopology(cfg => {
+ const net = getPath(cfg, NET);
+ const layerName = name.value.trim();
+ if (!/^[A-Za-z_][\w-]*$/.test(layerName) || net.layers.some(l => l.name === layerName))
+ throw new Error("Choose a unique layer name beginning with a letter or underscore; use letters, digits, hyphens and underscores.");
+ const e = structuredClone(last.populations[pyr.population]);
+ e.name = pyr.name;
+ const i = structuredClone(last.populations[(inh || pyr).population]);
+ i.name = inh?.name || uniqueName([e.name], "i");
+ i.polarity = "inhibitory";
+ const source = previous.readout === pyr.name ? "input" : pyr.id;
+ const layer = {
+ name: layerName, readout_population: e.name,
+ ...(last.population_defaults && { population_defaults: structuredClone(last.population_defaults) }),
+ populations: [i, e], connections: [{ source, target: i.name }, { source, target: e.name }],
+ };
+ if (localInhibition) layer.connections.push({ source: i.name, target: e.name });
+ if (mode.value === "recurrent") {
+ layer.recurrent = true;
+ if (!hasContacts(pyr, "rec_excitatory")) {
+ const own = e.population ||= {};
+ own.rec_excitatory_synapses = 1;
+ if (pyr.settings.rec_excitatory_synapses_by_level?.length) own.rec_excitatory_synapses_by_level = [];
+ }
+ layer.connections.push({ source: e.name, target: e.name, timing: "delayed" });
+ }
+ if (!net.readout_layer && net.readout_population && net.readout_population !== e.name) net.readout_layer = previous.name;
+ net.layers.push(layer);
+ return { kind: "layer", layer: index };
+ }, { revision, signal }),
+ });
}
-async function removePopulation(li, pi) {
+function suppliesReadout(net, li, layerName) {
+ return net.readout_layer ? net.readout_layer === layerName : li === net.layers.length - 1;
+}
+
+async function confirmRemovePopulation(li, pi, layerName, name) {
+ const revision = validationRevision;
const layer = layers()[li];
- const name = layer.populations[pi].name;
- const qualified = `${layer.name}.${name}`;
+ const item = layer?.populations?.[pi];
+ if (!item || (layer.name ?? layerView(li)?.name) !== layerName || (item.name ?? nodeView(li, pi)?.name) !== name)
+ throw new Error("The selection changed. Select the population again.");
+ const qualified = `${layerName}.${name}`;
const affected = (layer.connections || []).filter(c => c.source === name || c.target === name).length + layers().reduce((a, l) => a + (l.connections || []).filter(c => c.source === qualified).length, 0);
if (!(await confirmDialog({ title: "Remove population", text: `Remove ${qualified}${affected ? ` and its ${describeCount(affected, "connection")}` : ""}? Undo restores it.`, confirm: "Remove" }))) return;
- await edit(cfg => {
+ await safeTopology(cfg => {
const net = getPath(cfg, NET);
const l = net.layers[li];
l.populations.splice(pi, 1);
l.connections = (l.connections || []).filter(c => c.source !== name && c.target !== name);
for (const other of net.layers) other.connections = (other.connections || []).filter(c => c.source !== qualified);
if (l.readout_population === name) delete l.readout_population;
- }, { structural: true });
- select({ kind: "layer", layer: li });
+ if (net.readout_population === name && suppliesReadout(net, li, layerName)) delete net.readout_population;
+ return { kind: "layer", layer: li };
+ }, { revision, reindexes: true });
}
async function removeConnection(li, index) {
- await edit(cfg => getPath(cfg, `${NET}.layers.${li}.connections`).splice(index, 1), { structural: true });
- const remaining = (layers()[li].connections || []).length;
- select(remaining ? { kind: "connection", layer: li, index: Math.min(index, remaining - 1) } : { kind: "layer", layer: li });
+ await safeTopology(cfg => {
+ const list = getPath(cfg, NET).layers[li].connections;
+ list.splice(index, 1);
+ return list.length ? { kind: "connection", layer: li, index: Math.min(index, list.length - 1) } : { kind: "layer", layer: li };
+ }, { reindexes: true });
}
-async function removeLayer(li) {
+async function confirmRemoveLayer(li, name) {
+ const revision = validationRevision;
const layer = layers()[li];
- if (!(await confirmDialog({ title: "Remove layer", text: `Remove ${layer.name} with its ${describeCount(layer.populations.length, "population")}? Undo restores it.`, confirm: "Remove" }))) return;
- await edit(cfg => {
+ if (!layer || (layer.name ?? layerView(li)?.name) !== name)
+ throw new Error("The selection changed. Select the layer again.");
+ if (!(await confirmDialog({ title: "Remove layer", text: `Remove ${name} with its ${describeCount(layer.populations.length, "population")}? Undo restores it.`, confirm: "Remove" }))) return;
+ await safeTopology(cfg => {
const net = getPath(cfg, NET);
+ const removedReadout = suppliesReadout(net, li, name);
net.layers.splice(li, 1);
- const prefix = `${layer.name}.`;
+ const prefix = `${name}.`;
for (const other of net.layers) other.connections = (other.connections || []).filter(c => !String(c.source).startsWith(prefix));
- if (net.readout_layer === layer.name) delete net.readout_layer;
- }, { structural: true });
- select({ kind: "layer", layer: Math.max(0, li - 1) });
+ if (removedReadout) {
+ const next = net.layers.at(-1);
+ const pop = net.readout_population;
+ // An implicit last-layer override can still be valid on its successor.
+ const compatible = next?.populations.some(p => p.name === pop) && (!next.readout_population || next.readout_population === pop);
+ if (net.readout_layer || (pop && !compatible)) delete net.readout_population;
+ if (net.readout_layer) delete net.readout_layer;
+ }
+ return { kind: "layer", layer: Math.max(0, li - 1) };
+ }, { revision, reindexes: true });
}
function renamePopulation(li, pi, name) {
const layer = layers()[li];
- const old = layer.populations[pi].name;
+ const old = layer.populations[pi].name ?? nodeView(li, pi).name;
+ const layerName = layer.name ?? state.preview.layers[li].name;
if (!name || name === old) return;
if (!/^[A-Za-z_][\w-]*$/.test(name)) return toast("Use letters, digits, - and _ (starting with a letter).", { kind: "warn" });
if (layer.populations.some(p => p.name === name)) return toast(`${layer.name} already has a population called ${name}.`, { kind: "warn" });
@@ -999,13 +1222,13 @@ function renamePopulation(li, pi, name) {
if (c.target === old) c.target = name;
}
if (l.readout_population === old) l.readout_population = name;
- for (const other of net.layers) for (const c of other.connections || []) if (c.source === `${l.name}.${old}`) c.source = `${l.name}.${name}`;
- if (net.readout_population === old && (net.readout_layer || net.layers.at(-1).name) === l.name) net.readout_population = name;
+ for (const other of net.layers) for (const c of other.connections || []) if (c.source === `${layerName}.${old}`) c.source = `${layerName}.${name}`;
+ if (suppliesReadout(net, li, layerName) && net.readout_population === old) net.readout_population = name;
}, { structural: true });
}
function renameLayer(li, name) {
- const old = layers()[li].name;
+ const old = layers()[li].name ?? state.preview.layers[li].name;
if (!name || name === old) return;
if (!/^[A-Za-z_][\w-]*$/.test(name)) return toast("Use letters, digits, - and _ (starting with a letter).", { kind: "warn" });
if (layers().some(l => l.name === name)) return toast(`A layer called ${name} already exists.`, { kind: "warn" });
@@ -1017,16 +1240,35 @@ function renameLayer(li, name) {
}, { structural: true });
}
-function setFactors(li, pi, factors) {
+function setFactors(li, pi, update) {
const itemPath = `${NET}.layers.${li}.populations.${pi}`;
- const item = layers()[li].populations[pi];
- const levels = factors.length + 1;
- const stale = STREAMS.map(([k]) => `${k}_synapses_by_level`).filter(k => Array.isArray(item.population?.[k]) && item.population[k].length && item.population[k].length !== levels);
- edit(cfg => {
- const it = getPath(cfg, itemPath);
- it.branch_factors = factors;
- for (const key of stale) delete it.population[key];
- if (it.population && !Object.keys(it.population).length) delete it.population;
- }, { path: `${itemPath}.branch_factors`, structural: true });
- if (stale.length) toast("Per-level contact counts of this population were reset because the number of levels changed.", { kind: "info" });
+ return safeTopology(cfg => {
+ const node = nodeView(li, pi);
+ const layer = getPath(cfg, NET).layers[li];
+ const item = getPath(cfg, itemPath);
+ const setting = name => populationSetting(layer, item, name);
+ const factors = update(item.branch_factors ?? node.branch_factors);
+ const levels = factors.length + 1;
+ item.branch_factors = factors;
+ // Counts and time constants in YAML run from distal to soma. Retain
+ // every surviving depth and use the configured defaults on new branches.
+ for (const [key] of STREAMS) {
+ const scalar = key + "_synapses";
+ const field = scalar + "_by_level";
+ const old = setting(field);
+ if (old?.length && old.length !== levels) {
+ (item.population ||= {})[field] = Array.from({ length: levels }, (_, d) => old.at(-1 - d) ?? setting(scalar)).reverse();
+ }
+ }
+ const taus = setting("level_taus");
+ if (taus?.length && taus.length !== levels) {
+ const timing = { level_taus: taus, tau_base: setting("tau_base"), tau_ratio: setting("tau_ratio") };
+ (item.population ||= {}).level_taus = Array.from({ length: levels }, (_, d) => tauAtDepth(timing, d)).reverse();
+ }
+ for (const route of layer.connections || []) {
+ if (route.target !== (item.name ?? node.name) || !route.delay_steps_by_level || route.delay_steps_by_level.length === levels) continue;
+ const delays = route.delay_steps_by_level;
+ route.delay_steps_by_level = Array.from({ length: levels }, (_, depth) => delays.at(-1 - depth) ?? 1).reverse();
+ }
+ });
}
diff --git a/apps/studio/src/dendrinet_studio/web/js/dom.js b/apps/studio/src/dendrinet_studio/web/js/dom.js
index 083df3f0..d69d733a 100644
--- a/apps/studio/src/dendrinet_studio/web/js/dom.js
+++ b/apps/studio/src/dendrinet_studio/web/js/dom.js
@@ -134,7 +134,13 @@ export function download(filename, text, type = "text/plain") {
export async function copyText(text) {
try {
- await navigator.clipboard.writeText(text);
+ if (typeof text !== "string" && typeof ClipboardItem === "function" && navigator.clipboard.write) {
+ // Start the clipboard write during the click, even if serialization is pending.
+ const blob = text.then(value => new Blob([value], { type: "text/plain" }));
+ await navigator.clipboard.write([new ClipboardItem({ "text/plain": blob })]);
+ } else {
+ await navigator.clipboard.writeText(typeof text === "string" ? text : await text);
+ }
return true;
} catch (error) {
return false;
diff --git a/apps/studio/src/dendrinet_studio/web/js/fields.js b/apps/studio/src/dendrinet_studio/web/js/fields.js
index 5b1c08ab..cb829b04 100644
--- a/apps/studio/src/dendrinet_studio/web/js/fields.js
+++ b/apps/studio/src/dendrinet_studio/web/js/fields.js
@@ -95,7 +95,7 @@ export function textInput(value, onCommit, attrs = {}) {
return input;
}
-export function numberInput(value, onCommit, { integer = false, min, max, step, optional = false } = {}) {
+export function numberInput(value, onCommit, { integer = false, min, max, step, optional = false, positive = false } = {}) {
const input = h("input", { type: "number", class: "input num", value: value ?? "", step: step ?? (integer ? 1 : "any"), min, max, inputmode: integer ? "numeric" : "decimal" });
commitOn(
input,
@@ -107,6 +107,7 @@ export function numberInput(value, onCommit, { integer = false, min, max, step,
const v = Number(input.value);
if (!Number.isFinite(v)) throw new Error("Enter a finite number");
if (integer && !Number.isInteger(v)) throw new Error("Enter a whole number");
+ if (positive && v <= 0) throw new Error("Enter a number greater than zero");
if (min !== undefined && v < min) throw new Error(`Enter ${min} or more`);
if (max !== undefined && v > max) throw new Error(`Enter ${max} or less`);
return v;
@@ -129,7 +130,7 @@ export function stepper(value, onCommit, { min = 0, max, label = "" } = {}) {
input,
h("button", { type: "button", "aria-label": `Increase ${label}`, onclick: bump(1) }, [icon("plus")]),
]);
- wrap.id = input.id = nextId("st");
+ input.id = nextId("st");
return wrap;
}
@@ -243,25 +244,22 @@ export function factorEditor(factors, onCommit) {
wrap.append(
h("span", { class: "factor", title: `Level ${index + 1}: each compartment has ${b} children` }, [
h("span", { class: "factor-value", text: b }),
- h("button", { type: "button", "aria-label": `Fewer branches at level ${index + 1}`, onclick: () => {
- const next = [...factors];
+ h("button", { type: "button", "aria-label": `Fewer branches at level ${index + 1}`, onclick: () => onCommit(current => {
+ const next = [...current];
if (next[index] > 1) next[index] -= 1;
else next.splice(index, 1);
- onCommit(next);
- } }, [icon("minus")]),
- h("button", { type: "button", "aria-label": `More branches at level ${index + 1}`, onclick: () => {
- const next = [...factors];
- next[index] += 1;
- onCommit(next);
- } }, [icon("plus")]),
+ return next;
+ }) }, [icon("minus")]),
+ h("button", { type: "button", "aria-label": `More branches at level ${index + 1}`, onclick: () =>
+ onCommit(current => current.map((count, i) => i === index ? count + 1 : count)) }, [icon("plus")]),
])
);
});
- wrap.append(h("button", { type: "button", class: "btn small", onclick: () => onCommit([...factors, 2]) }, [icon("plus"), "level"]));
+ wrap.append(h("button", { type: "button", class: "btn small", onclick: () => onCommit(current => [...current, 2]) }, [icon("plus"), "level"]));
if (!factors.length) wrap.prepend(h("span", { class: "muted", text: "Soma only" }));
const presets = h("div", { class: "presets", role: "group", "aria-label": "Morphology presets" });
for (const preset of MORPHOLOGY_PRESETS) {
- presets.append(h("button", { type: "button", class: "chip mono", "aria-pressed": String(JSON.stringify(preset) === JSON.stringify(factors)), onclick: () => onCommit([...preset]), text: preset.length ? `[${preset.join(",")}]` : "soma only" }));
+ presets.append(h("button", { type: "button", class: "chip mono", "aria-pressed": String(JSON.stringify(preset) === JSON.stringify(factors)), onclick: () => onCommit(() => [...preset]), text: preset.length ? `[${preset.join(",")}]` : "soma only" }));
}
const box = h("div", { class: "factor-editor" }, [wrap, presets]);
box.id = nextId("fe");
@@ -288,8 +286,7 @@ export function humanize(name) {
const capitalize = text => text.charAt(0).toUpperCase() + text.slice(1);
-export function controlFor(spec, value, onCommit) {
- const label = humanize(spec.name);
+export function controlFor(spec, value, onCommit, label = humanize(spec.name)) {
switch (spec.kind) {
case "bool":
return switchInput(value ?? spec.default, onCommit, label);
diff --git a/apps/studio/src/dendrinet_studio/web/js/graph.js b/apps/studio/src/dendrinet_studio/web/js/graph.js
index 2692f396..1cbcdcd2 100644
--- a/apps/studio/src/dendrinet_studio/web/js/graph.js
+++ b/apps/studio/src/dendrinet_studio/web/js/graph.js
@@ -4,15 +4,16 @@
// ones in a bar; delayed connections are dashed and labelled Δt.
import { s, fmt } from "./dom.js";
+import { travelLabel, travelRange } from "./travel.js";
const CARD_W = 204;
-const CARD_H = 92;
-const GAP_Y = 26;
-const LANE_PAD = 26;
-const HEADER = 44;
-const IO_W = 156;
+const CARD_H = 105;
+const GAP_Y = 40;
+const LANE_PAD = 35;
+const HEADER = 92;
+const IO_W = 158;
const IO_H = 90;
-const SUB_GAP = 34;
+const LANE_GAP = 32;
const STREAM_LABEL = { ff_excitatory: "E", ff_inhibitory: "I", rec_excitatory: "rec E", rec_inhibitory: "rec I" };
@@ -45,50 +46,36 @@ function contactSummary(node, connections) {
return [ff.length ? ff.join(" · ") + " per comp." : "no feedforward contacts", rec.length ? rec.join(" · ") + " per comp." : null];
}
-// Layout: input lane, one lane per layer (inhibitory column left of and above
-// the excitatory column, so input reaching the excitatory cells passes below
-// the inhibitory ones and local inhibition points forward), decoder lane.
-const STAGGER = (CARD_H + GAP_Y) / 2;
-
+// One column per layer keeps populations aligned as the network grows. The
+// margins carry local connections. Long skips and feedback use rails below.
export function layoutNetwork(preview) {
- const lanes = [];
+ const lanes = [{ kind: "input", label: "Input", x: 8, width: IO_W }];
const positions = {};
- let x = 16;
- lanes.push({ kind: "input", label: "Input", x, width: IO_W + 2 * LANE_PAD });
- x += IO_W + 2 * LANE_PAD + 18;
- let stackHeight = CARD_H;
+ let x = 8 + IO_W + LANE_GAP;
+ let rows = 1;
preview.layers.forEach((layer, li) => {
const nodes = preview.nodes.filter(n => n.layer === li);
- const inh = nodes.filter(n => n.polarity === "inhibitory");
- const exc = nodes.filter(n => n.polarity !== "inhibitory");
- const columns = [inh, exc].filter(c => c.length);
- const both = columns.length === 2;
- const width = columns.length * CARD_W + (columns.length - 1) * SUB_GAP + 2 * LANE_PAD;
- lanes.push({ kind: "layer", label: layer.name, layer, x, width });
- columns.forEach((column, ci) => {
- const cx = x + LANE_PAD + ci * (CARD_W + SUB_GAP);
- const offset = both ? (ci === 0 ? -STAGGER : STAGGER) : 0;
- column.forEach((node, ri) => {
- positions[node.id] = { x: cx, y: 0, row: ri, count: column.length, offset };
- });
- const columnHeight = column.length * CARD_H + (column.length - 1) * GAP_Y;
- stackHeight = Math.max(stackHeight, columnHeight + (both ? 2 * STAGGER : 0));
+ const ordered = [...nodes.filter(n => n.name === layer.readout), ...nodes.filter(n => n.name !== layer.readout)];
+ rows = Math.max(rows, nodes.length);
+ ordered.forEach((node, row) => {
+ positions[node.id] = { x: x + LANE_PAD, y: HEADER + row * (CARD_H + GAP_Y), layer: li };
});
- x += width + 18;
+ lanes.push({ kind: "layer", label: layer.name, layer, x, width: CARD_W + 2 * LANE_PAD });
+ x += CARD_W + 2 * LANE_PAD + LANE_GAP;
});
- lanes.push({ kind: "output", label: "Readout", x, width: IO_W + 2 * LANE_PAD });
- const width = x + IO_W + 2 * LANE_PAD + 16;
- const height = Math.max(300, HEADER + 30 + stackHeight + 60);
- const top = HEADER + 20 + (height - HEADER - 50 - stackHeight) / 2;
- const mid = top + stackHeight / 2;
- for (const node of preview.nodes) {
- const p = positions[node.id];
- const columnHeight = p.count * CARD_H + (p.count - 1) * GAP_Y;
- p.y = mid - columnHeight / 2 + p.offset + p.row * (CARD_H + GAP_Y);
+ lanes.push({ kind: "output", label: "Decoder", x, width: IO_W });
+ const railTop = HEADER + rows * CARD_H + (rows - 1) * GAP_Y + 28;
+ const rails = new Map();
+ for (const edge of preview.edges) {
+ const src = positions[edge.source_id];
+ const dst = positions[edge.target_id];
+ if (src && (src.layer > dst.layer || dst.layer - src.layer > 1)) rails.set(edge, railTop + rails.size * 16);
}
- positions.__input = { x: lanes[0].x + LANE_PAD, y: mid - IO_H / 2 };
- positions.__output = { x: lanes.at(-1).x + LANE_PAD, y: mid - IO_H / 2 };
- return { lanes, positions, width, height };
+ const ioY = HEADER + (CARD_H - IO_H) / 2;
+ positions.__input = { x: 8, y: ioY };
+ positions.__output = { x, y: ioY };
+ const readoutRail = preview.layers.slice(0, -1).some(l => l.is_readout_layer) ? railTop + rails.size * 16 : null;
+ return { lanes, positions, rails, railTop, readoutRail, width: x + IO_W + 8, height: railTop + (rails.size + Number(readoutRail !== null)) * 16 + 12 };
}
// A number belongs on an edge only when it is the sole supplier of the stream.
@@ -103,7 +90,7 @@ function edgeCountLabel(preview, edge, connections) {
export function drawNetwork(svg, preview, { selection, onSelectPopulation, onSelectConnection, onSelectLayer, showCounts = true, zoom = 1 }) {
svg.replaceChildren();
- const { lanes, positions, width, height } = layoutNetwork(preview);
+ const { lanes, positions, width, height, rails, railTop, readoutRail } = layoutNetwork(preview);
svg.setAttribute("viewBox", `0 0 ${width} ${height}`);
svg.setAttribute("width", Math.round(width * zoom));
svg.setAttribute("height", Math.round(height * zoom));
@@ -118,14 +105,14 @@ export function drawNetwork(svg, preview, { selection, onSelectPopulation, onSel
// Lanes.
for (const lane of lanes) {
const g = s("g", { class: "lane" + (lane.kind === "layer" ? " layer-lane" : "") });
- g.append(s("rect", { x: lane.x, y: 8, width: lane.width, height: height - 16, rx: 10, class: "lane-bg" }));
- const label = s("text", { x: lane.x + 14, y: 32, class: "lane-label" }, [lane.label]);
+ if (lane.kind === "layer") g.append(s("rect", { x: lane.x, y: 8, width: lane.width, height: railTop - 18, rx: 12, class: "lane-bg" }));
+ const label = s("text", { x: lane.x + 14, y: 32, class: "lane-label" }, [lane.label.length > 29 ? lane.label.slice(0, 27) + "…" : lane.label]);
+ g.append(s("title", {}, [lane.label]));
g.append(label);
if (lane.kind === "layer") {
- const extras = [];
- if (lane.layer.recurrent) extras.push(`recurrent · dt ${lane.layer.dt}`);
- if (lane.layer.is_readout_layer) extras.push("readout layer");
- if (extras.length) g.append(s("text", { x: lane.x + lane.width - 14, y: 32, class: "lane-meta", "text-anchor": "end" }, [extras.join(" · ")]));
+ const mode = lane.layer.recurrent ? "Recurrent · dt " + lane.layer.dt
+ : lane.layer.steps_through_time ? "Stateful · dt " + lane.layer.dt : "Feedforward";
+ g.append(s("text", { x: lane.x + 14, y: 50, class: "lane-meta" }, [mode + (lane.layer.is_readout_layer ? " · readout" : "")]));
const index = preview.layers.indexOf(lane.layer);
g.classList.add("clickable");
g.addEventListener("click", event => {
@@ -152,6 +139,11 @@ export function drawNetwork(svg, preview, { selection, onSelectPopulation, onSel
const edgeLayer = s("g", { class: "edges" });
const chipLayer = s("g", { class: "edge-chips" });
svg.append(edgeLayer);
+ const occupied = Object.entries(positions).map(([id, p]) =>
+ ({ x: p.x, y: p.y, w: id.startsWith("__") ? IO_W : CARD_W, h: id.startsWith("__") ? IO_H : CARD_H }));
+ for (const lane of lanes) occupied.push({ x: lane.x, y: 12, w: lane.width, h: 41 });
+ const labelTasks = [];
+ const nodesById = new Map(preview.nodes.map(node => [node.id, node]));
preview.edges.forEach((edge, index) => {
const external = !positions[edge.source_id];
const src = external ? positions.__input : positions[edge.source_id];
@@ -163,23 +155,28 @@ export function drawNetwork(svg, preview, { selection, onSelectPopulation, onSel
const ty = portY[index];
let d;
if (edge.source_id === edge.target_id) {
- const left = dst.x + 30;
- const right = dst.x + CARD_W - 30;
- d = `M${right} ${dst.y} C ${right} ${dst.y - 44}, ${left} ${dst.y - 44}, ${left} ${dst.y - 2}`;
- } else if (tx > sx + 20) {
- const bend = Math.max(40, (tx - sx) / 2);
- d = `M${sx} ${sy} C ${sx + bend} ${sy}, ${tx - bend} ${ty}, ${tx} ${ty}`;
+ const start = dst.x + CARD_W * 0.72, end = dst.x + CARD_W * 0.28;
+ d = `M${start} ${dst.y} C ${start} ${dst.y - 36}, ${end} ${dst.y - 36}, ${end} ${dst.y - 3}`;
+ } else if (!external && src.layer === dst.layer) {
+ const side = inhibitory ? 1 : -1;
+ const boundary = inhibitory ? dst.x + CARD_W : dst.x;
+ const toY = dst.y + (inhibitory ? 66 : 34);
+ const channel = boundary + side * (14 + (index % 3) * 6);
+ d = `M${boundary} ${sy} Q ${channel} ${sy}, ${channel} ${sy + Math.sign(toY - sy) * 12} V${toY - Math.sign(toY - sy) * 12} Q ${channel} ${toY}, ${boundary + side * 3} ${toY}`;
+ } else if (rails.has(edge)) {
+ const rail = rails.get(edge), a = sx + 16, b = tx - 16;
+ d = `M${sx} ${sy} H${a} V${rail} H${b} V${ty} H${tx}`;
} else {
- const over = Math.min(src.y, dst.y) - 26;
- d = `M${sx} ${sy} C ${sx + 60} ${sy}, ${sx + 60} ${over}, ${(sx + tx) / 2} ${over} S ${tx - 60} ${ty}, ${tx} ${ty}`;
+ const bend = Math.max(12, (tx - sx) / 2);
+ d = `M${sx} ${sy} C ${sx + bend} ${sy}, ${tx - bend} ${ty}, ${tx} ${ty}`;
}
const classes = ["edge", inhibitory ? "inh" : "exc"];
if (edge.timing === "delayed") classes.push("delayed");
if (edge.enabled === false) classes.push("disabled");
const selected = selection.kind === "connection" && selection.layer === edge.layer && selection.index === layerIndex(preview, edge, index);
if (selected) classes.push("selected");
- const path = s("path", { d, class: classes.join(" "), "data-source": edge.source_id, "data-target": edge.target_id, "data-pathway": edge.pathway, "marker-end": edge.source_id === edge.target_id ? undefined : inhibitory ? "url(#m-inh)" : "url(#m-exc)" });
- const hit = s("path", { d, class: "edge-hit", tabindex: 0, role: "button", "aria-label": `Connection ${edge.source_id} to ${edge.target_id}` });
+ const path = s("path", { d, class: classes.join(" "), "data-source": edge.source_id, "data-target": edge.target_id, "data-pathway": edge.pathway, "data-timing": edge.timing, "marker-end": inhibitory ? "url(#m-inh)" : "url(#m-exc)" });
+ const hit = s("path", { d, class: "edge-hit", tabindex: 0, role: "button", "aria-label": `Connection ${edge.source_id} to ${edge.target_id}, ${edge.pathway}, ${edge.timing}` });
const pick = () => onSelectConnection(edge.layer, layerIndex(preview, edge, index));
hit.addEventListener("click", pick);
hit.addEventListener("keydown", e => {
@@ -188,26 +185,44 @@ export function drawNetwork(svg, preview, { selection, onSelectPopulation, onSel
pick();
}
});
- hit.append(s("title", {}, [`${edge.source_id} → ${edge.target_id} · ${edge.pathway.replace("_", " ")} · ${edge.timing === "delayed" ? "delayed" : "same step"}${edge.target_levels ? " · levels " + edge.target_levels.join(", ") : ""}${edge.probability != null ? " · p " + edge.probability : ""}${edge.enabled === false ? " · off" : ""}`]));
+ const countLabel = edgeCountLabel(preview, edge, incoming[edge.target_id]);
+ const travel = edge.timing === "delayed" ? travelRange(edge, nodesById.get(edge.target_id)) : null;
+ const timeLabel = travel ? `${travel} ${travel === "1" ? "step" : "steps"} of travel` : edge.timing === "delayed" ? "delayed" : "same step";
+ hit.append(s("title", {}, [`${edge.source_id} → ${edge.target_id} · ${countLabel} · ${timeLabel}${edge.target_levels ? " · levels " + edge.target_levels.join(", ") : ""}${edge.probability != null ? " · p " + edge.probability : ""}${edge.enabled === false ? " · off" : ""}`]));
edgeLayer.append(path, hit);
// Chip at the middle of the curve.
const labels = [];
- if (edge.timing === "delayed") labels.push("Δt");
+ if (travel) labels.push(travelLabel(travel));
if (edge.enabled === false) labels.push("off");
if (edge.target_levels) labels.push("→ " + edge.target_levels.join(","));
if (edge.probability != null) labels.push("p " + edge.probability);
if (showCounts || labels.length) {
- requestAnimationFrame(() => {
- if (!path.isConnected) return;
+ labelTasks.push({ selected, place: () => {
const length = path.getTotalLength();
- const point = path.getPointAtLength(length * 0.5);
- const text = [showCounts ? edgeCountLabel(preview, edge, incoming[edge.target_id]) : null, ...labels].filter(Boolean).join(" · ");
+ const text = [showCounts ? countLabel : null, ...labels].filter(Boolean).join(" · ");
const w = text.length * 6.2 + 14;
+ let point;
+ for (const offset of [0, -17, 17]) {
+ for (const fraction of [0.5, 0.32, 0.68, 0.2, 0.8]) {
+ const anchor = path.getPointAtLength(length * fraction);
+ const box = { x: anchor.x - w / 2, y: anchor.y + offset - 9, w, h: 18 };
+ if (box.x < 0 || box.y < 0 || box.x + w > width || box.y + 18 > height) continue;
+ if (occupied.some(p => box.x < p.x + p.w + 2 && box.x + w + 2 > p.x && box.y < p.y + p.h + 2 && box.y + 20 > p.y)) continue;
+ occupied.push(box);
+ point = { x: anchor.x, y: anchor.y + offset };
+ if (offset) chipLayer.append(s("path", { d: `M${anchor.x} ${anchor.y} V${point.y}`, class: "edge-chip-guide" }));
+ break;
+ }
+ if (point) break;
+ }
+ // Crowded diagrams retain every route in the outline and its full
+ // description on the line. Keep other labels and cards legible.
+ if (!point) return;
const chip = s("g", { class: "chip-edge " + (inhibitory ? "inh" : "exc") + (selected ? " selected" : "") });
chip.append(s("rect", { x: point.x - w / 2, y: point.y - 9, width: w, height: 18, rx: 9 }), s("text", { x: point.x, y: point.y + 4, "text-anchor": "middle" }, [text]));
chip.addEventListener("click", pick);
chipLayer.append(chip);
- });
+ } });
}
});
@@ -232,7 +247,9 @@ export function drawNetwork(svg, preview, { selection, onSelectPopulation, onSel
const sy = p.y + CARD_H / 2;
const tx = o.x - 2;
const ty = o.y + IO_H / 2;
- edgeLayer.append(s("path", { d: `M${sx} ${sy} C ${sx + 50} ${sy}, ${tx - 50} ${ty}, ${tx} ${ty}`, class: "edge readout", "marker-end": "url(#m-exc)" }));
+ const d = readoutRail === null ? `M${sx} ${sy} C ${sx + 50} ${sy}, ${tx - 50} ${ty}, ${tx} ${ty}`
+ : `M${sx} ${sy} H${sx + 24} V${readoutRail} H${tx - 12} V${ty} H${tx}`;
+ edgeLayer.append(s("path", { d, class: "edge readout", "marker-end": "url(#m-exc)" }));
}
// Population cards.
@@ -243,11 +260,14 @@ export function drawNetwork(svg, preview, { selection, onSelectPopulation, onSel
g.append(s("rect", { width: CARD_W, height: CARD_H, rx: 10, class: "card-bg" }));
if (node.polarity === "inhibitory") g.append(s("circle", { cx: 20, cy: 21, r: 6.5, class: "card-glyph" }));
else g.append(s("path", { d: "M20 13.5L27 27H13Z", class: "card-glyph" }));
- g.append(s("text", { x: 36, y: 26, class: "card-title" }, [node.name]));
+ g.append(s("title", {}, [node.id + " · " + ruleOf(node)[0]]));
const [rule, cls] = ruleOf(node);
- const tw = rule.length * 6.1 + 14;
+ const shortRule = rule.startsWith("Additive (") ? "Additive*" : rule;
+ const tw = shortRule.length * 6.1 + 14;
+ const maxName = Math.floor((CARD_W - tw - 52) / 8);
+ g.append(s("text", { x: 36, y: 26, class: "card-title" }, [node.name.length > maxName ? node.name.slice(0, maxName - 1) + "…" : node.name]));
g.append(s("rect", { x: CARD_W - 10 - tw, y: 12, width: tw, height: 18, rx: 4, class: "rule-tag " + cls }));
- g.append(s("text", { x: CARD_W - 10 - tw / 2, y: 25, "text-anchor": "middle", class: "rule-text " + cls }, [rule]));
+ g.append(s("text", { x: CARD_W - 10 - tw / 2, y: 25, "text-anchor": "middle", class: "rule-text " + cls }, [shortRule]));
g.append(s("text", { x: 14, y: 50, class: "card-line" }, [`${node.polarity === "inhibitory" ? "I" : "E"} · ${fmt(node.neurons)} neurons · ${node.branch_factors.length ? "[" + node.branch_factors.join(", ") + "]" : "soma only"}`]));
const [ff, rec] = contactSummary(node, incoming[node.id] || []);
g.append(s("text", { x: 14, y: 68, class: "card-line mono" }, [ff]));
@@ -263,7 +283,12 @@ export function drawNetwork(svg, preview, { selection, onSelectPopulation, onSel
});
svg.append(g);
}
- svg.append(chipLayer);
+ svg.insertBefore(chipLayer, svg.querySelector(".io-card"));
+ requestAnimationFrame(() => {
+ if (edgeLayer.isConnected) {
+ labelTasks.sort((a, b) => Number(b.selected) - Number(a.selected)).forEach(task => task.place());
+ }
+ });
return { width, height };
}
@@ -330,7 +355,7 @@ export function drawOverview(svg, preview) {
export function svgForExport(svg) {
const clone = svg.cloneNode(true);
const css = getComputedStyle(document.documentElement);
- const tokens = ["--ink", "--muted", "--line", "--line-strong", "--panel", "--sunk", "--exc", "--inh", "--shunt", "--add", "--edge"];
+ const tokens = ["--ink", "--muted", "--line", "--line-strong", "--panel", "--sunk", "--exc", "--inh", "--shunt", "--add", "--edge", "--shunt-ink", "--add-ink", "--edge-exc", "--inh-mark", "--ink-soft", "--mono", "--focus"];
const vars = tokens.map(t => `${t}: ${css.getPropertyValue(t).trim()};`).join(" ");
const sheet = [...document.styleSheets].flatMap(sheet => {
try {
diff --git a/apps/studio/src/dendrinet_studio/web/js/morphology.js b/apps/studio/src/dendrinet_studio/web/js/morphology.js
index a2f9095f..6fc24091 100644
--- a/apps/studio/src/dendrinet_studio/web/js/morphology.js
+++ b/apps/studio/src/dendrinet_studio/web/js/morphology.js
@@ -13,7 +13,12 @@ const BOTTOM = H - 40;
const MAX_SHOWN = 6;
const MAX_DRAWN_COMPARTMENTS = 160;
const MAX_DRAWN_LEVELS = 10;
-const LEVEL_NAMES = (depth, deepest) => (depth === 0 ? "soma" : depth === deepest ? `${depth} · distal` : depth === 1 ? "1 · primary" : String(depth));
+export const levelName = (depth, deepest) => (depth === 0 ? "soma" : depth === deepest ? `${depth} · distal` : depth === 1 ? "1 · primary" : String(depth));
+
+export function targetDepths(levels, count) {
+ const names = { soma: 0, primary: 1, distal: count - 1 };
+ return levels?.map(depth => names[depth] ?? depth);
+}
// JavaScript numbers can round the level sizes of a large imported tree.
export function compartmentLevels(factors) {
@@ -43,7 +48,7 @@ export function drawNeuron(svg, { polarity = "excitatory", factors = [], levels
for (let depth = 0; depth <= shown.length; depth++) {
const y = depth === 0 ? somaY : yOf(depth);
const active = highlight && highlight.includes(depth);
- svg.append(s("text", { x: 8, y: y + 4, class: "level-name" + (active ? " active" : "") }, [LEVEL_NAMES(depth, depthCount)]));
+ svg.append(s("text", { x: 8, y: y + 4, class: "level-name" + (active ? " active" : "") }, [levelName(depth, depthCount)]));
if (depth > 0) svg.append(s("line", { x1: 62, x2: W - 10, y1: y, y2: y, class: "level-guide" + (active ? " active" : "") }));
if (depth > 0 && shown[depth - 1] < factors[depth - 1]) {
svg.append(s("text", { x: W - 12, y: y + 12, "text-anchor": "end", class: "more" }, [`${shown[depth - 1]} of ${fmt(factors[depth - 1])} children per parent`]));
@@ -218,7 +223,7 @@ export function levelTable({ levels, counts, neurons }) {
const deepest = levels.length - 1;
const totals = Object.fromEntries(streams.map(([k]) => [k, 0n]));
for (let depth = deepest; depth >= 0; depth--) {
- const row = h("tr", {}, [h("td", { text: LEVEL_NAMES(depth, deepest) }), h("td", { text: fmt(levels[depth]) })]);
+ const row = h("tr", {}, [h("td", { text: levelName(depth, deepest) }), h("td", { text: fmt(levels[depth]) })]);
for (const [key] of streams) {
const v = (counts[key] || [])[depth] || 0;
totals[key] += BigInt(v) * levels[depth];
diff --git a/apps/studio/src/dendrinet_studio/web/js/store.js b/apps/studio/src/dendrinet_studio/web/js/store.js
index 5f8fa521..9bfac2b8 100644
--- a/apps/studio/src/dendrinet_studio/web/js/store.js
+++ b/apps/studio/src/dendrinet_studio/web/js/store.js
@@ -8,7 +8,9 @@
// The launcher puts the session token in the address fragment (#token&view=...).
const token = location.hash.slice(1).split("&")[0];
const listeners = new Map();
-const DRAFT_KEY = "dendrinet-studio-draft-v1";
+// A host can serve several personal Studios, each under its own URL prefix.
+const basePath = new URL(".", location.href).pathname;
+const DRAFT_KEY = "dendrinet-studio-draft-v1" + (basePath === "/" ? "" : ":" + basePath);
const HISTORY_LIMIT = 100;
export const state = {
@@ -46,11 +48,12 @@ export function emit(event, detail) {
}
}
-export async function api(path, data) {
+export async function api(path, data, signal) {
const response = await fetch("api/" + path, {
method: data === undefined ? "GET" : "POST",
headers: { "X-Studio-Token": token, "Content-Type": "application/json" },
body: data === undefined ? undefined : JSON.stringify(data),
+ signal,
});
let result;
try {
@@ -96,11 +99,11 @@ export function valueAt(path) {
export const isPopulationNetwork = () => state.config?.model?.core?.type === "population_network";
export function network() {
- return state.config.model.core.population_network;
+ return state.config?.model?.core?.population_network;
}
export function layers() {
- return network().layers;
+ return network()?.layers || [];
}
export function nodeView(layer, population) {
@@ -114,6 +117,100 @@ export function layerView(layer) {
// Editing -------------------------------------------------------------------
export let validationRevision = 0;
+let documentGeneration = 0;
+let topologyQueue = Promise.resolve();
+const pendingTopology = new Set();
+let validatedDraft = Promise.resolve();
+let finishValidation;
+
+function validationFinished() {
+ state.validating = false;
+ finishValidation?.();
+ finishValidation = undefined;
+}
+
+// Return synchronously when idle so Copy can use the browser's click gesture.
+export function waitForTopologyEdits() {
+ if (pendingTopology.size) return Promise.all(pendingTopology);
+}
+
+async function settleEdits() {
+ do {
+ await waitForTopologyEdits();
+ while (state.validating) await validatedDraft;
+ } while (pendingTopology.size);
+}
+
+export async function modelReady() {
+ await settleEdits();
+ if (state.error) throw new Error(state.error);
+}
+
+// Dialogs take their snapshot after earlier edits have reached the preview.
+export async function topologyReady({ allowRepair = false } = {}) {
+ const generation = documentGeneration;
+ await settleEdits();
+ if (generation !== documentGeneration) throw new Error("The design changed. Select the item and try again.");
+ if (!allowRepair && state.error) throw new Error(state.error);
+}
+
+// Stage a topology edit on a copy. A rejected route must never become the
+// document used by Train, by the YAML editor, or by draft recovery.
+export function editTopology(mutate, { revision, signal, reindexes = false } = {}) {
+ const generation = documentGeneration;
+ const pending = topologyQueue.then(async () => {
+ while (!signal?.aborted) {
+ while (state.validating) await validatedDraft;
+ if (signal?.aborted) return;
+ if (generation !== documentGeneration || (revision !== undefined && revision !== validationRevision)) {
+ throw new Error(revision === undefined ? "The design changed. Select the item and make the edit again." : "The design changed. Reopen this editor.");
+ }
+ // Bind confirmations to what the user saw. A matching revision may
+ // contain the very error the proposed edit will repair.
+ const base = validationRevision;
+ const draft = structuredClone(state.config);
+ const selection = mutate(draft);
+ const before = JSON.stringify(state.config);
+ if (JSON.stringify(draft) === before) {
+ if (selection) select(selection);
+ return;
+ }
+ let result;
+ try {
+ result = await api("preview", { config: draft }, signal);
+ } catch (error) {
+ if (signal?.aborted) return;
+ if (base !== validationRevision) continue;
+ throw error;
+ }
+ if (signal?.aborted) return;
+ // A field can also change while this request is in flight. Rebuild ordinary
+ // edits on the current draft. A dialog stays bound to the revision it showed.
+ if (base !== validationRevision) continue;
+ ++validationRevision;
+ if (reindexes) ++documentGeneration;
+ state.history.push(before);
+ if (state.history.length > HISTORY_LIMIT) state.history.shift();
+ state.future = [];
+ state.config = draft;
+ state.preview = result;
+ state.error = state.errorPath = null;
+ state.dirty = true;
+ if (selection) state.selection = selection;
+ fixSelection();
+ saveDraft();
+ emit("edited", { structural: true });
+ emit("preview", { structural: true });
+ emit("validated");
+ return;
+ }
+ });
+ // Waiting actions receive the rejection. A later edit can still be tried.
+ pendingTopology.add(pending);
+ const settled = () => { pendingTopology.delete(pending); };
+ topologyQueue = pending.then(settled, settled);
+ return pending;
+}
export function edit(mutate, options = {}) {
const before = JSON.stringify(state.config);
@@ -132,6 +229,7 @@ export function edit(mutate, options = {}) {
export function undo() {
if (!state.history.length) return;
+ ++documentGeneration;
state.future.push(JSON.stringify(state.config));
state.config = JSON.parse(state.history.pop());
state.dirty = true;
@@ -142,6 +240,7 @@ export function undo() {
export function redo() {
if (!state.future.length) return;
+ ++documentGeneration;
state.history.push(JSON.stringify(state.config));
state.config = JSON.parse(state.future.pop());
state.dirty = true;
@@ -152,6 +251,7 @@ export function redo() {
export async function validate(options = {}) {
const revision = ++validationRevision;
+ if (!state.validating) validatedDraft = new Promise(resolve => { finishValidation = resolve; });
state.validating = true;
emit("validating");
try {
@@ -170,7 +270,7 @@ export async function validate(options = {}) {
return false;
} finally {
if (revision === validationRevision) {
- state.validating = false;
+ validationFinished();
emit("validated");
}
}
@@ -186,7 +286,8 @@ export function adopt(result, name, { keepHistory = false, dirty = keepHistory }
state.future = [];
}
++validationRevision;
- state.validating = false;
+ ++documentGeneration;
+ validationFinished();
state.config = structuredClone(result.config);
state.preview = result;
state.error = null;
diff --git a/apps/studio/src/dendrinet_studio/web/js/travel.js b/apps/studio/src/dendrinet_studio/web/js/travel.js
new file mode 100644
index 00000000..3ab076f2
--- /dev/null
+++ b/apps/studio/src/dendrinet_studio/web/js/travel.js
@@ -0,0 +1,72 @@
+import { h } from "./dom.js";
+import { field, selectInput } from "./fields.js";
+import { levelName } from "./morphology.js";
+
+// The dialog presents depths from the soma outward. Only the YAML list is reversed.
+export function travelEditor(original) {
+ const number = value => h("input", { class: "input num", type: "number", min: 1, step: 1, value, required: true });
+ const uniform = number(original?.delay_steps || 1);
+ const individual = [];
+ const mode = selectInput(original?.delay_steps_by_level ? "levels" : "uniform", ["uniform", "levels"], render,
+ { allowCustom: false, labels: { uniform: "Same delay at every depth", levels: "Set delay by depth" } });
+ const uniformField = field({ label: "Travel delay (steps)", control: uniform });
+ const levels = h("div", { class: "form-grid cols-2" });
+ const element = h("fieldset", { class: "travel-controls" }, [
+ field({ label: "Travel delay", control: mode }),
+ uniformField, levels,
+ h("p", { class: "help", text: "A signal emitted on update 0 arrives on update N at a contacted depth with N steps of travel." }),
+ ]);
+ let target;
+ function render() {
+ const custom = mode.value === "levels";
+ uniform.disabled = uniformField.hidden = custom;
+ levels.hidden = !custom;
+ levels.replaceChildren();
+ if (!target || !custom) return;
+ const deepest = target.branch_factors.length;
+ for (let d = 0; d <= deepest; d++) {
+ individual[d] ||= number(original?.delay_steps_by_level?.at(-1 - d) ?? (uniform.valueAsNumber || 1));
+ levels.append(field({ label: "Travel steps at " + levelName(d, deepest), control: individual[d] }));
+ }
+ }
+ function steps(input) {
+ const n = input.valueAsNumber;
+ if (!Number.isSafeInteger(n) || n < 1) throw new Error("Travel delays must be positive whole numbers of updates.");
+ return n;
+ }
+ return {
+ element,
+ show(receiver, delayed) {
+ target = receiver;
+ element.disabled = element.hidden = !delayed || !target;
+ render();
+ },
+ save(route) {
+ if (element.disabled) {
+ if (route.delay_steps !== 0) delete route.delay_steps;
+ delete route.delay_steps_by_level;
+ } else if (mode.value === "levels") {
+ route.delay_steps_by_level = individual.slice(0, target.branch_factors.length + 1).map(steps).reverse();
+ delete route.delay_steps;
+ } else {
+ const value = steps(uniform);
+ if (value !== 1 || original?.delay_steps != null) route.delay_steps = value;
+ else delete route.delay_steps;
+ delete route.delay_steps_by_level;
+ }
+ },
+ };
+}
+
+export function travelRange(edge, target) {
+ if (edge.enabled === false || edge.probability === 0) return null;
+ const delays = edge.arrival_steps.filter((_, depth) =>
+ (edge.target_depths == null || edge.target_depths.includes(depth)) && target.received_per_level[edge.pathway][depth]);
+ if (!delays.length) return null;
+ const min = Math.min(...delays), max = Math.max(...delays);
+ return min === max ? String(min) : `${min}–${max}`;
+}
+
+export function travelLabel(range) {
+ return range === "1" ? "Δt" : range + " Δt";
+}
diff --git a/apps/studio/src/dendrinet_studio/web/js/ui.js b/apps/studio/src/dendrinet_studio/web/js/ui.js
index 6f8d2bb1..08046505 100644
--- a/apps/studio/src/dendrinet_studio/web/js/ui.js
+++ b/apps/studio/src/dendrinet_studio/web/js/ui.js
@@ -24,18 +24,47 @@ export function toast(text, { kind = "info", action = null, timeout = 5000 } = {
return item;
}
-export function dialog({ title, body, actions = [{ label: "Close", value: null, primary: true }], wide = false }) {
+export function dialog({ title, body, actions = [{ label: "Close", value: null, primary: true }], wide = false, onConfirm }) {
return new Promise(resolve => {
const box = h("dialog", { class: "dialog" + (wide ? " wide" : ""), "aria-label": title });
+ const controller = onConfirm ? new AbortController() : null;
const form = h("form", { method: "dialog" });
const footer = h("div", { class: "dialog-actions" });
for (const [index, action] of actions.entries()) {
const value = String(index);
const button = h("button", { type: action.submit === false ? "button" : "submit", class: "btn" + (action.primary ? " primary" : ""), value, text: action.label });
- if (action.submit === false) button.addEventListener("click", () => box.close(value));
+ if (action.submit === false) button.addEventListener("click", () => {
+ controller?.abort();
+ box.close(value);
+ });
footer.append(button);
}
form.append(h("h2", { text: title }), h("div", { class: "dialog-body" }, [].concat(body)), footer);
+ if (onConfirm) {
+ const message = h("p", { class: "field-error", role: "alert", hidden: true });
+ footer.before(message);
+ box.addEventListener("cancel", () => controller.abort(), { once: true });
+ box.addEventListener("close", () => controller.abort(), { once: true });
+ form.addEventListener("submit", async event => {
+ event.preventDefault();
+ const button = event.submitter;
+ if (!button || button.disabled) return;
+ button.disabled = true;
+ const body = form.querySelector(".dialog-body");
+ body.inert = true;
+ message.hidden = true;
+ try {
+ await onConfirm(controller.signal);
+ if (box.open) box.close(button.value);
+ } catch (error) {
+ message.textContent = error.message;
+ message.hidden = false;
+ } finally {
+ body.inert = false;
+ button.disabled = false;
+ }
+ });
+ }
box.append(form);
document.body.append(box);
box.addEventListener("close", () => {
diff --git a/apps/studio/src/dendrinet_studio/web/js/wiring.js b/apps/studio/src/dendrinet_studio/web/js/wiring.js
new file mode 100644
index 00000000..9191d930
--- /dev/null
+++ b/apps/studio/src/dendrinet_studio/web/js/wiring.js
@@ -0,0 +1,174 @@
+// A route belongs to its receiving layer. Edit the endpoints and the timing
+// together so the core validates one complete proposal.
+import { h } from "./dom.js";
+import { field } from "./fields.js";
+import { afferentMode } from "./afferents.js";
+import { state, api, editTopology, validationRevision } from "./store.js";
+import { dialog } from "./ui.js";
+import { travelEditor } from "./travel.js";
+import { targetDepths } from "./morphology.js";
+
+const option = (value, label) => h("option", { value, text: label });
+const selectBox = () => h("select", { class: "input" });
+const externalNames = ["input", "input_e", "input_i"];
+
+export async function connectionEditor(li, { index, from, to } = {}) {
+ const revision = validationRevision;
+ // A source can repair uncovered contacts. Derive its endpoints and budgets
+ // from this draft, then submit the proposed connection to full validation.
+ const view = state.error ? await api("wiring", { config: state.config }) : state.preview;
+ if (revision !== validationRevision || !view.layers[li]) throw new Error("The design changed. Reopen the connection editor.");
+ const original = view.edges.filter(e => e.layer === li)[index];
+ if (index !== undefined && !original) throw new Error("The connection changed. Select it again.");
+ const initialTarget = original?.target_id || to || (from ? "" : (state.selection.kind === "population" && state.selection.layer === li
+ ? view.nodes.find(n => n.layer === li && n.population === state.selection.population)?.id
+ : view.layers[li].name + "." + view.layers[li].readout));
+ const targets = selectBox();
+ targets.append(option("", "Choose a receiving population"));
+ for (const layer of view.layers) {
+ const group = h("optgroup", { label: layer.name });
+ for (const n of view.nodes.filter(n => n.layer_name === layer.name)) group.append(option(n.id, n.id + " · " + n.polarity));
+ targets.append(group);
+ }
+ targets.value = initialTarget || "";
+ const timing = selectBox();
+ timing.append(option("same_step", "Same step · feedforward"), option("delayed", "Delayed · recurrent"));
+ const start = view.nodes.find(n => n.id === from);
+ const end = view.nodes.find(n => n.id === to);
+ const needsDelay = start && end && (start.layer > end.layer || start.id === end.id);
+ timing.value = original?.timing || (needsDelay ? "delayed" : "same_step");
+ const sources = selectBox();
+ const travel = travelEditor(original);
+ const sign = selectBox();
+ const afferents = selectBox();
+ afferents.append(option("", "Choose input organization"), option("paired", "Distinct E and I afferents with matched features"), option("split", "Separate groups of input channels"));
+ const afferentField = field({ label: "External afferents for both signs", control: afferents,
+ help: "This biological network needs separate sources for excitatory and inhibitory input. This setting applies to the first layer." });
+ const summary = h("p", { class: "route-summary", role: "status" });
+ const contacts = h("input", { type: "number", class: "input", min: 1, step: 1, value: 1 });
+ const budgetField = field({ label: "Contacts per eligible compartment", control: contacts,
+ help: "The target currently has zero contacts on this pathway. This budget is shared by its sources." });
+ let selection = original ? (externalNames.includes(original.source) ? original.source : original.source_id) : from || "";
+ let explicitSign = original && state.config.model.core.population_network.layers[li].connections[index].pathway
+ ? original.pathway.split("_")[1] : "";
+ let target, pathway, delayed, eligible;
+ function refreshSources() {
+ target = view.nodes.find(n => n.id === targets.value);
+ delayed = timing.value === "delayed";
+ travel.show(target, delayed);
+ sources.replaceChildren(option("", "Choose a source"));
+ if (target && !delayed) {
+ const external = h("optgroup", { label: target.layer ? "Layer input" : "External input" });
+ if (target.layer) {
+ const prev = view.layers[target.layer - 1];
+ external.append(option("input", "Previous readout · " + prev.name + "." + prev.readout));
+ } else {
+ external.append(option("input", "Input features"), option("input_e", "Excitatory afferents"), option("input_i", "Inhibitory afferents"));
+ }
+ sources.append(external);
+ }
+ for (const [i, layer] of view.layers.entries()) {
+ if (target && !delayed && i > target.layer) continue;
+ const candidates = view.nodes.filter(n => n.layer === i && (delayed || n.id !== target?.id));
+ if (candidates.length) sources.append(h("optgroup", { label: layer.name },
+ candidates.map(n => option(n.id, n.id + " · " + n.polarity))));
+ }
+ sources.value = [...sources.options].some(o => o.value === selection) ? selection : "";
+ selection = sources.value;
+ updatePathway();
+ }
+ function updatePathway() {
+ const n = view.nodes.find(n => n.id === sources.value);
+ const previous = target?.layer > 0 ? view.layers[target.layer - 1] : null;
+ const inputPolarity = previous && sources.value === "input"
+ ? view.nodes.find(p => p.layer_name === previous.name && p.name === previous.readout)?.polarity : null;
+ const natural = n?.polarity || inputPolarity || (sources.value === "input_i" ? "inhibitory" : "excitatory");
+ sign.replaceChildren(option("", sources.value ? "Automatic · " + natural : "Automatic · source polarity"));
+ for (const polarity of ["excitatory", "inhibitory"]) {
+ if (!view.biological_neuron || polarity === natural || explicitSign === polarity)
+ sign.append(option(polarity, "Explicit · " + polarity));
+ }
+ sign.value = explicitSign;
+ pathway = (delayed ? "rec_" : "ff_") + (sign.value || natural);
+ const addingExternal = target?.layer === 0 && externalNames.includes(sources.value) && original?.enabled !== false;
+ const otherSign = natural === "inhibitory" ? "ff_excitatory" : "ff_inhibitory";
+ const needsAfferents = addingExternal && view.biological_neuron &&
+ afferentMode(state.config.model.core.population_network) === "shared" &&
+ view.edges.some(e => e !== original && e.layer === 0 && e.enabled !== false && externalNames.includes(e.source_id) && e.pathway === otherSign);
+ afferentField.hidden = !needsAfferents;
+ afferents.disabled = !needsAfferents;
+ const available = target?.configured_per_level[pathway] || [];
+ // A disabled soma and levels that an edited projection masks out cannot
+ // contribute contacts, even if the underlying population budget is nonzero.
+ const depths = targetDepths(original?.target_levels, available.length);
+ eligible = available.map((_, d) => (d > 0 || target.settings.somatic_synapses) && (depths == null || depths.includes(d)));
+ const active = original?.enabled !== false && original?.probability !== 0;
+ const needsContacts = active && target && sources.value && eligible.some(Boolean) && !available.some((v, d) => eligible[d] && v > 0);
+ budgetField.hidden = !needsContacts;
+ contacts.disabled = !needsContacts;
+ const notes = [];
+ if (target && sources.value) notes.push(sources.value + " → " + target.id + ".");
+ if (delayed) {
+ notes.push("Uses earlier source activity. The source is zero before the sequence starts.");
+ if (target && !view.layers[target.layer].recurrent) notes.push("This will enable recurrence on " + target.layer_name + ".");
+ } else notes.push("Uses the current input or population response. Same-step routes must be acyclic.");
+ if (target) {
+ const otherSources = new Set(view.edges.filter(e => e !== original && e.enabled !== false &&
+ e.target_id === target.id && e.pathway === pathway).map(e => e.source_id));
+ if (otherSources.size) notes.push("Existing " + pathway.replace("_", " ") + " sources: " +
+ [...otherSources].join(", ") + ". Sources on this pathway share the target's contact budget.");
+ }
+ if (target && sources.value && !eligible.some(Boolean)) notes.push("No receiving compartment is enabled. Check somatic contacts and target levels.");
+ summary.textContent = notes.join(" ");
+ }
+ targets.onchange = timing.onchange = refreshSources;
+ sources.onchange = () => { selection = sources.value; explicitSign = ""; updatePathway(); };
+ sign.onchange = () => { explicitSign = sign.value; updatePathway(); };
+ refreshSources();
+ return dialog({
+ title: original ? "Edit connection" : "Connect populations",
+ body: [field({ label: "Receiving population", control: targets }),
+ field({ label: "Timing", control: timing }), field({ label: "Source", control: sources }), travel.element,
+ field({ label: "Pathway sign", control: sign }), afferentField, budgetField, summary],
+ actions: [{ label: "Cancel", submit: false }, { label: original ? "Save connection" : "Add connection", primary: true, value: true }],
+ onConfirm: async signal => {
+ if (!target || !sources.value) throw new Error("Choose a receiving population and a source.");
+ if (!afferents.disabled && !afferents.value) throw new Error("Choose how the two external afferent populations receive their features.");
+ const n = view.nodes.find(n => n.id === sources.value);
+ const source = n?.layer === target.layer ? n.name : sources.value;
+ if (!eligible.some(Boolean) && original?.enabled !== false) throw new Error("This destination has no eligible compartment. Enable somatic contacts or change the target levels first.");
+ if (!contacts.disabled && (!Number.isSafeInteger(contacts.valueAsNumber) || contacts.valueAsNumber < 1))
+ throw new Error("Enter a positive whole number of contacts.");
+ await editTopology(cfg => {
+ const net = cfg.model.core.population_network;
+ if (!afferents.disabled) {
+ net.use_transfer = true;
+ const transfer = net.transfer_params ||= {};
+ transfer.independent_pathways = afferents.value === "split";
+ transfer.input_source_identity = afferents.value === "paired" ? "paired_afferents" : "shared";
+ }
+ const dst = net.layers[target.layer];
+ const list = dst.connections ||= [];
+ const route = original ? net.layers[li].connections.splice(index, 1)[0] : {};
+ if (!original || original.source !== source) route.source = source;
+ route.target = target.name;
+ if (delayed || "timing" in route) route.timing = timing.value;
+ travel.save(route);
+ if (sign.value) route.pathway = pathway;
+ else delete route.pathway;
+ if (delayed) dst.recurrent = true;
+ if (!contacts.disabled) {
+ const own = dst.populations[target.population].population ||= {};
+ const key = pathway + "_synapses";
+ const levels = target.configured_per_level[pathway];
+ if (target.settings[key + "_by_level"]?.length || eligible.includes(false)) {
+ own[key + "_by_level"] = levels.map((v, d) => eligible[d] ? contacts.valueAsNumber : v).reverse();
+ } else own[key] = contacts.valueAsNumber;
+ }
+ const pos = original && li === target.layer ? index : list.length;
+ list.splice(pos, 0, route);
+ return { kind: "connection", layer: target.layer, index: pos };
+ }, { revision, signal, reindexes: original && li !== target.layer });
+ },
+ });
+}
diff --git a/apps/studio/src/dendrinet_studio/web/js/yamlview.js b/apps/studio/src/dendrinet_studio/web/js/yamlview.js
index 5afe270d..c94b7924 100644
--- a/apps/studio/src/dendrinet_studio/web/js/yamlview.js
+++ b/apps/studio/src/dendrinet_studio/web/js/yamlview.js
@@ -3,7 +3,7 @@
// the design, and the line the reader stopped at is marked.
import { h, icon, download, copyText } from "./dom.js";
-import { state, api, adopt, validationRevision } from "./store.js";
+import { state, api, adopt, validationRevision, waitForTopologyEdits } from "./store.js";
import { toast } from "./ui.js";
let root = null;
@@ -11,6 +11,7 @@ let area = null;
let gutter = null;
let status = null;
let baseline = "";
+let baselineRevision = -1;
let editorRevision = 0;
// A response belongs to one request, one text edit and one model revision.
@@ -57,7 +58,7 @@ export function mountYaml(container) {
h("span", { class: "spacer" }),
h("button", { type: "button", class: "btn", onclick: () => file.click() }, [icon("upload"), "Import"]),
h("button", { type: "button", class: "btn", onclick: exportYaml }, [icon("download"), "Export"]),
- h("button", { type: "button", class: "btn", onclick: async () => toast((await copyText(area.value)) ? "YAML copied." : "Copy failed.", { kind: "info" }) }, [icon("copy"), "Copy"]),
+ h("button", { type: "button", class: "btn", onclick: copyYaml }, [icon("copy"), "Copy"]),
]),
h("div", { class: "yaml-editor" }, [gutter, area]),
h("div", { class: "panel-foot" }, [
@@ -95,21 +96,31 @@ export function mountYaml(container) {
refreshYaml(true);
}
+function currentDesignYaml() {
+ if (!state.error && typeof state.preview?.yaml === "string" &&
+ JSON.stringify(state.config) === JSON.stringify(state.preview.config)) return state.preview.yaml;
+ const config = structuredClone(state.config);
+ return api("dump", { config }).then(result => result.yaml, () => JSON.stringify(config, null, 2));
+}
+
+function yamlForOutput() {
+ const ready = waitForTopologyEdits();
+ if (ready) return ready.then(yamlForOutput);
+ // An edited buffer belongs to the user. A clean buffer can still show the
+ // previous design while an undo or a model edit is waiting for its preview.
+ return area.value !== baseline || baselineRevision === validationRevision ? area.value : currentDesignYaml();
+}
+
// Show the current configuration (unless the text holds unapplied edits).
export async function refreshYaml(force = false) {
if (!area) return;
if (!force && area.value !== baseline) return;
const current = beginRequest();
- let text = state.preview && !state.error ? state.preview.yaml : null;
- if (text === null || text === undefined || JSON.stringify(state.config) !== JSON.stringify(state.preview?.config)) {
- try {
- text = (await api("dump", { config: state.config })).yaml;
- } catch (error) {
- text = JSON.stringify(state.config, null, 2);
- }
- }
+ const yaml = currentDesignYaml();
+ const text = typeof yaml === "string" ? yaml : await yaml;
if (!current()) return;
baseline = text;
+ baselineRevision = validationRevision;
area.value = text;
syncGutter();
markChanged();
@@ -145,6 +156,7 @@ async function apply(name) {
if (!current()) return;
adopt(result, name || state.docName, { keepHistory: true });
baseline = area.value;
+ baselineRevision = validationRevision;
syncGutter();
markChanged();
toast("Configuration applied. Undo restores the previous design.", { kind: "ok" });
@@ -162,8 +174,24 @@ async function apply(name) {
}
}
-function exportYaml() {
- const name = (state.docName || "dendrinet_model").replace(/\.(ya?ml)$/i, "").replace(/[^\w.-]+/g, "_");
- download(`${name}.yaml`, area.value, "text/yaml");
- if (area.value !== baseline) toast("Exported the edited text, which has not been applied or checked.", { kind: "warn" });
+async function exportYaml() {
+ try {
+ const text = await yamlForOutput();
+ const name = (state.docName || "dendrinet_model").replace(/\.(ya?ml)$/i, "").replace(/[^\w.-]+/g, "_");
+ download(`${name}.yaml`, text, "text/yaml");
+ if (area.value !== baseline) toast("Exported the edited text, which has not been applied or checked.", { kind: "warn" });
+ } catch (error) {
+ toast(error.message, { kind: "error" });
+ }
+}
+
+async function copyYaml() {
+ try {
+ const text = yamlForOutput();
+ // Request clipboard access during the click and surface a rejected edit.
+ const [copied] = await Promise.all([copyText(text), text]);
+ toast(copied ? "YAML copied." : "Copy failed.", { kind: copied ? "info" : "error" });
+ } catch (error) {
+ toast(error.message, { kind: "error" });
+ }
}
diff --git a/apps/studio/src/dendrinet_studio/web/styles.css b/apps/studio/src/dendrinet_studio/web/styles.css
index a701b49a..b272c665 100644
--- a/apps/studio/src/dendrinet_studio/web/styles.css
+++ b/apps/studio/src/dendrinet_studio/web/styles.css
@@ -238,6 +238,10 @@ h4.eyebrow { margin-top: 6px; }
.tree-row.layer-row { margin-top: 6px; font-weight: 600; color: var(--ink); }
.tree-row.pop-row, .tree-row.conn-row { padding-left: 22px; }
.tree-row .indent { width: 16px; }
+.route-list { margin: 2px 0 5px 22px; }
+.route-list summary { cursor: pointer; color: var(--ink-soft); font-size: 12px; padding: 4px 0; }
+.route-row .grow { overflow-wrap: anywhere; }
+.route-summary { margin: 4px 0; padding: 10px 12px; border-left: 3px solid var(--line-strong); background: var(--sunk); color: var(--ink-soft); font-size: 13px; line-height: 1.5; }
.tree-row .meta { font-size: 11.5px; color: var(--muted); font-weight: 400; font-variant-numeric: tabular-nums; white-space: nowrap; }
.grow { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
@@ -248,12 +252,13 @@ h4.eyebrow { margin-top: 6px; }
.tile-source { font-size: 11px; color: var(--faint); }
.canvas-scroll { overflow: auto; padding: 6px; max-height: 64vh; }
+.pick-target { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 14px; background: var(--sunk); font-size: 13px; }
svg.network { display: block; }
.legend { display: flex; flex-wrap: wrap; gap: 6px 16px; padding: 8px 14px; border-top: 1px solid var(--line); font-size: 12px; color: var(--ink-soft); }
.legend-item { display: inline-flex; align-items: center; gap: 6px; }
/* Network drawing */
-.lane-bg { fill: var(--sunk); }
+.lane-bg { fill: var(--sunk); stroke: var(--line); stroke-width: 1; }
.layer-lane.clickable .lane-bg, .layer-lane.clickable .lane-label { cursor: pointer; }
.lane-label { font-size: 11px; font-weight: 650; letter-spacing: 0.08em; text-transform: uppercase; fill: var(--muted); }
.lane-meta { font-size: 11px; fill: var(--muted); }
@@ -290,6 +295,7 @@ svg.network { display: block; }
.chip-edge rect { fill: var(--panel); stroke: var(--line-strong); }
.chip-edge text { font-family: var(--mono); font-size: 10.5px; fill: var(--ink-soft); }
.chip-edge.selected rect { stroke: var(--ink); stroke-width: 1.6; }
+.edge-chip-guide { fill: none; stroke: var(--line-strong); stroke-width: 1; pointer-events: none; }
/* Neuron drawing */
.neuron-body { display: grid; grid-template-columns: minmax(0, 1.5fr) minmax(250px, 1fr); gap: 16px; padding: 14px; align-items: start; }
@@ -325,6 +331,7 @@ table.data .num { text-align: right; }
table.data th[scope="row"] { font-weight: 500; text-align: left; white-space: normal; }
table.data th.run-cell { white-space: nowrap; min-width: 180px; }
.table-scroll { overflow-x: auto; }
+.travel-controls { min-width: 0; margin: 0; padding: 0; border: 0; }
.equation { border-left: 3px solid var(--line-strong); background: var(--sunk); border-radius: 0 8px 8px 0; padding: 10px 12px; display: grid; gap: 4px; }
.equation.shunt { border-left-color: var(--shunt); }
.equation.add { border-left-color: var(--add); }
diff --git a/apps/studio/tests/test_browser.py b/apps/studio/tests/test_browser.py
index e7390ac1..03367474 100644
--- a/apps/studio/tests/test_browser.py
+++ b/apps/studio/tests/test_browser.py
@@ -90,12 +90,18 @@ def two_layer_document():
return raw
-def test_imported_file_keeps_its_omissions_and_draws_every_pathway(page):
- raw = two_layer_document()
+def open_design(page, raw):
page.get_by_role("tab", name="YAML").click()
page.locator("textarea.yaml-text").fill(yaml.safe_dump(raw, sort_keys=False))
page.get_by_role("button", name="Apply").click()
+ playwright.expect(page.locator(".yaml-status")).to_contain_text(
+ "Matches the current design"
+ )
page.get_by_role("tab", name="Model").click()
+
+
+def test_imported_file_keeps_its_omissions_and_draws_every_pathway(page):
+ open_design(page, two_layer_document())
playwright.expect(page.locator("svg.network .card")).to_have_count(4)
# Input reaching layer1 is the readout of layer0; inhibition ends in a bar.
playwright.expect(edge(page, "layer0.e", "layer1.i")).to_have_count(1)
@@ -146,6 +152,9 @@ def test_soma_only_projection_does_not_label_every_branch_with_soma_contacts(pag
raw = example("synthetic_population")
layer = raw["model"]["core"]["population_network"]["layers"][0]
layer["connections"][-1]["target_levels"] = ["soma"]
+ layer["populations"][1].setdefault("population", {})[
+ "ff_inhibitory_synapses_by_level"
+ ] = [0, 0, 4]
page.get_by_role("tab", name="YAML").click()
page.locator("textarea.yaml-text").fill(yaml.safe_dump(raw, sort_keys=False))
page.get_by_role("button", name="Apply").click()
@@ -184,6 +193,7 @@ def test_visual_edits_undo_and_export(page):
# A new layer is wired from the previous layer's readout and still builds.
page.get_by_role("tab", name="Model").click()
page.get_by_role("button", name="Layer", exact=True).click()
+ page.get_by_role("dialog").get_by_role("button", name="Add layer").click()
playwright.expect(page.locator("svg.network .card")).to_have_count(4)
playwright.expect(page.locator(".status.ok")).to_contain_text("Valid")
# An invalid edit is reported and the drawing keeps the last valid design.
@@ -194,6 +204,32 @@ def test_visual_edits_undo_and_export(page):
assert not page.errors, page.errors
+def test_contextual_example_opens_with_its_routes_and_exports(page):
+ template = page.get_by_role("button", name="Contextual remapping on EMNIST")
+ playwright.expect(template).to_contain_text("downloads data")
+ template.click()
+ playwright.expect(page.locator("svg.network .card")).to_have_count(4)
+ for source, target in (
+ ("input", "layer0.i"),
+ ("input", "layer0.e"),
+ ("layer0.i", "layer0.e"),
+ ("layer0.e", "layer1.i"),
+ ("layer0.e", "layer1.e"),
+ ("layer0.i", "layer1.i"),
+ ("layer0.i", "layer1.e"),
+ ("layer1.i", "layer1.e"),
+ ):
+ playwright.expect(edge(page, source, target)).to_have_count(1)
+ raw = exported(page)
+ assert raw == example("contextual_remapping_population")
+ task = raw["data"]["dataset_params"]["contextual_remapping"]
+ assert task["num_contexts"] == 32
+ assert raw["model"]["encoder"]["params"]["input_dim"] == 784 + task["num_contexts"]
+ assert raw["model"]["decoder"]["params"]["output_dim"] == 47
+ assert raw["training"]["main"]["strategy"] == "presentation_stream"
+ assert not page.errors, page.errors
+
+
def test_other_families_open_with_their_own_forms(page):
for title, family in (
("GRU baseline for regression", "GRU"),
@@ -325,7 +361,16 @@ def test_external_route_switch_preserves_custom_placement(page):
"input_source_identity": "paired_afferents",
"output_activation": "relu",
}
- routes = net["layers"][0]["connections"]
+ layer = net["layers"][0]
+ # A second somatic source keeps the receiver buildable when the external one is off.
+ layer["populations"].append({**layer["populations"][0], "name": "backup_i"})
+ routes = layer["connections"]
+ routes.extend(
+ [
+ {"source": "input", "target": "backup_i"},
+ {"source": "backup_i", "target": "e", "target_levels": ["soma"]},
+ ]
+ )
routes.append(
{"source": "input_inh", "target": "e", "target_levels": ["soma"], "seed": 11}
)
@@ -371,13 +416,403 @@ def test_structured_feedforward_sources_follow_presence_of_inhibitory_cells(page
assert not page.errors
+def wire(page, receiver, source, timing="same_step"):
+ page.get_by_role("button", name="Connect", exact=True).click()
+ dialog = page.get_by_role("dialog", name="Connect populations")
+ dialog.get_by_label("Receiving population").select_option(receiver)
+ dialog.get_by_label("Timing", exact=True).select_option(timing)
+ dialog.get_by_label("Source", exact=True).select_option(source)
+ return dialog
+
+
+def test_add_a_second_feedforward_excitatory_source_and_build_the_export(page):
+ import torch
+
+ from dendritic_modeling.config import config_from_mapping
+ from dendritic_modeling.scripts.script_utils.setup_utils import initialize_model
+
+ raw = two_layer_document()
+ page.get_by_role("tab", name="YAML").click()
+ page.locator("textarea.yaml-text").fill(yaml.safe_dump(raw, sort_keys=False))
+ page.get_by_role("button", name="Apply").click()
+ page.get_by_role("tab", name="Model").click()
+ page.get_by_role("button", name="Edit population layer0.e", exact=True).click()
+ page.get_by_role("button", name="E population", exact=True).first.click()
+ page.get_by_role("button", name="Edit population layer0.e2").wait_for()
+ target = page.get_by_role("button", name="Edit population layer1.e", exact=True)
+ target.click()
+ source_row = page.get_by_role(
+ "region", name="Synapse sources per neuron"
+ ).get_by_role("row", name=re.compile(r"^E "))
+ original_budget = source_row.get_by_role("cell").last.inner_text()
+ page.get_by_role("button", name="Add input source").click()
+ dialog = page.get_by_role("dialog", name="Connect populations")
+ playwright.expect(dialog.get_by_label("Receiving population")).to_have_value(
+ "layer1.e"
+ )
+ dialog.get_by_label("Source", exact=True).select_option("layer0.e2")
+ playwright.expect(dialog.get_by_role("status")).to_contain_text("layer0.e.")
+ dialog.get_by_role("button", name="Add connection").click()
+ playwright.expect(edge(page, "layer0.e2", "layer1.e")).to_have_attribute(
+ "data-pathway", "ff_excitatory"
+ )
+ playwright.expect(
+ page.get_by_text("Source delay: 0 steps.", exact=False)
+ ).to_be_visible()
+ target.click()
+ playwright.expect(
+ source_row.get_by_role("button", name="layer0.e", exact=True)
+ ).to_be_visible()
+ playwright.expect(
+ source_row.get_by_role("button", name="layer0.e2", exact=True)
+ ).to_be_visible()
+ assert source_row.get_by_role("cell").last.inner_text() == original_budget
+ saved = exported(page)
+ model, _ = initialize_model(config_from_mapping(saved).model)
+ first, second = model.core_network.layers
+ assert not first.is_recurrent and not second.is_recurrent
+ assert second._stream_sources("e", "same_step", "ff_excitatory") == [
+ "layer0.e",
+ "layer0.e2",
+ ]
+ received = []
+ handle = second.populations["e"].register_forward_pre_hook(
+ lambda module, inputs: received.append(inputs[0])
+ )
+ model.core_network(torch.ones(2, 16))
+ handle.remove()
+ expected = torch.cat([first._last_outputs["e"], first._last_outputs["e2"]], dim=-1)
+ torch.testing.assert_close(received[0], expected, rtol=0, atol=0)
+ assert not page.errors
+
+
+def test_response_times_and_route_delay_survive_visual_edits_and_export(page):
+ import torch
+
+ from dendritic_modeling.config import config_from_mapping
+ from dendritic_modeling.scripts.script_utils.setup_utils import initialize_model
+
+ raw = example("recurrent_decision_population")
+ layer = raw["model"]["core"]["population_network"]["layers"][0]
+ layer["dt"] = 0.5
+ layer["connections"][-2]["target_levels"] = ["distal"]
+ layer["populations"][0]["population"] = {
+ "rec_excitatory_synapses_by_level": [2, 0, 0]
+ }
+ page.get_by_role("tab", name="YAML").click()
+ page.locator("textarea.yaml-text").fill(yaml.safe_dump(raw, sort_keys=False))
+ page.get_by_role("button", name="Apply").click()
+ page.get_by_role("tab", name="Model").click()
+ loop = page.get_by_role(
+ "button",
+ name="Connection circuit.pyr to circuit.pyr, rec_excitatory, delayed",
+ exact=True,
+ )
+ loop.press("Enter")
+ table = page.get_by_role("table", name="Response times by depth")
+ playwright.expect(
+ page.get_by_text("Source delay: 1 step.", exact=False)
+ ).to_be_visible()
+ playwright.expect(table.locator("tbody tr")).to_have_count(1)
+ playwright.expect(table.get_by_role("cell")).to_have_text(["1", "40"])
+ page.get_by_role("button", name="Edit receiving population").click()
+ soma = table.get_by_role("spinbutton", name="Response time at soma")
+ primary = table.get_by_role("spinbutton", name="Response time at 1 · primary")
+ distal = table.get_by_role("spinbutton", name="Response time at 2 · distal")
+ for control, value in [(soma, "10"), (primary, "20"), (distal, "40")]:
+ playwright.expect(control).to_have_value(value)
+ distal.fill("55")
+ distal.press("Enter")
+ page.get_by_role("button", name="Use base and ratio").wait_for()
+ primary.fill("17.5")
+ primary.press("Enter")
+ page.get_by_label("Learn one time constant per depth").click()
+ playwright.expect(
+ table.get_by_role("columnheader", name="Initial τ (learned)")
+ ).to_be_visible()
+ result = exported(page)
+ layer = result["model"]["core"]["population_network"]["layers"][0]
+ assert layer["populations"][0]["population"]["level_taus"] == [55, 17.5, 10]
+ assert layer["dt"] == 0.5 and layer["connections"][-2]["timing"] == "delayed"
+ model, _ = initialize_model(config_from_mapping(result).model)
+ pyr = model.core_network.layers[0].populations["pyr"]
+ torch.testing.assert_close(
+ pyr.current_taus.detach(), torch.tensor([55.0, 17.5, 10.0])
+ )
+ page.get_by_role("tab", name="Model").click()
+ page.get_by_role("button", name="Use base and ratio").click()
+ playwright.expect(distal).to_have_value("40")
+ assert (
+ "level_taus"
+ not in exported(page)["model"]["core"]["population_network"]["layers"][0][
+ "populations"
+ ][0]["population"]
+ )
+ assert not page.errors
+
+
+def test_set_travel_delays_in_the_connection_editor(page):
+ from dendritic_modeling.config import config_from_mapping
+ from dendritic_modeling.scripts.script_utils.setup_utils import initialize_model
+
+ page.locator(".example", has_text="Recurrent decision population network").click()
+ loop = page.get_by_role(
+ "button",
+ name="Connection circuit.pyr to circuit.pyr, rec_excitatory, delayed",
+ exact=True,
+ )
+ loop.press("Enter")
+ page.get_by_role("button", name="Edit connection", exact=True).click()
+ dialog = page.get_by_role("dialog", name="Edit connection")
+ dialog.get_by_label("Travel delay", exact=True).select_option("levels")
+ dialog.get_by_label("Travel steps at 1 · primary").fill("2")
+ dialog.get_by_label("Travel steps at 2 · distal").fill("3")
+ dialog.get_by_role("button", name="Save connection").click()
+ table = page.get_by_role("table", name="Response times by depth")
+ playwright.expect(table.locator("tbody td")).to_have_text(
+ ["1", "10", "2", "20", "3", "40"]
+ )
+ playwright.expect(loop.locator("title")).to_contain_text(
+ "1\N{EN DASH}3 steps of travel"
+ )
+ selected = page.locator('.route-row[aria-current="true"] .meta')
+ playwright.expect(selected).to_have_text("E · 1\N{EN DASH}3 Δt")
+ raw = exported(page)
+ route = raw["model"]["core"]["population_network"]["layers"][0]["connections"][-2]
+ assert route["delay_steps_by_level"] == [3, 2, 1] and "delay_steps" not in route
+ model, _ = initialize_model(config_from_mapping(raw).model)
+ assert model.core_network.layers[0].delay_history_lengths == {"pyr": 2}
+ page.get_by_role("tab", name="Model").click()
+ page.get_by_role("button", name="Edit receiving population").click()
+ page.get_by_role("button", name="level", exact=True).click()
+ playwright.expect(table.locator("tbody tr")).to_have_count(4)
+ expanded = exported(page)["model"]["core"]["population_network"]["layers"][0]
+ assert expanded["connections"][-2]["delay_steps_by_level"] == [1, 3, 2, 1]
+ page.get_by_role("tab", name="Model").click()
+ presets = page.get_by_role("group", name="Morphology presets")
+ presets.get_by_text("[2,2]", exact=True).click()
+ playwright.expect(table.locator("tbody tr")).to_have_count(3)
+ loop.press("Enter")
+ page.get_by_role("button", name="Edit connection", exact=True).click()
+ dialog.get_by_label("Travel delay", exact=True).select_option("uniform")
+ dialog.get_by_label("Travel delay (steps)").fill("4")
+ dialog.get_by_role("button", name="Save connection").click()
+ playwright.expect(table.locator("tbody td")).to_have_text(
+ ["4", "10", "4", "20", "4", "40"]
+ )
+ saved = exported(page)["model"]["core"]["population_network"]["layers"][0][
+ "connections"
+ ][-2]
+ assert saved["delay_steps"] == 4 and "delay_steps_by_level" not in saved
+ assert not page.errors
+
+
+def test_create_rewire_and_undo_without_invalidating_the_document(page):
+ # The published Add Connection button immediately duplicated input -> e.
+ dialog = wire(page, "layer0.e", "input")
+ dialog.get_by_role("button", name="Add connection").click()
+ playwright.expect(dialog.get_by_role("alert")).to_contain_text("duplicate")
+ dialog.get_by_role("button", name="Cancel").click()
+ playwright.expect(page.locator("svg.network path.edge[data-source]")).to_have_count(
+ 3
+ )
+ playwright.expect(page.locator(".banner")).to_be_hidden()
+ page.get_by_role("button", name="E population", exact=True).first.click()
+ playwright.expect(
+ page.get_by_role("button", name="Edit population layer0.e2")
+ ).to_be_visible()
+ dialog = wire(page, "layer0.e", "layer0.e2")
+ dialog.get_by_role("button", name="Add connection").click()
+ playwright.expect(edge(page, "layer0.e2", "layer0.e")).to_have_attribute(
+ "data-pathway", "ff_excitatory"
+ )
+ page.get_by_role("button", name="Edit connection", exact=True).click()
+ dialog = page.get_by_role("dialog", name="Edit connection")
+ dialog.get_by_label("Timing", exact=True).select_option("delayed")
+ dialog.get_by_label("Contacts per eligible compartment").fill("2")
+ dialog.get_by_role("button", name="Save connection").click()
+ playwright.expect(edge(page, "layer0.e2", "layer0.e")).to_have_attribute(
+ "data-pathway", "rec_excitatory"
+ )
+ result = exported(page)["model"]["core"]["population_network"]["layers"][0]
+ assert (
+ result["recurrent"]
+ and result["populations"][1]["population"]["rec_excitatory_synapses"] == 2
+ )
+ assert result["connections"][-1] == {
+ "source": "e2",
+ "target": "e",
+ "timing": "delayed",
+ }
+ page.get_by_role("tab", name="Model").click()
+ page.keyboard.press("Control+z")
+ playwright.expect(edge(page, "layer0.e2", "layer0.e")).to_have_attribute(
+ "data-pathway", "ff_excitatory"
+ )
+ assert not page.errors
+
+
+def test_connecting_both_external_signs_selects_biological_afferents(page):
+ from dendritic_modeling.config import config_from_mapping
+ from dendritic_modeling.scripts.script_utils.setup_utils import initialize_model
+
+ dialog = wire(page, "layer0.e", "input_i")
+ dialog.get_by_role("button", name="Add connection").click()
+ playwright.expect(dialog.get_by_role("alert")).to_contain_text("afferent")
+ dialog.get_by_label("External afferents for both signs").select_option("paired")
+ dialog.get_by_role("button", name="Add connection").click()
+ playwright.expect(edge(page, "input_i", "layer0.e")).to_have_attribute(
+ "data-pathway", "ff_inhibitory"
+ )
+ cfg = config_from_mapping(exported(page))
+ assert (
+ cfg.model.core.population_network["transfer_params"]["input_source_identity"]
+ == "paired_afferents"
+ )
+ initialize_model(cfg.model)
+
+
+def test_hybrid_graph_runs_with_forward_and_delayed_feedback(page, tmp_path):
+ import torch
+
+ from dendritic_modeling.config import config_from_mapping
+ from dendritic_modeling.scripts.script_utils.setup_utils import setup_environment
+
+ page.get_by_role("button", name="Layer", exact=True).click()
+ dialog = page.get_by_role("dialog")
+ dialog.get_by_label("Layer name").fill("memory")
+ dialog.get_by_label("Layer dynamics").select_option("recurrent")
+ dialog.get_by_role("button", name="Add layer").click()
+ loop = edge(page, "memory.e", "memory.e")
+ playwright.expect(loop).to_have_attribute("marker-end", "url(#m-exc)")
+ # The second layer may receive first-layer outputs now and send its
+ # previous inhibitory output back, even if the sending layer is later.
+ dialog = wire(page, "memory.e", "layer0.i")
+ dialog.get_by_role("button", name="Add connection").click()
+ playwright.expect(edge(page, "layer0.i", "memory.e")).to_have_attribute(
+ "data-pathway", "ff_inhibitory"
+ )
+ dialog = wire(page, "layer0.e", "memory.i", "delayed")
+ dialog.get_by_role("button", name="Add connection").click()
+ playwright.expect(edge(page, "memory.i", "layer0.e")).to_have_attribute(
+ "data-pathway", "rec_inhibitory"
+ )
+ page.get_by_role("button", name="Layer", exact=True).click()
+ dialog = page.get_by_role("dialog")
+ dialog.get_by_label("Layer name").fill("output")
+ dialog.get_by_role("button", name="Add layer").click()
+ playwright.expect(
+ page.get_by_role("button", name="Edit population output.e")
+ ).to_be_visible()
+ raw = exported(page)
+ net = raw["model"]["core"]["population_network"]
+ assert [layer.get("recurrent", False) for layer in net["layers"]] == [
+ True,
+ True,
+ False,
+ ]
+ assert net["layers"][0]["connections"][-1]["source"] == "memory.i"
+ assert net["layers"][1]["connections"][-1]["source"] == "layer0.i"
+ raw["outputs"]["results_dir"] = str(tmp_path)
+ cfg = config_from_mapping(raw)
+ _, _, _, _, model, _ = setup_environment(
+ cfg.model, cfg.training, cfg.data, cfg.outputs, cfg.experiment, is_main=False
+ )
+ x = torch.linspace(0, 1, 3 * 4 * 16).reshape(3, 4, 16).requires_grad_()
+ core = model.core_network
+ y, hidden = core(x, return_hidden=True)
+ assert hidden is not None and torch.isfinite(y).all()
+ y.sum().backward()
+ assert torch.isfinite(x.grad).all() and x.grad[:, :-1].abs().sum() > 0
+ assert not page.errors
+
+
+def test_canvas_feedback_and_sequence_training_in_a_mixed_network(page, studio):
+ import math
+
+ raw = example("recurrent_decision_population")
+ task = raw["data"]["dataset_params"][raw["data"]["dataset_name"]]
+ task["n_samples"] = 96
+ raw["training"]["main"]["common"].update(epochs=1, batch_size=16)
+ page.get_by_role("tab", name="YAML").click()
+ page.locator("textarea.yaml-text").fill(yaml.safe_dump(raw, sort_keys=False))
+ page.get_by_role("button", name="Apply", exact=True).click()
+ page.get_by_role("tab", name="Model").click()
+ page.get_by_role("button", name="Layer", exact=True).click()
+ page.get_by_role("dialog").get_by_role("button", name="Add layer").click()
+ card = page.get_by_role("button", name="Edit population layer1.pv")
+ card.click()
+ page.get_by_role("button", name="Connect from this population").click()
+ page.get_by_role("button", name="Edit population circuit.pyr").click()
+ dialog = page.get_by_role("dialog")
+ playwright.expect(dialog.get_by_label("Source", exact=True)).to_have_value(
+ "layer1.pv"
+ )
+ playwright.expect(dialog.get_by_label("Timing", exact=True)).to_have_value(
+ "delayed"
+ )
+ dialog.get_by_role("button", name="Add connection").click()
+ playwright.expect(edge(page, "layer1.pv", "circuit.pyr")).to_have_attribute(
+ "data-timing", "delayed"
+ )
+ page.get_by_role("button", name="Train", exact=True).click()
+ name = page.get_by_role("dialog").locator("input")
+ name.fill("mixed sequence")
+ name.press("Enter")
+ card = page.locator(".run-card", has_text="mixed sequence")
+ playwright.expect(card.locator(".status")).to_contain_text(
+ "Completed", timeout=240_000
+ )
+ run = next(r for r in studio.studio_runs.snapshot()["runs"] if r["kind"] == "train")
+ (loss,) = run["summary"]["train_losses"]
+ assert math.isfinite(loss)
+ saved = yaml.safe_load((Path(run["cwd"]) / "config.yaml").read_text())
+ layers = saved["model"]["core"]["population_network"]["layers"]
+ assert [layer.get("recurrent", False) for layer in layers] == [True, False]
+ assert layers[0]["connections"][-1] == {
+ "source": "layer1.pv",
+ "target": "pyr",
+ "timing": "delayed",
+ }
+ assert not page.errors
+
+
+def test_adding_populations_and_changing_depth_keep_imported_layer_defaults(page):
+ raw = two_layer_document()
+ net = raw["model"]["core"]["population_network"]
+ net["readout_layer"] = "layer0"
+ page.get_by_role("tab", name="YAML").click()
+ page.locator("textarea.yaml-text").fill(yaml.safe_dump(raw, sort_keys=False))
+ page.get_by_role("button", name="Apply").click()
+ page.get_by_role("tab", name="Model").click()
+ page.get_by_role("button", name="Edit population layer0.e").click()
+ page.get_by_role("button", name="E population", exact=True).first.click()
+ card = page.get_by_role("button", name="Edit population layer0.e2")
+ playwright.expect(card).to_be_visible()
+ page.locator(".presets .chip", has_text="[3,3,3]").click()
+ playwright.expect(card).to_contain_text("[3, 3, 3]")
+ page.get_by_role("button", name="Layer", exact=True).click()
+ page.get_by_role("dialog").get_by_role("button", name="Add layer").click()
+ playwright.expect(
+ page.get_by_role("button", name="Edit population layer2.e")
+ ).to_be_visible()
+ net = exported(page)["model"]["core"]["population_network"]
+ assert net["readout_layer"] == "layer0"
+ assert net["layers"][0]["population_defaults"][
+ "ff_inhibitory_synapses_by_level"
+ ] == [4, 4, 6]
+ new = net["layers"][0]["populations"][-1]["population"]
+ assert new["ff_inhibitory_synapses_by_level"] == [4, 4, 4, 6]
+ assert not page.errors
+
+
def delay_next_response(page, endpoint):
"""Deliver one real API response after a second UI action has taken place."""
page.evaluate(
"""endpoint => {
const fetch = window.fetch.bind(window);
window.fetch = async (...args) => {
- if (new URL(args[0], location.href).pathname !== "/api/" + endpoint) return fetch(...args);
+ if (new URL(args[0], document.baseURI).href !== new URL("api/" + endpoint, document.baseURI).href) return fetch(...args);
window.fetch = fetch;
const response = await fetch(...args);
const json = response.json.bind(response);
@@ -396,16 +831,241 @@ def delay_next_response(page, endpoint):
)
+def test_readout_selection_updates_both_explicit_readouts(page):
+ raw = example("synthetic_population")
+ raw["model"]["core"]["population_network"]["readout_population"] = "e"
+ page.get_by_role("tab", name="YAML").click()
+ page.locator("textarea.yaml-text").fill(yaml.safe_dump(raw, sort_keys=False))
+ page.get_by_role("button", name="Apply").click()
+ page.get_by_role("tab", name="Model").click()
+ page.locator(".tree-row.layer-row").first.click()
+ page.get_by_label("Readout population", exact=True).select_option("i")
+ playwright.expect(
+ page.get_by_role("button", name="Edit population layer0.i")
+ ).to_contain_text("readout")
+ net = exported(page)["model"]["core"]["population_network"]
+ assert net["readout_population"] == net["layers"][0]["readout_population"] == "i"
+ assert not page.errors
+
+
+def test_cancel_while_checking_a_route_keeps_draft_and_history(page):
+ dialog = wire(page, "layer0.e", "layer0.e", "delayed")
+ delay_next_response(page, "preview")
+ dialog.get_by_role("button", name="Add connection").click()
+ page.wait_for_selector("html[data-response-ready]")
+ dialog.get_by_role("button", name="Cancel").click()
+ release_response(page)
+ playwright.expect(edge(page, "layer0.e", "layer0.e")).to_have_count(0)
+ before = example("synthetic_population")
+ assert exported(page) == before
+ assert not page.errors
+
+
def release_response(page):
# Let the promise handlers settle before checking the resulting UI.
- page.evaluate(
- """async () => {
+ page.evaluate("""async () => {
window.resumeStudioResponse();
delete window.resumeStudioResponse;
delete document.documentElement.dataset.responseReady;
await new Promise(done => setTimeout(done, 0));
- }"""
+ }""")
+
+
+def test_zero_budget_add_layer_omits_inactive_inhibition(page):
+ from dendritic_modeling.config import config_from_mapping
+ from dendritic_modeling.scripts.script_utils.setup_utils import initialize_model
+
+ raw = example("synthetic_population")
+ first = raw["model"]["core"]["population_network"]["layers"][0]
+ first["population_defaults"]["ff_inhibitory_synapses"] = 0
+ open_design(page, raw)
+ page.get_by_role("button", name="Layer", exact=True).click()
+ dialog = page.get_by_role("dialog", name="Add layer")
+ playwright.expect(dialog).to_contain_text("no eligible inhibitory contacts")
+ dialog.get_by_role("button", name="Add layer").click()
+ playwright.expect(page.locator("svg.network .card")).to_have_count(4)
+ assert edge(page, "layer1.i", "layer1.e").count() == 0
+ result = exported(page)
+ new = result["model"]["core"]["population_network"]["layers"][1]
+ assert new["population_defaults"]["ff_inhibitory_synapses"] == 0
+ assert new["connections"] == [
+ {"source": "input", "target": "i"},
+ {"source": "input", "target": "e"},
+ ]
+ initialize_model(config_from_mapping(result).model)
+ assert not page.errors
+
+
+def test_add_layer_rejects_broadcast_credit_for_stepped_template(page):
+ raw = example("synthetic_population")
+ layer = raw["model"]["core"]["population_network"]["layers"][0]
+ layer["population_defaults"]["autograd_credit_mode"] = "soma_broadcast"
+ open_design(page, raw)
+ page.get_by_role("button", name="Layer", exact=True).click()
+ dialog = page.get_by_role("dialog", name="Add layer")
+ dialog.get_by_label("Layer dynamics").select_option("recurrent")
+ dialog.get_by_role("button", name="Add layer").click()
+ playwright.expect(dialog.get_by_role("alert")).to_contain_text("exact")
+ assert page.locator("svg.network .card").count() == 2
+ dialog.get_by_role("button", name="Cancel").click()
+ assert exported(page) == raw
+ assert not page.errors
+
+
+def test_retimed_restricted_route_only_funds_the_selected_depth(page):
+ import torch
+
+ from dendritic_modeling.config import config_from_mapping
+ from dendritic_modeling.scripts.script_utils.setup_utils import initialize_model
+
+ raw = two_layer_document()
+ open_design(page, raw)
+ route = page.get_by_role(
+ "button",
+ name="Connection layer0.i to layer1.e, ff_inhibitory, same_step",
+ exact=True,
+ )
+ route.press("Enter")
+ page.get_by_role("switch", name="All levels").click()
+ page.locator("#lvl-0").uncheck()
+ page.locator("#lvl-1").uncheck()
+ page.get_by_role("button", name="Edit connection", exact=True).click()
+ dialog = page.get_by_role("dialog", name="Edit connection")
+ dialog.get_by_label("Timing", exact=True).select_option("delayed")
+ dialog.get_by_label("Contacts per eligible compartment").fill("3")
+ dialog.get_by_role("button", name="Save connection").click()
+ playwright.expect(edge(page, "layer0.i", "layer1.e")).to_have_attribute(
+ "data-pathway", "rec_inhibitory"
)
+ result = exported(page)
+ layer = result["model"]["core"]["population_network"]["layers"][1]
+ saved = next(c for c in layer["connections"] if c.get("source") == "layer0.i")
+ assert saved["target_levels"] == [2] and saved["timing"] == "delayed"
+ assert layer["populations"][1]["population"][
+ "rec_inhibitory_synapses_by_level"
+ ] == [3, 0, 0]
+ model, _ = initialize_model(config_from_mapping(result).model)
+ assert torch.isfinite(model.core_network(torch.ones(2, 5, 16))).all()
+ assert not page.errors
+
+
+@pytest.mark.parametrize("field", ["response time", "contact count"])
+def test_pending_depth_edit_survives_adding_a_morphology_level(page, field):
+ page.locator(".example", has_text="Recurrent decision population network").click()
+ page.get_by_role("button", name="Edit population circuit.pyr", exact=True).click()
+ if field == "response time":
+ label, value, key, expected = (
+ "Response time at 1 · primary",
+ "25",
+ "level_taus",
+ [80, 40, 25, 10],
+ )
+ else:
+ page.get_by_text("Set counts per level", exact=True).click()
+ label, value, key, expected = (
+ "Recurrent excitatory contacts at level 1 · primary",
+ "3",
+ "rec_excitatory_synapses_by_level",
+ [2, 2, 3, 2],
+ )
+
+ delay_next_response(page, "preview")
+ control = page.get_by_role("spinbutton", name=label, exact=True)
+ control.fill(value)
+ control.press("Enter")
+ page.wait_for_selector("html[data-response-ready]")
+ page.get_by_role("button", name="level", exact=True).click()
+ release_response(page)
+ table = page.get_by_role("table", name="Response times by depth")
+ playwright.expect(table.locator("tbody tr")).to_have_count(4)
+ saved = exported(page)["model"]["core"]["population_network"]["layers"][0][
+ "populations"
+ ][0]
+ assert saved["population"][key] == expected
+ assert not page.errors
+
+
+def test_queued_edits_to_connection_controls_survive_in_order(page):
+ page.locator(".example", has_text="Recurrent decision population network").click()
+ page.get_by_role(
+ "button",
+ name="Connection circuit.pyr to circuit.pyr, rec_excitatory, delayed",
+ exact=True,
+ ).press("Enter")
+ delay_next_response(page, "preview")
+ probability = page.get_by_label("Connection probability", exact=True)
+ probability.fill("0.4")
+ probability.press("Enter")
+ page.wait_for_selector("html[data-response-ready]")
+ seed = page.get_by_label("Seed", exact=True)
+ seed.fill("27")
+ seed.press("Enter")
+ release_response(page)
+ # Wait for the validated draft itself, independent of the values typed into the form.
+ page.wait_for_function(
+ """async () => {
+ const {state} = await import('./js/store.js');
+ const c = state.config.model.core.population_network.layers[0].connections.at(-2);
+ return c.probability === 0.4 && c.seed === 27;
+ }""",
+ timeout=5000,
+ )
+ page.get_by_role("button", name="Undo (Ctrl+Z)", exact=True).click()
+ playwright.expect(seed).to_have_value("")
+ saved = exported(page)["model"]["core"]["population_network"]["layers"][0][
+ "connections"
+ ][-2]
+ assert saved["probability"] == 0.4 and "seed" not in saved
+ assert not page.errors
+
+
+def test_stale_topology_dialog_waits_for_validation_then_rejects_later_edits(page):
+ page.get_by_role("button", name="Edit population layer0.e", exact=True).click()
+ delay_next_response(page, "preview")
+ contacts = page.locator(
+ 'input[data-key$="populations.1.population.ff_inhibitory_synapses"]'
+ )
+ contacts.fill("0")
+ contacts.press("Enter")
+ page.wait_for_selector("html[data-response-ready]")
+ page.get_by_role("button", name="Layer", exact=True).click()
+ dialog = page.get_by_role("dialog", name="Add layer")
+ assert not dialog.count()
+ release_response(page)
+ playwright.expect(dialog).to_contain_text("no eligible inhibitory contacts")
+ page.evaluate("""async () => {
+ const {edit} = await import('./js/store.js');
+ await edit(cfg => { cfg.experiment.seed = 753; });
+ }""")
+ dialog.get_by_role("button", name="Add layer").click()
+ playwright.expect(dialog.get_by_role("alert")).to_contain_text("design changed")
+ dialog.get_by_role("button", name="Cancel").click()
+ saved = exported(page)
+ assert saved["experiment"]["seed"] == 753
+ assert len(saved["model"]["core"]["population_network"]["layers"]) == 1
+ assert not page.errors
+
+
+def test_queued_edits_rebase_morphology_on_a_later_field_edit(page):
+ page.locator(".example", has_text="Recurrent decision population network").click()
+ page.get_by_role("button", name="Edit population circuit.pyr", exact=True).click()
+ delay_next_response(page, "preview")
+ add = page.get_by_role("button", name="More branches at level 1", exact=True)
+ add.click()
+ page.wait_for_selector("html[data-response-ready]")
+ add.click()
+ primary = page.get_by_role("spinbutton", name="Response time at 1 · primary")
+ primary.fill("25")
+ primary.press("Enter")
+ release_response(page)
+ playwright.expect(
+ page.get_by_role("button", name="Edit population circuit.pyr")
+ ).to_contain_text("[4, 2]")
+ saved = exported(page)["model"]["core"]["population_network"]["layers"][0][
+ "populations"
+ ][0]
+ assert saved["population"]["level_taus"] == [40, 25, 10]
+ assert not page.errors
def test_morphology_drawing_is_bounded_and_keeps_the_real_level_counts(page):
@@ -439,14 +1099,12 @@ def test_morphology_drawing_is_bounded_and_keeps_the_real_level_counts(page):
playwright.expect(neuron).to_have_attribute(
"aria-label", re.compile(f"{drawn} of {total:,} compartments")
)
- label = page.evaluate(
- """async () => {
+ label = page.evaluate("""async () => {
const { drawNeuron } = await import("./js/morphology.js");
const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
drawNeuron(svg, {counts: {ff_excitatory: [2000000]}});
return [svg.querySelector(".count-label").textContent, svg.querySelectorAll(".bouton").length];
- }"""
- )
+ }""")
assert label == ["2000000 E each", 0]
assert not page.errors, page.errors
@@ -472,12 +1130,10 @@ def test_adopting_an_example_supersedes_inflight_model_validation(page, invalid)
page.get_by_role("button", name="Train", exact=True)
).to_be_enabled()
release_response(page)
- assert page.evaluate(
- """async () => {
+ assert page.evaluate("""async () => {
const { state } = await import("./js/store.js");
return !state.validating && !state.error && JSON.stringify(state.config) === JSON.stringify(state.preview.config);
- }"""
- )
+ }""")
assert not page.errors, page.errors
@@ -525,12 +1181,10 @@ def test_delayed_yaml_dump_preserves_newer_text_or_document(page, intervening_ac
page.get_by_role("tab", name="YAML").click()
editor = page.locator("textarea.yaml-text")
delay_next_response(page, "dump")
- page.evaluate(
- """async () => {
+ page.evaluate("""async () => {
const { edit } = await import("./js/store.js");
await edit(config => { config.unknown_option = true; });
- }"""
- )
+ }""")
page.locator("html[data-response-ready]").wait_for()
if intervening_action == "type":
expected = "# keep my edit\n" + editor.input_value()
@@ -572,3 +1226,559 @@ def test_typing_during_apply_preserves_the_new_yaml(page, invalid_submission):
page.get_by_role("button", name="Apply").click()
playwright.expect(page.locator(".yaml-status")).to_contain_text("Matches")
assert page.evaluate(read_seed) == 102
+
+
+@pytest.mark.parametrize("inherited", [False, True])
+def test_uniform_reset_preserves_later_depth_edit(page, inherited):
+ raw = example("synthetic_population")
+ layer = raw["model"]["core"]["population_network"]["layers"][0]
+ field = "ff_inhibitory_synapses_by_level"
+ settings = (
+ layer["population_defaults"]
+ if inherited
+ else layer["populations"][1].setdefault("population", {})
+ )
+ settings[field] = [2, 3, 6]
+ if inherited:
+ # The inhibitory population has a shallower tree than the receiver.
+ layer["populations"][0].setdefault("population", {})[field] = []
+ open_design(page, raw)
+ page.get_by_role("button", name="Edit population layer0.e", exact=True).click()
+ page.get_by_text("Set counts per level", exact=True).click()
+ delay_next_response(page, "preview")
+ page.get_by_role("button", name="Use one count for all levels").click()
+ page.wait_for_selector("html[data-response-ready]")
+ primary = page.get_by_role(
+ "spinbutton", name="Inhibitory contacts at level 1 · primary"
+ )
+ primary.fill("7")
+ primary.press("Enter")
+ release_response(page)
+ page.evaluate("async () => (await import('./js/store.js')).topologyReady()")
+ saved = exported(page)["model"]["core"]["population_network"]["layers"][0]
+ assert saved["populations"][1]["population"][field] == [4, 7, 4]
+ undo = page.get_by_role("button", name="Undo (Ctrl+Z)", exact=True)
+ undo.click()
+ rolled_back = exported(page)["model"]["core"]["population_network"]["layers"][0]
+ assert rolled_back["populations"][1].get("population", {}).get(field) == (
+ [] if inherited else None
+ )
+ undo.click()
+ assert exported(page) == raw
+ assert not page.errors
+
+
+@pytest.mark.parametrize("primary_source", [False, True])
+def test_retimed_route_requires_coverage_for_existing_contacts(page, primary_source):
+ from dendritic_modeling.config import config_from_mapping
+ from dendritic_modeling.scripts.script_utils.setup_utils import initialize_model
+
+ raw = two_layer_document()
+ layer = raw["model"]["core"]["population_network"]["layers"][1]
+ layer["connections"][2]["target_levels"] = ["distal"]
+ field = "rec_inhibitory_synapses_by_level"
+ layer["populations"][1].setdefault("population", {})[field] = [0, 2, 0]
+ if primary_source:
+ layer["recurrent"] = True
+ layer["connections"].append(
+ {
+ "source": "i",
+ "target": "e",
+ "timing": "delayed",
+ "target_levels": ["primary"],
+ }
+ )
+ open_design(page, raw)
+ page.get_by_role(
+ "button",
+ name="Connection layer0.i to layer1.e, ff_inhibitory, same_step",
+ exact=True,
+ ).press("Enter")
+ page.get_by_role("button", name="Edit connection", exact=True).click()
+ dialog = page.get_by_role("dialog", name="Edit connection")
+ dialog.get_by_label("Timing", exact=True).select_option("delayed")
+ dialog.get_by_label("Contacts per eligible compartment").fill("1")
+ dialog.get_by_role("button", name="Save connection").click()
+ if primary_source:
+ playwright.expect(dialog).not_to_be_visible()
+ result = exported(page)
+ saved = result["model"]["core"]["population_network"]["layers"][1]
+ assert saved["populations"][1]["population"][field] == [1, 2, 0]
+ initialize_model(config_from_mapping(result).model)
+ else:
+ playwright.expect(dialog.get_by_role("alert")).to_contain_text("depth 1")
+ dialog.get_by_role("button", name="Cancel").click()
+ assert exported(page) == raw
+ assert not page.errors
+
+
+def capture_clipboard(page):
+ page.evaluate("""() => {
+ Object.defineProperty(navigator.clipboard, "writeText", {
+ value: async text => {
+ window.copiedYaml = text;
+ document.documentElement.dataset.copyReady = "yes";
+ }
+ });
+ Object.defineProperty(navigator.clipboard, "write", {
+ value: async ([item]) => {
+ window.copiedYaml = await (await item.getType("text/plain")).text();
+ document.documentElement.dataset.copyReady = "yes";
+ }
+ });
+ }""")
+
+
+@pytest.mark.parametrize("action", ["Export", "Copy"])
+def test_yaml_output_follows_undo_while_preview_is_pending(page, action):
+ capture_clipboard(page)
+ page.get_by_role("tab", name="YAML").click()
+ editor = page.locator("textarea.yaml-text")
+ original = yaml.safe_load(editor.input_value())
+ page.evaluate("""async () => {
+ const {edit} = await import("./js/store.js");
+ await edit(cfg => { cfg.experiment.seed = 284; });
+ }""")
+ playwright.expect(editor).to_have_value(re.compile(r"seed: 284\b"))
+ delay_next_response(page, "preview")
+ page.get_by_role("button", name="Undo (Ctrl+Z)", exact=True).click()
+ page.wait_for_selector("html[data-response-ready]")
+
+ def output():
+ button = page.get_by_role("button", name=action, exact=True)
+ if action == "Export":
+ with page.expect_download() as event:
+ button.click()
+ return Path(event.value.path()).read_text()
+ page.evaluate("delete document.documentElement.dataset.copyReady")
+ button.click()
+ page.locator("html[data-copy-ready]").wait_for()
+ return page.evaluate("window.copiedYaml")
+
+ assert yaml.safe_load(output()) == original
+ edited = "# Unapplied text\nexperiment: ["
+ editor.fill(edited)
+ assert output() == edited
+ release_response(page)
+ assert editor.input_value() == edited
+ assert not page.errors
+
+
+def test_connection_depth_can_repair_an_invalid_contact_edit(page):
+ raw = example("synthetic_population")
+ layer = raw["model"]["core"]["population_network"]["layers"][0]
+ layer["connections"][-1]["target_levels"] = ["distal"]
+ field = "ff_inhibitory_synapses_by_level"
+ layer["populations"][1]["population"] = {field: [4, 0, 0]}
+ open_design(page, raw)
+ page.get_by_role("button", name="Edit population layer0.e", exact=True).click()
+ page.get_by_text("Set counts per level", exact=True).click()
+ primary = page.get_by_role(
+ "spinbutton", name="Inhibitory contacts at level 1 · primary"
+ )
+ primary.fill("2")
+ primary.press("Enter")
+ page.wait_for_function(
+ """async () => (await import('./js/store.js')).state.error?.includes('depth 1')"""
+ )
+ page.get_by_role(
+ "button", name="Connection layer0.i to layer0.e, ff_inhibitory, same_step"
+ ).press("Enter")
+ page.locator("#lvl-1").click()
+ page.wait_for_function(
+ """async () => !(await import('./js/store.js')).state.error""", timeout=4000
+ )
+ saved = exported(page)["model"]["core"]["population_network"]["layers"][0]
+ assert saved["connections"][-1]["target_levels"] == [1, 2]
+ assert saved["populations"][1]["population"][field] == [4, 2, 0]
+ assert not page.errors
+
+
+@pytest.mark.parametrize("operation", ["reset", "undo", "redo"])
+def test_tau_edit_uses_current_depth_settings(page, operation):
+ raw = example("recurrent_decision_population")
+ layer = raw["model"]["core"]["population_network"]["layers"][0]
+ own = layer["populations"][0].setdefault("population", {})
+ own["level_taus"] = [61, 31, 11]
+ open_design(page, raw)
+ page.get_by_role("button", name="Edit population circuit.pyr", exact=True).click()
+ reset = page.get_by_role("button", name="Use base and ratio")
+ undo = page.get_by_role("button", name="Undo (Ctrl+Z)", exact=True)
+ redo = page.get_by_role("button", name=re.compile("^Redo"))
+ distal = page.get_by_role("spinbutton", name="Response time at 2 · distal")
+ if operation != "reset":
+ reset.click()
+ playwright.expect(distal).to_have_value("40")
+ if operation == "redo":
+ undo.click()
+ playwright.expect(distal).to_have_value("61")
+ delay_next_response(page, "preview")
+ {"reset": reset, "undo": undo, "redo": redo}[operation].click()
+ page.wait_for_selector("html[data-response-ready]")
+ primary = page.get_by_role("spinbutton", name="Response time at 1 · primary")
+ primary.fill("25")
+ primary.press("Enter")
+ release_response(page)
+ page.evaluate("async () => (await import('./js/store.js')).topologyReady()")
+ pop = exported(page)["model"]["core"]["population_network"]["layers"][0][
+ "populations"
+ ][0]
+ assert pop["population"]["level_taus"] == (
+ [61, 25, 11] if operation == "undo" else [40, 25, 10]
+ )
+ assert not page.errors
+
+
+@pytest.mark.parametrize("kind", ["population", "layer"])
+def test_rapid_renames_follow_current_references(page, kind):
+ raw = two_layer_document()
+ net = raw["model"]["core"]["population_network"]
+ net.update(readout_layer="layer0", readout_population="e")
+ open_design(page, raw)
+ if kind == "population":
+ page.get_by_role("button", name="Edit population layer0.e", exact=True).click()
+ else:
+ page.locator(".tree-row.layer-row").first.click()
+ name = page.get_by_label("Name", exact=True)
+ delay_next_response(page, "preview")
+ name.fill("intermediate")
+ name.press("Enter")
+ page.wait_for_selector("html[data-response-ready]")
+ name.fill("final")
+ name.press("Enter")
+ release_response(page)
+ page.evaluate("async () => (await import('./js/store.js')).topologyReady()")
+ saved = exported(page)["model"]["core"]["population_network"]
+ first, second = saved["layers"]
+ if kind == "population":
+ assert (
+ first["populations"][1]["name"]
+ == first["readout_population"]
+ == saved["readout_population"]
+ == "final"
+ )
+ assert [c["target"] for c in first["connections"]] == ["i", "final", "final"]
+ assert second["connections"][1]["source"] == "layer0.final"
+ else:
+ assert first["name"] == saved["readout_layer"] == "final"
+ assert [c["source"] for c in second["connections"][1:3]] == [
+ "final.e",
+ "final.i",
+ ]
+ assert not page.errors
+
+
+@pytest.mark.parametrize("action", ["Check model", "Train", "Export", "Copy"])
+def test_model_actions_wait_for_connection_edit(page, action):
+ capture_clipboard(page)
+ page.route(
+ "**/api/run",
+ lambda route: route.fulfill(
+ json={"id": "captured", "name": "captured", "kind": "train"}
+ ),
+ )
+ page.get_by_role(
+ "button", name="Connection layer0.i to layer0.e, ff_inhibitory, same_step"
+ ).press("Enter")
+ delay_next_response(page, "preview")
+ probability = page.get_by_label("Connection probability", exact=True)
+ probability.fill("0.4")
+ probability.press("Enter")
+ page.wait_for_selector("html[data-response-ready]")
+ if action in ("Copy", "Export"):
+ page.get_by_role("tab", name="YAML").click()
+ button = page.get_by_role("button", name=action, exact=True)
+ if action == "Export":
+ with page.expect_download() as event:
+ button.click()
+ release_response(page)
+ document = yaml.safe_load(Path(event.value.path()).read_text())
+ elif action == "Copy":
+ button.click()
+ release_response(page)
+ page.locator("html[data-copy-ready]").wait_for()
+ document = yaml.safe_load(page.evaluate("window.copiedYaml"))
+ else:
+ with page.expect_response("**/api/run") as launched:
+ button.click()
+ if action == "Train":
+ # The confirmation describes the validated model and its dataset.
+ playwright.expect(
+ page.get_by_role("dialog", name="Train this model")
+ ).to_have_count(0, timeout=1000)
+ release_response(page)
+ if action == "Train":
+ page.get_by_role("button", name="Start training", exact=True).click()
+ document = launched.value.request.post_data_json["config"]
+ route = document["model"]["core"]["population_network"]["layers"][0]["connections"][
+ -1
+ ]
+ assert route.get("probability") == 0.4
+ assert not page.errors
+
+
+@pytest.mark.parametrize("action", ["Check model", "Train", "Export", "Copy"])
+def test_rejected_topology_edit_aborts_action_and_allows_retry(page, action):
+ runs = []
+ downloads = []
+ capture_clipboard(page)
+ page.on("download", lambda download: downloads.append(download))
+
+ def capture_run(route):
+ runs.append(route.request.post_data_json)
+ route.fulfill(json={"id": "captured"})
+
+ page.route("**/api/run", capture_run)
+ delay_next_response(page, "preview")
+ page.evaluate("""async () => {
+ const {editTopology} = await import('./js/store.js');
+ editTopology(cfg => {cfg.model.core.population_network.layers[0].connections[0].target = 'missing';}).catch(() => {});
+ }""")
+ page.wait_for_selector("html[data-response-ready]")
+ if action in ("Export", "Copy"):
+ page.get_by_role("tab", name="YAML").click()
+ page.get_by_role("button", name=action, exact=True).click()
+ release_response(page)
+ playwright.expect(
+ page.locator(".toast").filter(has_text="missing").first
+ ).to_be_visible(timeout=4000)
+ assert not runs and not downloads
+ assert page.evaluate("window.copiedYaml") is None
+ playwright.expect(page.get_by_role("dialog")).not_to_be_visible()
+ with page.expect_response("**/api/run"):
+ page.get_by_role("button", name="Check model", exact=True).click()
+ assert len(runs) == 1
+ assert not page.errors
+
+
+@pytest.mark.parametrize("inactive", [{"enabled": False}, {"probability": 0.0}])
+def test_saving_inactive_connection_preserves_shared_zero_budget(page, inactive):
+ raw = two_layer_document()
+ layer = raw["model"]["core"]["population_network"]["layers"][1]
+ layer["connections"][2].update(inactive)
+ field = "ff_inhibitory_synapses_by_level"
+ layer["populations"][1].setdefault("population", {})[field] = [0, 0, 0]
+ open_design(page, raw)
+ routes = page.locator("details.route-list").nth(1)
+ routes.locator("summary").click()
+ routes.locator(".route-row").nth(2).click()
+ page.get_by_role("button", name="Edit connection", exact=True).click()
+ dialog = page.get_by_role("dialog", name="Edit connection")
+ playwright.expect(
+ dialog.get_by_label("Contacts per eligible compartment")
+ ).to_be_hidden()
+ dialog.get_by_role("button", name="Save connection").click()
+ playwright.expect(dialog).not_to_be_visible()
+ saved = exported(page)["model"]["core"]["population_network"]["layers"][1]
+ assert saved["populations"] == layer["populations"]
+ assert saved["connections"] == layer["connections"]
+ assert not page.errors
+
+
+@pytest.mark.parametrize(
+ "readout",
+ ["unique", "compatible", "conflicting", "explicit_final", "explicit_elsewhere"],
+)
+def test_remove_last_layer_resolves_readout_before_deletion(page, readout):
+ raw = two_layer_document()
+ net = raw["model"]["core"]["population_network"]
+ first, last = net["layers"]
+ if readout == "unique":
+ last["populations"][1]["name"] = last["readout_population"] = "output"
+ for conn in last["connections"]:
+ if conn["target"] == "e":
+ conn["target"] = "output"
+ net["readout_population"] = "output"
+ elif readout == "explicit_final":
+ net.update(readout_layer="layer1", readout_population="e")
+ elif readout == "explicit_elsewhere":
+ net.update(readout_layer="layer0", readout_population="e")
+ else:
+ net["readout_population"] = last["readout_population"] = "i"
+ if readout == "compatible":
+ del first["readout_population"]
+ open_design(page, raw)
+ page.locator(".tree-row.layer-row").last.click()
+ page.get_by_role("button", name="Remove layer", exact=True).click()
+ page.get_by_role("dialog", name="Remove layer").get_by_role(
+ "button", name="Remove", exact=True
+ ).click()
+ playwright.expect(page.locator(".tree-row.layer-row")).to_have_count(1)
+ saved = exported(page)["model"]["core"]["population_network"]
+ assert saved["layers"] == [first]
+ assert saved.get("readout_population") == {
+ "compatible": "i",
+ "explicit_elsewhere": "e",
+ }.get(readout)
+ assert saved.get("readout_layer") == (
+ "layer0" if readout == "explicit_elsewhere" else None
+ )
+ page.get_by_role("button", name="Undo (Ctrl+Z)", exact=True).click()
+ assert exported(page) == raw
+ assert not page.errors
+
+
+def invalid_population_times(page, li, pi):
+ # An ordinary edit retains invalid input so the user can correct it.
+ assert (
+ page.evaluate(
+ """async ([li, pi]) => {
+ const {edit} = await import('./js/store.js');
+ return edit(cfg => {
+ const pop = cfg.model.core.population_network.layers[li].populations[pi];
+ (pop.population ||= {}).level_taus = [7];
+ }, {structural: true});
+ }""",
+ [li, pi],
+ )
+ is False
+ )
+ playwright.expect(page.locator(".banner")).to_contain_text("level_taus")
+
+
+@pytest.mark.parametrize("kind", ["population", "layer"])
+def test_removal_repairs_invalid_draft_and_undo_restores_it(page, kind):
+ raw = two_layer_document()
+ open_design(page, raw)
+ invalid_population_times(page, 1, 0)
+ if kind == "population":
+ page.get_by_role("button", name="Edit population layer1.i", exact=True).click()
+ else:
+ page.locator(".tree-row.layer-row").last.click()
+ title = f"Remove {kind}"
+ page.get_by_role("button", name=title, exact=True).click()
+ dialog = page.get_by_role("dialog", name=title)
+ playwright.expect(dialog).to_be_visible(timeout=4000)
+ dialog.get_by_role("button", name="Remove", exact=True).click()
+ playwright.expect(page.locator(".banner")).to_be_hidden()
+ saved = exported(page)["model"]["core"]["population_network"]["layers"]
+ before = raw["model"]["core"]["population_network"]["layers"]
+ assert saved[0] == before[0]
+ if kind == "population":
+ assert saved[1]["populations"] == [before[1]["populations"][1]]
+ assert saved[1]["connections"] == before[1]["connections"][1:3]
+ else:
+ assert len(saved) == 1
+ page.get_by_role("button", name="Undo (Ctrl+Z)", exact=True).click()
+ invalid = exported(page)["model"]["core"]["population_network"]["layers"]
+ assert invalid[1]["populations"][0]["population"]["level_taus"] == [7]
+ page.get_by_role("button", name="Undo (Ctrl+Z)", exact=True).click()
+ assert exported(page) == raw
+ assert not page.errors
+
+
+@pytest.mark.parametrize("decision", ["cancel", "stale", "unrelated"])
+def test_removal_repair_never_commits_a_stale_or_invalid_proposal(page, decision):
+ raw = two_layer_document()
+ open_design(page, raw)
+ invalid_population_times(page, 1, 0)
+ li = 0 if decision == "unrelated" else 1
+ page.get_by_role("button", name=f"Edit population layer{li}.i", exact=True).click()
+ page.get_by_role("button", name="Remove population", exact=True).click()
+ dialog = page.get_by_role("dialog", name="Remove population")
+ playwright.expect(dialog).to_be_visible(timeout=4000)
+ if decision == "stale":
+ page.evaluate("""async () => {
+ const {edit} = await import('./js/store.js');
+ await edit(cfg => { cfg.experiment.seed = 913; });
+ }""")
+ dialog.get_by_role(
+ "button", name="Cancel" if decision == "cancel" else "Remove", exact=True
+ ).click()
+ if decision != "cancel":
+ playwright.expect(page.locator(".toast.error").last).to_contain_text(
+ "design changed" if decision == "stale" else "level_taus"
+ )
+ actual = exported(page)
+ expected = raw["model"]["core"]["population_network"]["layers"]
+ expected[1]["populations"][0]["population"]["level_taus"] = [7]
+ assert actual["model"]["core"]["population_network"]["layers"] == expected
+ if decision == "stale":
+ assert actual["experiment"]["seed"] == 913
+ assert not page.errors
+
+
+def test_inspector_handles_a_population_removed_by_pending_undo(page):
+ page.get_by_role("button", name="I population", exact=True).click()
+ added = page.get_by_role("button", name="Edit population layer0.i2", exact=True)
+ playwright.expect(added).to_be_visible()
+ delay_next_response(page, "preview")
+ page.get_by_role("button", name="Undo (Ctrl+Z)", exact=True).click()
+ page.wait_for_selector("html[data-response-ready]")
+ added.click()
+ assert not page.errors
+ playwright.expect(
+ page.get_by_role("button", name="Remove population", exact=True)
+ ).not_to_be_visible()
+ release_response(page)
+ playwright.expect(added).to_have_count(0)
+ assert exported(page) == example("synthetic_population")
+ assert not page.errors
+
+
+def test_interrupted_inline_edit_names_the_action_the_user_can_retry(page):
+ page.get_by_role(
+ "button", name="Connection layer0.i to layer0.e, ff_inhibitory, same_step"
+ ).press("Enter")
+ seed = page.get_by_label("Seed", exact=True)
+ seed.fill("21")
+ seed.press("Enter")
+ page.evaluate("async () => (await import('./js/store.js')).topologyReady()")
+ delay_next_response(page, "preview")
+ probability = page.get_by_label("Connection probability", exact=True)
+ probability.fill("0.3")
+ probability.press("Enter")
+ page.wait_for_selector("html[data-response-ready]")
+ page.get_by_role("button", name="Undo (Ctrl+Z)", exact=True).click()
+ release_response(page)
+ playwright.expect(page.locator(".toast.error").last).to_contain_text("edit again")
+ assert exported(page) == example("synthetic_population")
+ assert not page.errors
+
+
+@pytest.mark.parametrize("intervening_undo", [False, True])
+def test_connection_dialog_repairs_uncovered_contacts_from_current_draft(
+ page, intervening_undo
+):
+ raw = two_layer_document()
+ layer = raw["model"]["core"]["population_network"]["layers"][1]
+ layer["connections"].pop()
+ layer["connections"][2]["target_levels"] = ["distal"]
+ field = "ff_inhibitory_synapses_by_level"
+ layer["populations"][1].setdefault("population", {})[field] = [4, 0, 0]
+ open_design(page, raw)
+ page.get_by_role("button", name="Edit population layer1.e", exact=True).click()
+ page.get_by_text("Set counts per level", exact=True).click()
+ count = page.get_by_role(
+ "spinbutton", name="Inhibitory contacts at level 1 · primary"
+ )
+ count.fill("2")
+ count.press("Enter")
+ playwright.expect(page.locator(".banner")).to_contain_text("depth 1")
+ if intervening_undo:
+ delay_next_response(page, "wiring")
+ page.get_by_role("button", name="Connection", exact=True).click()
+ dialog = page.get_by_role("dialog", name="Connect populations")
+ if intervening_undo:
+ page.wait_for_selector("html[data-response-ready]", timeout=5000)
+ page.get_by_role("button", name="Undo (Ctrl+Z)", exact=True).click()
+ release_response(page)
+ playwright.expect(page.locator(".toast.error").last).to_contain_text(
+ "design changed"
+ )
+ playwright.expect(dialog).not_to_be_visible()
+ assert exported(page) == raw
+ else:
+ playwright.expect(dialog).to_be_visible(timeout=4000)
+ dialog.get_by_label("Receiving population").select_option("layer1.e")
+ dialog.get_by_label("Source", exact=True).select_option("layer1.i")
+ dialog.get_by_role("button", name="Add connection").click()
+ playwright.expect(dialog).not_to_be_visible()
+ playwright.expect(page.locator(".banner")).to_be_hidden()
+ layers = exported(page)["model"]["core"]["population_network"]["layers"]
+ assert layers[1]["connections"] == [
+ *layer["connections"],
+ {"source": "i", "target": "e"},
+ ]
+ assert layers[1]["populations"][1]["population"][field] == [4, 2, 0]
+ assert not page.errors
diff --git a/apps/studio/tests/test_studio.py b/apps/studio/tests/test_studio.py
index 59cb905f..b1eb120e 100644
--- a/apps/studio/tests/test_studio.py
+++ b/apps/studio/tests/test_studio.py
@@ -53,6 +53,17 @@ def test_yaml_roundtrip_retains_unexposed_settings_and_random_state():
assert result["nodes"][1]["compartments_per_neuron"] == 7
+@pytest.mark.parametrize("source", ["input", "input_e", "input_i"])
+def test_preview_rejects_delayed_external_input_like_the_builder(source):
+ document = example("recurrent_decision_population")
+ layer = document["model"]["core"]["population_network"]["layers"][0]
+ layer["connections"].append(
+ {"source": source, "target": "pyr", "timing": "delayed"}
+ )
+ with pytest.raises(ValueError, match="population output"):
+ inspect_document(document)
+
+
def test_soma_only_preview_is_distinct_from_one_branch():
raw = example("synthetic_population")
raw["model"]["core"]["population_network"]["layers"][0]["populations"][1][
@@ -63,6 +74,46 @@ def test_soma_only_preview_is_distinct_from_one_branch():
assert result["nodes"][1]["compartments_per_neuron"] == 1
+@pytest.mark.parametrize("inherit", [False, True])
+@pytest.mark.parametrize("explicit_recurrence", [False, True])
+def test_preview_matches_native_credit_for_stepped_populations(
+ inherit, explicit_recurrence
+):
+ raw = example("synthetic_population")
+ layer = raw["model"]["core"]["population_network"]["layers"][0]
+ settings = layer["populations"][1].setdefault("population", {})
+ credit = layer["population_defaults"] if inherit else settings
+ credit["autograd_credit_mode"] = "soma_broadcast"
+ assert not inspect_document(raw)["layers"][0]["steps_through_time"]
+ initialize_model(config_from_mapping(raw).model)
+ if explicit_recurrence:
+ layer["recurrent"] = True
+ else:
+ # The other population makes the whole layer stepped. Neither
+ # definition violates the constraints of its own credit rule alone.
+ layer["populations"][0]["population"].update(
+ soma_feedback_enabled=True, autograd_credit_mode="exact"
+ )
+ for check in (
+ lambda: inspect_document(raw),
+ lambda: initialize_model(config_from_mapping(raw).model),
+ ):
+ with pytest.raises(ValueError, match=r"soma_broadcast.*exact"):
+ check()
+
+
+def test_response_times_follow_the_effective_population_dynamics():
+ raw = example("synthetic_population")
+ layer = raw["model"]["core"]["population_network"]["layers"][0]
+ assert not inspect_document(raw)["layers"][0]["steps_through_time"]
+ settings = layer["populations"][1].setdefault("population", {})
+ settings["soma_feedback_enabled"] = True
+ assert inspect_document(raw)["layers"][0]["steps_through_time"]
+ settings["level_taus"] = [10, 20]
+ with pytest.raises(ValueError, match="level_taus needs 3"):
+ inspect_document(raw)
+
+
def test_preview_keeps_projection_aliases_in_yaml_and_draws_the_resolved_pathway():
raw = example("synthetic_population")
core = raw["model"]["core"]
@@ -121,6 +172,47 @@ def test_configured_contacts_equal_the_synapses_of_the_built_model(document):
assert preview["synapses_total"] == model_resource_summary(model)["active_synapses"]
+@pytest.mark.parametrize(
+ "other_route", [None, {"enabled": False}, {"probability": 0.0}]
+)
+def test_preview_and_builder_reject_contacts_without_a_source_at_their_depth(
+ other_route,
+):
+ raw = _two_layer_document()
+ layer = raw["model"]["core"]["population_network"]["layers"][1]
+ layer["recurrent"] = True
+ target = layer["populations"][1].setdefault("population", {})
+ target["rec_inhibitory_synapses_by_level"] = [1, 2, 0]
+ layer["connections"].append(
+ {
+ "source": "layer0.i",
+ "target": "e",
+ "timing": "delayed",
+ "target_levels": ["distal"],
+ }
+ )
+ if other_route is not None:
+ layer["connections"].append(
+ {
+ "source": "i",
+ "target": "e",
+ "timing": "delayed",
+ "target_levels": ["primary"],
+ **other_route,
+ }
+ )
+ with pytest.raises(ValueError, match="depth 1"):
+ initialize_model(config_from_mapping(raw).model)
+ with pytest.raises(ValueError, match="depth 1"):
+ inspect_document(raw)
+
+ target["rec_inhibitory_synapses_by_level"] = [1, 0, 0]
+ preview = inspect_document(raw)
+ receiver = next(n for n in preview["nodes"] if n["id"] == "layer1.e")
+ assert receiver["received_per_level"]["rec_inhibitory"] == [0, 0, 1]
+ initialize_model(config_from_mapping(raw).model)
+
+
def test_invalid_keys_and_unresolved_composition_are_rejected():
raw = example("synthetic_population")
raw["model"]["core"]["biological_neuronn"] = True
@@ -153,6 +245,8 @@ def test_example_catalog_lists_the_tutorial_first_and_marks_downloads():
assert {item["name"] for item in catalog} == set(example_names())
by_name = {item["name"]: item for item in catalog}
assert by_name["mnist_population"]["download"] is True
+ assert by_name["contextual_remapping_population"]["download"] is True
+ assert by_name["contextual_remapping_population"]["recurrent"] is False
assert by_name["synthetic_population"]["download"] is False
assert by_name["adding_problem_gru"]["task"] == "regression"
assert by_name["recurrent_decision_population"]["recurrent"] is True
@@ -355,6 +449,20 @@ def test_progress_lines_become_partial_curves():
assert progress_from_log("no progress here") is None
+def test_presentation_stream_progress_keeps_accuracy_separate_from_loss():
+ log = (
+ "[PresentationStream] epoch=1/3 train_loss=3.9200 noisy_acc=0.0319 "
+ "clean_acc=0.0266\n"
+ "[PresentationStream] epoch=2/3 train_loss=3.8100 noisy_acc=0.0372"
+ )
+ progress = progress_from_log(log)
+ assert progress["epoch"] == 2 and progress["epochs"] == 3
+ assert progress["points"] == [
+ {"epoch": 1, "train_loss": 3.92, "valid_loss": None},
+ {"epoch": 2, "train_loss": 3.81, "valid_loss": None},
+ ]
+
+
def test_run_configurations_are_read_only_for_known_runs(tmp_path):
runs = Runs(tmp_path)
with pytest.raises(ValueError, match="No run"):
@@ -489,3 +597,30 @@ def test_inspection_matches_training_with_inferred_input_width(
"active_synapses",
):
assert summary[key] == trained[key]
+
+
+def test_wiring_repair_view_keeps_the_draft_budget_and_run_validation(studio):
+ raw = example("synthetic_population")
+ layer = raw["model"]["core"]["population_network"]["layers"][0]
+ layer["connections"][-1]["target_levels"] = ["distal"]
+ layer["populations"][1]["population"] = {
+ "ff_inhibitory_synapses_by_level": [4, 2, 0]
+ }
+ view, _ = studio.request("/api/wiring", {"config": raw})
+ target = next(node for node in view["nodes"] if node["id"] == "layer0.e")
+ assert target["configured_per_level"]["ff_inhibitory"] == [0, 2, 4]
+ assert target["received_per_level"]["ff_inhibitory"] == [0, 0, 4]
+ assert not {"config", "yaml", "validation"}.intersection(view)
+ for path, payload in (
+ ("/api/preview", {"config": raw}),
+ ("/api/run", {"config": raw, "kind": "inspect", "device": "cpu"}),
+ ):
+ with pytest.raises(urllib.error.HTTPError) as exc:
+ studio.request(path, payload)
+ assert exc.value.code == 400
+ assert "depth 1" in json.load(exc.value)["error"]
+ layer["populations"][1]["population"]["level_taus"] = [7]
+ with pytest.raises(urllib.error.HTTPError) as exc:
+ studio.request("/api/wiring", {"config": raw})
+ assert exc.value.code == 400
+ assert "level_taus" in json.load(exc.value)["error"]
diff --git a/docs/_static/studio/hybrid.png b/docs/_static/studio/hybrid.png
new file mode 100644
index 00000000..746bb0fe
Binary files /dev/null and b/docs/_static/studio/hybrid.png differ
diff --git a/docs/_static/studio/model_view.png b/docs/_static/studio/model_view.png
index 50bb4a9d..d527102e 100644
Binary files a/docs/_static/studio/model_view.png and b/docs/_static/studio/model_view.png differ
diff --git a/docs/_static/studio/recurrent_view.png b/docs/_static/studio/recurrent_view.png
index 26d0c6b5..46064e7f 100644
Binary files a/docs/_static/studio/recurrent_view.png and b/docs/_static/studio/recurrent_view.png differ
diff --git a/docs/cli_reference.rst b/docs/cli_reference.rst
index fd5324f0..d989183e 100644
--- a/docs/cli_reference.rst
+++ b/docs/cli_reference.rst
@@ -758,12 +758,12 @@ Entry point: ``dendritic_modeling.scripts.tools.export_example:main``
.. code-block:: text
usage: dendritic-example [-h] [--output OUTPUT]
- [{adding_problem_gru,mnist_population,recurrent_decision_population,structured_tree_synthetic,synthetic_population}]
+ [{adding_problem_gru,contextual_remapping_population,mnist_population,recurrent_decision_population,structured_tree_synthetic,synthetic_population}]
List or export a small installed DendriNet example.
positional arguments:
- {adding_problem_gru,mnist_population,recurrent_decision_population,structured_tree_synthetic,synthetic_population}
+ {adding_problem_gru,contextual_remapping_population,mnist_population,recurrent_decision_population,structured_tree_synthetic,synthetic_population}
Example to export. Omit to list examples.
options:
diff --git a/docs/index.rst b/docs/index.rst
index 41cac220..682125f6 100644
--- a/docs/index.rst
+++ b/docs/index.rst
@@ -21,12 +21,12 @@ data for one CPU epoch:
.. code-block:: bash
- python -m pip install dendritic-modeling==0.5.0
+ python -m pip install --upgrade dendritic-modeling
dendritic-example synthetic_population --output demo.yaml
dendritic-train demo.yaml --epochs 1
For a graphical first run, install the companion package with
-``python -m pip install dendrinet-studio==0.1.0`` and follow :ref:`studio-first-run`.
+``python -m pip install --upgrade dendrinet-studio`` and follow :ref:`studio-first-run`.
Every model has three parts: an **encoder** that prepares the input, a
**core** that holds the dendritic network (or a baseline), and a **decoder**
diff --git a/docs/installation.rst b/docs/installation.rst
index a48d1a82..313eefbe 100644
--- a/docs/installation.rst
+++ b/docs/installation.rst
@@ -22,22 +22,27 @@ the released core package:
.. code-block:: bash
- python -m pip install dendritic-modeling==0.5.0
+ python -m pip install --upgrade dendritic-modeling
python -m pip check
The Python import name is ``dendritic_modeling``. For a graphical editor,
-install ``dendrinet-studio==0.1.0`` and launch it locally:
+install ``dendrinet-studio`` and launch it locally:
.. code-block:: bash
- python -m pip install dendrinet-studio==0.1.0
+ python -m pip install --upgrade dendrinet-studio
dendrinet-studio --workspace my-runs
-Installing Studio on its own also installs a compatible core (0.5.x).
-See :ref:`studio-first-run` to train a synthetic network in the browser.
+Pip selects a compatible core when you install Studio. Studio 0.2.0 uses
+core 0.6.x and supports per-depth travel delays. Studio 0.1.0 uses core
+0.5.x. To check which pair you have, run
+``python -m pip show dendrinet-studio dendritic-modeling``.
+See :ref:`studio-first-run` to train a synthetic network in the browser or
+:ref:`studio-cluster-gpu` to use an allocated GPU from Open OnDemand, Cursor
+or SSH.
The published files are on the
-`core PyPI page `_ and the
-`Studio PyPI page `_.
+`core PyPI page `_ and the
+`Studio PyPI page `_.
Pip resolves PyTorch and torchvision as dependencies. To select Linux
CPU-only wheels or a particular CUDA build, install a compatible torch and
diff --git a/docs/population_networks.rst b/docs/population_networks.rst
index 1376a8a8..00fd49c1 100644
--- a/docs/population_networks.rst
+++ b/docs/population_networks.rst
@@ -35,7 +35,7 @@ configuration loads; the corresponding settings are population options (see
``layers[].connections[]``
Directed records from a source (the network input, a population of the same
layer or a population of another layer) to a population of the layer, read
- either in the same timestep or from the previous timestep.
+ either in the same timestep or after a configured number of updates.
``layers[].population_defaults`` and ``layers[].populations[].population``
Population options: synapse counts, integration rule, reactivation gates,
@@ -87,7 +87,7 @@ How a layer computes
~~~~~~~~~~~~~~~~~~~~
Each population has up to four input streams: the same-step streams
-``ff_excitatory`` and ``ff_inhibitory``, and the delayed (previous-timestep)
+``ff_excitatory`` and ``ff_inhibitory``, and the delayed
streams ``rec_excitatory`` and ``rec_inhibitory``. A connection adds its source
to one stream of its target: the network input and excitatory populations
enter an excitatory stream, inhibitory populations an inhibitory stream. The
@@ -171,7 +171,15 @@ directed connection into a population of that layer:
* - ``timing``
- ``same_step``
- ``same_step`` reads the source in the current timestep; ``delayed``
- reads its output from the previous timestep.
+ reads an earlier output (one update earlier by default).
+ * - ``delay_steps``
+ - 0 for same-step, 1 for delayed
+ - Integer travel delay shared by the contacted depths. A delayed
+ projection requires at least one update.
+ * - ``delay_steps_by_level``
+ - ``null``
+ - Alternative to ``delay_steps`` for a delayed projection. Supply one
+ positive integer per depth, from the most distal level to the soma.
* - ``pathway``
- from the source
- Input stream of the target: ``ff_excitatory`` or ``ff_inhibitory`` for
@@ -277,7 +285,7 @@ Cross-layer sources
A source of the form ``layer_name.population_name`` (a qualified source) reads
a population of another layer. Same-step qualified sources must come from
earlier layers. Delayed qualified sources may come from any other layer,
-including later layers, and read that population's previous-timestep output;
+including later layers, and read that population's output at the specified lag;
the target layer must set ``recurrent: true``. A qualified source that names
its own layer raises; use the plain population name instead.
@@ -312,9 +320,9 @@ Timing
Same-step connections between populations of a layer must form a directed
acyclic graph; a cycle such as ``i -> e`` together with ``e -> i`` raises when
the configuration loads. Delayed connections (``timing: delayed``) read the
-source's output from the previous timestep, so they may form cycles, including
+source's output from an earlier timestep, so they may form cycles, including
a population connected to itself. They require ``recurrent: true`` on the
-layer, and at the first timestep they read zeros. Mutual E/I interaction is
+layer. A source sample preceding the start of the sequence is zero. Mutual E/I interaction is
therefore written as one same-step direction and one delayed direction, or as
two delayed connections.
@@ -542,7 +550,8 @@ controls:
``model.core.population_network.layers[].dt``
The integration step :math:`\Delta t` of every population in the layer
- (default 1.0). A delayed connection always reads the previous step.
+ (default 1.0). All layers advance once per network update. Travel
+ delays count these updates; ``dt`` sets the target layer's time scale.
``tau_base`` and ``tau_ratio``
Per-level time constants when ``level_taus`` is empty:
@@ -560,9 +569,22 @@ controls:
``learnable_tau``
Learns one time constant per level, stored as its logarithm.
-``connections[].timing``
- ``delayed`` connections read the source output of the previous step;
- ``same_step`` connections read the current step.
+``connections[].delay_steps`` and ``delay_steps_by_level``
+ Travel delay selects the source sample before the receiving compartment
+ filters it. In a tree with two dendritic depths, a delayed projection
+ with ``delay_steps_by_level: [3, 2, 1]`` delivers the same source pulse
+ to the soma one update later, to primary branches two updates later,
+ and to distal branches three updates later. Each source can have its own
+ delay even when several share an excitatory or inhibitory contact budget.
+ ``target_levels`` still determines which depths have eligible contacts.
+ A uniform delay of one is the default. A same-step projection has zero delay.
+
+When processing a sequence in chunks, supply the returned hidden state to
+the next call to retain signals in transit. A fresh state starts with zero
+history. Longer delays retain additional source outputs in the receiving
+layer's state. A projection with ``probability: 0`` keeps its columns in
+the synapse mask but requires no history for that route. No additional
+synaptic weights are required.
Receptor traces (``synapse_types``), the spiking soma (``spike_tau``,
``spike_readout_tau``) and dendritic plateaus (``dendritic_spike_plateau_tau``)
diff --git a/docs/releases.rst b/docs/releases.rst
index 1c51a372..89285c93 100644
--- a/docs/releases.rst
+++ b/docs/releases.rst
@@ -25,11 +25,11 @@ normal installation of Studio can resolve its dependency. Pull requests and
pushes to ``develop`` build and test the packages without uploading to an
index. **TestPyPI uploads are publicly downloadable too.**
-The examples below use core **0.5.0** and Studio **0.1.0**. Substitute the
-approved versions for a new release. Both example versions are already on
-PyPI. For installation, see :doc:`installation`. For the paper's example
-configurations, data and scripts, see the
+The commands below stage and publish core **0.6.0** and Studio **0.2.0**.
+For the install commands readers should use, see :doc:`installation`.
+The empirical paper's examples and data remain attached to the
`v0.5.0 release `_.
+Its supplement records the versions used for training and for the worked examples.
1. Prepare the release pull request
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -37,7 +37,7 @@ configurations, data and scripts, see the
* Set the core version in ``pyproject.toml`` and
``src/dendritic_modeling/__init__.py``. Set the Studio version in
``apps/studio/pyproject.toml`` and ``apps/studio/src/dendrinet_studio/__init__.py``.
- For this stable pair, use ``dendritic_modeling>=0.5.0,<0.6`` in Studio's
+ For this pair, use ``dendritic_modeling>=0.6.0,<0.7`` in Studio's
dependencies. Include the release notes in ``CHANGELOG.md``.
* Push only the reviewed candidate branch and open its PR against ``develop``.
Review the package contents and any public study examples. The
@@ -49,7 +49,7 @@ configurations, data and scripts, see the
* Merge after review and passing CI. Record the merge commit from the PR
and verify the checks on ``develop``. The documentation workflow also
deploys the Sphinx site to the Pages branch on this push. The hosted page
- is the Studio manual. The application runs locally. Under **Settings →
+ is the Studio manual. Readers can run the application locally or in the linked personal Binder session. Under **Settings →
Pages**, verify the publishing source and access for the intended readers.
Before announcing public documentation, open the
`Studio guide `_
@@ -58,7 +58,8 @@ configurations, data and scripts, see the
2. Set up publishing access
~~~~~~~~~~~~~~~~~~~~~~~~~~~
-This one-time setup can be done while the PR is under review.
+Both projects already exist on both indices. Reuse their publishing settings.
+Review the environment restrictions and credentials before staging.
#. Use maintainer accounts on both `PyPI `_ and
`TestPyPI `_. The indices use separate accounts.
@@ -100,28 +101,49 @@ after verifying the published files.
3. Tag the reviewed merge
~~~~~~~~~~~~~~~~~~~~~~~~~
-From an authenticated clone, set ``release_commit`` to the merged PR's
-full commit SHA. Verify its ancestry and versions before creating tags. If
-the branch has advanced, keep the reviewed SHA.
+After the PR has merged and checks on ``develop`` pass, open its merge
+commit in GitHub and copy the **full commit SHA**. In an authenticated
+clone, set ``release_commit`` to that SHA. The example below retrieves it
+from PR 404 using the official GitHub CLI. The guard stops if the commit
+is absent from ``origin/develop``. Both tags point to the same commit even
+if another change has since landed on the branch.
.. code-block:: bash
- git fetch origin develop
- git merge-base --is-ancestor "$release_commit" origin/develop
- git show "${release_commit}:pyproject.toml"
- git show "${release_commit}:apps/studio/pyproject.toml"
- git tag -a v0.5.0 "$release_commit" -m "DendriNet 0.5.0"
- git tag -a studio-v0.1.0 "$release_commit" -m "DendriNet Studio 0.1.0"
- git push origin refs/tags/v0.5.0 refs/tags/studio-v0.1.0
-
-Use a remote configured for authorized pushes. The release check requires
-the tag to match the distribution's declared version and its commit to be
-in the history of ``origin/develop``. Pushing a tag alone does not upload files.
+ (
+ set -eu
+ repo=KempnerInstitute/DendriNet
+ release_commit=$(gh pr view 404 --repo "$repo" --json mergeCommit --jq '.mergeCommit.oid // empty')
+ test -n "$release_commit"
+ git fetch origin develop
+ git merge-base --is-ancestor "$release_commit" origin/develop
+ git show "${release_commit}:pyproject.toml" | grep -Fx 'version = "0.6.0"'
+ git show "${release_commit}:apps/studio/pyproject.toml" | grep -Fx 'version = "0.2.0"'
+ git tag -a v0.6.0 "$release_commit" -m "DendriNet 0.6.0"
+ git tag -a studio-v0.2.0 "$release_commit" -m "DendriNet Studio 0.2.0"
+ git push --atomic origin refs/tags/v0.6.0 refs/tags/studio-v0.2.0
+ )
+
+Use a remote configured for authorized pushes. If a push fails after the
+local tags are created, verify that both resolve to the reviewed commit
+with ``git rev-parse 'v0.6.0^{commit}' 'studio-v0.2.0^{commit}'``. Then
+repeat the push to the authorized remote. Pushing tags alone does not
+upload packages. After the tags appear on GitHub, open the Studio documentation’s
+Binder link and check that the tagged session opens before staging the packages.
+
+For a Studio-only release, bump the version in ``apps/studio/pyproject.toml``
+and ``apps/studio/src/dendrinet_studio/__init__.py`` together. Create only
+the matching ``studio-vX.Y.Z`` tag on the reviewed merge. Run the staging
+and promotion workflows below for ``distribution=studio`` using this tag.
+Install and test the staged Studio wheel with the published compatible core.
+Users with an earlier Studio install can upgrade it with
+``python -m pip install --upgrade dendrinet-studio``.
4. Stage and install both packages from TestPyPI
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-Use an authenticated GitHub CLI on your workstation. GitHub registers a
+Use the `official GitHub CLI `_ on your workstation.
+Run ``gh --version`` and ``gh auth status`` first. GitHub registers a
manually dispatched workflow from the repository's default branch, which
must already contain ``.github/workflows/package.yml``. Pass the **tag**
as the workflow ref. See the `GitHub manual dispatch guide
@@ -130,10 +152,11 @@ as the workflow ref. See the `GitHub manual dispatch guide
.. code-block:: bash
repo=KempnerInstitute/DendriNet
- gh workflow run package.yml --repo "$repo" --ref v0.5.0 \
- -f distribution=core -f target=testpypi
- gh workflow run package.yml --repo "$repo" --ref studio-v0.1.0 \
- -f distribution=studio -f target=testpypi
+ upload_auth=trusted-publisher # use project-token for environment-scoped tokens
+ gh workflow run package.yml --repo "$repo" --ref v0.6.0 \
+ -f distribution=core -f target=testpypi -f authentication="$upload_auth"
+ gh workflow run package.yml --repo "$repo" --ref studio-v0.2.0 \
+ -f distribution=studio -f target=testpypi -f authentication="$upload_auth"
In GitHub Actions, record the numeric **run ID** from each run's URL
(``/actions/runs/``) with its distribution and tag. Wait for both runs,
@@ -148,7 +171,7 @@ dependencies from the production index at installation.
. .venv/bin/activate
python -m pip download --index-url https://test.pypi.org/simple/ \
--only-binary=:all: --no-deps --dest wheels \
- 'dendritic-modeling==0.5.0' 'dendrinet-studio==0.1.0'
+ 'dendritic-modeling==0.6.0' 'dendrinet-studio==0.2.0'
python -m pip install --index-url https://pypi.org/simple/ wheels/*.whl
python -m pip check
dendritic-example synthetic_population --output demo.yaml
@@ -164,16 +187,19 @@ explains why dependencies are downloaded separately.
5. Promote core, then Studio
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-Set ``core_stage_id`` and ``studio_stage_id`` to the respective IDs from
-step 4. Run the first command and wait for a successful **publish** job.
-Then run the second and wait for it to succeed.
+In the same shell, set ``core_stage_id`` and ``studio_stage_id`` to the
+numeric run IDs from step 4. Use the authentication configured for the
+production environment. Run the core command first. Wait for the upload
+job to succeed and check the core version on PyPI before starting Studio.
.. code-block:: bash
- gh workflow run package.yml --repo "$repo" --ref v0.5.0 \
- -f distribution=core -f target=pypi -f staging_run_id="$core_stage_id"
- gh workflow run package.yml --repo "$repo" --ref studio-v0.1.0 \
- -f distribution=studio -f target=pypi -f staging_run_id="$studio_stage_id"
+ gh workflow run package.yml --repo "$repo" --ref v0.6.0 \
+ -f distribution=core -f target=pypi -f authentication="$upload_auth" \
+ -f staging_run_id="$core_stage_id"
+ gh workflow run package.yml --repo "$repo" --ref studio-v0.2.0 \
+ -f distribution=studio -f target=pypi -f authentication="$upload_auth" \
+ -f staging_run_id="$studio_stage_id"
For each distribution, CI verifies the staging run's repository, workflow,
release tag, commit and successful TestPyPI upload job. It downloads the
@@ -186,22 +212,20 @@ To compare the filenames and SHA-256 digests after an upload, run the
current verifier from a checkout at the release tag with its ``origin/develop``
ref. It reads package metadata from that commit. Use Python 3.11 or later
with ``packaging`` installed and the two files downloaded from the build.
-For the original v0.5.0 tag, set ``verifier`` to the absolute path of
-``setup/verify_release.py`` in the current maintainer checkout:
+From the checked-out release tag, run:
.. code-block:: bash
- python "$verifier" core refs/tags/v0.5.0 --staged dist/core --index testpypi
- python "$verifier" core refs/tags/v0.5.0 --staged dist/core --index pypi
-
-The workflow's project-token option is available on release tags that
-contain the updated workflow.
+ python setup/verify_release.py core refs/tags/v0.6.0 --staged dist/core --index testpypi
+ python setup/verify_release.py core refs/tags/v0.6.0 --staged dist/core --index pypi
+ python setup/verify_release.py studio refs/tags/studio-v0.2.0 --staged dist/studio --index testpypi
+ python setup/verify_release.py studio refs/tags/studio-v0.2.0 --staged dist/studio --index pypi
Finally, in a second empty environment, install only
-``python -m pip install dendrinet-studio==0.1.0``. Run ``python -m pip check``,
+``python -m pip install dendrinet-studio==0.2.0``. Run ``python -m pip check``,
inspect both installed versions with
``python -m pip show dendritic-modeling dendrinet-studio``, and repeat the
-local tutorial. The core-only install is ``python -m pip install dendritic-modeling==0.5.0``.
+local tutorial. The core-only install is ``python -m pip install dendritic-modeling==0.6.0``.
Link the two PyPI pages and the Studio guide in the release notes. Keep
research workflows on their recorded versions until their numerical
comparisons qualify a newer release.
diff --git a/docs/studio.rst b/docs/studio.rst
index 2c976695..ddebccba 100644
--- a/docs/studio.rst
+++ b/docs/studio.rst
@@ -4,10 +4,25 @@ DendriNet Studio
================
DendriNet Studio lets you draw a network, inspect the inputs to a neuron,
-train the model and compare runs in a browser on your computer. The editor
+train the model and compare runs in a browser. The editor
and the command line use the same experiment YAML and the same DendriNet
model builders and trainer. You can move a design between them at any point.
+**Try it online.** `Open DendriNet Studio 0.2.0
+`_
+to start a personal CPU session in your browser. Binder builds the environment
+on the first visit to a new revision. Once the editor opens, the two-class
+example is ready. Set **Training → Epochs** to ``1``, then choose **Train**.
+The example generates its own data.
+
+Use **YAML → Export** to save the configuration. In **Runs**, select your
+completed run and choose **Curves (CSV)** to save the training and validation
+history. Binder reclaims idle sessions and their workspace. For longer runs
+and persistent results, follow the local installation instructions below.
+The online link uses the Studio release tag, so each visitor starts with the same
+software and tutorial. Before the tag is available, the **Try it** link in
+`PR #404 `_ opens the review version.
+
.. contents:: On this page
:local:
:depth: 1
@@ -33,7 +48,7 @@ from PyPI. Pip installs the compatible core library and PyTorch.
.. code-block:: bash
- python -m pip install dendrinet-studio==0.1.0
+ python -m pip install --upgrade dendrinet-studio
dendrinet-studio --workspace my-runs
For an editable install, run ``python -m pip install -e . -e ./apps/studio``
@@ -69,20 +84,79 @@ its dependencies and any required datasets have been downloaded.
- Also accept requests addressed to ``NAME``, for a trusted proxy in
front of the local port. Repeatable.
-On a remote machine (a workstation or a cluster compute node), start Studio
-with ``--no-browser``, forward its port from your computer and open the
-printed address locally:
+.. _studio-cluster-gpu:
-.. code-block:: bash
+Train on a cluster GPU
+----------------------
+
+Studio trains on the machine where you start the server. To use a cluster
+GPU, start Studio inside a GPU allocation and open the editor from your
+browser. The public Binder demo runs on a CPU.
+
+**1. Open a terminal on an allocated GPU node.** If you already have a GPU
+session, use its terminal. Otherwise, choose one of these routes.
- # on the remote machine
- dendrinet-studio --workspace ~/studio-runs --no-browser
- # on your computer
- ssh -L 8765:127.0.0.1:8765 user@remote-host
+* **Browser only.** In Open OnDemand, choose **Interactive Apps → Remote
+ Desktop** and request one GPU on your lab's partition and account. For a
+ small example, four CPU cores, 16 GB of host memory and one hour are
+ sufficient. Launch the desktop and open a terminal inside it. On Harvard's
+ Cannon cluster, connect to the FASRC VPN first. The ``kempner_interactive``
+ partition provides 20 GB A100 slices. See the
+ `FASRC Remote Desktop guide `_
+ and the `Kempner partition guide `_.
+* **Slurm terminal.** From a login shell, run the following command with
+ your GPU partition and billing account in place of ``PARTITION`` and
+ ``ACCOUNT``. Once the allocation starts, ``hostname`` gives you the
+ compute node to use for port forwarding.
-Use the actual port printed by Studio on both sides of the tunnel. If a
-scheduler assigned a compute node, the tunnel must reach the machine running
-Studio. A new session prints a new token.
+ .. code-block:: bash
+
+ srun --partition=PARTITION --account=ACCOUNT --nodes=1 --ntasks=1 \
+ --gres=gpu:1 --cpus-per-task=4 --mem=16G --time=01:00:00 --pty bash -l
+
+**2. Start Studio on the compute node.** Activate a Python environment with
+a CUDA-enabled PyTorch build (see :doc:`installation`). Install Studio once
+in that environment. From a writable shared directory where you want to keep
+your runs, check that PyTorch can see the allocated device, then start Studio.
+
+.. code-block:: bash
+
+ python -m pip install dendrinet-studio
+ python -c "import torch; print(torch.cuda.get_device_name(0))" && \
+ dendrinet-studio --no-browser --threads 4 --workspace "$PWD/studio-runs"
+
+If the check fails, verify the GPU allocation and the PyTorch installation
+in that shell. Keep the Studio process running while you use the editor.
+
+**3. Open the editor.** Use the full printed URL, including the session
+token after ``#``.
+
+* **Open OnDemand.** Paste the URL into the browser **inside the remote
+ desktop**. This route needs no SSH tunnel.
+* **Cursor or VS Code.** Connect the editor's remote window to the
+ **allocated compute node**. In the **Ports** panel, choose **Forward a
+ Port** and enter Studio's printed port. Open the forwarded local address
+ in your laptop browser and append the printed ``#`` and token. If the
+ editor assigned a different local port, use the one shown in **Ports**.
+* **SSH.** From your laptop, the example below forwards port 8765 through
+ a login host to Studio on the compute host. Substitute your SSH username,
+ the two hostnames and the port Studio printed. Then open that URL in your
+ laptop browser. For a directly accessible workstation, omit
+ ``-J user@login-host`` and use the workstation as the destination.
+
+ .. code-block:: bash
+
+ ssh -N -o ExitOnForwardFailure=yes -J user@login-host \
+ -L 127.0.0.1:8765:127.0.0.1:8765 user@compute-host
+
+**4. Train and verify the device.** Choose **GPU if available** beside
+**Train**. Studio uses CPU by default, and a GPU request also falls back to
+CPU if PyTorch cannot see CUDA. After training, open ``model_resources.json``
+under the run's ``results`` directory. A GPU run records ``runtime_device``
+as ``cuda`` and gives the GPU model in ``cuda_device_name``. The
+``device`` field in ``studio_run.json`` records the requested mode
+(``auto`` or ``cpu``). You can select **CPU** for the next run in the same
+session. Stop Studio with Ctrl+C and end the allocation when you finish.
.. _studio-first-run:
@@ -110,6 +184,113 @@ Train your first network
``dendritic-train demo.yaml``. To get the original, unedited example
directly, use ``dendritic-example synthetic_population --output original.yaml``.
+.. _studio-connect:
+
+Connect populations and mix layer dynamics
+------------------------------------------
+
+The population editor in Studio 0.2.0 can put feedforward and recurrent
+layers in the same design. E and I identify the sign of a population's
+outgoing synapses. Timing identifies which source activity its target uses.
+
+#. Open the **Recurrent decision population network** example in **Model**.
+ Choose **Layer**, name the new layer ``readout``, choose **Feedforward**,
+ and select **Add layer**. The new populations receive the current output
+ of the first layer. An explicitly selected decoder layer stays selected.
+#. Select the inhibitory population ``readout.pv`` on the diagram. Choose
+ **Connect from this population**, then select ``circuit.pyr`` on the
+ diagram. The editor proposes **Delayed** for this feedback path.
+ Check the source, destination and inhibitory sign and choose **Add
+ connection**. The same operation is available through **Connect** on
+ the diagram toolbar, using menus for both populations.
+#. Expand **connections** under the receiving layer or select the line in
+ the diagram to inspect the route. The inhibitory line ends in a bar.
+ Dashes indicate a delayed route. The label gives its travel time in steps
+ (Δt for one step, a range for times that differ by depth). Use **Edit connection** to
+ rewire it or the inspector to set its probability and target depths.
+ Synapse counts belong to the receiving population and are shared by
+ sources on the same pathway. The editor asks for a positive budget
+ when its eligible depths have zero contacts. On a depth-restricted
+ route, this sets the budget only at the selected depths.
+ When a biological model receives both signs from external input, choose
+ matched afferent populations or separate channel groups in the editor.
+#. Open **YAML** to see the route under ``circuit.connections``, with source
+ ``readout.pv``, target ``pyr`` and ``timing: delayed``. Choose **Check
+ model** to construct it, or **Train** to run the sequence task.
+
+**Same step** uses current activity. Its source may be the layer input, a
+population in an earlier layer, or a local population if the route keeps
+same-step wiring acyclic. **Delayed** uses an earlier population output,
+one update earlier by default. It supports self-connections, loops within a layer and
+feedback from a later layer. Adding one enables recurrence on the receiving
+layer. A recurrent layer can receive both kinds of input. A feedforward
+layer can supply delayed activity to another layer.
+
+When copying a layer, Studio adds local inhibition only if the receiving E
+population has eligible inhibitory contacts. You can add an inhibitory
+route and set its budget later with **Add input source**. A layer that steps
+through time requires ``autograd_credit_mode: exact`` for every population,
+including settings inherited from layer defaults. Studio checks this before
+it saves the design.
+
+To combine excitation from two populations, select the receiving population
+and choose **Add input source**. Choose **Same step** and select the source
+by name. Repeat for the second source. For example, ``layer0.e`` and
+``layer0.e2`` can both supply ``layer1.e`` with recurrence off.
+**Previous readout** selects only the previous layer's designated readout.
+The neuron's **Synapse sources per neuron** table lists the two named
+sources together. A budget of four excitatory contacts per compartment
+selects four across both source pools; the split can vary among compartments.
+
+To connect at just one depth, select the connection, open **Placement**,
+turn off **All levels of the target**, and leave only the desired depth
+checked. Depth 0 is the soma. For a pathway with restricted target levels,
+each receiving depth with a positive contact count needs at least one enabled
+source with a positive connection probability. If changing a route would leave
+a depth without a source, Studio identifies the population, pathway and depth.
+Connect another source there first, or set the count to zero under
+**Synapses per compartment → Set counts per level**. **Use one count for all
+levels** restores the population's uniform counts. You can then override an
+individual depth; Undo reverses the two edits separately.
+
+Select a recurrent connection to see its source delay and the response
+time constant (τ) at each depth it contacts. To edit those times, select
+**Edit receiving population**, then **Time constants**. In the decision
+example, the soma, primary branches and distal branches of ``circuit.pyr``
+have response times of 10, 20 and 40 model time units. Larger values
+smooth the input over more time. Editing a row writes ``level_taus`` in
+the core's distal-to-soma order. **Use base and ratio** restores the
+geometric progression. **Learn one time constant per depth** shows the
+values that training starts from. For a uniform response time, use
+**Use base and ratio** and set **Ratio per outward depth** to 1.
+
+To change when a signal arrives, open **Edit connection → Travel delay**.
+Choose one whole number of steps for the projection, or select **Set delay
+by depth**. For example, enter 1 at the soma, 2 at the primary branches and
+3 at the distal branches. A signal emitted on update 0 then arrives on
+updates 1, 2 and 3. Select the finished connection to see travel steps and
+response τ side by side. Each projection has its own travel settings;
+all projections into a receiving depth share its compartment time constant.
+If you add a dendritic depth, its explicit travel delay starts at one step.
+The layer's **Time step dt** sets the target's integration time per update.
+Use a sequence with enough updates for the longest delay. Signals in transit
+at the end of a sequence are retained when the core's hidden state is carried
+into the next chunk.
+
+Configurable travel delays are available in Studio 0.2.0 with DendriNet
+0.6.x. Check the installed versions with
+``python -m pip show dendrinet-studio dendritic-modeling``. See
+:ref:`studio-install` for PyPI and source installation instructions.
+
+.. figure:: _static/studio/hybrid.png
+ :alt: Two layers with E and I populations. Current-step excitation flows
+ from the decision circuit into the readout layer. A dashed return
+ path ends in an inhibitory bar on the circuit's excitatory cells.
+ :width: 100%
+
+ The feedback circuit from the example above. Select a line or its entry
+ in the receiving layer's connection list to see its source and timing.
+
.. _studio-afferents:
Trace excitation and inhibition into a neuron
@@ -191,7 +372,7 @@ What Studio supports
the soma, the integration rule (shunting or the additive rules), leak,
dendritic gates, initialization, time constants and every other
population option; connections between populations with their timing
- (same step or delayed by one step), pathway, target levels,
+ (same step or delayed, including by depth), pathway, target levels,
probability and seed.
* - Structured dendritic trees (``dendritic_shunting``,
``dendritic_additive``, ``einet`` and the other structured types)
@@ -242,10 +423,39 @@ The installed examples cover each kind of model:
sequence.
* - ``mnist_population``
- The tutorial's network on MNIST digits; the first run downloads MNIST.
+ * - ``contextual_remapping_population``
+ - The same EMNIST character has a different target under each of 32 cues.
+ Two feedforward E/I layers receive the image and cue through the first layer.
Export any of them without Studio with
``dendritic-example --output my_model.yaml``.
+Contextual remapping on EMNIST
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+In **Model → Start from**, choose **Contextual remapping on EMNIST**.
+Each presentation has 784 image pixels and an uncorrupted one-hot cue.
+Gain and noise vary across presentations. The target is
+``(character class + cue index) % 47``. For example, the same class-10
+character has target 10 with cue 0 and target 11 with cue 1.
+
+Select the excitatory population **e** in the second layer to trace its
+inputs. It receives excitation from the first layer's **e** population and
+inhibition from both the first layer's **i** and its own layer's **i**.
+Both first-layer populations receive the external image and cue.
+Choose **CPU**, then **Check model** or **Train**. The first build or run
+downloads the EMNIST archive (about 536 MiB compressed) to the shared data
+cache. With EMNIST Balanced already cached, the template also runs offline.
+
+The short run demonstrates wiring and training. It uses 48 excitatory and
+18 inhibitory neurons per layer, fixed leak and three epochs of 1,024 freshly
+sampled presentations. Its trainable branch gates start from the slope and
+offset given in the YAML. For the paper's Figure 7 settings, the
+`empirical project `_
+provides the full shunting and additive configurations, the training-stream
+gate calibration and the library version used for those experiments. Use
+**YAML → Import** to explore either full-size network in Studio.
+
Working in Studio
-----------------
@@ -265,7 +475,7 @@ To extend a population network:
per cell. The **soma only** preset gives a point neuron. Use **Contacts
on the soma** when the design calls for direct somatic input.
#. Use **Connection** to choose a source and target. Set whether the
- connection carries current-step or previous-step activity and which
+ connection carries current or delayed activity and which
target depths receive it. Use **Synapses** on the receiving population
for the corresponding feedforward or recurrent E or I contact count.
#. Use **Layer** to extend the stack. Select a layer to choose its readout
@@ -273,6 +483,16 @@ To extend a population network:
network to choose which layer supplies the decoder.
An invalid edit is reported and the drawing keeps the last valid preview.
+If a depth has contacts but no source, select its connection and include
+that depth in **Placement**, add a source with **Connection**, or set the
+receiving count to zero. The connection editor reads the current draft's
+endpoints and budgets. You can also remove a population or layer containing an
+invalid setting. Studio checks the entire proposed design before saving a
+repair. **Undo** restores the previous draft, including the setting you removed.
+**Check model**, **Train**, **Export** and **Copy** wait for pending connection
+edits. If an edit is rejected, Studio shows the reason so you can correct it
+before trying the action again. Editing a disabled or zero-probability route
+preserves the contact budget it shares with other sources.
Small neurons are drawn in full when their branches fit. For large trees,
the neuron view draws representative branches and labels how many children
each represents. The caption gives the number drawn and the total, including
@@ -300,9 +520,11 @@ loader checks it before replacing the current design. If you continue typing
during validation, choose **Apply** again to use the latest text. Restoring
an unsaved design keeps its browser draft available across reloads. Syntax errors include
the line when the parser can identify it. **Import** opens a standalone
-experiment. **Export** writes its settings as YAML. Re-exporting preserves
-configuration values, including options without a graphical control.
-Comments and original formatting are lost. For a sweep, use
+experiment. **Export** and **Copy** use the current design, even immediately
+after **Undo** or **Redo**. If the editor contains unapplied changes, both use the text
+exactly as written. The generated YAML preserves configuration values,
+including options without a graphical control. Applying a file regenerates
+its formatting and omits its comments. For a sweep, use
``dendritic-sweep --config my_sweep.yaml --generate-only`` and import one
generated experiment. For a file that uses ``extends``, open an already
composed experiment with its parent settings included. See :ref:`config-extends`
@@ -369,7 +591,7 @@ Troubleshooting
* **Browser says the site cannot be reached.** Confirm the command is still
running and use its printed port. A browser on another computer needs a
- connection to that host (see :ref:`studio-install`). If the page opens but
+ connection to that host (see :ref:`studio-cluster-gpu`). If the page opens but
cannot reach the local service, reopen the complete URL with its current token.
* **The diagram looks valid but Check model fails.** The live preview validates
the configuration. The check also constructs the model with a sample from the
diff --git a/pyproject.toml b/pyproject.toml
index 9a67348c..5c248a0a 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "dendritic_modeling"
-version = "0.5.0"
+version = "0.6.0"
description = "DendriNet: PyTorch library for neural networks of dendritic neurons"
readme = "README_PYPI.md"
license = "MIT"
diff --git a/src/dendritic_modeling/__init__.py b/src/dendritic_modeling/__init__.py
index 202b2c88..e888c9db 100644
--- a/src/dendritic_modeling/__init__.py
+++ b/src/dendritic_modeling/__init__.py
@@ -38,7 +38,7 @@
logger = logger_manager.get_logger()
# Version information
-__version__ = "0.5.0"
+__version__ = "0.6.0"
_LAZY_SUBMODULES: set[str] = {
"analysis",
diff --git a/src/dendritic_modeling/analysis/utils/state_transition.py b/src/dendritic_modeling/analysis/utils/state_transition.py
index 28264107..24ba3b4a 100644
--- a/src/dendritic_modeling/analysis/utils/state_transition.py
+++ b/src/dendritic_modeling/analysis/utils/state_transition.py
@@ -146,7 +146,8 @@ class PopulationStateCodec:
The order is network layer order, population declaration order, the five
trace-bank names in ``TRACE_FIELDS`` order, level order within a bank, and
finally that population's delayed output. Dictionary insertion order in a
- runtime state therefore cannot change the vector convention.
+ runtime state therefore cannot change the vector convention. Extra travel-delay
+ histories follow each layer's populations in sorted source-name order.
"""
TRACE_FIELDS = _TRACE_FIELDS
@@ -304,6 +305,26 @@ def _validate_structure(
f"[batch, {expected_output_dim}], got {tuple(output.shape)}"
)
tensors.append(output)
+ histories = layer_state.delay_history or {}
+ if set(histories) != set(layer.delay_history_lengths):
+ raise ValueError(
+ f"layer {layer_index} travel-delay history keys differ"
+ )
+ for source in sorted(histories):
+ tensor = histories[source]
+ expected = (
+ layer.delay_history_lengths[source],
+ layer._source_dim(source),
+ )
+ if (
+ not isinstance(tensor, torch.Tensor)
+ or tensor.ndim != 3
+ or tuple(tensor.shape[1:]) != expected
+ ):
+ raise ValueError(
+ f"invalid delay_history shape for {source!r}, expected [batch, {expected}]"
+ )
+ tensors.append(tensor)
if not tensors:
raise ValueError("PopulationNetwork recurrent state has no tensors")
@@ -371,6 +392,23 @@ def _build_specs(
)
)
offset = stop
+ for source in sorted(layer_state.delay_history or {}):
+ tensor = tensors[tensor_index]
+ tensor_index += 1
+ stop = offset + tensor.numel()
+ specs.append(
+ StateTensorSpec(
+ layer_index=layer_index,
+ layer_name=self._layer_names[layer_index],
+ population_name=source,
+ field="delay_history",
+ level_index=None,
+ shape=tuple(tensor.shape),
+ start=offset,
+ stop=stop,
+ )
+ )
+ offset = stop
return tuple(specs)
def _ordered_tensors(
@@ -447,6 +485,15 @@ def unflatten(self, vector: torch.Tensor) -> list[PopulationLayerState]:
PopulationLayerState(
population_states=population_states,
outputs=outputs,
+ delay_history={
+ source: values[
+ f"layers[{layer_index}].{self._layer_names[layer_index]}.{source}.delay_history"
+ ]
+ for source in self.network.layers[
+ layer_index
+ ].delay_history_lengths
+ }
+ or None,
)
)
return rebuilt
diff --git a/src/dendritic_modeling/config/population_routing.py b/src/dendritic_modeling/config/population_routing.py
index c660520a..e868418c 100644
--- a/src/dendritic_modeling/config/population_routing.py
+++ b/src/dendritic_modeling/config/population_routing.py
@@ -33,3 +33,36 @@ def projection_pathway(timing: str, source_polarity: str, explicit: str) -> str:
"""An explicit pathway takes precedence over source polarity."""
prefix = "ff" if timing == "same_step" else "rec"
return explicit or f"{prefix}_{source_polarity}"
+
+
+def projection_delays(
+ timing: str,
+ delay_steps: int | None,
+ delay_steps_by_level: list[int] | None,
+ n_levels: int | None = None,
+) -> tuple[int, ...]:
+ """Validate travel times and return update counts in distal-to-soma order."""
+ if delay_steps_by_level is not None:
+ if delay_steps is not None or timing != "delayed":
+ raise ValueError(
+ "delay_steps_by_level requires delayed timing and no delay_steps"
+ )
+ if not isinstance(delay_steps_by_level, list) or not delay_steps_by_level:
+ raise ValueError(
+ "delay_steps_by_level must be a nonempty list of positive integers"
+ )
+ if any(type(step) is not int or step < 1 for step in delay_steps_by_level):
+ raise ValueError("delay_steps_by_level entries must be positive integers")
+ if n_levels is not None and len(delay_steps_by_level) != n_levels:
+ raise ValueError(
+ f"delay_steps_by_level needs {n_levels} values, distal to soma"
+ )
+ return tuple(delay_steps_by_level)
+ steps = int(timing == "delayed") if delay_steps is None else delay_steps
+ if type(steps) is not int:
+ raise ValueError("delay_steps must be an integer number of updates")
+ if timing == "delayed" and steps < 1:
+ raise ValueError("delay_steps must be positive for delayed connections")
+ if timing == "same_step" and steps != 0:
+ raise ValueError("same_step connections require zero delay_steps")
+ return (steps,) * (n_levels if n_levels is not None else 1)
diff --git a/src/dendritic_modeling/config/validation.py b/src/dendritic_modeling/config/validation.py
index 0c8f60e1..c2fad9a1 100644
--- a/src/dendritic_modeling/config/validation.py
+++ b/src/dendritic_modeling/config/validation.py
@@ -23,6 +23,7 @@
INPUT_POLARITIES as _EXTERNAL_POLARITIES,
canonical_input_source as _canonical_external_source,
population_readout,
+ projection_delays,
projection_pathway,
)
from dendritic_modeling.config.recurrence import _STRUCTURED_EI_TYPES
@@ -500,6 +501,11 @@ def _validate_population_network_connections(
layer_name = layer_names[layer_idx]
local_names = set(population_dims.get(layer_name, {}))
local_polarities = population_polarities.get(layer_name, {})
+ target_levels = {
+ pop.get("name"): len(_as_list(pop.get("branch_factors", [1]))) + 1
+ for pop in layer.get("populations", []) or []
+ if isinstance(pop, dict)
+ }
input_polarity = previous_readout_polarity
override = (
config.get("readout_population") if layer_name == readout_layer else None
@@ -531,6 +537,16 @@ def _validate_population_network_connections(
f"{target!r} is not a population"
)
continue
+ if "delay_steps" in connection or "delay_steps_by_level" in connection:
+ try:
+ projection_delays(
+ timing,
+ connection.get("delay_steps"),
+ connection.get("delay_steps_by_level"),
+ target_levels.get(target),
+ )
+ except ValueError as exc:
+ errors.append(f"{layer_name} connection {source}->{target}: {exc}")
if timing == _DELAYED and not bool(layer.get("recurrent", False)):
errors.append(
f"population_network layer {layer_name!r} delayed connection "
diff --git a/src/dendritic_modeling/examples/contextual_remapping_population.yaml b/src/dendritic_modeling/examples/contextual_remapping_population.yaml
new file mode 100644
index 00000000..f0895e04
--- /dev/null
+++ b/src/dendritic_modeling/examples/contextual_remapping_population.yaml
@@ -0,0 +1,172 @@
+# Contextual remapping on EMNIST. One of 32 cues changes the required answer
+# for the same character. Two feedforward layers each contain excitatory and
+# inhibitory shunting neurons. Compact CPU tutorial; downloads EMNIST once.
+config_version: 4
+experiment:
+ seed: 62000
+ train_valid_split: 0.0
+ checkpointing:
+ enabled: false
+data:
+ dataset_name: contextual_remapping
+ dataset_params:
+ contextual_remapping:
+ download: true
+ generator_device: cpu
+ num_contexts: 32
+ context_scale: 8.0
+ gain_min: 0.05
+ gain_max: 20.0
+ noise_divisor_min: 1.0
+ noise_divisor_max: 4.0
+ pool_per_class: 200
+ validation_per_class: 4
+model:
+ task: classification
+ encoder:
+ type: identity
+ params:
+ input_dim: 816
+ core:
+ type: population_network
+ biological_neuron: true
+ population_network:
+ # 784 pixels followed by an uncorrupted 32-channel cue.
+ input_dim: 816
+ input_transform: nonnegative
+ layers:
+ - name: layer0
+ readout_population: e
+ population_defaults:
+ ff_excitatory_synapses: 40
+ ff_excitatory_synapses_by_level: [40, 40, 0]
+ ff_inhibitory_synapses: 4
+ rec_excitatory_synapses: 0
+ rec_inhibitory_synapses: 0
+ topk_type: standard
+ weight_transform: exp
+ use_shunting: true
+ leak_conductance: 1.0
+ learnable_leak: false
+ reactivate: true
+ reactivation_type: param_tanh
+ reactivation_init_m: 1.5
+ reactivation_init_b: 0.5
+ reactivation_init_policy: fixed
+ dbl_init_method: analytical_expectation
+ initial_child_conductance: 1.0
+ efficient_blocklinear: true
+ somatic_synapses: true
+ adaptive_initialization: false
+ populations:
+ - name: i
+ n_neurons: 18
+ polarity: inhibitory
+ branch_factors: [3, 2]
+ population:
+ ff_inhibitory_synapses_by_level: [0, 0, 0]
+ - name: e
+ n_neurons: 48
+ polarity: excitatory
+ branch_factors: [3, 2]
+ population:
+ ff_inhibitory_synapses_by_level: [4, 4, 6]
+ connections:
+ - {source: input, target: i}
+ - {source: input, target: e}
+ - {source: i, target: e}
+ - name: layer1
+ readout_population: e
+ population_defaults:
+ ff_excitatory_synapses: 40
+ ff_excitatory_synapses_by_level: [40, 40, 0]
+ ff_inhibitory_synapses: 4
+ ff_inhibitory_synapses_by_level: [4, 4, 4]
+ rec_excitatory_synapses: 0
+ rec_inhibitory_synapses: 0
+ topk_type: standard
+ weight_transform: exp
+ use_shunting: true
+ leak_conductance: 1.0
+ learnable_leak: false
+ reactivate: true
+ reactivation_type: param_tanh
+ reactivation_init_m: 1.5
+ reactivation_init_b: 0.5
+ reactivation_init_policy: fixed
+ dbl_init_method: analytical_expectation
+ initial_child_conductance: 1.0
+ efficient_blocklinear: true
+ somatic_synapses: true
+ adaptive_initialization: false
+ populations:
+ - name: i
+ n_neurons: 18
+ polarity: inhibitory
+ branch_factors: [3, 2]
+ - name: e
+ n_neurons: 48
+ polarity: excitatory
+ branch_factors: [3, 2]
+ connections:
+ - {source: layer0.e, target: i}
+ - {source: layer0.e, target: e}
+ - {source: layer0.i, target: i}
+ - {source: layer0.i, target: e}
+ - {source: i, target: e}
+ decoder:
+ type: MLP
+ params:
+ hidden_dims: []
+ output_dim: 47
+ output_init: xavier_uniform
+training:
+ main:
+ strategy: presentation_stream
+ common:
+ epochs: 3
+ batch_size: 64
+ loss_function: ce
+ early_stopping: false
+ load_best_state_dict: true
+ lr_schedule: cosine
+ grad_clip_value: 0.0
+ weight_boosting: false
+ synapse_decay_rate: 0.01
+ use_amp: false
+ param_groups:
+ lr: 0.002
+ split_params: true
+ topk_lr: 0.002
+ blocklinear_lr: 0.002
+ reactivation_lr: 0.002
+ decoder_lr: 0.002
+ print_every: 1
+ suppress_prints: false
+ plot_losses: false
+ num_workers: 0
+ optimizer:
+ name: adam
+ lr: 0.002
+ weight_decay: 0.0
+ strategies:
+ presentation_stream:
+ presentations_per_epoch: 1024
+ lr_terminal_multiplier: 0.01
+ evaluation_batch_size: 64
+ encoder:
+ strategy: standard
+ common:
+ epochs: 0
+analysis:
+ performance_analysis:
+ enabled: true
+ final_splits: [valid]
+ params:
+ accuracy: true
+ categorical_loglikelihood: true
+outputs:
+ run_name: contextual_remapping_population
+ results_dir: outputs
+distributed:
+ mode: none
diff --git a/src/dendritic_modeling/networks/architectures/recurrent/population_common.py b/src/dendritic_modeling/networks/architectures/recurrent/population_common.py
index a5fdf2ff..da046ea2 100644
--- a/src/dendritic_modeling/networks/architectures/recurrent/population_common.py
+++ b/src/dendritic_modeling/networks/architectures/recurrent/population_common.py
@@ -144,10 +144,29 @@ def population_requires_temporal_state(pop_config: PopulationConfig) -> bool:
)
+def validate_stepped_credit_modes(
+ name: str, populations: dict[str, PopulationConfig]
+) -> None:
+ """All populations in a layer that steps through time need exact gradients."""
+ broadcast = sorted(
+ key
+ for key, pop in populations.items()
+ if pop.autograd_credit_mode.lower() != "exact"
+ )
+ if broadcast:
+ raise ValueError(
+ f"population_network layer {name!r} steps its populations through time, "
+ f"but {broadcast} set autograd_credit_mode='soma_broadcast', which "
+ "applies only to feedforward layers. Set autograd_credit_mode to 'exact' "
+ "for stepped populations."
+ )
+
+
__all__ = [
"PopulationDefinitionConfig",
"as_population_definition_config",
"population_config_from_definition",
"population_level_dims",
"population_requires_temporal_state",
+ "validate_stepped_credit_modes",
]
diff --git a/src/dendritic_modeling/networks/architectures/recurrent/population_configs.py b/src/dendritic_modeling/networks/architectures/recurrent/population_configs.py
index c37a6246..92addc66 100644
--- a/src/dendritic_modeling/networks/architectures/recurrent/population_configs.py
+++ b/src/dendritic_modeling/networks/architectures/recurrent/population_configs.py
@@ -6,6 +6,7 @@
from typing import Any
from dendritic_modeling.config.base import BaseConfig
+from dendritic_modeling.config.population_routing import projection_delays
from dendritic_modeling.networks.architectures.recurrent.population_common import (
PopulationDefinitionConfig,
)
@@ -43,6 +44,10 @@ class PopulationProjectionConfig(BaseConfig):
# "primary" (children of the soma), "distal" (outermost level) or depths
# from the soma (0 = soma). None contacts every level.
target_levels: list[str | int] | None = None
+ # Whole network updates before source activity reaches this projection.
+ # Write a common delay or one delay per target level, distal through soma.
+ delay_steps: int | None = None
+ delay_steps_by_level: list[int] | None = None
def __post_init__(self) -> None:
self.source = str(self.source)
@@ -58,6 +63,7 @@ def __post_init__(self) -> None:
"connection timing must be 'same_step' or 'delayed', "
f"got {self.timing!r}"
)
+ projection_delays(self.timing, self.delay_steps, self.delay_steps_by_level)
if self.probability is not None:
self.probability = float(self.probability)
if self.probability < 0.0 or self.probability > 1.0:
diff --git a/src/dendritic_modeling/networks/architectures/recurrent/population_delays.py b/src/dendritic_modeling/networks/architectures/recurrent/population_delays.py
new file mode 100644
index 00000000..f0a67f09
--- /dev/null
+++ b/src/dendritic_modeling/networks/architectures/recurrent/population_delays.py
@@ -0,0 +1,106 @@
+"""Deliver past population outputs to existing synapses without changing their weights."""
+
+from __future__ import annotations
+
+from collections import defaultdict
+from dataclasses import dataclass
+
+import torch
+
+from dendritic_modeling.config.population_routing import projection_delays
+from dendritic_modeling.networks.architectures.recurrent.dendritic_geometry import (
+ resolve_synapses_by_level,
+)
+from dendritic_modeling.networks.architectures.recurrent.ei_config import (
+ PopulationConfig,
+)
+from dendritic_modeling.networks.architectures.recurrent.population_configs import (
+ PopulationProjectionConfig,
+)
+
+
+@dataclass(frozen=True)
+class DelayedStream:
+ """One vector of source ages for each distinct timing pattern in a pathway."""
+
+ sources: tuple[str, ...]
+ patterns: tuple[tuple[int, ...], ...]
+ level_indices: tuple[int, ...]
+
+ def read(
+ self, previous: list[torch.Tensor], history: dict[str, torch.Tensor] | None
+ ) -> torch.Tensor | tuple[torch.Tensor, ...]:
+ if history is None:
+ raise ValueError(
+ "This population network requires its multi-step delay history"
+ )
+ streams = []
+ for pattern in self.patterns:
+ values = [
+ value if age == 1 else history[source][:, age - 2, :]
+ for source, value, age in zip(self.sources, previous, pattern)
+ ]
+ streams.append(values[0] if len(values) == 1 else torch.cat(values, dim=-1))
+ if len(streams) == 1:
+ return streams[0]
+ return tuple(streams[index] for index in self.level_indices)
+
+
+def plan_delayed_streams(
+ connections: list[PopulationProjectionConfig],
+ populations: dict[str, PopulationConfig],
+) -> tuple[dict[tuple[str, str], DelayedStream], dict[str, int]]:
+ """Group equal delays across levels and retain older outputs only where used."""
+ by_stream = defaultdict(list)
+ history_lengths: dict[str, int] = {}
+ for conn in connections:
+ if conn.timing != "delayed":
+ continue
+ pop = populations[conn.target]
+ n = len(pop.branch_factors) + 1
+ delays = projection_delays(
+ conn.timing, conn.delay_steps, conn.delay_steps_by_level, n
+ )
+ if not conn.enabled:
+ continue
+ # A zero-probability source still occupies its input columns, but
+ # its mask is empty at every depth, so no older samples are needed.
+ if conn.probability == 0:
+ delays = (1,) * n
+ elif max(delays) > 1:
+ depths = conn.target_depths(n)
+ field = f"{conn.pathway}_synapses"
+ contacts = resolve_synapses_by_level(
+ per_level=getattr(pop, field + "_by_level"),
+ fallback=getattr(pop, field),
+ n_levels=n,
+ field_name=field + "_by_level",
+ )
+ delays = tuple(
+ (
+ age
+ if count
+ and (depth != 0 or pop.somatic_synapses)
+ and (depths is None or depth in depths)
+ else 1
+ )
+ for age, count, depth in zip(delays, contacts, reversed(range(n)))
+ )
+ if max(delays) > 1:
+ history_lengths[conn.source] = max(
+ history_lengths.get(conn.source, 0), max(delays) - 1
+ )
+ by_stream[conn.target, conn.pathway].append((conn.source, delays))
+
+ streams = {}
+ for key, routes in by_stream.items():
+ sources, delays_by_route = zip(*routes)
+ if all(max(delays) == 1 for delays in delays_by_route):
+ continue
+ patterns_by_level = tuple(zip(*delays_by_route))
+ patterns = tuple(dict.fromkeys(patterns_by_level))
+ indices = {pattern: i for i, pattern in enumerate(patterns)}
+ streams[key] = DelayedStream(
+ sources, patterns, tuple(indices[p] for p in patterns_by_level)
+ )
+ return streams, history_lengths
diff --git a/src/dendritic_modeling/networks/architectures/recurrent/population_layer.py b/src/dendritic_modeling/networks/architectures/recurrent/population_layer.py
index dcc80529..249dd74b 100644
--- a/src/dendritic_modeling/networks/architectures/recurrent/population_layer.py
+++ b/src/dendritic_modeling/networks/architectures/recurrent/population_layer.py
@@ -28,6 +28,7 @@
population_config_from_definition as _population_config_from_definition,
population_level_dims as _population_level_dims,
population_requires_temporal_state as _population_requires_temporal_state,
+ validate_stepped_credit_modes,
)
from dendritic_modeling.networks.architectures.recurrent.population_configs import (
PopulationLayerConfig,
@@ -45,6 +46,9 @@
_REC_INH,
_SAME_STEP,
)
+from dendritic_modeling.networks.architectures.recurrent.population_delays import (
+ plan_delayed_streams,
+)
from dendritic_modeling.networks.architectures.recurrent.population_sources import (
_as_projection_config,
_canonical_external_source,
@@ -74,7 +78,7 @@ class PopulationLayer(nn.Module):
"""A directional population-network layer.
Same-step population-to-population edges must form a DAG. Delayed edges use
- previous-timestep outputs and may be cyclic.
+ earlier source outputs and may be cyclic.
"""
def __init__(
@@ -229,6 +233,9 @@ def __init__(
dt=config.dt,
)
+ self._delay_streams, self.delay_history_lengths = plan_delayed_streams(
+ self.connections, self.population_configs
+ )
self.output_dim = self._population_dims[self.readout_population]
self._is_recurrent = (
self.recurrent
@@ -238,17 +245,7 @@ def __init__(
if self._is_recurrent: # forward() steps every population
for population in self.populations.values():
population.prepare_stepped_gradient_scaling()
- broadcast = sorted(
- name
- for name, pop_cfg in self.population_configs.items()
- if str(pop_cfg.autograd_credit_mode).lower() != "exact"
- )
- if self._is_recurrent and broadcast:
- raise ValueError(
- f"population_network layer {config.name!r} steps its populations "
- f"through time, but {broadcast} set autograd_credit_mode="
- "'soma_broadcast', which applies only to feedforward layers"
- )
+ validate_stepped_credit_modes(config.name, self.population_configs)
# Tensors of the last forward pass kept for analyses; copies and pickles
# hold them detached (networks.utils.forward_caches).
@@ -765,6 +762,17 @@ def init_state(
return PopulationLayerState(
population_states=population_states,
outputs=outputs,
+ delay_history={
+ source: torch.zeros(
+ batch_size,
+ length,
+ self._source_dim(source),
+ device=device,
+ dtype=dtype,
+ )
+ for source, length in self.delay_history_lengths.items()
+ }
+ or None,
)
def _collect_stream(
@@ -777,7 +785,8 @@ def _collect_stream(
delayed_external_inputs: dict[str, torch.Tensor] | None,
current_outputs: dict[str, torch.Tensor],
previous_outputs: dict[str, torch.Tensor],
- ) -> torch.Tensor | None:
+ delay_history: dict[str, torch.Tensor] | None = None,
+ ) -> torch.Tensor | tuple[torch.Tensor, ...] | None:
values = []
source_outputs = current_outputs if timing == _SAME_STEP else previous_outputs
for source in self._stream_sources(target, timing, pathway):
@@ -795,6 +804,10 @@ def _collect_stream(
values.append(source_inputs[source])
else:
values.append(source_outputs[source])
+ if timing == _DELAYED and self._delay_streams:
+ plan = self._delay_streams.get((target, pathway))
+ if plan is not None:
+ return plan.read(values, delay_history)
return _concat_or_none(values)
def forward(
@@ -890,6 +903,7 @@ def step(
delayed_external_inputs=delayed_external_inputs,
current_outputs=current_outputs,
previous_outputs=state.outputs,
+ delay_history=state.delay_history,
)
rec_inh = self._collect_stream(
target=name,
@@ -899,6 +913,7 @@ def step(
delayed_external_inputs=delayed_external_inputs,
current_outputs=current_outputs,
previous_outputs=state.outputs,
+ delay_history=state.delay_history,
)
if x_ff is None:
raise ValueError(
@@ -914,9 +929,25 @@ def step(
current_outputs[name] = out
new_population_states[name] = new_state
+ history = None
+ if self.delay_history_lengths:
+ # Each planned stream has already read its history. Rotate it only
+ # after all populations have read the same preceding network update.
+ previous = {**state.outputs, **delayed_external_inputs}
+ history = {
+ source: torch.cat(
+ (
+ previous[source].unsqueeze(1),
+ state.delay_history[source][:, :-1, :],
+ ),
+ dim=1,
+ )
+ for source in self.delay_history_lengths
+ }
new_layer_state = PopulationLayerState(
population_states=new_population_states,
outputs=current_outputs,
+ delay_history=history,
)
self._last_outputs = current_outputs
if self.store_routing:
diff --git a/src/dendritic_modeling/networks/architectures/recurrent/population_state.py b/src/dendritic_modeling/networks/architectures/recurrent/population_state.py
index 87129cd6..04f247eb 100644
--- a/src/dendritic_modeling/networks/architectures/recurrent/population_state.py
+++ b/src/dendritic_modeling/networks/architectures/recurrent/population_state.py
@@ -15,6 +15,9 @@ class PopulationLayerState:
population_states: dict[str, DendriNetState]
outputs: dict[str, torch.Tensor]
+ # Supplied one-step-old source activities from earlier updates, newest first.
+ # Each tensor has shape [batch, extra delay steps, source neurons].
+ delay_history: dict[str, torch.Tensor] | None = None
def detach(self) -> PopulationLayerState:
return PopulationLayerState(
@@ -22,6 +25,11 @@ def detach(self) -> PopulationLayerState:
name: state.detach() for name, state in self.population_states.items()
},
outputs={name: output.detach() for name, output in self.outputs.items()},
+ delay_history=(
+ {name: v.detach() for name, v in self.delay_history.items()}
+ if self.delay_history
+ else None
+ ),
)
def clone(self) -> PopulationLayerState:
@@ -30,6 +38,11 @@ def clone(self) -> PopulationLayerState:
name: state.clone() for name, state in self.population_states.items()
},
outputs={name: output.clone() for name, output in self.outputs.items()},
+ delay_history=(
+ {name: v.clone() for name, v in self.delay_history.items()}
+ if self.delay_history
+ else None
+ ),
)
def to(self, device: torch.device) -> PopulationLayerState:
@@ -38,6 +51,11 @@ def to(self, device: torch.device) -> PopulationLayerState:
name: state.to(device) for name, state in self.population_states.items()
},
outputs={name: output.to(device) for name, output in self.outputs.items()},
+ delay_history=(
+ {name: v.to(device) for name, v in self.delay_history.items()}
+ if self.delay_history
+ else None
+ ),
)
diff --git a/src/dendritic_modeling/networks/architectures/recurrent/stateful_dendrinet.py b/src/dendritic_modeling/networks/architectures/recurrent/stateful_dendrinet.py
index f21f6226..574ea156 100644
--- a/src/dendritic_modeling/networks/architectures/recurrent/stateful_dendrinet.py
+++ b/src/dendritic_modeling/networks/architectures/recurrent/stateful_dendrinet.py
@@ -951,8 +951,8 @@ def step(
self,
x: torch.Tensor,
inhibitory_input: Optional[torch.Tensor] = None,
- recurrent_input: Optional[torch.Tensor] = None,
- rec_inhibitory_input: Optional[torch.Tensor] = None,
+ recurrent_input: torch.Tensor | tuple[torch.Tensor, ...] | None = None,
+ rec_inhibitory_input: torch.Tensor | tuple[torch.Tensor, ...] | None = None,
state: Optional[DendriNetState] = None,
) -> tuple[torch.Tensor, DendriNetState]:
"""Recurrent step with per-level trace integration.
@@ -960,8 +960,9 @@ def step(
Args:
x: FF excitatory input [batch, excitatory_input_dim].
inhibitory_input: FF inhibitory input [batch, inhibitory_input_dim].
- recurrent_input: Recurrent excitatory input [batch, rec_e_dim].
- rec_inhibitory_input: Recurrent inhibitory input [batch, rec_i_dim].
+ recurrent_input: Recurrent excitatory input [batch, rec_e_dim],
+ shared across levels or one tensor per level (distal to soma).
+ rec_inhibitory_input: Recurrent inhibitory input with the same layout.
state: Previous DendriNetState (auto-initialized if None).
Returns:
@@ -974,6 +975,12 @@ def step(
"gradients only in the feedforward forward; a stepped (recurrent) "
"population would train with exact gradients"
)
+ for name, stream in (
+ ("recurrent_input", recurrent_input),
+ ("rec_inhibitory_input", rec_inhibitory_input),
+ ):
+ if isinstance(stream, tuple) and len(stream) != self.n_levels:
+ raise ValueError(f"{name} needs one tensor per level, distal to soma")
batch_size = x.shape[0]
device = x.device
dtype = x.dtype
@@ -1006,8 +1013,16 @@ def step(
layer=layer,
x=x,
inhibitory_input=inhibitory_input,
- recurrent_input=recurrent_input,
- rec_inhibitory_input=rec_inhibitory_input,
+ recurrent_input=(
+ recurrent_input[level_idx]
+ if isinstance(recurrent_input, tuple)
+ else recurrent_input
+ ),
+ rec_inhibitory_input=(
+ rec_inhibitory_input[level_idx]
+ if isinstance(rec_inhibitory_input, tuple)
+ else rec_inhibitory_input
+ ),
batch_size=batch_size,
level_dim=self._level_dims[level_idx],
device=device,
diff --git a/tests/test_installed_examples.py b/tests/test_installed_examples.py
index 9a1bd2fa..589b5326 100644
--- a/tests/test_installed_examples.py
+++ b/tests/test_installed_examples.py
@@ -2,6 +2,8 @@
from __future__ import annotations
+import json
+import math
import sys
import pytest
@@ -52,6 +54,42 @@ def test_examples_cover_the_model_kinds_studio_documents():
assert kinds & {"dendritic_shunting", "einet", "dendritic_additive"}
+def test_contextual_example_trains_from_a_fresh_stream_without_a_checkpoint(
+ tmp_path, monkeypatch
+):
+ from dendritic_modeling.datasets import contextual_remapping
+ from dendritic_modeling.scripts.script_utils import setup_utils
+ from dendritic_modeling.scripts.training import train_experiments
+
+ def character_fixture(root, *, train, **kwargs):
+ labels = torch.arange(47).repeat(3 if train else 1)
+ rng = torch.Generator().manual_seed(int(train))
+ return torch.rand(len(labels), 784, generator=rng), labels
+
+ monkeypatch.setattr(contextual_remapping, "load_emnist_balanced", character_fixture)
+ monkeypatch.setattr(torch.cuda, "is_available", lambda: False)
+ monkeypatch.setattr(
+ setup_utils.logger_manager, "set_log_directory", lambda *_: None
+ )
+ raw = yaml.safe_load(example_text("contextual_remapping_population"))
+ raw["data"]["dataset_params"]["contextual_remapping"].update(
+ pool_per_class=1, validation_per_class=1
+ )
+ main = raw["training"]["main"]
+ main["common"].update(epochs=1, batch_size=8)
+ main["strategies"]["presentation_stream"]["presentations_per_epoch"] = 8
+ raw["outputs"]["results_dir"] = str(tmp_path / "results")
+ path = tmp_path / "model.yaml"
+ path.write_text(yaml.safe_dump(raw))
+ train_experiments.main(str(path))
+
+ (metrics_path,) = (tmp_path / "results").rglob("metrics.jsonl")
+ epoch = json.loads(metrics_path.read_text())
+ assert epoch["epoch"] == 1 and math.isfinite(epoch["train_loss"])
+ assert set(epoch["validation"]) == {"noisy", "clean"}
+ assert all(math.isfinite(v["loss"]) for v in epoch["validation"].values())
+
+
def test_export_never_overwrites_existing_file(tmp_path, monkeypatch):
target = tmp_path / "example.yaml"
target.write_text("keep me")
diff --git a/tests/test_population_delays.py b/tests/test_population_delays.py
new file mode 100644
index 00000000..ebc808a0
--- /dev/null
+++ b/tests/test_population_delays.py
@@ -0,0 +1,391 @@
+"""Travel times affect which source sample each existing synapse receives."""
+
+from contextlib import ExitStack
+from unittest.mock import patch
+
+import pytest
+import torch
+import yaml
+
+from dendritic_modeling.analysis.utils.state_transition import PopulationStateCodec
+from dendritic_modeling.config import config_from_mapping
+from dendritic_modeling.examples import example_text
+from dendritic_modeling.networks.architectures.recurrent import (
+ PopulationNetwork,
+ PopulationNetworkConfig,
+)
+
+
+def _population(name, polarity="excitatory", factors=()):
+ return {
+ "name": name,
+ "polarity": polarity,
+ "n_neurons": 1,
+ "branch_factors": list(factors),
+ }
+
+
+def _network(delays=True):
+ defaults = {
+ "ff_excitatory_synapses": 1,
+ "ff_inhibitory_synapses": 0,
+ "rec_excitatory_synapses": 0,
+ "rec_inhibitory_synapses": 0,
+ "somatic_synapses": True,
+ "reactivate": False,
+ "weight_transform": "softplus",
+ "use_shunting": True,
+ "tau_base": 2.0,
+ "tau_ratio": 2.0,
+ }
+ upstream = {
+ "name": "up",
+ "readout_population": "e",
+ "population_defaults": defaults,
+ "populations": [
+ _population("e"),
+ _population("other"),
+ _population("i", "inhibitory"),
+ ],
+ "connections": [
+ {"source": "input", "target": target} for target in ("e", "other", "i")
+ ],
+ }
+ downstream = {
+ "name": "down",
+ "recurrent": True,
+ "population_defaults": {
+ **defaults,
+ "rec_excitatory_synapses": 2,
+ "rec_inhibitory_synapses": 1,
+ },
+ "populations": [_population("pyr", factors=(1, 1))],
+ "connections": [
+ {"source": "input", "target": "pyr"},
+ {"source": "up.e", "target": "pyr", "timing": "delayed"},
+ {"source": "up.other", "target": "pyr", "timing": "delayed"},
+ {"source": "up.i", "target": "pyr", "timing": "delayed"},
+ ],
+ }
+ if delays:
+ downstream["connections"][1]["delay_steps_by_level"] = [3, 2, 1]
+ downstream["connections"][2]["delay_steps"] = 2
+ downstream["connections"][3]["delay_steps_by_level"] = [1, 2, 3]
+ torch.manual_seed(17)
+ return PopulationNetwork(
+ PopulationNetworkConfig(
+ input_dim=1, output_mode="all", layers=[upstream, downstream]
+ )
+ ).double()
+
+
+def test_pulse_arrives_at_each_depth_and_source_at_its_configured_update():
+ net = _network()
+ x = torch.tensor(
+ [[[1.0], [0.0], [0.0], [0.0], [0.0]]], dtype=torch.float64, requires_grad=True
+ )
+ hidden = None
+ sources = []
+ arrivals = []
+
+ def sample(source, step, age):
+ return sources[step - age][source] if step >= age else x.new_zeros((1, 1))
+
+ with ExitStack() as resources:
+ reads = [
+ resources.enter_context(
+ patch.object(
+ layer, "compute_raw_currents", wraps=layer.compute_raw_currents
+ )
+ )
+ for layer in net.layers[1].populations["pyr"].branch_layers
+ ]
+ for t in range(x.shape[1]):
+ _, hidden = net(x[:, t : t + 1], hidden, return_hidden=True)
+ sources.append(hidden[0].outputs)
+ arrivals.append(reads[0].call_args.kwargs["recurrent_input"][:, 0])
+ for idx, read in enumerate(reads):
+ exc = torch.cat(
+ [sample("e", t, (3, 2, 1)[idx]), sample("other", t, 2)], dim=-1
+ )
+ inh = sample("i", t, (1, 2, 3)[idx])
+ torch.testing.assert_close(
+ read.call_args.kwargs["recurrent_input"], exc, rtol=0, atol=0
+ )
+ torch.testing.assert_close(
+ read.call_args.kwargs["rec_inhibitory_input"], inh, rtol=0, atol=0
+ )
+ assert arrivals[3].item() > 0 and all(v.item() == 0 for v in arrivals[:3])
+ grad = torch.autograd.grad(arrivals[3].sum(), x)[0]
+ assert grad[0, 0, 0] != 0 and grad[0, 1:].count_nonzero() == 0
+
+
+def test_history_carries_across_chunks_and_state_codec():
+ net = _network()
+ x = torch.rand(2, 7, 1, dtype=torch.float64)
+ full = net(x)
+ start, hidden = net(x[:, :2], return_hidden=True)
+ assert hidden[0].delay_history is None
+ histories = hidden[1].delay_history
+ assert {k: v.shape[1] for k, v in histories.items()} == {
+ "up.e": 2,
+ "up.other": 1,
+ "up.i": 2,
+ }
+ clone = hidden[1].clone()
+ assert all(
+ clone.delay_history[k].data_ptr() != v.data_ptr() for k, v in histories.items()
+ )
+ assert all(not v.requires_grad for v in hidden[1].detach().delay_history.values())
+ codec = PopulationStateCodec(net, hidden)
+ for state in (
+ hidden,
+ codec.unflatten(codec.flatten(hidden)),
+ [hidden[0], clone.to(x.device)],
+ ):
+ tail = net(x[:, 2:], state)
+ torch.testing.assert_close(
+ torch.cat([start, tail], dim=1), full, rtol=0, atol=0
+ )
+
+
+@pytest.mark.parametrize("source", ["e", "down.pyr"])
+def test_local_recurrence_and_feedback_from_a_later_layer(source):
+ config = _network(delays=False).config
+ first = config.layers[0]
+ first["recurrent"] = True
+ first["populations"][0]["population"] = {"rec_excitatory_synapses": 1}
+ first["connections"].append(
+ {"source": source, "target": "e", "timing": "delayed", "delay_steps": 3}
+ )
+ net = PopulationNetwork(config).double()
+ x = torch.rand(1, 5, 1, dtype=torch.float64)
+ states = []
+ hidden = None
+ branch = net.layers[0].populations["e"].branch_layers[0]
+ with patch.object(
+ branch, "compute_raw_currents", wraps=branch.compute_raw_currents
+ ) as read:
+ for t in range(5):
+ _, hidden = net(x[:, t : t + 1], hidden, return_hidden=True)
+ states.append(
+ hidden[0].outputs["e"] if source == "e" else hidden[1].outputs["pyr"]
+ )
+ expected = states[t - 3] if t >= 3 else torch.zeros_like(states[0])
+ torch.testing.assert_close(
+ read.call_args.kwargs["recurrent_input"], expected, rtol=0, atol=0
+ )
+ assert states[0].abs().sum() > 0
+
+
+def test_masked_depths_and_disabled_routes_use_no_unnecessary_history():
+ config = _network(delays=False).config
+ target = config.layers[1]
+ target["connections"][1].update(
+ target_levels=["soma"], delay_steps_by_level=[300, 200, 1]
+ )
+ target["connections"][2].update(delay_steps=42, enabled=False)
+ target["population_defaults"]["rec_excitatory_synapses_by_level"] = [0, 0, 1]
+ net = PopulationNetwork(config)
+ assert not net.layers[1].delay_history_lengths
+
+
+def _branched_config():
+ config = _network().config
+ config.input_dim = 4
+ upstream, downstream = config.layers
+ for source, size in zip(upstream["populations"], (4, 7, 5), strict=True):
+ source["n_neurons"] = size
+ downstream["populations"][0].update(n_neurons=3, branch_factors=[2, 3])
+ downstream["population_defaults"]["topk_type"] = "indexed"
+ return config
+
+
+def test_branched_sparse_arrivals_and_chunked_gradients():
+ config = _branched_config()
+ torch.manual_seed(182)
+ net = PopulationNetwork(config).double()
+ x = torch.rand(2, 8, 4, dtype=torch.float64, requires_grad=True)
+ branches = net.layers[1].populations["pyr"].branch_layers
+ exc = [b.branch_recurrent for b in branches]
+ inh = [b.branch_rec_inhibition for b in branches]
+ for synapse, rows in zip(exc, (18, 6, 3), strict=True):
+ assert synapse.connection_indices.shape == (rows, 2)
+ assert synapse.in_features == 11
+ assert any((s.connection_indices < 4).any() for s in exc)
+ assert any((s.connection_indices >= 4).any() for s in exc)
+
+ # Independently gather the stored contacts from the appropriate source
+ # frames. This checks what the synapses deliver to every compartment.
+ sources = []
+
+ def at(source, t, delay):
+ return (
+ sources[t - delay][source]
+ if t >= delay
+ else torch.zeros_like(sources[0][source])
+ )
+
+ with torch.no_grad(), ExitStack() as hooks:
+ currents = {}
+
+ def capture(module, args, output):
+ currents[module] = output
+
+ for synapse in exc + inh:
+ hooks.enter_context(synapse.register_forward_hook(capture))
+ hidden = None
+ for t in range(x.shape[1]):
+ _, hidden = net(x[:, t : t + 1], hidden, return_hidden=True)
+ sources.append(hidden[0].outputs)
+ for level, (e_syn, i_syn) in enumerate(zip(exc, inh, strict=True)):
+ arrivals = torch.cat(
+ (at("e", t, (3, 2, 1)[level]), at("other", t, 2)), dim=-1
+ )
+ for syn, past in (
+ (e_syn, arrivals),
+ (i_syn, at("i", t, (1, 2, 3)[level])),
+ ):
+ expected = (
+ past[:, syn.connection_indices] * syn.effective_sparse_weight()
+ ).sum(-1)
+ torch.testing.assert_close(currents[syn], expected)
+ assert all(
+ any(s[name].abs().any() for s in sources) for name in ("e", "other", "i")
+ )
+
+ weights = tuple(net.parameters())
+
+ def evaluate(chunks):
+ hidden = None
+ parts = []
+ for chunk in chunks:
+ out, hidden = net(chunk, hidden, return_hidden=True)
+ parts.append(out)
+ values = torch.cat(parts, dim=1)
+ grads = torch.autograd.grad(
+ values.square().sum(), (x, *weights), allow_unused=True
+ )
+ return values, grads
+
+ full, full_grads = evaluate([x])
+ chunked, chunked_grads = evaluate(x.split((1, 2, 5), dim=1))
+ torch.testing.assert_close(chunked, full, rtol=0, atol=0)
+ assert full_grads[0].abs().sum() > 0
+ for actual, expected in zip(chunked_grads, full_grads, strict=True):
+ if expected is None:
+ assert actual is None
+ else:
+ torch.testing.assert_close(actual, expected, rtol=1e-12, atol=1e-14)
+
+
+def test_zero_probability_delay_keeps_source_columns_without_storing_history():
+ config = _branched_config()
+ edge = config.layers[1]["connections"][1]
+ del edge["delay_steps_by_level"]
+ edge.update(probability=0, delay_steps=10000)
+ torch.manual_seed(27)
+ net = PopulationNetwork(config).double()
+ layer = net.layers[1]
+ assert layer.delay_history_lengths == {"up.other": 1, "up.i": 2}
+ assert layer._stream_sources("pyr", "delayed", "rec_excitatory") == [
+ "up.e",
+ "up.other",
+ ]
+ edge["delay_steps"] = 1
+ torch.manual_seed(27)
+ reference = PopulationNetwork(config).double()
+ x = torch.rand(2, 6, 4, dtype=torch.float64)
+ out, hidden = net(x, return_hidden=True)
+ assert "up.e" not in hidden[1].delay_history
+ torch.testing.assert_close(out, reference(x), rtol=0, atol=0)
+ for branch in layer.populations["pyr"].branch_layers:
+ assert branch.branch_recurrent.in_features == 11
+ assert (branch.branch_recurrent.connection_indices >= 4).all()
+
+
+def test_invalid_travel_history_and_per_level_streams_are_rejected():
+ net = _network()
+ x = torch.rand(2, 3, 1, dtype=torch.float64)
+ _, hidden = net(x, return_hidden=True)
+ codec = PopulationStateCodec(net, hidden)
+ invalid = [hidden[0], hidden[1].clone()]
+ invalid[1].delay_history = None
+ with pytest.raises(ValueError, match="delay history keys differ"):
+ codec.flatten(invalid)
+ with pytest.raises(ValueError, match="delay history"):
+ net(x, invalid)
+ for value in (0, torch.zeros(2, 2), torch.zeros(2, 2, 3)):
+ invalid[1] = hidden[1].clone()
+ invalid[1].delay_history["up.e"] = value
+ with pytest.raises(ValueError, match="invalid delay_history shape"):
+ codec.flatten(invalid)
+ pop = net.layers[1].populations["pyr"]
+ for field in ("recurrent_input", "rec_inhibitory_input"):
+ with pytest.raises(ValueError, match=f"{field} needs one tensor per level"):
+ pop.step(x[:, 0], **{field: (x[:, 0],)})
+
+
+def test_checkpoint_reload_and_compiled_layer_preserve_travel_delays(tmp_path):
+ net = _network()
+ path = tmp_path / "weights.pt"
+ torch.save(net.state_dict(), path)
+ restored = _network()
+ restored.load_state_dict(torch.load(path, weights_only=True))
+ restored.layers[1].compile(backend="eager")
+ x = torch.rand(1, 5, 1, dtype=torch.float64)
+ results = []
+ for model in (net, restored):
+ inp = x.clone().requires_grad_()
+ out = model(inp)
+ results.append((out, torch.autograd.grad(out.sum(), inp)[0]))
+ for actual, expected in zip(*results, strict=True):
+ torch.testing.assert_close(actual, expected, rtol=0, atol=0)
+
+
+def test_explicit_one_step_preserves_parameters_outputs_and_gradients():
+ baseline = _network(delays=False)
+ configs = baseline.layer_configs
+ configs[1].connections[1]["delay_steps_by_level"] = [1, 1, 1]
+ configs[1].connections[2]["delay_steps"] = 1
+ torch.manual_seed(17)
+ explicit = PopulationNetwork(
+ PopulationNetworkConfig(input_dim=1, output_mode="all", layers=configs)
+ ).double()
+ for key, value in baseline.state_dict().items():
+ torch.testing.assert_close(explicit.state_dict()[key], value, rtol=0, atol=0)
+ x = torch.rand(2, 5, 1, dtype=torch.float64)
+ observed = []
+ for net in (baseline, explicit):
+ inp = x.clone().requires_grad_()
+ y, hidden = net(inp, return_hidden=True)
+ assert all(state.delay_history is None for state in hidden)
+ y.sum().backward()
+ observed.append(
+ [y, inp.grad, *(p.grad for p in net.parameters() if p.grad is not None)]
+ )
+ for first, second in zip(*observed, strict=True):
+ torch.testing.assert_close(first, second, rtol=0, atol=0)
+
+
+@pytest.mark.parametrize(
+ "options",
+ [
+ {"delay_steps": 0},
+ {"delay_steps": -1},
+ {"delay_steps": True},
+ {"delay_steps": 1.5},
+ {"delay_steps_by_level": "321"},
+ {"delay_steps_by_level": []},
+ {"delay_steps_by_level": [1, 2]},
+ {"delay_steps_by_level": [3, False, 1]},
+ {"delay_steps": 2, "delay_steps_by_level": [3, 2, 1]},
+ {"timing": "same_step", "delay_steps": 1},
+ ],
+)
+def test_invalid_delay_is_rejected_by_the_loader(options):
+ raw = yaml.safe_load(example_text("recurrent_decision_population"))
+ route = raw["model"]["core"]["population_network"]["layers"][0]["connections"][-2]
+ route.update(options)
+ with pytest.raises(ValueError, match="delay_steps"):
+ config_from_mapping(raw)