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
Trials and other time intervals¶
Intervals and Interval, imported from the top level
(from neurospatial import Intervals): half-open time windows with stable
ids and named fields, from detect_trials, a task log or an NWB trials
table, usable as epochs= in any analysis. See the
tutorial.
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 Classes and Functions:
LayoutEngine: The protocol every layout implementsRegularGridLayout,HexagonalLayout,MaskedGridLayout,ShapelyPolygonLayout,GraphLayout,ImageMaskLayout,TriangularMeshLayout: Concrete layout implementationscreate_layout(),list_available_layouts(): Build a layout by name
Aligning environments¶
Move probability between the bins of aligned environments.
Key Functions:
map_probabilities(): Move probability mass (posteriors, occupancy) onto another environment's bins
Affine transforms and calibration¶
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 Functions (all public at neurospatial.encoding):
compute_spatial_rate(),detect_place_fields(),is_place_cell(): Place fields and spatial firing-rate mapsspatial_autocorrelation(),grid_score(): Grid cellscompute_directional_rate(),is_head_direction_cell(): Head-direction cells and tuning curvesborder_score(): Border / boundary cell metricscompute_object_vector_rate(),compute_egocentric_rate(): Object-vector cells and egocentric tuningcompute_view_rate(): Spatial-view cells and gaze-based fieldscompute_phase_precession(): Theta-phase precessioncompute_tuning_curve(): Tuning curves over one behavioral variablepopulation_coverage(),population_vector_correlation(): Population-level metrics
Key Functions:
compute_spatial_rate()/compute_spatial_rates(): Build firing-rate mapscompute_directional_rate(): Head-direction tuning curvecompute_tuning_curve()/compute_tuning_curves(): Firing rate against one behavioral variable, such as progress or distance to a goalcompute_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_jointly(): Decode several sets of rate maps (running directions, tracks) in one posterior; returns aJointDecodingResultwith each set's probability per time bindecode_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 metrics
Key Classes:
DecodingResult: Posterior + helpers (MAP, mean, entropy)DecodingSummary: Per-time decode summary (MAP / mean / entropy / peak) from the memory-safe summary decoders
neurospatial.replay¶
Score decoded candidate replay events and test them against shuffles. Detecting the candidate events (ripples, population bursts) is not included.
fit_isotonic_trajectory(),fit_linear_trajectory(),detect_trajectory_radon(): Fit replay trajectories along a track (Michon et al. 2019; Karlsson & Frank 2009 and Wu et al. 2017; Davidson et al. 2009); slopes are in environment units per secondfit_circular_sequence(): Fit the decoded path around a circular track, through the start of its linear position (Wikenheiser & Redish 2013)weighted_correlation(): Posterior-weighted correlation of time and position (Wu & Foster 2014)regression_line_score(): Posterior mass within a band of the least-squares line through each time bin's most likely position (Harvey et al. 2023; Soula et al. 2023)trajectory_metrics(),template_fractions(): Per-event metrics that criteria-based replay detection thresholds (jumps, spread, range, path length, dispersion, coverage, empty time bins) and the directional fraction of a joint decodereplay_segments(): Cut an event into segments in which the decoded position moves smoothly, by the jump, gap, merge and duration rules of Pfeiffer & Foster, Igata et al., Carey et al., Widloski & Foster and Mallory et al.; keep the longest or allreplay_significance(): Test any replay score against shuffles: column-cycle, unit-identity and pseudo-event (the default), spike-train and place-field circular shifts, time-bin permutation (the "time swap"), circular shifts of the time bins ("time_bin_circular", Bhattarai et al. 2020), spike times redrawn uniformly in the event ("spike_time_uniform", Stella et al. 2019) and the weighted column cycle ("column_cycle_weighted", Farooq et al. 2019; options throughnull_options=); significant when every null run rejects the eventrank_order_correlation(),rank_order_significance(): Spearman correlation of field order and firing order in an event, with a cell-order permutation test;multi_field_cells="exclude"leaves out cells with several place fields; needs no decodingpairwise_order_score(),pairwise_order_significance(): Firing order of every pair of spikes less than 80 ms apart against the cells' place-field order, summed (Gupta et al. 2010), with spike-time and cell-identity shuffles; cells with several fields take their best field;unit_groups=compares only cells on different tetrodes or shanks; needs no decodingdetect_replay(),compare_replay_methods(): Apply published replay methods (neurospatial.replay.methods: Davidson 2009, Karlsson & Frank 2009, Pfeiffer & Foster 2013 and 2015, Wikenheiser & Redish 2013, Ólafsdóttir 2015, 2016 and 2017, Silva 2015, Ambrose 2016, Grosmark 2016, Jadhav 2016, Tang 2017, Wu 2017, Yamamoto & Tonegawa 2017, Maboudi 2018, Carey 2019, Farooq 2019, Michon 2019, Muessig 2019, Shin 2019, Igata 2021, Bush 2022, Tirole 2022, Berners-Lee 2022, Widloski & Foster 2022, Harvey 2023 (weighted correlation and regression line), Liu 2023, Soula 2023, Mallory 2025, Chang 2025, Widloski & Foster 2025) to decoded events, including joint decodes over running directions, and compare their verdicts;ReplaySegmentationsets how criteria-based methods find the trajectory segmentnull_events(),simulated_null_events(),decode_intervals(): Events without replay (cell-identity, spike-shift, uniform-spike-time and rate-matched Poisson copies of real events, simulated random and stationary events) for false-positive ratesevent_properties(),detection_rates(),method_agreement(),score_agreement(): Calibrate methods on a comparison table: rates by event property with confidence intervals (false positives on null data), and agreement between methods' verdicts and scoresmatched_alpha(),apply_alpha(): Each method's α that holds its false-positive rate on null data to a target (Takigawa et al. 2024), and a comparison table's verdicts at those αdataset_values(),dataset_test(),CriterionGrid: Data-set-level replay tests: per-event values of the real data set and of null data sets measured by one method, and a Monte Carlo test of the share of events passing a grid of thresholds, such as Silva et al.'s (2015) significance matrix, withDatasetTestResult.plot();distribution_test()compares real and pooled null events' values (KS, rank-sum, Levene, side stated in terms of the values);shuffle_events()gives shuffled data sets as events;relative_rank_template()andtemplate_correlation_test()run Liu et al.'s (2019) template test;neurospatial.replay.datasetholds the papers' tests as recipes (SILVA_2015_MATRIX,SILVA_2015_RANK_ORDER,GROSMARK_2016_SURROGATES,FAROOQ_2019_*,LIU_2019_TEMPLATES,STELLA_2019_JITTER,XU_2019_ROTATION)detect_arm_replay(),ArmReplayMethod: Single-arm and joint-arm replay on a multi-arm maze (Wu & Foster 2014; Berners-Lee et al. 2021)detect_rank_order_replay(),RankOrderMethod: Apply published rank-order tests (Foster & Wilson 2006, Diba & Buzsáki 2007) to an event's spikes;compare_replay_methods(spike_times=...)compares them with the decoded methods and runs Chenani 2019, which tests an epoch's events togetherbest_sequence_match(),sequence_matching_index(): Template matching of firing order without decoding: Lee & Wilson's (2002) best (x, y) match of an event's letters, with the probability over the orderings of its letters, and Ji & Wilson's (2007) matching index with its exact p-value;burst_onset_times()andspike_words()cut spike trains into letters and wordsdetect_template_match_replay(),TemplateMatchMethod: Apply the template-matching recipes (LEE_WILSON_2002,JI_WILSON_2007) to an event;compare_replay_methods(spike_times=...)compares them with the other methods, andtemplate_match_dataset_test()runs the papers' data-set tests (binomial counts of pairs, triplets and low-probability words; chance and template-shuffle significance of replaying frames)recurring_spike_sequences(),recurring_sequences_significance(),surrogate_spike_trains(),RecurringSequenceMethod: Spike sequences that recur within a session, tested against interval-shuffle, jitter, across-train and theta-phase surrogates (Nádasdy et al. 1999,NADASDY_1999; session level, no per-event verdict)detect_pairwise_order_replay(),PairwiseOrderMethod: Apply the pairwise-order test of Gupta et al. 2010 (GUPTA_2010) to an event's spikes on every template (such as each lap), forward and backward;compare_replay_methods(spike_times=...)runs it with the other methodspairwise_bias_matrix(),mean_pairwise_bias(),bias_similarity(),bias_similarity_significance(): Skew-bias matrices of firing order for an event or averaged over many (such as theta cycles), and the cosine between two against permuted cell labels (Liu et al. 2023, after Drieu et al. 2018);detect_bias_sequence_replay(),BiasSequenceMethodandLIU_2023_BIASapply the published test, andcompare_replay_methods(template_bias=...)runs it with the other methodsshuffle_cell_identity(),shuffle_spike_counts_circular(),shuffle_spike_counts_uniform(),shuffle_place_fields_circular(),shuffle_posterior_circular(),shuffle_posterior_weighted_circular(): Replay shuffles;replay_significance(nulls=...)runs them by name
neurospatial.reactivation¶
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 correlationspairwise_activation(): co-firing in each bin weighted by every pair's template correlation, the full-matrix reactivation strength of Tingley & Peyrache (2020); its mean over a period is the inner product of the two periods' pair correlationsexplained_variance_reactivation(): EV (Kudrimoti et al., 1999) and REV (Pennartz et al., 2004) effect sizes over all pairs or selected pairs (unit_groups=for different tetrodes or regions,pair_mask=), with one or several control periods and a pair-level p-value that is anticonservative because pairs share cellsassembly_reactivation(): A pattern's mean activation strength after a task minus before it (van de Ven et al., 2016) and the share of post-task bins above the pre-task 99th percentile (Peyrache et al., 2010); effect sizes rather than significance verdictsdetect_assemblies(component_threshold=...): Marchenko-Pastur (default), Tracy-Widom, bin-shuffle or circular-shift eigenvalue thresholdsReactivationMethod,ReactivationWindows,EventResponse,PUBLISHED_REACTIVATION_METHODSandcompare_reactivation_methods(): published EV, assembly and member co-firing analyses (Kudrimoti 1999 to Robinson 2026) as recipes with their bin sizes, pair rules, windows and tests, applied to one session's spike times; spikes counted in fixed bins or one bin per event (SWRs, theta cycles), and assemblies followed around SWR onsetsdetect_assemblies(member_rule=...): members by absolute or signed weight z-scores, Otsu's split or weights above 1/√Nassembly_member_cofiring(): correlations of a pattern's members in two periods (El-Gaby et al., 2021);assembly_similarity(): absolute cosine similarity and best matches between sessions' patternsassembly_event_response(): R(t) averaged around events such as SWR onsets, each event's response and a signed-rank test against a baselineexplained_variance_contributions(): each pair's and unit's share of EV (Oliva et al., 2020);ev_rev_contrast(): (EV − REV) / (EV + REV)null_reactivation_data(),simulated_reactivation_session()andreactivation_detection_rates(): data without reactivation, a simulated session with a rate-change confound, and verdict rates with exact intervalsequalize_firing_rates(): subsample spikes so each unit fires at one rate before and after the task, the rate control of Giri et al. (2019)
See Comparing reactivation methods and the complete public workflow.
neurospatial.behavior¶
Behavioral analysis built on trajectory + environment.
Key Functions (all public at neurospatial.behavior):
step_lengths(),compute_cumulative_distance(),mean_square_displacement(),compute_planar_curvature(),compute_planar_turn_angles(),compute_movement_angular_velocity(),compute_home_range(): Trajectory metricscompute_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 dataresample_by_distance(): Distance resampling of observed runscompute_path_efficiency(),compute_goal_directed_metrics(),graph_turn_sequence(): Path efficiency, goal-directed metrics, graph turn sequencespath_progress(): Per-sample progress from a start to a goal, 0 to 1, in 1-D, 2-D and 3-D, per trial withintervals=distance_to_goal(),distance_to_boundary(),distance_to_reward(): Per-sample distance to a goal, the environment's edge or the reward location (GLM covariates)detect_laps(),detect_region_crossings(),segment_by_velocity(),detect_goal_directed_runs(): Laps, region crossings, movement epochs and goal-directed runs, each asIntervalsdetect_region_visits(): Observed visits to named regions with original sample indices and gap censoringdetect_trials(),trials_between_visits(): Trials, the runs between consecutive visits, from tracked positions or from port visits you bringcompute_decision_analysis(),compute_vte_session(): Decision-point analysis, vicarious trial-and-errorregion_reward_field(),goal_reward_field(): 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
Egocentric transforms¶
Allocentric ↔ egocentric coordinate transforms.
Key Functions:
allocentric_to_egocentric(),egocentric_to_allocentric(): Frame conversionsegocentric_bearing(),egocentric_distance(): Relate animal to external targets
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
Visibility and viewsheds¶
Visibility / gaze / viewshed computations.
Key Classes:
FieldOfView: Symmetric / rat / primate FOV presetsViewshedResult: Visible bins + visibility fraction
Key Functions:
viewshed(),view_field(),viewshed_trajectory(): Viewshed from positions / headingsviewed_location(): Gaze-direction projectionvisibility_occupancy(),visible_cues(): View-time aggregates
Spatial basis functions¶
Spatial basis functions for regression / kernel methods.
Key Functions:
select_basis_centers(): K-means / random / farthest-point placementgeodesic_rbf_basis(),heat_kernel_basis(),chebyshev_filter_basis(): Graph-aware kernelsspatial_basis(),plot_basis_functions(): Unified spatial-basis API
neurospatial.stats¶
Circular statistics, surrogates, and shuffle controls.
Key Functions (all public at neurospatial.stats):
rayleigh_test(),circular_mean(),circular_circular_correlation(),circular_linear_correlation(),circular_basis(): Circular statisticsshuffle_time_bins(),shuffle_pvalue(),shuffle_zscore(): Temporal, trial and spike-train shuffles and Monte Carlo p-values; replay shuffles are inneurospatial.replaygenerate_poisson_surrogates(),generate_inhomogeneous_poisson_surrogates(),generate_jittered_spikes(): 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 types (interval tables asIntervals)write_environment(),write_spatial_rates(),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.datasets¶
Loaders for published spatial neuroscience datasets, requiring
neurospatial[datasets] to load. See Public Datasets.
Key Functions and Classes:
catalog(): One row per session of every dataset, without downloadingload(),fetch_all(): Download, verify, check and read a session; download every session of a datasetRecording,Conversion,Provenance,VideoSource,LFPSource: A loaded session, each conversion applied (with its basis), where the file came from, and a session's camera video and local field potential, fetched on requestDatasetCheckError: Raised when a session fails the clock or units checkDownloadWarning: Issued before a session's file is downloaded, with its size, URL and cache directory
neurospatial.simulation v0.2.0+¶
Generate synthetic spatial data, neural activity, and spike trains for testing and validation.
Everything below is public at neurospatial.simulation; the maze builders are
in neurospatial.simulation.mazes.
Replay events:
simulate_replay_event(): A candidate replay event with a known path (sweep, stationary, jump or random), for comparing replay methods;drop_fraction=andn_noise_spikes=degrade it to measure each method's sensitivity (Tingley & Peyrache 2020)
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):
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):
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):
restrict(times, *arrays, epochs=...): Slicetimesand time-aligned arrays to a set of epochs.in_epochs(times, epochs): Boolean mask,Truewheretimesfalls in any epoch.restrict_spike_trains(spike_times, epochs): Mask ragged per-unit trains, each by its own timestamps; returns aSpikeTrainsthat keeps unit labels and metadata.
Bayesian decoder object (neurospatial.decoding):
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) — requires neurospatial[pynapple]:
from_pynapple(obj):TsGroup→(trains, unit_ids, epochs),Ts→(spike_times, epochs),Tsd/TsdFrame→(times, values, epochs),IntervalSet→Intervals(metadata as fields);epochsis the object's time support.to_pynapple(times, values=..., epochs=...): Decoded track / arrays →Tsd/TsdFramewhose time support isepochsor the decode'sspike_window.
NWB adapters (neurospatial.io.nwb) — requires neurospatial[nwb]:
read_position(...)→NWBPosition(times, positions, units, *, frame),read_head_direction(...)→NWBHeadDirection(times, headings, *, frame)andread_pose(...)→NWBPose(bodyparts, times, skeleton, *, units, frame, confidence). Several matching series or containers raise; choose one by name or path.read_position,environment_from_positionandposition_overlay_from_nwbtakecolumns=[0, 1]to keep the spatial columns of a series that also stores speed or other values.read_units(nwbfile, *, unit_ids=None, lazy=False)→NWBUnits(spike_times, unit_ids, obs_intervals, *, unit_table, resolution). Unit labels are unique table IDs; the derivedspike_windowintersects the selected units' acquisition coverage.unit_tableholds per-unit metadata such as brain region (electrode_location) and cell type, ready forSpikeTrains(..., unit_table=...). 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_spatial_rates(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.