API Reference¶
Complete API documentation for neurospatial, automatically generated from source code docstrings.
Start with the root workflows¶
from neurospatial import (
Environment,
compute_spatial_rate,
compute_spatial_rates,
SpatialRateResult,
SpatialRatesResult,
decode_position,
DecodingResult,
peri_event_histogram,
PeriEventResult,
)
These workflows load lazily. Use domain imports for specialized analyses. The shared-unit workflow shows simulation and four-array encoding followed by separate decoding and population-statistics branches.
Core Modules¶
neurospatial.environment¶
The Environment class: bins, their connectivity graph and named regions,
with methods for spatial queries, occupancy, smoothing, plotting and saving.
Key Classes:
Environment: Discretized spatial environment, built with factory classmethods such asEnvironment.from_samplesandEnvironment.from_polygonBinSequenceWithRuns: Result ofEnvironment.bin_sequence_with_runsBinMapping: Result ofEnvironment.bin_mapping_from, the exact bin pairs between an environment and the one it was derived fromCartesianSystem,EgocentricPolarSystem: What the bin coordinates mean
Every method is documented on the
Environment reference page. The
_-prefixed modules in this package hold private implementations.
Combining environments¶
Build one ordinary environment from disjoint component environments.
Key Classes:
Environment.combine: Combine disjoint environments with automatic navigation bridges
neurospatial.regions¶
Define and manage named regions of interest (ROIs).
Key Classes:
Region: Immutable point or polygon regionRegions: Container for managing multiple regions
neurospatial.annotation¶
Draw arena boundaries, holes, named regions, walls and landmarks on a video frame. See the video annotation guide.
annotate_video(video_path, *, project_path=None, autosave_interval=30.0, segmentation_provider=None, ...): Open a reference frame in napari;Noneselects the default CPU outline provider.annotate_project(project, *, project_path=None, autosave_interval=30.0, segmentation_provider=None): Resume a saved path or anAnnotationProjectusing its embedded reference frame.AnnotationProject,AnnotationShape: Portable editable drafts in pixel coordinates, withAnnotationProject.save(path)and.load(path).RegionGrowProvider,SegmentAnythingProvider: CPU color segmentation and an optional adapter for a separately installed SAM 2 image predictor.SegmentationPrompt,SegmentationProposal,SegmentationProvider,mask_to_polygons: Viewer-independent point prompts, mask results, provider contract and exact pixel-cell polygon conversion.
neurospatial.layout¶
Layout engines for discretizing continuous space.
Key Modules:
layout.base:LayoutEngineprotocol definitionlayout.engines.*: Concrete layout implementationslayout.factories: Factory functions for creating layouts
neurospatial.ops.alignment¶
Move probability between the bins of aligned environments.
Key Functions:
map_probabilities(): Move probability mass (posteriors, occupancy) onto another environment's bins
neurospatial.ops.transforms¶
Affine transformations and video calibration.
Key Classes:
AffineND: Composable affine transformations in any dimension
neurospatial.encoding¶
Neural encoding analyses: how neurons represent space, direction, egocentric targets, and gaze.
Key Modules:
encoding.spatial: Place fields and spatial firing-rate mapsencoding.grid: Grid cells (autocorrelation, gridness score)encoding.directional: Head-direction cells and tuning curvesencoding.border: Border / boundary cell metricsencoding.egocentric: Object-vector cells and egocentric tuningencoding.view: Spatial-view cells and gaze-based fieldsencoding.phase_precession: Theta-phase precessionencoding.population: Population-level metrics
Key Functions:
compute_spatial_rate()/compute_spatial_rates(): Build firing-rate mapscompute_directional_rate(): Head-direction tuning curvecompute_egocentric_rate(): Object-vector tuningcompute_view_rate(): Spatial-view tuningcompute_phase_precession(): Theta-phase slope, offset and fit qualitydetect_place_fields(): Threshold-and-cluster on a rate mapspatial_information(),sparsity(),selectivity(),border_score(),grid_score(): Classic place / boundary / grid metrics
neurospatial.decoding¶
Bayesian decoding of position from spike counts.
Key Functions:
decode_position(): Single-step or sequential Bayesian decoderdecode_session(): End-to-end decode of a full session (encode + decode) returning aDecodingResultdecode_position_summary()/decode_session_summary(): Memory-safe, streaming decoders that return per-time summaries (MAP / mean / entropy / peak) without materializing the full(n_time, n_bins)posterior — for long sessions / thousands of unitsdecoding_error(),median_decoding_error(): Accuracy metricsfit_isotonic_trajectory(),fit_linear_trajectory(),detect_trajectory_radon(): Fit replay trajectories along a track; slopes are in environment units per secondreplay_trajectory_significance(): Davidson et al. (2009) replay test, the replay score against column-cycle, unit-identity and pseudo-event shuffles
Key Classes:
DecodingResult: Posterior + helpers (MAP, mean, entropy)DecodingSummary: Per-time decode summary (MAP / mean / entropy / peak) from the memory-safe summary decoders
neurospatial.decoding.assemblies¶
Population covariance and reactivation analyses take count matrices with the
same units in the template, match and control periods. Pass each period's
column labels (unit_ids= or template_unit_ids=, match_unit_ids=,
control_unit_ids=) to match cells by label; without labels the columns pair
by position:
detect_assemblies(): Dimensions above the Marchenko-Pastur reference and fitted patterns; a selected dimension may have no thresholded core membersassembly_activation(): Activation strength (co-firing of the pattern's cells) in each bin of a chosen period; descriptive rather than a calibrated bin-level significance testpairwise_correlations(): Upper-triangle neuron-pair correlationsexplained_variance_reactivation(): EV and controlled REV effect sizes; pass an explicit baseline control and avoid treating EV > REV as a p-valuereactivation_strength(): Mean activation strength in the match period over the template period; an effect size rather than a significance verdict
See the complete public workflow.
neurospatial.behavior¶
Behavioral analysis built on trajectory + environment.
Key Modules:
behavior.trajectory: Speed, step lengths, cumulative distance, MSD, curvature, planar turning angles, planar curvature, movement angular velocity, home rangecompute_speed(times, positions),heading_from_velocity(times, positions),heading_from_body_orientation(times, nose, tail): Per-sample speed and heading (radians, 0 = East) from tracking databehavior.resampling: Distance resampling of observed runsbehavior.navigation: Path efficiency, goal-directed metrics, graph turn sequencesdistance_to_region(),distance_to_boundary(),distance_to_reward(): Per-sample distance to a goal, the environment's edge or the reward location (GLM covariates)behavior.segmentation: Laps, trials, region crossings, velocity-based segmentationdetect_region_visits(),region_transitions(): Observed visits and entry-to-entry transitions with original sample indices and gap censoringbehavior.decisions/behavior.vte: Decision-point analysis, vicarious trial-and-errorbehavior.reward: Reward-field construction
neurospatial.events¶
Peri-event spike alignment and GLM regressors.
Key Functions:
peri_event_histogram(): PSTH around discrete eventsplot_peri_event_response(): Matching raster and PSTH using the same retained events and half-open histogram binsalign_spikes_to_events(): Per-trial spike rastersalign_continuous_to_events(): Speed, heading or zone sampled around events only where observed, with per-kind means and category countstime_to_nearest_event(),event_count_in_window(),event_indicator(): Time-based GLM regressors
neurospatial.ops.egocentric¶
Allocentric ↔ egocentric coordinate transforms.
Key Functions:
allocentric_to_egocentric(),egocentric_to_allocentric(): Frame conversionscompute_egocentric_bearing(),compute_egocentric_distance(): Relate animal to external targets
neurospatial.ops.feature_sampling¶
Read bin-valued feature maps (floor texture, zones, heights) along the path.
Key Functions:
sample_spatial_features(env, fields, positions): Value of the bin that contains each position, NaN outside the environmentsample_egocentric_features(env, fields, positions, headings, ego_points): The same at points fixed in the animal's frame (ahead, left)SpatialFeatureResult: Sampled values with per-sample support and bins
neurospatial.ops.visibility¶
Visibility / gaze / viewshed computations.
Key Classes:
FieldOfView: Symmetric / rat / primate FOV presetsViewshedResult: Visible bins + visibility fraction
Key Functions:
compute_viewshed(),compute_view_field(),compute_viewshed_trajectory(): Viewshed from positions / headingscompute_viewed_location(): Gaze-direction projectionvisibility_occupancy(),visible_cues(): View-time aggregates
neurospatial.ops.basis¶
Spatial basis functions for regression / kernel methods.
Key Functions:
select_basis_centers(): K-means / random / farthest-point placementgeodesic_rbf_basis(),heat_kernel_wavelet_basis(),chebyshev_filter_basis(): Graph-aware kernelsspatial_basis(),plot_basis_functions(): Unified spatial-basis API
neurospatial.stats¶
Circular statistics, surrogates, and shuffle controls.
Key Modules:
stats.circular: Rayleigh test, circular mean / variance / R, circular-circular and circular-linear correlations, circular basisstats.shuffle: Position / cell / posterior shuffles with reproducibility helpersstats.surrogates: Poisson and inhomogeneous-Poisson surrogates, jittered-spike controls
neurospatial.animation¶
Spatial fields over time on the recording clock: napari, notebook widget and fastplotlib viewers, and video, GIF and HTML exports.
Key Function:
Environment.animate_fields(): One call that opens a view (AnimationView) or writes a file (Path)
Key Classes:
Animation,AnimationField: Reusable scenes of named fields, each on its own clock, shared by every view and exportAnimationView,EventInspector: Recording-time controls, and review of identified eventsPositionOverlay,BodypartOverlay,HeadDirectionOverlay,EventOverlay,VideoOverlay,TimeSeriesOverlay,SpikeRasterOverlay,EpochOverlay,ObjectVectorOverlay: Composable overlays for animations
neurospatial.io.nwb¶
NWB (Neurodata Without Borders) read / write integration.
Key Functions:
read_environment(),read_position(),read_units(),read_head_direction(),read_pose(),read_events(),read_intervals(),read_trials(): Read NWB components into neurospatial typeswrite_environment(),write_place_field(),write_occupancy(),write_events(),write_laps(),write_region_crossings(),write_trials(): Persist neurospatial results back into an NWBFileenvironment_from_position(): Build an environment directly from the position channel of an NWB file
neurospatial.simulation v0.2.0+¶
Generate synthetic spatial data, neural activity, and spike trains for testing and validation.
Key Modules:
simulation.trajectory: Trajectory generation (OU process, structured laps)simulation.models: Neural models (place, border, boundary-vector and grid cells)simulation.spikes: Spike generation (Poisson process, refractory periods)simulation.session: High-level session simulation APIsimulation.validation: Automated validation against ground truthsimulation.examples: Pre-configured example sessions
Key Classes:
PlaceCellModel: Gaussian place field model with ground truthBorderCellModel: Firing from the distance to the nearest wallBoundaryVectorCellModel: Boundary vector cell (walls at a preferred distance and direction)GridCellModel: Hexagonal grid cell model (2D only)SimulationSession: Complete simulation session dataclassSimulationValidationResult: Per-unit recovery of simulated place fields
Key Functions:
simulate_trajectory_ou(): Ornstein-Uhlenbeck process for realistic explorationsimulate_trajectory_sinusoidal(): Sinusoidal movement for 1D trackssimulate_trajectory_laps(): Structured lap-based trajectoriesgenerate_poisson_spikes(): Generate spikes from firing ratesgenerate_population_spikes(): Generate spikes for neuron populationssimulate_session(): One-call workflow for complete sessionsvalidate_simulation(): Compare detected place fields to ground truth (returns aSimulationValidationResult)open_field_session(),linear_track_session(), etc.: Pre-configured examples
See Also:
- Simulation Workflows Tutorial: Comprehensive examples and quick start guide
Interoperability and data holders¶
Named data holders and optional adapters for the array-first API
(see the Interoperability guide). The array
path never depends on these; import neurospatial never imports pynapple or
pynwb.
Simulator holder (neurospatial.simulation.session):
SimulationSession: Immutable attributesenv,spike_times(a tuple of read-only arrays),unit_ids,times,positions,models, integer-labelground_truth, andmetadata(read-only mappings). Pass attributes explicitly to analyses.validate_simulation(sim, *, unit_ids=...)andplot_session_summary(sim, *, unit_ids=...)select simulation units by label.
Spike-train container (neurospatial.encoding.spike_trains):
SpikeTrains: Frozen ragged per-unit spike trains withunit_ids/ optionalunit_table. Positional access (st[i]), label selection (st.sel(unit_id=...)), iteration,.filter(query); flows directly into the batchcompute_*/decode_*functions. Population results select units the same way:rates[i]by position,rates.sel(unit_id=...)by label.
Epoch selection (neurospatial.behavior.epochs):
restrict(times, *arrays, epochs=...): Slicetimesand time-aligned arrays to a set of epochs.in_epochs(t, epochs): Boolean mask,Truewheretfalls in any epoch.restrict_spike_trains(spike_times, epochs): Mask ragged per-unit trains, each by its own timestamps.
Bayesian decoder object (neurospatial.decoding.estimator):
BayesianDecoder: Frozenfit(...)→predict(...)/predict_summary(...)/score(...)wrapper overdecode_session(byte-exact). Decodes through theEnvironment, so linearized-track / geodesic decoding works.BayesianDecoder.from_rates(rates, dt=...): Fitted decoder from aSpatialRatesResult, preserving unit identity and training spike-window provenance. Prediction takes spikes and array timestamps; supplied labels align by identity, generated labels pair by position.BayesianDecoder.from_models(env, encoding_models, unit_ids=..., spatial_support=..., dt=...): Fitted decoder from hand-built(n_units, n_bins)rate maps, such as a simulation's ground truth. The constructor takes configuration only; fitted decoders come fromfit,from_ratesorfrom_models.fit(spike_times, times, positions, unit_ids=...)requires tracking positions; explicit labels must match a labelled spike group's values and order.decode_sessionalso requires positions and computes its own encoding maps.
pynapple adapters (neurospatial.io.pynapple) — requires neurospatial[pynapple]:
from_pynapple(obj):TsGroup→(trains, unit_ids),Tsd/TsdFrame→(times, positions),IntervalSet→(start, end).to_pynapple(times, values=...): Decoded track / arrays →Tsd/TsdFrame.
NWB adapters (neurospatial.io.nwb) — requires neurospatial[nwb]:
read_position(...)→NWBPosition(times, positions, units)andread_head_direction(...)→NWBHeadDirection(times, headings).read_units(nwbfile, *, unit_ids=None, lazy=False)→NWBUnits(spike_times, unit_ids, obs_intervals, spike_window). Unit labels are table IDs;spike_windowintersects the selected units' acquisition coverage. Choose analysis epochs withread_intervals(nwbfile, interval_name="epochs").- Holders are frozen and cannot be tuple-unpacked. Position units describe
converted values; missing declarations are
None.read_position/read_pose/read_unitsacceptlazy=True(handles valid only while the file is open; eager arrays remain usable after close). - The complete NWB recipe carries physical units, labels, selected epochs and acquisition coverage through population fields, a fitted decoder, summary tables and overlays.
write_spatial_rates(nwbfile, result)/read_place_field(nwbfile, env=None): Round-trip aSpatialRatesResult(firing rates / occupancy / unit ids /unit_table+ a persisted, connected environment).
Layout Engines¶
Detailed documentation for each layout engine:
- RegularGridLayout
- HexagonalLayout
- GraphLayout
- MaskedGridLayout
- ShapelyPolygonLayout
- TriangularMeshLayout
- ImageMaskLayout
Navigation¶
Use the sidebar to browse the complete API reference, or search for specific functions, classes, or methods.
Docstring Format¶
All docstrings follow NumPy docstring conventions for consistency with the scientific Python ecosystem.