Skip to content

10. Operation Specifications & API Invariants

The architectural and numerical contracts every 0.2 release holds to: what a function does with randomness and devices, how it reports a fit it cannot support, the shapes and units it speaks in, and, per operation, the estimator, the result type, and the failure semantics.

These are contracts for callers. The rules for adding an operation are in CONTRIBUTING.md.


1. Cross-Cutting Architectural Invariants

Every operation added in 0.2 follows these conventions.

1. RNG Convention

Functions consuming stochasticity take rng and resolve it through jnwb._rng.resolve_rng, so every one accepts the same values. The value is checked no later than the function's first draw from it:

Accepted rng Functions Other values
an int seed, a Generator, or None the StatisticalAnalysis methods, build_permutation_plan, cluster_permutation_test, coherence_bias_floor, cross_area_coherence, cross_modal_comparison, curate_and_label, exact_sign_flip, granger, granger_nonparametric, granger_spectral, granger_time_reversed, jrsa, nested_cv_linear_svm, paired_fire_prob_test, partial_coherence, permute_labels, phase_slope_index, PopulationAnalyzer.compare_criteria, resample_onsets, screen_units_against_labels, shuffle_pvalue_paired, shuffle_pvalue_unpaired, shuffle_r2_ci, transfer_entropy, UnitAnalyzer.psth, wavemap, wavemap_resolution_sweep, xflip, zflip, the testing.synth builders and testing.SynthNWBBuildOptions TypeError, for a float, a bool, a SeedSequence, a bit generator and a list alike

build_canonical_tutorial_nwb and SynthNWBBuildOptions spell the argument seed.

build_permutation_plan names each draw by an integer seed: a Generator or None gives one integer base seed, which the plan returns as seed.

  • The default you see is the seed you get. Most rng parameters default to the seed the function will use (42, 0, or no default at all where the caller must choose), so inspect.signature and help() report the stream a bare call draws. A body that reads a None default and substitutes a fixed seed is a repaired defect: five functions did that, so two calls a caller believed were independent returned the same null. jnwb/_rng.py holds the history and the resolver.
  • None means fresh OS entropy, as in NumPy. Three public functions default to it because drawing fresh per call is their contract: cross_modal_comparison, jrsa and xflip.
  • Generator Preservation & Resolution: If isinstance(rng, np.random.Generator), the caller's generator is used directly, so the call advances the caller's stream. If rng is an integer seed or None, it is converted via:
    local_rng = rng if isinstance(rng, np.random.Generator) else np.random.default_rng(rng)
    
    granger, granger_spectral, phase_slope_index, transfer_entropy, cross_modal_comparison, cross_area_coherence, xflip and zflip instead draw one child seed from a Generator, run on default_rng(child) and record the child as surrogate_seed_entropy, so the result alone reproduces its p-values.
  • Prohibited: Never call np.random.seed(), random.seed(), or manipulate global RNG state.
  • Parallel Workers: a result computed across workers is fixed by iteration index and identical at every n_jobs, because every draw an iteration needs is made from the caller's rng before any worker starts:
Function Drawn from rng before the workers start
cluster_permutation_test one child seed per permutation, from jnwb._parallel.spawn_seeds: one integer drawn from rng seeds np.random.SeedSequence(entropy).spawn(n_permutations)
jrsa one integer seed per permutation
cross_area_coherence every surrogate shift

2. Device Convention

  • Functions with a device argument accept device: str = "cpu", "cuda" or "metal".
  • Resolution occurs through jnwb._backend.resolve_device(device, context=...).
  • GPU paths: "cuda" computes on the GPU in complex_tfr, cross_area_coherence, PopulationAnalyzer.population_trajectory, spectral_tilt, harmonic_analysis, imaginary_coherency, wpli, granger, UnitAnalyzer.autocorrelogram and compute_population_trajectory. "metal" computes on the GPU only in complex_tfr with dtype=np.complex64, and every other function warns on it and computes on the CPU; the Metal path is implemented and has not been run on Metal hardware.
  • No GPU path: band_power, relative_power, rdm, vflip, vflip_from_lfp and jrsa warn on "cuda" and compute on the CPU even with a GPU present.
  • Fallback Observability: When a GPU is requested but unavailable, or the GPU run raises, the call computes on the CPU and emits a RuntimeWarning via jnwb._backend.warn_device_fallback(context, exc).
  • The result records the device that ran: .device on the ComplexTFR from complex_tfr, device_used on the other GPU-capable results.

3. Missing/Invalid Data vs Non-Identifiability

  • Invalid Input / Misuse: Nonsensical dimensions, negative frequencies, negative power values passed into logarithmic transforms, incompatible array shapes, or missing required metadata fail loudly by raising ValueError or TypeError.
  • Non-Identifiability: When mathematically valid data fails to support an empirical fit (e.g. support score below threshold, diverging parameter optimization, zero variance across contacts), the function must not raise an unhandled exception and must never return fabricated numbers or silently substitute fallbacks. Instead, it returns an explicit structured state with accepted=False, boundary status flags, and crossover_contact=None or layer label 'na'.

4. Structured Return Types

  • Complex multi-parameter estimators return dataclasses (e.g. VFlipResult, AperiodicFitResult, DirectedResult, JRSAResult, ComplexTFR, EventTable).
  • AperiodicFitResult, DirectedResult, LaminarCurationResult, VFlipResult, VFlip2Result, XFlipResult and ZFlipResult implement .to_dict() and mapping access (__getitem__), so they unpack like the dictionaries they replaced and serialize. ComplexTFR, EffectiveRate, EventTable, JRSAResult, ProbeGeometry, SynthLaminarReceipt, SynthVFlip2Receipt and TickClock are attribute-only: read their fields as attributes (result.value, result.p).

5. Axis & Dimension Vocabulary

  • Array dimensions follow standard named tensor shapes:
  • Continuous signals: channel-major (n_channels, n_times), except where a function says otherwise in its own signature. This line read (n_times, n_channels) until 0.2.5 and named the minority: of the ten exported functions taking a 2-D continuous signal, eight are channel-major (bipolar_reference, laplacian_reference, channel_correlation_matrix, current_source_density_1d, voltage_curvature_1d, vflip_from_lfp, xflip, zflip: the spatial, re-reference and depth family, for which a channel axis is the axis being operated on) and two are time-major (compute_psd, whose axis argument selects it explicitly and defaults to 0, and epoch_continuous, which returns (n_events, n_window_samples, n_channels)). A blanket claim matters here because a reader consults this section exactly when a docstring is silent, and a transposed array of a probe with many channels stays plausible: laplacian_reference on it returns the right shape and the wrong numbers.
  • Trial-aligned epochs: (n_trials, n_channels, n_times)
  • Time-frequency representations: (n_trials, n_channels, n_freqs, n_times) or (n_channels, n_freqs, n_times)
  • Spectral profiles: (n_channels, n_freqs)
  • Axis arguments default to explicit keywords (e.g., axis=-1, aggregate_over=None).

6. Physical Units

  • Coordinates and electrode contact depths: micrometers.
  • Sampling rates and spectral frequencies: Hertz (\(\text{Hz}\)).
  • Continuous time: seconds (\(\text{s}\)).
  • Peristimulus / raster windows and bin sizes: milliseconds (\(\text{ms}\)) when prefixed with _ms (e.g., win_ms, bin_ms, tau_ms).
  • Power & Spectral Density: Preserves and derives input signal units rather than assuming microvolts. For an input signal in unit \(U\) (e.g., \(\text{V}\) or \(\mu\text{V}\)), raw spectral density is \((U)^2/\text{Hz}\) and integrated band power is \((U)^2\). When input units are unrecorded or generic arrays are processed, dimensional quantities are \((U_{\text{in}})^2/\text{Hz}\) and \((U_{\text{in}})^2\). Conversion to decibels (\(\text{dB}\)) is dimensionless ratio-scale relative to baseline, explicitly controlled via to_db or aggregate_to_db and computed last.

7. Estimand Disambiguation: Population Trajectory PCA

  • PopulationAnalyzer.population_trajectory(X): Unstandardized covariance PCA (centering only, \(\mathbf{X} - \boldsymbol{\mu}\)). Features with higher firing rates dominate variance.
  • compute_population_trajectory(session, ...): Standardized correlation PCA (z-score scaling, \((\mathbf{X} - \boldsymbol{\mu})/\boldsymbol{\sigma}\)). Units contribute equally regardless of baseline rate.
  • The two are distinct estimands and must not be substituted for each other.

8. Synthetic Data Policy (testing.synth)

  • Synthetic generators and null fixtures belong in jnwb/testing/ (e.g. jnwb/testing/synth.py).
  • Synthetic generators are test infrastructure and are never presented as empirical observations.

2. Operation Specifications

Operation Module Location Input & Shapes Units Estimator & Math Output / Result Type Failure & Non-Identifiability Randomness & Device Composition & Tests
aperiodic_fit jnwb.spectral freqs: (n_freqs,), psd: (n_freqs,) or (..., n_freqs), freq_range: Tuple[float, float], mode: str = "fixed" \(\text{Hz}\), \((U_{\text{in}})^2/\text{Hz}\) Fits \(L(f) = b - \log_{10}(k + f^\chi)\) in log-log space. Fixed mode sets \(k=0\); knee mode optimizes \(k > 0\). Does not recompute PSD. AperiodicFitResult dataclass with offset, exponent, knee, r_squared, freq_range, mode, accepted. Raises ValueError for non-positive freqs/psd or \(<4\) points. Returns accepted=False if optimization fails to converge. Deterministic (no RNG). Runs on CPU. Composes with compute_psd. Tested against analytic power-law spectra.
relative_power jnwb.spectral power: (...), baseline: (...), model: str = "mean_of_ratios" \((U_{\text{in}})^2\) or \((U_{\text{in}})^2/\text{Hz}\) (ratio is dimensionless or \(\text{dB}\)) Ratio of power to baseline. Explicit model selection: "mean_of_ratios" (\(\mathbb{E}[P/P_0]\)), "ratio_of_means" (\(\mathbb{E}[P]/\mathbb{E}[P_0]\)), or "log_ratio" (\(10 \log_{10}(P/P_0)\)). np.ndarray matching broadcast shape. Raises ValueError for negative or non-finite inputs, zero baseline division, or unrecognized model. Deterministic. CPU only: device="cuda" or "metal" warns and computes on the CPU. Composes with band_power and aggregate_to_db. Tested for distinct numerical results across models.
Session-level exact stats jnwb.statistics (StatisticalAnalysis) exact_sign_flip(diffs), mann_whitney_p_floor(n1, n2), clopper_pearson(k, n, alpha), fdr_correct(p_values) Unitless p-values / proportions Exact permutations (\(2^N\) sign flips), combinatorial p-value floor (\(\binom{n_1+n_2}{n_1}^{-1}\) one-sided, doubled and capped at 1 two-sided), exact binomial inversion, and Benjamini-Hochberg FDR. Exact p-values, confidence interval tuples, or adjusted array. Raises ValueError for \(N=0\) or invalid probability inputs. Handles ties conservatively. Exact combinatorial (no RNG required for \(N \le 20\); Monte Carlo for \(N > 20\) with rng). Composes with group comparison tests. Tested against full enumeration.
stream_npz_array jnwb.io file_path: Path, key: str, slice_tuple: Tuple[slice, ...] Array dtype Streams memory-mapped or chunked slices from compressed/uncompressed NPZ archives without full-file RAM allocation. np.ndarray slice, indexed as NumPy indexes: an integer removes its axis Raises KeyError if key missing; raises ValueError for corrupt archives or unsupported compression layouts; raises IndexError and ValueError for an invalid index where NumPy does (a non-integer scalar such as 1.0 included), and TypeError for an index NumPy accepts that is not an integer or a slice (None, ..., a boolean, a list or an array). Deterministic. IO bound. Verified by comparing memory consumption and array equality against np.load.
derive_tick_clock jnwb.continuous tick_segments: 1-D tick arrays in recording order, spike_times: one array or a sequence, in seconds ticks in, seconds out One positive tick step shared by every segment; tick rate = tick span / spike span; the first sample is placed at the first spike, an assumption the caller checks TickClock (fs_hz, seconds(ticks)) ValueError: no segments, an empty or non-1-D segment, no single positive step, a non-finite tick or spike, fewer than two spikes, zero spike span Deterministic. CPU only. examples/tutorials/09_open_data.py
effective_rate jnwb.continuous data: 1-D (n_samples,), n_samples >= 2, all finite; rate: positive finite Hz data in its own units; the repeat fraction and the power share are unitless Repeat fraction: share of consecutive sample pairs that are exactly equal. Repeat runs: runs of identical samples at least two long, counted by length in samples. Power share: Welch power above rate / 4 over total power. held is True when the repeat fraction is at least HELD_MIN_REPEAT_FRACTION (0.25), a module constant and not a parameter; the power share does not enter the decision EffectiveRate (repeat_fraction, repeat_runs, power_above_quarter, held) ValueError: not 1-D or fewer than two samples, a NaN or infinite value, a non-positive or non-finite rate. A constant series reports held True and a NaN power share Deterministic. CPU only. Tested on a 500 Hz signal held to 1 kHz and on native broadband noise.
gaze_departure_onsets jnwb.continuous gaze: (n_samples,) or (n_samples, n_axes), NaN allowed, infinity refused; rate: Hz; trial_starts: 1-D seconds on the gaze clock; baseline_window_s: (start_s, stop_s) relative to each trial start; reference_trials: integer trial indices; keyword-only envelope_percentile (99.5), hold_s (0.025), walkback_fraction (0.5) seconds in, seconds out; gaze in its own units Per trial, deviation is the Euclidean distance from the median gaze over the baseline window. Envelope: envelope_percentile of the deviations pooled over the reference trials. Departure: first sample from which the deviation stays above the envelope for hold_s. Onset: the last earlier sample at or below walkback_fraction times the envelope, or the departure sample if there is none. Search runs from a trial start to the next start, or to the end of the data for the last trial (n_trials,) float array of onset times in seconds on the gaze clock; NaN for a trial with no departure ValueError: a malformed argument, an empty reference_trials, a baseline that is empty or outside the data, reference deviations that are all NaN. Every threshold is a parameter: envelope_percentile, hold_s, walkback_fraction and the baseline window Deterministic. CPU only. Tested against planted departures, a trial without one, and a deviation shorter than the hold.
probe_geometry jnwb.addressing electrodes_table: an NWB electrodes table or a coordinate frame carrying (n_channels, 3) positions, units: str = "um", probe_name: Optional[str] = None micrometers Extracts contact spacing, linear ordering, and probe layout. Validates inter-contact pitch within tolerance without assuming anatomical identity. ProbeGeometry dataclass with contact_positions, nominal_pitch, is_linear, orientation. Raises ValueError for ambiguous/duplicate coordinates or unsupported units. Deterministic. CPU only. Composes with NWB electrode tables and laminar profiling.
vflip jnwb.laminar psd: (n_channels, n_freqs), freqs: (n_freqs,), band_low: Tuple, band_high: Tuple micrometers, \(\text{Hz}\) Computes the frequency layer inversion profile from min-max relative power per frequency across contacts, differencing the two band depth profiles after each is rescaled to \([0, 1]\); evaluates jnwb's bin-count-normalized support score \(S\), which is not vFLIP2's omega, against min_support_score. VFlipResult dataclass with crossover_contact, support_score, accepted, profile. Non-interactive. Rejection when \(S\) < min_support_score returns accepted=False and crossover_contact=None. Deterministic. CPU only: device="cuda" or "metal" warns and computes on the CPU. Composes with probe_geometry and PSD arrays. Tested on inverted and non-motif spectra.
vflip_from_lfp jnwb.laminar lfp: (n_channels, n_times), fs: float, band_low: Tuple, band_high: Tuple Input voltage \(U_{\text{in}}\), \(\text{Hz}\) Strict composition: compute_psd(lfp, fs, axis=-1) -> vflip(psd, freqs). Time is the last axis; compute_psd's default axis=0 would run over channels. VFlipResult Propagates PSD and vflip validation errors. Deterministic. CPU only: device="cuda" or "metal" warns and computes on the CPU. Tested for exact numerical identity against manual composition.
vflip2 jnwb.laminar psd: (n_channels, n_freqs), freqs: (n_freqs,) uniform, contact_spacing: float (micrometers, at most 200), orientation: str = "both", layer4_thickness_mm: Optional[float] = None, omega_cut: float = 6.0 micrometers, \(\text{Hz}\) vFLIP2.m (Major et al. 2025), step by step: every window at least one layer 4 thick, relative power per frequency, two-group spectra, band profiles, goodness and omega; the best window by omega. VFlip2Result with omega, accepted (omega above omega_cut), crossover_channel, proximal_channel, distal_channel (0-based rows), orientation, motif_quality (fixed tiers at 6 and 12). Below the cut accepted=False with the best window kept; every field but accepted and omega_cut is None when no window passed. ValueError for the input errors its docstring lists. Deterministic. CPU only. Feeds xflip and zflip through window=, and fuse_laminar_anchors through vflip2_um. Matches vFLIP2.m's output.
vflip2_from_lfp jnwb.laminar lfp: (n_channels, n_samples) continuous, (n_channels, n_samples, n_trials) or a list of trials, fs: float, contact_spacing: float (micrometers, at most 200), orientation: str = "both", layer4_thickness_mm: Optional[float] = None, omega_cut: float = 6.0 Input voltage, \(\text{Hz}\) vFLIP2.m's Hanning-window PSD (continuous input cut into 1 s trials), then vflip2. VFlip2Result ValueError for a bad fs or lfp shape, input shorter than one trial, an fs that puts 150 Hz past the FFT length, and every vflip2 error. Deterministic. CPU only. Tested against vFLIP2.m's PSD.
label_layers jnwb.laminar vflip_result: VFlipResult, probe_geometry: ProbeGeometry Categorical labels Assigns superficial, input, and deep cortical layer labels relative to verified crossover contact. Dict[Any, str] mapping each value of probe_geometry.channel_ids to a layer label ("deep", "input", "superficial", or "na"). The keys are channel identifiers, not positional indices, and they are not necessarily int -- synth_laminar_motif produces str ids. The signature is Dict[Any, str] for that reason. If vflip_result.accepted is False, all channels receive 'na'. Never guesses or imputes layers on failed fit. Deterministic. CPU only. Composes with vflip and probe_geometry.
detect_bad_channels jnwb.laminar_curation data: (n_channels, n_samples) or (n_channels, n_epochs, n_samples), fs: float, nperseg: int = 512 \(\text{Hz}\), data units\(^2\)/Hz Flags a contact whose median correlation with its good neighbors (decimated signal) or whose log10 mean power in power_band_hz is a robust-z outlier; iterated to a fixed point. Power is averaged on the linear scale before the logarithm. dict: bad_mask, neighbor_correlation, log_power, each (n_channels,). ValueError on non-finite data, fewer than 3 contacts or a band not below Nyquist. Deterministic. CPU only. Feeds interpolate_channel_runs and curate_and_label.
interpolate_channel_runs jnwb.laminar_curation data: (n_channels, ...), bad_mask: (n_channels,), max_run: int = 3 contacts Linear interpolation across a run of at most max_run adjacent bad contacts whose two outer neighbors exist, are good and are not blocked. dict: data (a copy), interpolated_mask, unresolved_mask. A longer, edge or blocked run is left unchanged and named in unresolved_mask. Deterministic. CPU only. Composes with detect_bad_channels.
evoked_csd_sink jnwb.laminar_curation erp: (n_channels, n_times), times_ms: (n_times,), pitch_um: float micrometers, \(\text{ms}\) Baseline-subtracted potential, Gaussian smoothing of SD smooth_um, CSD as the negative second difference over usable contacts; the strongest sink in sink_window_ms and the earliest sink, both against the baseline CSD SD. dict with strongest_contact, strongest_z, strongest_position_um, earliest_contact, earliest_onset_ms, earliest_position_um. NaN where the sink is below min_sink_z, no onset exists or fewer than min_contacts are usable; ValueError without a pre-stimulus baseline. Deterministic. CPU only. Reported by curate_and_label; it never moves the anchor.
fuse_laminar_anchors jnwb.laminar_curation vFLIP2, vFLIP, spectral-motif, xFLIP and CSD positions in micrometers (each optional; vFLIP2's is an accepted result's crossover_channel * contact_spacing, from row 0), window_um: (n_windows,), two consistency fractions, contact_spacing_um (micrometers, optional) micrometers Anchor is the vFLIP2 position, else the vFLIP position, else the motif position; the grade comes from the SD of the per-window estimates and the lower consistency fraction; the vFLIP2, vFLIP, xFLIP and CSD positions are reported as distances to the anchor; xFLIP and CSD never enter it. With both crossovers present and contact_spacing_um given, the agreement reads 'agree' when their separation is at most VFLIP2_VFLIP_AGREEMENT_T_CONTACTS and 'disagree' above it; otherwise it reads 'unresolved'. With both present, an 'A' grade is capped at 'B' unless the agreement is 'agree'. contact_spacing_um reads their separation in contact spacings. An accepted vFLIP2 fit is not by itself evidence of a crossover (omega_cut 6 accepts 18 of 100 noise-only probes), so a vFLIP2 anchor's grade rests on its stability and consistency. dict: anchor_um, anchor_source (vflip2, vflip, motif or None), grade ("A" to "D", "F"), stable, window_sd_um, n_windows_ok, consistency, agreement ('agree', 'disagree' or 'unresolved'), separation_contacts, distance_um (keys vflip, vflip2, xflip, csd). Grade "F" and a NaN anchor without an estimate. Deterministic. CPU only. Called by curate_and_label, which passes its pitch_um as contact_spacing_um.
curate_and_label jnwb.laminar_curation lfp: (n_channels, n_epochs, n_samples), fs: float, pitch_um: float, optional erp and erp_times_ms, max_interpolate_run: int = 3, min_contacts: int = 8, min_edge_contacts: int = 11, nperseg: int = 512 micrometers, \(\text{Hz}\) detect_bad_channels, bad-dense zones, interpolate_channel_runs, silent ends, vFLIP or motif anchor, stability over n_windows blocks of epochs, fuse_laminar_anchors, then labels by distance from the anchor. vFLIP2 runs beside them when fs is at least 300 Hz, the trials are at least fs samples long and pitch_um is at most 200 micrometers; it is reported and never the anchor. One cortical sheet. LaminarCurationResult, which records fs, rng and xflip_surrogate_seed_entropy in its parameters and carries the xFLIP result in xflip; the xFLIP distance is NaN unless xFLIP is accepted, and xflip.rejection_reason says why; vflip2 holds the VFlip2Result (None when skipped), vflip2_distance_um its absolute distance to the anchor, as distance_um of fuse_laminar_anchors (NaN unless vFLIP2 is accepted, or when either is missing) and vflip2_skipped the bound it did not meet (None when it ran); labels hold "superficial", "input", "deep", "WM", "outside_cortex" or "na". Grade "F" sets every label to "na"; labels are never imputed onto a fit that does not hold. ValueError on invalid shapes, pitch_um, n_windows, erp without erp_times_ms, or a band at or above fs / 2 (it names the band). band_low_hz and band_high_hz set the motif profiles; vFLIP keeps its own bands. Deterministic for a fixed rng, which seeds the xFLIP surrogates. CPU only. Composes the four parts above with vflip, vflip2_from_lfp, xflip and evoked_csd_sink.
testing.synth jnwb.testing.synth n_channels: int, n_samples: int, fs: float, motif parameters \(\mu\text{V}\), \(\text{s}\) Generates synthetic signals (laminar crossover motifs, AR noise, pink/white noise, shared common response). np.ndarray from synth_white_noise, synth_ar_noise, synth_periodic_response and synth_phase_gradient; a SynthLaminarReceipt from synth_laminar_motif; a SynthVFlip2Receipt from synth_vflip2_crossover; (data, true_labels, true_corr) from synth_correlation_blocks; (g1, g2) from synth_unequal_groups; (nwb, ground_truth) from build_canonical_tutorial_nwb. Raises ValueError for non-positive dimensions or invalid parameters. Fully controlled via rng: Optional[Union[Generator, int]]. Used across test suites to verify calibration, false positive rates, and recovery.
xflip jnwb.laminar data: (n_channels, n_channels) correlation matrix or (n_channels, n_samples) raw array, is_corr_matrix: Optional[bool] = None selecting which, method: str = "pearson" Correlation coefficient Evaluates contiguous cross-channel correlation blocks; tests boundary significance against surrogates that keep the probe's lag-averaged correlation, so a smooth spatial decay is not significant. XFlipResult dataclass with block_bounds, p_values, accepted, null_method (the surrogate null that ran, or None when no surrogate test ran). Raises ValueError for non-square or ill-conditioned matrices. Rejection returns accepted=False. Surrogate generation controlled via rng; surrogate_seed_entropy records the seed for an int or None, and the child seed drawn from a Generator, so the result reproduces its p-values. Composes with channel_correlation_matrix. Tested against block models and white noise.
zflip jnwb.laminar lfp_matrix: (n_channels, n_samples) ordered along the probe shaft, fs: float, orientation: Union[str, VFlip2Result] ("superficial_to_deep" when row 0 is the most superficial contact, "deep_to_superficial" when it is the deepest, or an accepted VFlip2Result, whose orientation names one of the two; no default), window: Union[VFlip2Result, Tuple[int, int], None] = None (an accepted result or an inclusive pair of probe rows), pitch_um: Optional[float] = None micrometers, \(\text{Hz}\) Computes the cross-spectra itself, then evaluates phase-gradient asymmetry and imaginary coherency across layers, reducing sensitivity to zero-phase-lag coupling. ZFlipResult dataclass with adjacent_wpli, adjacent_delays_s, adjacent_linearity_r2, mean_wpli, tau_per_channel_s, apparent_velocity_m_s, directionality, p_value and accepted. directionality is a direction in depth named from orientation. apparent_velocity_m_s is an apparent phase velocity, not a conduction velocity. Raises TypeError when orientation is omitted. Raises ValueError for an orientation string other than the two above, a rejected or windowless VFlip2Result as orientation or window, two different VFlip2Results as window and orientation, a window that is not an integer pair, outside the probe or under 3 rows, an array that is not 2-D (a (n_channels, n_channels, n_freqs) cross-spectrum included), fewer than 3 channels, a NaN or Inf sample, fs or pitch_um not positive and finite, a freq_range that is not an increasing non-negative pair, alpha outside (0, 1), a negative or non-integer n_surrogates, a threshold outside [0, 1], or a segmentation into fewer than 2 segments. Fewer than 3 frequency bins in freq_range returns accepted=False. Controlled via rng when permutation is used. Composes with imaginary_coherency and wpli.

Peak-Channel Layer Labels and Past-Only Gaussian Smoothing

jnwb.map_peak_channel_to_layer(units_df, curation, channel_ids) gives each unit the curated label of its peak_channel_id. channel_ids holds the electrode id of each LFP row, in the order given to curate_and_label, and the labels come back one per unit. An id that is absent or NaN gets na. A duplicate or non-integer id, and a units table without a peak_channel_id column, are refused.

jnwb.causal_gaussian_smooth(rate, sigma_bins) smooths with a kernel that reaches only into the past, and returns the smoothed rate with its mean lag in bins. The mean lag is the kernel centroid, about \(0.798\sigma\) bins for large \(\sigma\). A step's half-rise falls at the kernel median, about \(0.674\sigma\) bins, so report the two as separate numbers.

References

  • Major et al. (2025)