Metadata-Version: 2.4
Name: neuroforge-science
Version: 0.1.0
Summary: Transparent morphology analysis, network assembly, and spiking-network experiments
License-Expression: MIT
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Science/Research
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy<3,>=1.24
Provides-Extra: ui
Requires-Dist: streamlit<2,>=1.66; extra == "ui"
Requires-Dist: plotly<7,>=5.24; extra == "ui"
Requires-Dist: pandas<4,>=2; extra == "ui"
Provides-Extra: dev
Requires-Dist: pytest<10,>=8; extra == "dev"
Requires-Dist: build<2,>=1; extra == "dev"
Dynamic: license-file

# NeuroForge Science

**Upload reconstructed neurons, assemble a circuit, analyze its structure, and
explore its simulated signals in an interactive playbox.**

An installable Python package with a familiar API:

```python
import neuroforge as nf
from neuroforge import view
```

This is a working **alpha research prototype**, independent of NeuroM. It is
not a drop-in replacement or an established, experimentally validated simulator.
The distribution name is `neuroforge-science`; the Python import is `neuroforge`.
This download is installable locally; it has not been published to PyPI.

## Start on Windows

1. Install Python 3.11 or newer if needed. Python 3.12 is the tested version.
2. Extract the complete ZIP. Open its `neuroforge-science` folder.
3. Double-click **START_PLAYBOX.bat**. The first launch creates a local virtual
   environment and installs dependencies; it needs an Internet connection.
4. Open **http://localhost:8501** if a browser tab does not open automatically.

Or use PowerShell inside the extracted folder:

```powershell
python -m venv .venv
.venv\Scripts\python.exe -m pip install ".[ui]"
.venv\Scripts\python.exe -m neuroforge playbox
```

The startup batch file uses its own Python executable, so PowerShell activation
policy does not need to change. It does not require administrator access.

## Start on macOS / Linux

```bash
python3 -m venv .venv
.venv/bin/python -m pip install '.[ui]'
.venv/bin/python -m neuroforge playbox
```

Alternatively, run `bash start_playbox.sh`. Stop the local server with Ctrl+C.
The playbox binds to `127.0.0.1`; it is not a public website. Uploaded experiment
data remain in the running local application unless you export them. Export
before stopping: session state is not a persistent project database.

## What scientists can upload

| Input | Purpose |
| --- | --- |
| One or more `.swc` files | Traced 3D neuron reconstructions: one rooted tree per file |
| Optional synapse `.csv` | Source/target names, signed current weights, transmission delays, evidence labels |
| A saved NeuroForge network `.json` | Reopen an assembled circuit with geometry, registration and connections |

The current release does **not** trace neurons from microscopy TIFFs, screenshots,
or EM volumes, interpret SWC+ metadata, or load ASC/H5/NWB/NeuroML directly.
Convert those inputs to standard SWC reconstructions using appropriate
domain tools first. A file named `neuron_A.swc` becomes neuron `neuron_A` in the UI.
Use those exact names in the synapse table.

Standard SWC columns:

```text
# id type x y z radius parent
1 1 0 0 0 5 -1
2 2 20 0 0 0.8 1
3 3 -10 15 0 1.0 1
4 3 -20 25 5 0.6 3
```

Type 1 is soma, 2 axon, 3 basal dendrite, and 4 apical dendrite. Other nonnegative
types are retained; unknown/glial/custom types are not used for proximity matches.
Coordinates and radii default to micrometers. Set `unit_scale_um=1000` for input
in millimeters; the scale applies to both coordinates and radii.

The parser rejects duplicate IDs, invalid/missing parents, cycles, multiple roots,
negative radii, nonfinite coordinates, and malformed columns. It accepts unordered
parent references as a tolerant extension and canonicalizes SWC exports. Zero
radii, missing soma annotations and zero-length segments produce quality warnings.
It cannot certify that a reconstruction is biologically complete.

## The playbox workflow

1. Try the original four-neuron **synthetic demo** already loaded at startup.
2. In **Circuit map**, rotate the 3D neuron geometry and inspect connections.
3. In **Analysis**, inspect cable length, branch points, terminal points, axon and
   dendrite length, estimated neurite surface/volume, degrees, components and density.
4. In **Playbox**, set current pulses, time step, electrical parameters, noise,
   random seed and output neuron groups. Press **Run experiment**.
5. Press **Play spikes** inside the 3D chart. Highlighted cell bodies fired in
   that time bin. Inspect the spike raster and membrane voltage traces below.
6. In **Export**, download a reproducible experiment ZIP, network JSON or synapse CSV.
7. Replace the synthetic demo with your own SWC reconstructions and evidence.

Demo: stronger left input (`0.35 nA` versus `0.22 nA`) selects the Left/A readout.
Swap the currents to select Right/B. Equal symmetric input produces a tie. This
behavior comes from a configured four-cell circuit with assumed excitation and
cross-inhibition; it is not inferred cognition or a fitted biological experiment.

Output groups are your operational definition of a choice. The readout compares
**mean spike counts per neuron**, preventing larger groups from winning merely
because they contain more cells. Groups must be nonempty and disjoint. Ties and
insufficient activity produce `None`/Undecided. Score shares are **not** probabilities
or confidence intervals. There is no learning or synaptic plasticity in this release.

## Load and analyze a real reconstruction

```python
import neuroforge as nf
from neuroforge import view

neuron = nf.load_morphology("neuron_A.swc")
print(nf.analyze(neuron))
view.morphology(neuron).show()
```

Surface area is the sum of truncated-cone lateral areas along non-soma child
segments; volume is the sum of their truncated-cone volumes. These exclude soma,
end caps, spines and overlap corrections at branches. Cable length excludes
soma-to-soma edges. Branch counts exclude soma samples, and root path lengths
are measured along the sampled tree. These definitions are explicit and may
differ from metrics produced by other morphology packages.

## Assemble multiple neurons

```python
a = nf.load_morphology("neuron_A.swc", name="A")
b = nf.load_morphology("neuron_B.swc", name="B")
network = nf.Network([a, b])
network.import_synapses("synapses.csv")
print(network.analyze())
view.network(network).show()
network.save("network.json")
```

Minimum synapse CSV:

```csv
source,target,weight_nA,delay_ms,provenance,note
A,B,0.8,1.0,manual,Assumed excitatory link for exploration
B,A,-0.4,2.0,manual,Assumed inhibitory link for exploration
```

`weight_nA` is a **signed peak current jump** on spike arrival, not a conductance
or an automatically calibrated physiological measurement. Negative inhibits;
positive excites. CSV imports require weights and delays, rather than making up
missing electrical parameters. Optional `source_node` and `target_node` values
refer to SWC sample IDs. Multiple synapses per pair and self connections are allowed.

The `provenance` field accepts `manual`, `measured`, `inferred`, or `synthetic`.
The `measured` label is supplied by the investigator, not verified by this package.
An anatomical contact count alone does not supply a measured current or delay.
Record separate evidence and calibration in the note and your experiment records.
Imports validate every row before adding any rows. Missing CSV provenance defaults
to `manual`; it never defaults to `measured`.

## Registration and optional geometric hypotheses

Independent reconstructions often have local coordinate origins. They cannot
be connected meaningfully by proximity until registered in a common tissue frame.
NeuroForge applies **supplied rigid transforms**; it does not recover unknown
registration or stitch broken neurite fragments automatically.

```python
import numpy as np

# Replace these example transforms with your experiment's actual registration.
a = a.translated([0, 0, 0], coordinate_frame="slice_01_um")
b = b.translated([100, 0, 0], coordinate_frame="slice_01_um")
# For a rotation + translation: a.transformed(matrix_4x4, coordinate_frame="slice_01_um")
network = nf.Network([a, b])

# Inspect suggestions without modifying the graph.
for suggestion in network.propose_connections(max_distance_um=3):
    print(suggestion)

# Explicit opt-in: add inferred links only where no directed pair already exists.
network.infer_connections(max_distance_um=3, weight_nA=0.1, delay_ms=1.0)
```

The inference routine finds the nearest **axon-sample center to dendrite-sample
center** for each directed pair within the supplied threshold, excluding self
links. It does not compute continuous segment or membrane contact, detect real
synapses, infer neurotransmitters, or learn electrical weights/delays. Sparse
sampling can miss close segments. Every suggestion records sample IDs, distance,
assumed electrical values and `inferred` provenance. Existing measured/manual
pairs are preserved. Changing registration in the UI removes inferred links.

## Simulate a configured circuit

```python
network = nf.demo_network()
result = nf.simulate(
    network,
    duration_ms=500,
    dt_ms=0.1,
    seed=42,
    parameters=nf.LIFParameters(noise_std_nA=0.0),
    stimuli=[
        nf.Stimulus("input_left", current_nA=0.35, start_ms=20, end_ms=450),
        nf.Stimulus("input_right", current_nA=0.22, start_ms=20, end_ms=450),
    ],
)
print(result.firing_rates_hz())
print(result.choice({"Left": ["choice_left"], "Right": ["choice_right"]}))
view.raster(result).show()
view.voltage(result).show()
view.save_playback(network, result, "playback.html")
result.save("simulation.npz")
```

Core equations, with time in ms, voltage in mV, resistance in MΩ and current in nA:

```text
tau_m * dV/dt = -(V - V_rest) + R * (I_external + I_synaptic + I_noise)
tau_syn * dI_synaptic/dt = -I_synaptic
on delayed spike arrival: I_synaptic += signed weight_nA
if V >= V_threshold: record spike; reset V; enforce refractory period
```

Each SWC neuron becomes **one point-neuron electrical unit**. Dendritic shape,
segment radii, placement and branch count do not set membrane parameters or
intracellular signal propagation. The shape is used for analysis and optional
connectivity hypotheses. All cells share one parameter set in this release.

Voltage integration uses an exponential constant-current update. Synaptic current
is held over each step then exponentially decayed, so this is an approximation
to coupled dynamics. Threshold crossings are detected at grid endpoints. Pulse
boundaries and duration must align to the time step. Delays and refractory periods
round upward to grid intervals. A spike recorded at time `t` arrives at
`t + ceil(delay/dt)*dt`; its first effect appears at the following voltage endpoint.
Saved voltages are **after reset**, not plotted action-potential waveforms.

Noise is a per-bin independent Gaussian current, not continuous white-noise
diffusion; changing dt changes its effective statistics. Set noise to zero for
deterministic experiments. For scientific work, check time-step convergence and
compare against measured electrophysiology. Use a validated compartmental
simulator such as NEURON when active dendrites, channels, or detailed cable
dynamics are the research objective.

## Commands

```bash
python -m neuroforge playbox
python -m neuroforge demo --output demo_results
python -m neuroforge demo --left 0.22 --right 0.35 --output reverse_results
python -m neuroforge analyze neuron_A.swc --output morphology_report.json
python -m neuroforge assemble neuron_A.swc neuron_B.swc --synapses synapses.csv --output network.json
python -m neuroforge simulate network.json --stimuli stimuli.json --duration-ms 500 --output run.npz
```

Stimulus JSON is an array of objects with `target`, `current_nA`, `start_ms`, and
`end_ms`. The demo command writes an example. Installing without the optional
UI uses only NumPy: `python -m pip install .`. The demo's HTML playback is created
when Plotly is installed; the numerical demo works without it.

## Export and reproducibility

The experiment bundle includes morphology SWCs, network JSON, analysis JSON,
synapse CSV, and (after a run) compressed arrays, model metadata and readout groups.
Network JSON preserves original sample order alongside canonical SWC. Simulation
metadata embeds the exact network snapshot, pulse definitions, seed, parameters,
effective delays and package/NumPy versions. Input hashes cover the decoded SWC
text before scaling/registration, not necessarily byte-for-byte source files
with a BOM. They track provenance and are not authenticated signatures.

```python
import json
import numpy as np

with np.load("simulation.npz", allow_pickle=False) as arrays:
    times = arrays["times_ms"]       # [time]
    voltage = arrays["voltage_mV"]   # [time, neuron]
    spikes = arrays["spikes"]        # bool [time, neuron]
    metadata = json.loads(str(arrays["metadata_json"]))
```

Reproducibility assumes the same data, parameters, dt, seed and compatible
runtime versions. Results are not promised bit-identical across different
NumPy/platform versions. The UI limits uploads to 60 neurons / 100,000 samples;
the default simulation caps traces at 5 million time-by-neuron values. Proximity
matching caps candidate pair comparisons. This is a small-circuit workbench,
not a whole-brain platform.

## Tests and development

```bash
python -m pip install -e '.[ui,dev]'
python -m pytest -q
python -m build
```

Tests cover known geometry and unit conversions; corrupt/deep SWC trees;
registration; inference labeling and measured-edge preservation; atomic CSV
imports; graph topology; JSON roundtrips; a closed-form passive response and
first-spike timing; delay rounding and event ordering; inhibition; seeded
reproducibility; reversed/tied demo choices; and the interactive app's run/export
journey. These are numerical/software checks, not experimental validation.

## Scientific references

- [SWC specification](https://swc-specification.readthedocs.io/en/latest/swc.html):
  reconstruction columns, type definitions, parent links and soma representation.
- [NeuroM quickstart](https://neurom.readthedocs.io/en/stable/quickstart.html):
  the morphology-analysis/visualization workflow that inspired the simple API.
- Gerstner et al., [Neuronal Dynamics, §1.3](https://neuronaldynamics.epfl.ch/online/Ch1.S3.html):
  leaky integrate-and-fire equations, threshold events and reset.
- [NEURON scripting tutorial](https://www.neuronsimulator.org/en/9.0.1/tutorials/scripting-neuron-basics.html):
  a route to more detailed compartmental biophysics; not integrated in this release.

MIT licensed. All included SWCs and example circuitry are original synthetic
teaching data, with no claim to represent a recorded cell or animal experiment.

