Skip to content

Interoperability

neurospatial is array-first. Every analysis in the library runs on plain NumPy arrays and needs no optional dependencies — you build an Environment, pass spike times / timestamps / positions as arrays, and get results back as arrays (or result objects that wrap them).

Loaders and simulators return frozen holders with named attributes. Pass those attributes explicitly to analysis functions; timestamps always precede positions. The pynapple adapters, SpikeTrains and BayesianDecoder preserve unit identity at array handoffs.

The array path is always available

import neurospatial never imports pynapple or pynwb. The array path is byte-for-byte identical whether or not the optional extras are installed — the extras only add adapters at the boundary.

Install the optional extras only when you need the corresponding adapters:

pip install neurospatial[pynapple]   # pynapple TsGroup / Tsd / IntervalSet adapters
pip install neurospatial[nwb]        # NWB read/write (pynwb)

Array-first stays primary

Everything below runs on plain arrays with a bare pip install neurospatial. The example computes rate maps and decodes position from arrays, then uses the same arrays with a fitted decoder.

import numpy as np

from neurospatial import Environment
from neurospatial.encoding import compute_spatial_rates
from neurospatial.decoding import BayesianDecoder, decode_session, decoding_error
from neurospatial.simulation import (
    PlaceCellModel,
    generate_population_spikes,
    simulate_trajectory_ou,
)

# --- Array-first: plain NumPy arrays, no optional dependencies -------------
# (In a real analysis, load your own env, spike_times, times, and positions.)
env = Environment.from_samples(
    np.linspace(0.0, 100.0, 51).reshape(-1, 1), bin_size=2.0
)
env = env.with_metadata(units="cm")
positions, times = simulate_trajectory_ou(
    env, duration=120.0, dt=0.02, speed_mean=15.0, rng=0, speed_units="cm"
)
cells = [
    PlaceCellModel(env, center=np.array([c]), width=10.0, max_rate=20.0, rng=i)
    for i, c in enumerate(np.linspace(5.0, 95.0, 15))
]
spike_times = generate_population_spikes(
    cells, times, positions, rng=0, show_progress=False
)

# Rate maps and a one-call decode, straight from arrays.
rates = compute_spatial_rates(env, spike_times, times, positions)
result = decode_session(env, spike_times, times, positions, dt=0.1)
actual = np.interp(result.times, times, positions[:, 0]).reshape(-1, 1)
print(f"array-first median error: "
      f"{np.nanmedian(decoding_error(env, result.map_position, actual)):.1f} cm")

# --- BayesianDecoder: the same decode as an object ------------------------
decoder = BayesianDecoder(env, dt=0.1).fit(spike_times, times, positions)
prediction = decoder.predict(spike_times, times)
# Equal here because no position is missing (see the BayesianDecoder section).
assert np.array_equal(prediction.posterior, result.posterior)
error = decoder.score(spike_times, times, positions, metric="median_error")
print(f"BayesianDecoder.score median error: {error:.1f} cm")

Installed snapshot adapters

An external package can supply an installed SnapshotAdapter object that converts its data into the explicit binning records. Publication validates and owns the resulting built-in data. It retains no provider callbacks and does not register custom query algorithms or builders.

Role Required result
"locator" A built-in locator, such as NearestBinLocator
"track" TrackLinearization
"arena" Built-in Arena data
"binning" Binning with supported built-in components

For example, a package module my_lab.adapters could expose this object. snapshot and decode must be pure: they return data without changing their inputs. provider_type matches the exact external type; subclasses need their own declaration.

import numpy as np
from neurospatial.binning import NearestBinLocator
from neurospatial.extensions import SnapshotAdapter

class RecordedSites:
    def __init__(self, centers):
        self.centers = np.asarray(centers, dtype=float)

def snapshot_sites(provider):
    return NearestBinLocator(provider.centers, max_distance=0.25)

def decode_sites(metadata, arrays, prefix):
    return NearestBinLocator(
        arrays[f"{prefix}/centers"], max_distance=metadata["max_distance"]
    )

adapter = SnapshotAdapter(
    name="my_lab.recorded_sites",
    version=1,
    role="locator",
    provider_type=RecordedSites,
    snapshot=snapshot_sites,
    decode=decode_sites,
)
assert adapter.role == "locator"
provider = RecordedSites([[0.0, 0.0], [2.0, 0.0]])
snapshot = adapter.snapshot(provider)
np.testing.assert_array_equal(snapshot.locate(np.array([[0.0, 0.0]])), [0])
restored = adapter.decode(
    {"max_distance": 0.25}, {"sites/centers": provider.centers}, "sites"
)
np.testing.assert_array_equal(restored.locate(np.array([[2.0, 0.0]])), [1])

Declare the object in that package's pyproject.toml, then install the package:

[project.entry-points."neurospatial.snapshot_adapters.v1"]
recorded_sites = "my_lab.adapters:adapter"

The entry point exposes an object, rather than a factory. Its group versions the adapter API; version identifies the custom stored payload that decode accepts. Custom records use the adapter's name as codec and its version as codec_version. The decoder receives the supplied array namespace and prefix. Names must not collide with built-in codecs or other installed adapters; only one adapter may handle a given provider type and role.

The package is required to publish its external providers or load its original custom records. After loading and saving an environment, the saved data use canonical built-in codecs and can be loaded without that package. Missing adapters and unsupported versions raise with installation guidance.

Use the public contract helper with boundary answers derived independently from the intended geometry. It checks lookup, outside sentinels, ownership, missing-face refusal and copy/storage round trips. This native grid example specifies the internal boundary owner (the bin above a shared face), the outer edge (which belongs to the last bin) and a point outside:

import numpy as np
from neurospatial import Environment
from neurospatial.testing import assert_environment_contract

env = Environment.from_grid_mask(
    np.ones((2, 1), dtype=bool),
    grid_edges=(np.array([0.0, 1.0, 2.0]), np.array([0.0, 1.0])),
)
assert_environment_contract(
    env,
    points=[[0.0, 0.5], [1.0, 0.5], [2.0, 0.5], [-0.1, 0.5]],
    expected_bins=[0, 1, 1, -1],
)

Run the same helper on environments published by an installed adapter, using that geometry's own hand-checked boundary and outside points.

Simulator attributes feed analyses

A SimulationSession carries env, spike_times, unit_ids, times, positions, models, integer-label ground_truth and metadata. It is immutable: its arrays are read-only, spike_times and models are tuples, and ground_truth and metadata are read-only mappings; build a changed session with dataclasses.replace. Spike arrays, labels and models must align one-to-one. Unit labels also select the ground truth for validation and the rate panels for plotting.

from neurospatial.encoding import compute_spatial_rates
from neurospatial.simulation import open_field_session, validate_simulation

sim = open_field_session(duration=60, n_place_cells=5, rng=0)
rates = compute_spatial_rates(
    sim.env, sim.spike_times, sim.times, sim.positions, unit_ids=sim.unit_ids,
)
assert set(sim.ground_truth) == set(sim.unit_ids)
print(rates.unit_ids.tolist())
validation = validate_simulation(sim, unit_ids=[0, 3, 4])
print(validation.summary_table()[["center_error", "correlation", "status"]])
assert validation.unit_status == ("passed", "failed", "passed")

validate_simulation returns one row per selected unit; one minute is too short to recover every field, so unit 3 fails the default center-error limit here. plot_session_summary(sim, unit_ids=[1, 3]) uses the same label selection. Analysis functions take arrays; the validation and summary plot functions need the simulator holder because it carries simulation-specific data.

SpikeTrains and epoch selection

SpikeTrains is a frozen bundle of ragged per-unit spike trains plus their identity labels (unit_ids) and an optional per-unit metadata table (unit_table). It gives you positional access, label selection, iteration and a metadata-driven filter, and it flows directly into the batch encoding / decoding functions (it duck-types as a spike-input group, so its unit_ids are carried into the result).

import numpy as np
import pandas as pd
from neurospatial.encoding import SpikeTrains

st = SpikeTrains(
    [np.array([0.1, 1.5, 2.9]), np.array([0.5, 3.0, 6.0])],
    unit_ids=np.array([7, 9]),
    unit_table=pd.DataFrame({"region": ["CA1", "CA3"], "quality": [0.9, 0.4]}),
)

st.index          # unit_ids (the group-key surface): array([7, 9])
list(st)          # iterate -> the per-unit train arrays
st[1]             # by position -> array([0.5, 3. , 6. ])
st.sel(unit_id=9) # by label: the same unit

# Metadata-driven selection (returns a new SpikeTrains).
ca1 = st.filter("region == 'CA1' and quality > 0.5")

# Flows straight into batch compute — unit_ids are carried into the result.
rates = compute_spatial_rates(env, st, times, positions)
rates.sel(unit_id=9)  # that unit's rate map; rates[1] is the same unit

Restricting to epochs

For occupancy, firing rates, movement metrics and decoding, keep the original arrays and pass epochs= directly to each analysis. This preserves excluded intervals even when they are shorter than max_gap. For example:

from neurospatial import compute_spatial_rates

run_epochs = np.array([[1.0, 4.0], [7.0, 9.0]])
rates = compute_spatial_rates(
    env, spike_times_list, times, positions, epochs=run_epochs,
)
print("Analyzed windows:", rates.analysis_settings["epochs"])
print("Observed time (s):", rates.occupancy.sum())

Spatial, directional, view and object-vector rate results all carry analysis_settings and spatial_support. The settings record the resolved windows, the intervals actually retained after filtering, and the estimator's choices. The support mask identifies bins with positive, sufficient occupancy and finite rates; its coordinates follow the result (locations, angles or polar object vectors). Smoothing can predict a finite rate outside observed coverage, so use the support mask when an analysis requires observed bins. These fields survive population indexing, DataFrame and xarray export; xarray stores the settings as JSON for NetCDF compatibility. Manually constructed results default to analysis_settings=None.

Spatial and view smoothing default to a physical bandwidth: 5 cm converted to declared metric units. With unset, pixel or custom units they fall back to 2.5 median graph-edge lengths and warn with the resolved value. Smoothed object-vector and boundary-vector maps share the 5 cm default but have no fallback: without metric units a kernel method needs an explicit bandwidth=. Object-vector results inherit the supplied environment's distance units; their angles remain radians. Directional smoothing keeps its explicit angular bandwidth, and object-vector method="binned" applies no smoothing. Supply explicit distance ranges and gaze distances in your coordinate units.

restrict, in_epochs, and restrict_spike_trains select time windows. restrict(times, *arrays, epochs=...) slices times and any number of arrays aligned to it by the same in-epoch mask; in_epochs(times, epochs) returns the boolean mask; and restrict_spike_trains(spike_times, epochs) masks ragged trains (each unit by its own timestamps). It returns a SpikeTrains that keeps each unit's label and metadata row, so a restricted TsGroup with units 5, 6 and 7 still names them 5, 6 and 7 in every result computed from it.

from neurospatial.behavior import restrict, in_epochs, restrict_spike_trains

run_epochs = np.array([[1.0, 4.0], [7.0, 9.0]])   # (n_intervals, 2)

# Slice aligned arrays (position samples share one time axis).
t_kept, pos_kept = restrict(times, positions, epochs=run_epochs)

# Boolean mask over timestamps.
mask = in_epochs(times, run_epochs)

# Ragged per-unit spikes: each train masked by its own timestamps.
kept = restrict_spike_trains(st, run_epochs)

epochs accepts a (start, stop) pair, an (n, 2) array or list of interval rows (including [[0, 5], [10, 15]]), or a pynapple IntervalSet. Parallel start/stop arrays are rejected: convert them with np.column_stack([starts, stops]).

Sliced samples do not retain observation windows

restrict() warns when aligned arrays would join separate windows. Passing those arrays to an analysis without epochs= can reintroduce excluded time. Prefer the original arrays with epochs=; if using sliced arrays, pass the windows again. Point selection uses the same [start, stop) windows as the analyses, so adjacent train/test windows never share a spike or event. A pynapple IntervalSet includes its end, and its rows are converted so a point at end stays inside; for plain arrays of pynapple bounds, pass closed="both" to match pynapple's restrict.

Analysis settings and exports

Spatial rate results retain analysis_settings: selected epochs, the intervals actually observed after gating, spike-recording windows, speed source and threshold, gap threshold, occupancy threshold, smoothing and estimator choices. spatial_support marks observed bins meeting the occupancy threshold with finite rates. Indexing a population result preserves these settings.

from neurospatial import compute_spatial_rates

rates = compute_spatial_rates(
    env, spike_times_list, times, positions, epochs=(1.0, 4.0),
    bandwidth=5.0, min_occupancy=0.05,
)
table = rates.to_dataframe()
assert table.attrs["analysis_settings"]["epochs"] == [[1.0, 4.0]]
print(table.attrs["units"])
print("Supported bins:", int(rates.spatial_support.sum()))

to_xarray() stores these settings as JSON in attrs["analysis_settings"], alongside a spatial_support variable; they survive NetCDF export. write_spatial_rates stores them in NWB too (spatial-rates schema 2.6); read_spatial_rates refuses records written with an earlier schema, so recompute and rewrite those. Results you construct by hand without these choices have analysis_settings=None. CSV does not preserve DataFrame attributes: save the settings as a JSON sidecar, or use NetCDF/NWB.

Combining sessions

Every table keeps its settings in table.attrs, but pd.concat silently empties attrs when they differ between tables, even by one value. A table joined across sessions then no longer records how it was made. Collect the settings yourself before you combine, with the package version:

from importlib.metadata import version

import pandas as pd

from neurospatial import compute_spatial_rates
from neurospatial.simulation import linear_track_session

session = linear_track_session(duration=60.0, n_place_cells=4, n_laps=4, rng=0)
tables = {
    name: compute_spatial_rates(
        session.env, session.spike_times, session.times, session.positions,
        bandwidth=bandwidth, min_occupancy=0.05,
    ).summary_table()
    for name, bandwidth in {"day_1": 5.0, "day_2": 8.0}.items()
}
assert pd.concat(tables.values()).attrs == {}  # the settings are gone

combined = pd.concat(table.assign(session=name) for name, table in tables.items())
combined.attrs["sessions"] = {name: table.attrs for name, table in tables.items()}
combined.attrs["neurospatial_version"] = version("neurospatial")
assert combined.attrs["sessions"]["day_2"]["bandwidth"] == 8.0

Parquet keeps these attributes. CSV does not.

BayesianDecoder

BayesianDecoder is an optional object wrapper over the functional decode_session path. It is frozen: fit(...) builds the encoding models and returns a new fitted decoder, predict(...) returns a DecodingResult, predict_summary(...) returns a memory-safe DecodingSummary, and score(...) returns a scalar decode error.

from neurospatial.decoding import BayesianDecoder

decoder = BayesianDecoder(env, dt=0.1)
decoder.is_fitted                       # False

fitted = decoder.fit(spike_times, times, positions)   # returns a NEW decoder
fitted.is_fitted                        # True

result = fitted.predict(spike_times, times)                  # DecodingResult
summary = fitted.predict_summary(spike_times, times, time_chunk=1024)
error = fitted.score(spike_times, times, positions,
                     metric="median_error", distance="euclidean")

# Train/test split: fit on one epoch, evaluate on another.
fitted = decoder.fit(spike_times, times, positions, epochs=(0.0, 60.0))

On a recording without missing tracking, fit(...).predict(...) on the same inputs and parameters equals decode_session exactly. With NaN positions they differ: decode_session does not decode tracking losses longer than max_gap, while predict, which takes no positions, decodes them. decode_session fits and decodes the same data, an in-sample decode; fit and predict on separate epochs to measure accuracy on held-out data.

Because decoding runs through the Environment, BayesianDecoder decodes linearized tracks, masked open fields, and graph-based layouts — not just a rectangular grid — and score(..., distance="geodesic") measures error as the shortest path between the decoded and the true position that stays inside the environment: along a track, around walls.

pynapple interop

pynapple objects convert to and from plain arrays at the boundary with from_pynapple / to_pynapple, or pass straight into analysis functions (see Passing pynapple objects directly).

Requires the pynapple extra

pip install neurospatial[pynapple], which installs pynapple 0.11.3 or later: earlier releases round interval bounds to 1 ns, so a sample exactly at a window's stop would be kept. Only these two adapter functions import pynapple, and they import it lazily.

A pynapple object is defined only on its time_support: the recording epochs, with gaps between them for artifacts, sleep boxes or lost tracking. from_pynapple returns that support as epochs, a (n_epochs, 2) array of half-open [start, stop) rows in seconds, so you can pass it to the analysis and keep the gaps out of occupancy and rates. An IntervalSet itself, such as trials, comes back as Intervals: its metadata columns become fields and an interval_id column, which to_pynapple writes, becomes the ids, so trials keep their ids through pynapple and back.

from neurospatial.encoding import compute_spatial_rates
from neurospatial.io import from_pynapple, to_pynapple

# Ingress: pynapple -> plain arrays plus their time support.
times, positions, epochs = from_pynapple(tsdframe)   # TsdFrame / Tsd
# A TsGroup's support is the recording coverage only if it was built with the
# acquisition intervals; by default it runs from the first to the last spike.
trains, unit_ids, recorded = from_pynapple(tsgroup)  # TsGroup
spike_times, unit_epochs = from_pynapple(ts)         # one unit's Ts
trials = from_pynapple(intervalset)                  # IntervalSet -> Intervals

rates = compute_spatial_rates(
    env, trains, times, positions,
    epochs=epochs, spike_window=recorded, unit_ids=unit_ids,
)

Without epochs=, a gap shorter than max_gap (1 s by default) is counted as time spent at the last position before it, which inflates occupancy in that bin.

Positions come back in the frame's column order. A TsdFrame whose columns are the axis names in another order, such as ["y", "x"], is refused rather than silently swapping the axes; reorder it with tsdframe.loc[["x", "y"]] first.

pynapple intervals include their end, while neurospatial windows are half-open [start, stop). Each pynapple end becomes the next float above it (np.nextafter(end, np.inf)), so the epochs hold exactly the timestamps pynapple holds: a sample or spike at an epoch end, such as the last spike of a TsGroup's default support, stays inside. An IntervalSet passed directly as epochs= or spike_window= is converted the same way, and to_pynapple converts back.

Exporting results to pynapple

to_pynapple turns a decode result, behavior records, or plain arrays into the matching pynapple object, so you can continue in pynapple with restrict, compute_perievent or its plotting.

Decoded position. A decode result records the windows its time bins cover as result.time_support. These are the epochs you decoded, less tracking gaps longer than max_gap, time outside spike_window, and any remainder shorter than one time bin. The export uses them as its time support, so a decode over two epochs stays two intervals and the time between them is not read as decoded time:

from neurospatial.decoding import decode_session
from neurospatial.io import to_pynapple

result = decode_session(
    env, spike_times, times, positions, dt=0.025, epochs=[[0, 600], [900, 1500]]
)
track = to_pynapple(result)            # TsdFrame of the MAP position, columns x, y
mean = to_pynapple(result, quantity="mean_position")
posterior = to_pynapple(result, quantity="posterior")

quantity="posterior" returns a TsdFrame with one column per environment bin. Column j is bin j, and each value is the probability mass in that bin, so each row sums to 1 (or is all NaN for a time bin that could not be decoded). Each column carries its bin center as metadata (bin_center_x, bin_center_y), so you can select bins by place, for example the posterior mass in the reward arm with posterior[:, posterior.bin_center_x > 80].sum(axis=1). A column per bin, rather than a TsdTensor shaped like the grid, works for tracks, graphs and masked arenas alike and never pads bins outside the environment with values. On unequal bins (a linearized track with short junction bins, for example), the bin with the largest mass is not the MAP bin: the MAP ranks density, mass divided by env.bin_sizes. Use the exported MAP track for the decoded position. A DecodingSummary keeps no posterior, so only its MAP and mean tracks can be exported.

Decoding the same data with pynapple's own nap.decode_bayes gives different posteriors near unvisited bins. pynapple sums each bin's log-likelihood with np.nansum, so a cell whose rate is NaN in a bin drops out of that bin's likelihood instead of excluding the bin, and its uniform prior is flat over bins rather than over space. neurospatial gives a bin where any rate is missing zero probability, and its default prior is proportional to bin size.

Trials, laps, region visits and movement epochs. The detectors and labels_to_epochs return Intervals, and any Intervals becomes an IntervalSet with one interval per row, with interval_id and every field as metadata columns (start_region, end_region and outcome for trials; direction for laps; region, entry_observed and exit_observed for visits; label for labels_to_epochs). A list of records is refused: pass the Intervals the detector returned. Select rows the way you would in pynapple:

from neurospatial.behavior import detect_laps, detect_trials, labels_to_epochs

trials = detect_trials(env, times, positions, regions=["home", "left", "right"])
iset = to_pynapple(trials)
left = iset[iset.end_region == "left"]  # interval_id stays with each trial
spikes_on_left_trials = tsgroup.restrict(left)

laps = to_pynapple(detect_laps(env, times, positions))
clockwise = laps[laps.direction == "clockwise"]

conditions = to_pynapple(labels_to_epochs(times, task_phase))
sampling = conditions[conditions.label == "sampling"]  # one task phase

A row covers [start, stop). The exported interval ends one float below the stop, so restrict selects exactly the samples that in_epochs selects with the same windows: a sample at a lap's end belongs to the next lap, not to both. A row without duration, such as a region visit seen in a single sample just before a tracking loss longer than max_gap, holds no time and cannot be a pynapple interval, so it is dropped with a warning. Overlapping rows, such as visits to overlapping regions, are refused: pynapple merges overlapping intervals and drops all their metadata, so export them in separate calls. An empty Intervals exports as an empty IntervalSet with its columns.

Region crossings. pynapple time series carry no per-event labels, so crossings become a TsGroup with one Tsd per region and direction. Its values are the bin index at each crossing, and the group has region and direction metadata. Without epochs=, its time support runs from the first crossing to the last; pass the epochs the crossings were detected in, or the recording span, instead:

from neurospatial.behavior import detect_region_crossings

crossings = to_pynapple(
    detect_region_crossings(env, times, positions, region="reward"),
    epochs=(times[0], times[-1] + 1 / 30),  # through the last 30 Hz frame
)
reward_entries = crossings[crossings.direction == "entry"]

Plain arrays work too. Pass the windows they were observed in as epochs=:

tsd = to_pynapple(times, linear_position, epochs=epochs)

Passing pynapple objects directly

Analysis functions also take pynapple objects without conversion. They apply the conversions from_pynapple applies (time support as epochs, inclusive ends, x/y/z column order), so both routes give the same numbers; a TsGroup passed directly also brings its metadata.

A TsGroup as spike input supplies the spike times, the unit labels (its index) and its metadata. Population results carry the metadata as unit_table, so you can select units by region or quality after the analysis. pynapple's rate column is left out: pynapple computes it as spike count over the group's time support, which is not the time the analysis observed, so it is not a property of the unit. SpikeTrains(tsgroup) builds the same labelled container, and restrict_spike_trains(tsgroup, epochs) returns a SpikeTrains that keeps the labels and metadata, so units 5, 6 and 7 are still 5, 6 and 7 after restricting.

from neurospatial.decoding import decode_session

rates = compute_spatial_rates(env, tsgroup, times, positions)
rates.unit_table              # tsgroup.metadata without the rate column
ca1 = SpikeTrains(tsgroup).filter("region == 'CA1'")

result = decode_session(
    env, tsgroup, times, positions, dt=0.1, spike_window=recording_intervals
)

A TsGroup's time_support is not used: without spike_window=, spikes are assumed to have been recorded wherever position was tracked. Use the group's time support as spike_window= only if you set it to the true acquisition intervals: a TsGroup built from spike times alone gets a default support that runs from its first spike to its last, which is not recording coverage.

A TsdFrame or Tsd as positions or headings keeps its time support. With epochs=None, every public function that takes epochs and positions or headings uses the sample's time_support as its epochs, so a tracking gap shorter than max_gap is not counted as occupancy. Results that carry analysis_settings record the adopted windows in analysis_settings["epochs"]. An explicit epochs= is intersected with the sample's time_support, so only time inside both is analyzed. When those epochs are an Intervals, rate results record in analysis_settings["epoch_interval_ids"] the ids of its rows that overlap the support; a trial that falls entirely in a gap of the support is not listed. A Tsd passed as values to compute_tuning_curve(s) is read the same way. When positions and headings are both pynapple objects with different supports, the call is refused until you pass epochs= (for example their intersection). Every public function with a positions argument (also true_positions, actual_positions and decoded_positions), including Environment.from_samples and env.bin_at, refuses a TsdFrame whose columns are x/y/z in another order, as from_pynapple does.

A pynapple object as times (or frame_times, true_times, position_times, start_times, stop_times) is read as its timestamps, .t; so is one unit's Ts or Tsd passed as spike_times. np.asarray(tsd) would give the values instead, so times=speed_tsd would read speeds as seconds and a Tsd of spike amplitudes would put every spike at its amplitude. The time support of a pynapple times is not adopted as epochs; pass epochs=times.time_support if you need it.

# Same occupancy: the TsdFrame's two recording epochs are kept.
env.occupancy(tsdframe.t, tsdframe)
env.occupancy(tsdframe.t, tsdframe.values, epochs=tsdframe.time_support)

An IntervalSet is accepted wherever neurospatial takes intervals: epochs=, spike_window=, filter_by_intervals, intervals_to_events (its metadata columns are fields that preserve_fields= copies onto the events), the trial functions (trials_between_visits, time_to_goal, path_progress, distance_to_goal, compute_vte_session), write_trials and write_laps, which read it as from_pynapple does (metadata as fields, an interval_id column as the ids), the per-event replay functions such as mean_pairwise_bias, and, as a one-row set, the interval= of the one-event replay functions. Each inclusive end becomes the next float above it, so a point at end stays inside, as in pynapple. Pass the set itself rather than iset.as_dataframe(): that table's end column is inclusive, but read as a stop it would be treated as exclusive. A time series is not a set of intervals: epochs=tsd is refused with a pointer to tsd.time_support.

Event times passed as event_times=, reward_times= or theta_peak_times= accept a pynapple Ts or Tsd directly, and are read by its timestamps: a Tsd of reward sizes aligns to the reward times, not to the sizes. A TsGroup there is refused, because it holds one spike train per unit; pass tsgroup[unit_id] for one unit's spikes.

Trials and laps written to NWB

write_trials and write_laps store each row as start_time and stop_time, and neurospatial reads every row as the half-open window [start_time, stop_time): a sample exactly at stop_time is outside it. NWB does not say whether stop_time is inclusive, and pynapple's load_file reads the same table as an IntervalSet with an inclusive end. When trials stop exactly on a sample, the two routes select different samples:

Route Meaning of stop_time Samples kept (two trials, 100 Hz)
read_trials(nwbfile) as epochs= exclusive 500
nap.load_file(path)["trials"] with pynapple's restrict inclusive 502
that IntervalSet as epochs= inclusive 502

To get identical selections, pick one meaning and use it on both routes:

trials = read_trials(nwbfile)
rows = np.column_stack([trials.start, trials.stop])
iset = nap.load_file(path)["trials"]

# Half-open, as written: Intervals and plain arrays are read as [start, stop).
in_epochs(times, trials)
in_epochs(times, np.column_stack([iset.start, iset.end]))

# Inclusive, as pynapple reads it.
in_epochs(times, rows, closed="both")
in_epochs(times, iset)

Checking results against pynapple

Some results match pynapple exactly; others differ by design:

  • Spike counts. bin_spikes_in_time(tsgroup, dt=..., epochs=...) equals tsgroup.count(dt, ep=...), bin for bin.
  • 1-D Bayesian decoding. With equal-size bins, the posterior of decode_position matches nap.decode_bayes with its default uniform prior to floating-point precision. neurospatial's default prior is uniform over space (each bin's prior mass is proportional to its size), pynapple's is uniform over bins, so they differ when bin sizes differ. pynapple skips NaN rates when it sums the log-likelihood, so a bin with unknown rates counts as likelihood 1 and can collect posterior mass; neurospatial gives such bins zero posterior mass.
  • Rate maps differ from nap.compute_tuning_curves by design. With the default time_allocation="start", neurospatial assigns each spike to the position sample at or before it, pynapple to the nearest sample. Occupancy is the elapsed time to the next sample, while pynapple counts samples and converts with the mean sampling rate, so the two differ for irregular tracking. method="binned" is unsmoothed unless you pass a bandwidth, like pynapple's tuning curves.
  • Recording window. Use read_units(...).spike_window, the intersection of the units' observation intervals, as spike_window=. A TsGroup loaded from NWB by nap.load_file gets a time support from its first spike to its last and ignores obs_intervals.
  • What pynapple loads. nap.load_file does not load region crossings or other ndx-events tables, such as rewards; read them with read_events(nwbfile, table_name=...).

NWB interop

The NWB adapters read population spikes, position, and pose out of an NWB file, and round-trip a SpatialRatesResult back into one.

Requires the nwb extra

pip install neurospatial[nwb]. As with pynapple, import neurospatial never imports pynwb; the readers import it only when called.

Read components explicitly. These readers return frozen, non-iterable holders:

Reader Holder attributes
read_position NWBPosition.times, .positions, .units, .frame
read_head_direction NWBHeadDirection.times, .headings (radians), .frame
read_pose NWBPose.bodyparts, .times, .skeleton, .units, .frame, .confidence
read_units NWBUnits.spike_times, .unit_ids, .obs_intervals, .spike_window, .unit_table, .resolution

When a file holds more than one matching series or container, for example raw pixel and calibrated position, the reader raises and lists their paths instead of picking one. Pass the name or full path to position_name=, compass_name= or pose_estimation_name=.

Some files keep non-spatial values in the position series. DANDI 000447, for example, stores x, y and speed in one series with unit "centimeters; centimeters/second". Binning all three columns would treat speed as a third spatial axis, so read_position, environment_from_position and position_overlay_from_nwb refuse a series whose unit lists several units, or that has three or more columns under a unit that is not one length or pixel unit. The error quotes the series description, which often names the columns. Choose the spatial columns with columns=; when the series unit does not apply to them, state it:

pos = read_position(nwbfile, columns=[0, 1])        # x and y; pos.units is None
env = environment_from_position(nwbfile, bin_size=2.0, columns=[0, 1], units="cm")
overlay = position_overlay_from_nwb(nwbfile, columns=[0, 1], units="cm")

Position values already include the stored conversion and offset. Recognized unit aliases become m, cm, mm, um or px without scaling those values again. Other nonempty declarations remain visible; None means no unit was declared. Choose the physical unit explicitly in that case before creating an environment: environment_from_position refuses an undeclared unit unless you pass units=, and refuses units= or frame= values that conflict with the series declarations. Position reads also preserve nonempty SpatialSeries.reference_frame descriptions verbatim in .frame; None means no frame was declared. The position_overlay_from_nwb adapter forwards both units and frame and rejects keyword overrides that would erase or change a known declaration. Supply missing metadata explicitly, or transform the coordinates before using a different frame or physical unit. Equivalent unit spellings do not require conversion.

Head direction angles stored with unit radians or degrees are returned in radians; any other unit, including pynwb's default meters, raises because the angles could be either. .frame carries the series reference frame verbatim. The headings are assumed to be zero East and counterclockwise; if .frame says otherwise (for example "0 = North, clockwise"), convert with np.pi / 2 - hd.headings.

read_pose returns an NWBPose and checks that every bodypart uses the same sample clock, units and reference frame. Untracked keypoints stay NaN, and low-confidence keypoints are returned unchanged with their scores in .confidence; choose a threshold for your tracker and mask them yourself. Different clocks must be aligned explicitly before combining them into a pose. The bodypart_overlay_from_nwb adapter carries the declared units and reference frame into BodypartOverlay, which checks them against the environment. Convert coordinates explicitly when these declarations differ; supplying a different metadata label does not perform that conversion. Lazy pose reads validate the clocks without materializing the coordinate arrays.

Population fields, decoding and a truthful overlay

This recipe reads eager arrays from session.nwb, selects the named epochs table's rows tagged run, and uses those windows in both encoding and decoding. Adapt the table name, tags and 5-unit bin size to your experiment. Epochs are an explicit analysis choice; readers do not infer them from spike times.

units.spike_window is acquisition coverage: the intersection of observation intervals for the units selected by read_units(..., unit_ids=...). It can differ from the chosen analysis epochs. If the file has no obs_intervals column, it is None and analysis results report assumed spike coverage. A recorded empty intersection stays empty and analyses reject it; read units with different coverage in separate calls if their shared window is too short.

import matplotlib.pyplot as plt
import numpy as np
from pynwb import NWBHDF5IO

from neurospatial import Environment, compute_spatial_rates
from neurospatial.decoding import BayesianDecoder
from neurospatial.encoding import SpikeTrains
from neurospatial.io.nwb import read_intervals, read_position, read_units

with NWBHDF5IO("session.nwb", "r") as io:
    file = io.read()
    units = read_units(file)  # Or unit_ids=[7, 11] to select table labels.
    pos = read_position(file)
    all_epochs = read_intervals(file, interval_name="epochs")

# NWB tags are a tuple per epoch; keep the run epochs, selected by field.
epochs = all_epochs[all_epochs.tags.map(lambda tags: "run" in tags)]

# Eager arrays and interval metadata remain usable after the file closes.
position_units = pos.units
if position_units is None:
    raise ValueError("Choose position_units explicitly from the experiment's physical units.")
env = Environment.from_samples(pos.positions, bin_size=5.0, units=position_units)
cells = SpikeTrains(units.spike_times, unit_ids=units.unit_ids, unit_table=units.unit_table)
rates = compute_spatial_rates(
    env, cells, pos.times, pos.positions,
    epochs=epochs, spike_window=units.spike_window,
)
rate_table = rates.summary_table()
print(rate_table)

# Reuse the maps; the labelled trains meet their own cells' maps.
decoder = BayesianDecoder.from_rates(rates, dt=0.2)
result = decoder.predict(
    cells, pos.times, epochs=epochs, spike_window=units.spike_window,
)
print(result.summary())

# Align the original tracking and preserve gaps through the plotting API.
# A 2-D environment draws the x(t) and y(t) marginals on two axes.
axes = result.plot(
    show_map=True,
    true_times=pos.times, true_positions=pos.positions, max_gap=decoder.max_gap,
)
plt.show()

The posterior plot's y-axis is position in the environment's units. The actual overlay follows the same display coordinates as the posterior and MAP line, with breaks across missing tracking and recording gaps. See the decoder plotting recipe for the continuous/gapped-clock comparison. If an environment was already persisted in the file, use read_environment(file) inside the with block instead of inferring bins, with its coordinates matching the position channel.

read_units, read_position, and read_pose accept lazy=True for large files. Lazy position reads require identity conversion and offset.

Lazy handles are only valid while the file is open

Slice or materialize lazy arrays inside the with NWBHDF5IO(...) block. Eager arrays (the default), IDs and observation-window metadata remain valid after close.

with NWBHDF5IO("session.nwb", "r") as io:
    units = read_units(io.read(), lazy=True)
    first_unit = np.asarray(units.spike_times[0])

Selecting units by brain region

units.unit_table is a DataFrame with one row per unit, indexed by unit_id in the order of units.unit_ids. It holds every units-table column with one value per unit, such as location, cell_type or a curation quality, exactly as the file stores them. When units link electrodes, it adds electrode_location, the brain region from the electrodes table, and electrode_group, for example the tetrode. Pass the table to SpikeTrains and select cells with filter; encoding results carry it into their summary tables:

units = read_units(nwbfile)
cells = SpikeTrains(units.spike_times, unit_ids=units.unit_ids, unit_table=units.unit_table)
ca1 = cells.filter("electrode_location == 'CA1'")   # or the file's own "location"
rates = compute_spatial_rates(env, ca1, times, positions)

Region names are free text chosen by each lab ("CA1", "lCA1", "rCA1"), so check units.unit_table[column].unique() before filtering. A unit recorded on electrodes in several regions lists each region once, joined by ", ". units.resolution is the spike-time precision in seconds (usually one over the sampling rate), or None when the file does not state it. The table is read eagerly; with lazy=True only the spike times stay on disk.

Streaming from DANDI

You can analyze a DANDI file without downloading it. fsspec reads the remote file in blocks over HTTP, h5py opens it, and NWBHDF5IO reads the NWB structure with the file's own extension definitions (load_namespaces=True). Only the arrays you read are transferred, so read spike times lazily and position eagerly. Streaming needs the nwb extra plus fsspec and aiohttp: pip install "neurospatial[nwb]" fsspec aiohttp.

This example reads one linear-maze session of DANDI 000044 (Grosmark and Buzsáki, 2016). Find the asset id of your file in the "Files" view of the dandiset on the DANDI website.

import fsspec
import h5py
from pynwb import NWBHDF5IO

from neurospatial.io.nwb import environment_from_position, read_position, read_units

asset_id = "185b8a36-d671-4688-ba05-9e89a902c486"  # sub-Buddy, 2013-06-27
url = f"https://api.dandiarchive.org/api/assets/{asset_id}/download/"

remote = fsspec.filesystem("http").open(url, "rb", cache_type="blockcache")
with h5py.File(remote, "r") as h5, NWBHDF5IO(file=h5, mode="r", load_namespaces=True) as io:
    nwbfile = io.read()
    table = read_units(nwbfile, lazy=True).unit_table   # metadata, no spike times
    print(table["location"].value_counts())             # lCA1 61, rCA1 7
    left_ca1 = table.index[table["location"] == "lCA1"].tolist()
    units = read_units(nwbfile, unit_ids=left_ca1)      # these units' spikes

    # The file has an x-y series and a linearized series; name the one you want.
    xy = "1.6mLinearMazeSpatialSeries"
    pos = read_position(nwbfile, position_name=xy)
    env = environment_from_position(nwbfile, position_name=xy, bin_size=0.02)  # meters

read_position without position_name= raises here and lists both series paths. Everything read eagerly stays valid after the with block closes; lazy spike times must be read inside it. This file has no obs_intervals column, so units.spike_window is None; pass the recording epochs from read_intervals as spike_window= if you know them. Import ndx_events and ndx_pose before opening the file if you read events or pose.

Round-tripping rate maps

write_spatial_rates persists a population SpatialRatesResult — the per-unit firing-rate maps, shared occupancy, unit_ids, optional unit_table, and the Environment the maps were estimated on — and read_spatial_rates reconstructs an equal result. Because the environment round-trips with its connectivity intact, graph operations work on the restored env with no env= argument.

from pynwb import NWBHDF5IO
from neurospatial.encoding import compute_spatial_rates
from neurospatial.io.nwb import write_spatial_rates, read_spatial_rates

ca1 = compute_spatial_rates(env, ca1_spike_times, times, positions)
ca3 = compute_spatial_rates(env, ca3_spike_times, times, positions)

# Write. Rates estimated on one environment share one saved copy of it.
with NWBHDF5IO("session.nwb", "r+") as io:
    nwbfile = io.read()
    write_spatial_rates(nwbfile, ca1, name="ca1_place_fields", environment_name="open_field")
    write_spatial_rates(nwbfile, ca3, name="ca3_place_fields", environment_name="open_field")
    io.write(nwbfile)

# Read back (env restored from the file; an env= you pass must equal it).
with NWBHDF5IO("session.nwb", "r") as io:
    nwbfile = io.read()
    restored = read_spatial_rates(nwbfile, name="ca1_place_fields")
    restored.firing_rates.shape   # (n_units, n_bins)

Without environment_name=, each record saves its environment as f"{name}_environment". A record that already holds exactly the same environment (bins, arena, regions, landmarks, units, frame and name) is reused; a different environment under that name raises, so a rate map is never read with bins it was not estimated on. To link rates to an environment saved with write_environment(nwbfile, env, name="open_field"), pass environment_name="open_field". The rates also store a fingerprint of the environment record (environment_sha256), and read_spatial_rates refuses them if the record has changed since.

To replace a record, open the file with "r", call write_spatial_rates(..., overwrite=True), and save a copy with NWBHDF5IO(new_path, "w").export(src_io=io, nwbfile=nwbfile). pynwb cannot delete objects already written to a file opened with "r+", so overwrite=True refuses such files. An environment record that rates use is never replaced by a different environment, by write_spatial_rates or by write_environment(..., overwrite=True). When replacement rates name another environment, the replaced rates' default f"{name}_environment" record is removed if nothing else uses it.

What other NWB tools see

Saved environments and rate maps are standard DynamicTables in the file's top-level /analysis group, which NWB provides for shareable analysis results. Any NWB reader (pynwb, MatNWB, NWB Widgets, DANDI) can open them without neurospatial:

Path Contents
/analysis/ca1_place_fields One row per unit: unit_id, firing_rate (n_units, n_bins) in Hz, any unit_table columns. Its description is JSON metadata, with "format": "neurospatial.SpatialRates" and environment_name.
/analysis/ca1_place_fields/units Written when every unit_id is an id of nwbfile.units: a link from each row to that unit's row, so a rate map joins its spike times, electrodes and quality metrics.
/analysis/ca1_place_fields_occupancy One row per bin: occupancy in seconds.
/analysis/open_field The environment: one row, one column per array. Its description is JSON metadata with "format": "neurospatial.Environment".

In the environment record each column is named by its array, for example bin_centers (n_bins, n_dims) and binning.bins.sizes (bin area or length). Arrays are stored flat; the table description lists each array's shape and dtype under array_specs. Bin adjacency is binning.connections.all_pairs (pairs of bin indices) with binning.connections.all_distances; binning.connections.is_open is False where a wall closes the pair. No connectivity graph is stored: neurospatial rebuilds it from these arrays when it reads the record.

Trials round trip

write_trials writes an Intervals to the NWB trials table: each trial's interval_id is stored in an interval_id column (the table id is the row number, as NWB readers such as pynapple expect, so a selection of trials loads there too), and every field becomes a column. read_trials reads the table back as an Intervals with the same ids and fields, so trials detected in one session and trials loaded from a shared file go through the same analysis. NWB text columns cannot hold None, so a missing value, such as the end region of a trial that timed out, is stored as "" and read back as None.

A task log goes through the same path: read it into a DataFrame, name the column with the trial numbers, and write it. Its columns, such as the instructed goal, become fields of the trials table.

from datetime import datetime, timezone

import pandas as pd
from pynwb import NWBHDF5IO, NWBFile

from neurospatial import Intervals
from neurospatial.io.nwb import read_trials, write_trials

# One row per trial, as a behavior rig would log it (seconds, recording clock).
log = pd.DataFrame(
    {
        "trial": [1, 2, 3, 4],
        "start_time": [2.0, 14.5, 27.0, 40.2],
        "stop_time": [9.1, 21.0, 35.5, 52.0],
        "instructed_goal": ["left", "right", "left", "right"],
        "rewarded": [True, False, True, True],
        "end_region": ["left", None, "left", "right"],
    }
)
trials = Intervals.from_dataframe(log, id_column="trial")

nwbfile = NWBFile(
    session_description="T-maze session",
    identifier="trials-round-trip",
    session_start_time=datetime(2024, 1, 1, tzinfo=timezone.utc),
)
write_trials(nwbfile, trials)
with NWBHDF5IO("trials.nwb", "w") as io:
    io.write(nwbfile)

with NWBHDF5IO("trials.nwb", "r") as io:
    loaded = read_trials(io.read())

print(loaded)
print(loaded.intervals_table())
left = loaded[loaded.instructed_goal == "left"]
print(f"left trials: {left.interval_ids.tolist()}")

loaded has the trial numbers of the log as interval_ids, the same fields in the same order, and None where the log had no end region. Select a condition by field and pass it as epochs=, exactly as with trials from detect_trials.

Trials, laps, crossings and events

write_trials, write_laps, write_region_crossings and write_events store behavioral records as NWB tables. write_trials and write_laps take an Intervals and store its interval_ids in an interval_id column. A session with zero records writes no table: NWB best practice is not to write empty tables (nwbinspector reports them, and some of its checks crash on them, so dandi validate exits with an error). The writer writes nothing, without a warning, and reading that table back raises KeyError, so treat a missing table as zero trials, laps, crossings or events. Laps found without a template lap (detect_laps(..., method="region")) have no overlap score, so their table has no overlap_score column.

Event tables (write_events, write_region_crossings) are EventsTables. With pynwb 4 or later (NWB schema 2.10+), EventsTable is part of the NWB core schema, and a file written with it cannot be read by pynwb 3: the older reader does not know the newer core types, so read_events reports the table as missing. Use pynwb 4 or later to read files written with pynwb 4 or later. Files written with pynwb 3 read with either version.

See Also

Next Steps

  • Read components: select units and epochs explicitly, then pass holder attributes and acquisition coverage to your analysis.
  • Filter and restrict: attach a unit_table to SpikeTrains and select cells with .filter(...); carve out running epochs with restrict(...).
  • Decode as an object: reach for BayesianDecoder when you want a fit / predict / score surface — remembering it is byte-exact with decode_session.