Skip to content

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 as Environment.from_samples and Environment.from_polygon
  • BinSequenceWithRuns: Result of Environment.bin_sequence_with_runs
  • BinMapping: Result of Environment.bin_mapping_from, the exact bin pairs between an environment and the one it was derived from
  • CartesianSystem, 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 region
  • Regions: 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; None selects the default CPU outline provider.
  • annotate_project(project, *, project_path=None, autosave_interval=30.0, segmentation_provider=None): Resume a saved path or an AnnotationProject using its embedded reference frame.
  • AnnotationProject, AnnotationShape: Portable editable drafts in pixel coordinates, with AnnotationProject.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 implements
  • RegularGridLayout, HexagonalLayout, MaskedGridLayout, ShapelyPolygonLayout, GraphLayout, ImageMaskLayout, TriangularMeshLayout: Concrete layout implementations
  • create_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 maps
  • spatial_autocorrelation(), grid_score(): Grid cells
  • compute_directional_rate(), is_head_direction_cell(): Head-direction cells and tuning curves
  • border_score(): Border / boundary cell metrics
  • compute_object_vector_rate(), compute_egocentric_rate(): Object-vector cells and egocentric tuning
  • compute_view_rate(): Spatial-view cells and gaze-based fields
  • compute_phase_precession(): Theta-phase precession
  • compute_tuning_curve(): Tuning curves over one behavioral variable
  • population_coverage(), population_vector_correlation(): Population-level metrics

Key Functions:

  • compute_spatial_rate() / compute_spatial_rates(): Build firing-rate maps
  • compute_directional_rate(): Head-direction tuning curve
  • compute_tuning_curve() / compute_tuning_curves(): Firing rate against one behavioral variable, such as progress or distance to a goal
  • compute_egocentric_rate(): Object-vector tuning
  • compute_view_rate(): Spatial-view tuning
  • compute_phase_precession(): Theta-phase slope, offset and fit quality
  • detect_place_fields(): Threshold-and-cluster on a rate map
  • spatial_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 decoder
  • decode_session(): End-to-end decode of a full session (encode + decode) returning a DecodingResult
  • decode_jointly(): Decode several sets of rate maps (running directions, tracks) in one posterior; returns a JointDecodingResult with each set's probability per time bin
  • decode_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 units
  • decoding_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 second
  • fit_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 decode
  • replay_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 all
  • replay_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 through null_options=); significant when every null run rejects the event
  • rank_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 decoding
  • pairwise_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 decoding
  • detect_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; ReplaySegmentation sets how criteria-based methods find the trajectory segment
  • null_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 rates
  • event_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 scores
  • matched_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, with DatasetTestResult.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() and template_correlation_test() run Liu et al.'s (2019) template test; neurospatial.replay.dataset holds 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 together
  • best_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() and spike_words() cut spike trains into letters and words
  • detect_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, and template_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 methods
  • pairwise_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(), BiasSequenceMethod and LIU_2023_BIAS apply the published test, and compare_replay_methods(template_bias=...) runs it with the other methods
  • shuffle_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 members
  • assembly_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 test
  • pairwise_correlations(): Upper-triangle neuron-pair correlations
  • pairwise_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 correlations
  • explained_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 cells
  • assembly_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 verdicts
  • detect_assemblies(component_threshold=...): Marchenko-Pastur (default), Tracy-Widom, bin-shuffle or circular-shift eigenvalue thresholds
  • ReactivationMethod, ReactivationWindows, EventResponse, PUBLISHED_REACTIVATION_METHODS and compare_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 onsets
  • detect_assemblies(member_rule=...): members by absolute or signed weight z-scores, Otsu's split or weights above 1/√N
  • assembly_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' patterns
  • assembly_event_response(): R(t) averaged around events such as SWR onsets, each event's response and a signed-rank test against a baseline
  • explained_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() and reactivation_detection_rates(): data without reactivation, a simulated session with a rate-change confound, and verdict rates with exact intervals
  • equalize_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 metrics
  • compute_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 data
  • resample_by_distance(): Distance resampling of observed runs
  • compute_path_efficiency(), compute_goal_directed_metrics(), graph_turn_sequence(): Path efficiency, goal-directed metrics, graph turn sequences
  • path_progress(): Per-sample progress from a start to a goal, 0 to 1, in 1-D, 2-D and 3-D, per trial with intervals=
  • 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 as Intervals
  • detect_region_visits(): Observed visits to named regions with original sample indices and gap censoring
  • detect_trials(), trials_between_visits(): Trials, the runs between consecutive visits, from tracked positions or from port visits you bring
  • compute_decision_analysis(), compute_vte_session(): Decision-point analysis, vicarious trial-and-error
  • region_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 events
  • plot_peri_event_response(): Matching raster and PSTH using the same retained events and half-open histogram bins
  • align_spikes_to_events(): Per-trial spike rasters
  • align_continuous_to_events(): Speed, heading or zone sampled around events only where observed, with per-kind means and category counts
  • time_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 conversions
  • egocentric_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 environment
  • sample_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 presets
  • ViewshedResult: Visible bins + visibility fraction

Key Functions:

  • viewshed(), view_field(), viewshed_trajectory(): Viewshed from positions / headings
  • viewed_location(): Gaze-direction projection
  • visibility_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 placement
  • geodesic_rbf_basis(), heat_kernel_basis(), chebyshev_filter_basis(): Graph-aware kernels
  • spatial_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 statistics
  • shuffle_time_bins(), shuffle_pvalue(), shuffle_zscore(): Temporal, trial and spike-train shuffles and Monte Carlo p-values; replay shuffles are in neurospatial.replay
  • generate_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 export
  • AnimationView, EventInspector: Recording-time controls, and review of identified events
  • PositionOverlay, 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 as Intervals)
  • write_environment(), write_spatial_rates(), write_events(), write_laps(), write_region_crossings(), write_trials(): Persist neurospatial results back into an NWBFile
  • environment_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 downloading
  • load(), fetch_all(): Download, verify, check and read a session; download every session of a dataset
  • Recording, 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 request
  • DatasetCheckError: Raised when a session fails the clock or units check
  • DownloadWarning: 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= and n_noise_spikes= degrade it to measure each method's sensitivity (Tingley & Peyrache 2020)

Key Classes:

  • PlaceCellModel: Gaussian place field model with ground truth
  • BorderCellModel: Firing from the distance to the nearest wall
  • BoundaryVectorCellModel: Boundary vector cell (walls at a preferred distance and direction)
  • GridCellModel: Hexagonal grid cell model (2D only)
  • SimulationSession: Complete simulation session dataclass
  • SimulationValidationResult: Per-unit recovery of simulated place fields

Key Functions:

  • simulate_trajectory_ou(): Ornstein-Uhlenbeck process for realistic exploration
  • simulate_trajectory_sinusoidal(): Sinusoidal movement for 1D tracks
  • simulate_trajectory_laps(): Structured lap-based trajectories
  • generate_poisson_spikes(): Generate spikes from firing rates
  • generate_population_spikes(): Generate spikes for neuron populations
  • simulate_session(): One-call workflow for complete sessions
  • validate_simulation(): Compare detected place fields to ground truth (returns a SimulationValidationResult)
  • open_field_session(), linear_track_session(), etc.: Pre-configured examples

See Also:

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 attributes env, spike_times (a tuple of read-only arrays), unit_ids, times, positions, models, integer-label ground_truth, and metadata (read-only mappings). Pass attributes explicitly to analyses.
  • validate_simulation(sim, *, unit_ids=...) and plot_session_summary(sim, *, unit_ids=...) select simulation units by label.

Spike-train container (neurospatial.encoding):

  • SpikeTrains: Frozen ragged per-unit spike trains with unit_ids / optional unit_table. Positional access (st[i]), label selection (st.sel(unit_id=...)), iteration, .filter(query); flows directly into the batch compute_* / 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=...): Slice times and time-aligned arrays to a set of epochs.
  • in_epochs(times, epochs): Boolean mask, True where times falls in any epoch.
  • restrict_spike_trains(spike_times, epochs): Mask ragged per-unit trains, each by its own timestamps; returns a SpikeTrains that keeps unit labels and metadata.

Bayesian decoder object (neurospatial.decoding):

  • BayesianDecoder: Frozen fit(...) → predict(...) / predict_summary(...) / score(...) wrapper over decode_session (byte-exact). Decodes through the Environment, so linearized-track / geodesic decoding works.
  • BayesianDecoder.from_rates(rates, dt=...): Fitted decoder from a SpatialRatesResult, 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 from fit, from_rates or from_models.
  • fit(spike_times, times, positions, unit_ids=...) requires tracking positions; explicit labels must match a labelled spike group's values and order. decode_session also 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); epochs is the object's time support.
  • to_pynapple(times, values=..., epochs=...): Decoded track / arrays → Tsd / TsdFrame whose time support is epochs or the decode's spike_window.

NWB adapters (neurospatial.io.nwb) — requires neurospatial[nwb]:

  • read_position(...) → NWBPosition(times, positions, units, *, frame), read_head_direction(...) → NWBHeadDirection(times, headings, *, frame) and read_pose(...) → NWBPose(bodyparts, times, skeleton, *, units, frame, confidence). Several matching series or containers raise; choose one by name or path. read_position, environment_from_position and position_overlay_from_nwb take columns=[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 derived spike_window intersects the selected units' acquisition coverage. unit_table holds per-unit metadata such as brain region (electrode_location) and cell type, ready for SpikeTrains(..., unit_table=...). Choose analysis epochs with read_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_units accept lazy=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 a SpatialRatesResult (firing rates / occupancy / unit ids / unit_table + a persisted, connected environment).

Layout Engines

Detailed documentation for each layout engine:

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.