API

This page provides a detailed reference for the public ncpi API. The main classes and their roles within the ncpi workflow are summarized below.

  • Simulation configures, runs, and organizes neural circuit simulations.
  • FieldPotential transforms simulated neural activity into CDM, LFP, EEG, and MEG signals using biophysical kernels, forward models, or proxies.
  • Features extracts quantitative and interpretable features from simulated or empirical electrophysiological signals.
  • Inference trains inverse models and estimates neural circuit parameters from extracted features.
  • Analysis provides statistical testing and visualization tools for features, predictions, and simulation results.
  • EphysDatasetParser converts heterogeneous electrophysiological datasets into a consistent tabular representation for downstream processing.
  • tools contains shared utility functions used across ncpi workflows.

Simulation

Module: ncpi/Simulation.py

  • run_script(script_path, param_path, output_folder): source
    Run a Python script with a parameter module and output folder.
    Parameters
    • script_path script filename type: str | PathLike
    • param_path parameter filename type: str | PathLike
    • output_folder destination directory. type: str | PathLike
  • Simulation.__init__(param_folder, python_folder, output_folder): source
    Create a simulation runner bound to folders for parameter files, executable scripts, and outputs.
    Parameters
    • param_folder params directory type: str | PathLike
    • python_folder scripts directory type: str | PathLike
    • output_folder output directory (created if missing). type: str | PathLike
  • Simulation.network(script_path, param_path): source
    Execute network-generation stage.
    Parameters
    • script_path script under python_folder type: str | PathLike
    • param_path params under param_folder. type: str | PathLike
  • Simulation.simulate(script_path, param_path): source
    Execute simulation stage with the same path semantics as network.
    Parameters
    • script_path simulation script filename relative to python_folder (or absolute path) type: str | PathLike
    • param_path parameter filename relative to param_folder (or absolute path). type: str | PathLike
  • Simulation.analysis(script_path, param_path): source
    Execute analysis stage with the same path semantics as network.
  • Simulation.bundle_output_folder(output_folder, output_filename='simulation.pkl', remove_source_files=False): source
    Pack core simulation artifacts into one pickle payload for downstream use.
    Parameters
    • output_folder folder to bundle type: str | PathLike
    • output_filename bundle name type: str
    • remove_source_files delete source pickle files after bundling. type: bool
  • Simulation.bundle_outputs(output_filename='simulation.pkl', remove_source_files=False): source
    Convenience wrapper around bundle_output_folder using the instance output folder.
    Parameters
    • output_filename name of the bundled pickle written inside output_folder type: str
    • remove_source_files remove per-run pickle files after successful bundling. type: bool

FieldPotential

Module: ncpi/FieldPotential.py

  • FieldPotential.__init__(): source
    Initialize internal kernel/proxy registries and lazy dependency handles.
  • FieldPotential.roll_with_zeros(arr, shift): source
    Shift a 1D array and zero-fill exposed elements.
    Parameters
    • arr input array type: np.ndarray
    • shift positive/negative integer shift. type: int
  • FieldPotential.create_kernel(MC_folder, params, biophys, dt, tstop, *, output_sim_path=None, electrodeParameters=None, CDM=True, probes=None, cdm_probe=None, mean_nu_X=None, Vrest=None, t_X=None, tau=None, g_eff=None, n_ext=None, weights=None): source
    Build multicompartment kernels for CDM/LFP workflows.
    Parameters
    • MC_folder model folder type: str | PathLike
    • params network parameter object/module type: object | module | dict
    • biophys biophysical setup list type: list[dict]
    • dt/tstop simulation timing type: float
    • output_sim_path optional path to simulation outputs for inferred rates/resting state type: str | PathLike | None
    • electrodeParameters LFP probe settings type: dict | None
    • CDM include CDM probe type: bool
    • probes direct probe override type: object | list | None
    • cdm_probe CDM probe class/name type: str | object | None
    • mean_nu_X/Vrest manual alternatives when no output path is provided type: array-like | None
    • t_X/tau/g_eff/n_ext/weights kernel and synaptic overrides. type: array-like | None
  • FieldPotential.compute_cdm_lfp_from_kernels(kernels, spike_times, dt, tstop, population_sizes=None, transient=0.0, probe='KernelApproxCurrentDipoleMoment', component=2, mode='same', scale=1.0, aggregate=None): source
    Convolve spike trains with precomputed kernels to obtain CDM/LFP traces.
    Parameters
    • kernels kernel dictionary type: dict
    • spike_times spikes by population type: dict[str, array-like]
    • dt/tstop output grid type: float
    • population_sizes optional normalization type: dict | None
    • transient discard pre-window type: float
    • probe probe key type: str
    • component dipole component selection type: int
    • mode convolution mode type: str
    • scale scalar multiplier type: float
    • aggregate optional sum output. type: str | None
  • FieldPotential.compute_MEEG(CDM, dipole_locations=None, sensor_locations=None, model=None, model_kwargs=None, align_to_surface=True): source
    Apply EEG/MEG forward models to CDM trajectories.
    Parameters
    • CDM dipole time series (single or multi-dipole) type: np.ndarray | array-like
    • dipole_locations dipole positions type: array-like | None
    • sensor_locations sensor positions (non-NYHead models) type: array-like | None
    • model forward model name type: str | None
    • model_kwargs constructor args type: dict | None
    • align_to_surface NYHead orientation alignment. type: bool
  • FieldPotential.compute_proxy(method, sim_data, sim_step, *, excitatory_only=None): source
    Compute scalar proxy signals (FR/AMPA/GABA/Vm/I/I_abs/LRWS/ERWS1/ERWS2).
    Parameters
    • method proxy key type: str
    • sim_data required simulation arrays map type: dict
    • sim_step timestep in ms (mandatory for delayed proxies) type: float
    • excitatory_only key-resolution preference for excitatory/all channels. type: bool | None

Features

Module: ncpi/Features.py

  • Features.__init__(method='catch22', params=None): source
    Configure feature extraction backend and options.
    Parameters
    • method one of catch22, specparam, dfa, fEI, hctsa. type: str
    • params method-specific options dictionary (e.g., {'normalize': True}). type: dict | None
  • Features.catch22(sample): source
    Compute the 22 canonical catch22 features from a 1D sample.
    Parameters
    • sample input time-series. type: np.ndarray
  • Features.specparam(sample=None, *, freqs=None, power_spectrum=None, fs=None, freq_range=None, welch_kwargs=None, model_kwargs=None, select_peak=None, debug=None, metric_thresholds=None, metric_policy=None): source
    Fit an aperiodic/periodic spectral model from time-domain or PSD inputs.
    Parameters
    • sample time-domain signal (mutually exclusive with freqs/power_spectrum) type: np.ndarray
    • freqs frequency axis type: np.ndarray | None
    • power_spectrum PSD values type: np.ndarray | None
    • fs sampling frequency (when sample used) type: float | None
    • freq_range fit range type: tuple[float, float] | None
    • welch_kwargs PSD options type: dict | None
    • model_kwargs spectral-model options type: dict | None
    • select_peak peak selection strategy type: str | None
    • debug enable debug output type: bool | None
    • metric_thresholds fit-quality thresholds type: dict | None
    • metric_policy threshold handling (reject/flag). type: str | None ('reject'|'flag')
  • Features.dfa(sample, *, sampling_frequency=None, fit_interval=None, compute_interval=None, overlap=None, frequency_range=None, spectrum_range=None, bad_idxes=None, input_is_envelope=None, filter_kwargs=None, trim_seconds=None, hilbert_n_fft=None): source
    Compute detrended fluctuation analysis features.
    Parameters
    • sample 1D/2D input type: np.ndarray
    • sampling_frequency Hz type: float | None
    • fit_interval/compute_interval DFA windows type: tuple[float, float] | None
    • overlap overlapping windows flag type: bool | None
    • frequency_range band mode type: tuple[float, float] | None
    • spectrum_range spectrum mode type: tuple[float, float] | None
    • bad_idxes channel exclusions type: array-like[int] | None
    • input_is_envelope envelope flag type: bool | None
    • filter_kwargs MNE filter settings type: dict | None
    • trim_seconds edge trim type: float | None
    • hilbert_n_fft Hilbert FFT length. type: int | None
  • Features.fEI(sample, *, sampling_frequency=None, window_size_sec=None, window_overlap=None, dfa_value=None, dfa_threshold=None, dfa_fit_interval=None, dfa_compute_interval=None, dfa_overlap=None, frequency_range=None, spectrum_range=None, bad_idxes=None, input_is_envelope=None, filter_kwargs=None, trim_seconds=None, hilbert_n_fft=None): source
    Compute functional excitation-inhibition index from envelopes/spectra.
    Parameters
    • sample 1D/2D input type: np.ndarray
    • sampling_frequency Hz type: float | None
    • window_size_sec/window_overlap fEI window config type: float | None
    • dfa_value optional precomputed DFA type: float | None
    • dfa_threshold minimum DFA threshold type: float | None
    • dfa_fit_interval/dfa_compute_interval/dfa_overlap internal DFA settings type: tuple[float, float] | None
    • frequency_range/spectrum_range band mode type: tuple[float, float] | None
    • bad_idxes channel indices to exclude. type: array-like[int] | None
    • input_is_envelope set to True if the input already is an amplitude envelope. type: bool | None
    • filter_kwargs extra filtering options passed to MNE filtering utilities. type: dict | None
    • trim_seconds seconds trimmed from each edge after filtering/Hilbert transform. type: float | None
    • hilbert_n_fft. type: int | None
  • Features.hctsa(samples, hctsa_folder, workers=None, return_meta=False): source
    Run MATLAB-based hctsa feature extraction.
    Parameters
    • samples collection of 1D series type: list[np.ndarray] | np.ndarray
    • hctsa_folder HCTSA installation path type: str | PathLike
    • workers MATLAB worker count type: int | None
    • return_meta include metadata in output. type: bool
  • Features.compute_features(samples, n_jobs=None, chunksize=None, start_method='spawn', progress_callback=None, log_callback=None): source
    Parallel feature extraction entry point.
    Parameters
    • samples list/array of 1D signals type: list[np.ndarray] | np.ndarray
    • n_jobs worker count type: int | None
    • chunksize dispatch chunk size type: int | None
    • start_method multiprocessing method type: str
    • progress_callback progress hook type: callable | None
    • log_callback log hook. type: callable | None

Inference

Module: ncpi/Inference.py

  • Inference.__init__(model, hyperparams=None): source
    Initialize sklearn or SBI backend based on model.
    Parameters
    • model regressor name or SBI key (NPE/NLE/NRE) type: str | None
    • hyperparams backend-specific configuration. type: dict | None
  • Inference.add_simulation_data(features, parameters, *, append=False, copy=False): source
    Register training feature/target arrays, with optional append mode.
    Parameters
    • features feature matrix/vector type: array-like
    • parameters target matrix/vector type: array-like
    • append concatenate to existing data type: bool
    • copy force copying. type: bool
  • Inference.initialize_sbi(hyperparams): source
    Build an SBI inference object and estimator configuration.
    Parameters
    • hyperparams dict including required prior and optional inference_kwargs type: dict | None
    • estimator optional SBI estimator identifier/constructor override. type: str | callable | None
    • estimator_kwargs extra keyword arguments passed to the SBI estimator builder. type: dict | None
    • build_posterior_kwargs. type: dict | None
  • Inference.train(param_grid=None, *, n_splits=10, n_repeats=10, train_params=None, result_dir='data', scaler=None, seed=0, sklearn_verbose=None, sbi_eval_sampling_kwargs=None): source
    Train a model (single-fit or repeated CV search) and persist artifacts.
    Parameters
    • param_grid optional hyperparameter candidates type: list[dict] | None
    • n_splits/n_repeats repeated CV settings type: int
    • train_params extra SBI train args type: dict | None
    • result_dir artifact output folder type: str | PathLike
    • scaler transformer or bool flag type: bool | object
    • seed reproducibility seed type: int
    • sklearn_verbose default estimator verbosity type: int | bool | None
    • sbi_eval_sampling_kwargs posterior-sampling kwargs used for SBI CV scoring. type: dict | None
  • Inference.predict(features, *, result_dir='data', scaler=False, n_jobs=None, chunksize=None, start_method='spawn', sbi_eval_sampling_kwargs=None): source
    Load trained artifacts and generate predictions from new feature rows.
    Parameters
    • features input feature rows type: array-like
    • result_dir artifact location type: str | PathLike
    • scaler whether to apply saved scaler type: bool | object
    • n_jobs/chunksize/start_method sklearn parallelism settings type: int | None
    • sbi_eval_sampling_kwargs posterior sampling controls. type: dict | None

Analysis

Module: ncpi/Analysis.py

  • extract_variables(formula): source
    Tokenize an R-style formula and extract variable-like terms.
    Parameters
    • formula expression like Y ~ group * epoch + (1|id). type: str
  • PosthocConfig: source
    Configuration object for post-hoc testing in Analysis.lmer_tests.
    Fields
    • adjust p-value adjustment method passed to emmeans/contrast/test. type: str
    • pairwise_method all-pairs comparison backend (pairs or contrast). type: str
    • pairwise_contrast_method contrast method used when pairwise_method='contrast'. type: str
    • treatment_method treatment-vs-control contrast method. type: str
    • treatment_ref optional control/reference-level override. type: str | int | None
  • LmerTestsResult: source
    Return object used by Analysis.lmer_tests when likelihood-ratio tests or model metadata are requested.
    Fields
    • posthoc post-hoc result DataFrames keyed by spec. type: dict[str, pandas.DataFrame]
    • lrt likelihood-ratio test table, if requested. type: pandas.DataFrame | None
    • model_info optional model-selection metadata. type: dict | None
  • Analysis.__init__(data): source
    Store an analysis data object (typically a pandas DataFrame for statistical methods).
    Parameters
    • data source container. type: DataFrame | Any
  • Analysis.lmer_tests(models, group_col=None, control_group=None, numeric=None, specs=None, *, posthoc=None, print_info=True, lrt=False, lrt_drop=None, return_model_info=False): source
    Fit lm/lmer models through R, run post-hoc tests, optionally run LRT and return model metadata.
    Parameters
    • models formula(s) type: str | list[str]
    • group_col group field type: str | None
    • control_group control level type: str | None
    • numeric numeric variables type: list[str] | None
    • specs post-hoc specs type: list[str] | None
    • posthoc post-hoc policy/config type: dict | bool | None
    • print_info print diagnostics type: bool
    • lrt run likelihood-ratio test type: bool
    • lrt_drop reduced-model terms type: list[str] | None
    • return_model_info include selection metadata. type: bool
  • Analysis.lmer_selection(full_model, numeric=None, *, crit=None, random_crit='BIC', fixed_crit='LRT', include=None, print_info=True): source
    Backward model selection using R buildmer for random and/or fixed terms.
    Parameters
    • full_model starting formula type: str
    • numeric numeric variable list type: list[str] | None
    • crit single criterion override type: str | None
    • random_crit random-effects criterion type: str
    • fixed_crit fixed-effects criterion type: str
    • include forced terms type: list[str] | None
    • print_info print selected model. type: bool
  • Analysis.cohend(*, control_group='HC', data_col='Y', data_index=-1, group_col='group', sensor_col='sensor', min_n=3, drop_zeros=True): source
    Compute sensor-wise Cohen’s d for each non-control group vs control.
    Parameters
    • control_group baseline level type: str | None
    • data_col measurement column type: str
    • data_index element index for sequence-valued rows type: int
    • group_col group column type: str | None
    • sensor_col sensor column type: str
    • min_n minimum per-group samples type: int
    • drop_zeros remove zero-valued rows. type: bool
  • Analysis.eeg_topomap(values=None, ch_names=None, *, position_offset, sensor_col='sensor', data_col='data', data_index=-1, montage='standard_1005', ch_type='eeg', sphere=0.28, cmap='jet', vmin=None, vmax=None, colorbar=True, colorbar_fmt='%0.2f', colorbar_label=None, colorbar_label_fontsize=None, colorbar_tick_fontsize=8, sensors=None, outlines=None, contours=None, res=300, extrapolate=None, image_interp=None, axes=None, show=True, title=None, names=None): source
    Render EEG scalp topography from passed values or from self.data.
    Parameters
    • values/ch_names explicit map input (or infer from data columns) type: array-like | None
    • position_offset mandatory (y,z) offset type: tuple[float, float]
    • sensor_col/data_col/data_index DataFrame mapping type: str
    • montage/ch_type channel geometry type: str
    • sphere/cmap/vmin/vmax style and limits type: float | tuple
    • colorbar* colorbar controls type: Any
    • sensors/outlines/contours/res/extrapolate/image_interp MNE topomap options type: bool | str | None
    • axes/show/title/names display controls. type: matplotlib.axes.Axes | None
  • Analysis.meg_surface(values=None, ch_names=None, *, sensor_col='sensor', data_col='data', data_index=-1, atlas='dk', subject='fsaverage', subjects_dir=None, surface='inflated', hemisphere='both', views='lat', cmap='coolwarm', vmin=None, vmax=None, center=None, alpha=1.0, smoothing_steps=5, colorbar=True, colorbar_kwargs=None, cortex='low_contrast', background='white', size=(1000, 600), show=True, axes=None, auto_fetch=True, hcp_accept=False, backend='auto', verbose=None, **brain_kwargs): source
    Plot parcel-wise MEG values on cortical surfaces using MNE/FreeSurfer parcellations.
    Parameters
    • values/ch_names explicit parcel values and names (or infer from self.data) type: array-like | None
    • sensor_col/data_col/data_index DataFrame mapping used when values is omitted type: str | int | None
    • atlas parcellation name type: str
    • subject/subjects_dir source anatomy type: str
    • surface/hemisphere/views viewing geometry type: str
    • cmap/vmin/vmax/center/alpha/smoothing_steps rendering style type: str
    • colorbar/colorbar_kwargs color scale type: bool
    • cortex/background/size scene styling type: str
    • show/axes matplotlib target behavior type: bool
    • auto_fetch auto-download fsaverage type: bool
    • hcp_accept HCP-MMP license acceptance type: bool
    • backend rendering backend selector. type: str
    • verbose MNE verbosity type: bool | str | int | None
    • brain_kwargs additional Brain constructor args. type: dict

EphysDatasetParser

Module: ncpi/EphysDatasetParser.py

  • CanonicalFields: source
    Declarative locator map for canonical parsed fields.
    Fields
    • data signal accessor (array-like expected). type: DataFrame | Any
    • fs sampling-frequency accessor in Hz. type: float | None
    • ch_names channel-name accessor/list. type: list[str] | None
    • time time-axis accessor. type: field spec | None
    • data_domain domain label accessor (time/frequency). type: field spec | None
    • freqs frequency-axis accessor for spectral inputs. type: np.ndarray | None
    • spectral_kind spectral representation accessor. type: field spec | None
    • epoch epoch index accessor. type: field spec | None
    • metadata extra metadata accessor/map. type: dict | callable | None
    • table_layout tabular layout selector. type: str | None
    • channel_columns channel columns for wide tables. type: list[str] | None
    • long_channel_col channel-name column for long tables. type: str | None
    • long_value_col value column for long tables. type: str | None
    • long_time_col time column for long tables. type: str | None
    • array_axes. type: tuple | list | None
  • ParseConfig: source
    Parser behavior configuration for loading, segmentation, epoching, normalization, and aggregation.
    Fields
    • fields canonical field locator configuration. type: CanonicalFields
    • epoch_length_s epoch length in seconds. type: float | None
    • epoch_step_s epoch step in seconds. type: float | None
    • segment_t0_s optional segment start time (seconds). type: float | None
    • segment_t1_s optional segment end time (seconds). type: float | None
    • preload whether to preload source data into memory. type: bool
    • pick_types channel-picking rules. type: dict | None
    • max_seconds optional maximum duration to keep from each recording. type: float | None
    • drop_bads drop channels marked as bad. type: bool
    • zscore apply z-score normalization. type: bool
    • zscore_after_epoch apply z-score after epoching. type: bool
    • exclude_last_epoch drop incomplete last epoch. type: bool
    • align_epoch_count_to_minimum align all channels to minimum epoch count. type: bool
    • aggregate_over axes to aggregate over (e.g., sensor). type: tuple[str, ...] | None
    • aggregate_method aggregation operation name. type: str
    • aggregate_labels custom labels for aggregated outputs. type: dict | None
    • warn_unimplemented. type: bool
  • EphysDatasetParser.__init__(config=None): source
    Construct a parser instance with explicit configuration.
    Parameters
    • config optional ParseConfig (defaults applied when omitted). type: ParseConfig | None
  • EphysDatasetParser.parse(source): source
    Parse in-memory objects or file paths into canonical DataFrame rows.
    Parameters
    • source path or object (supports MNE objects, arrays, dict-like, DataFrame, and several file formats). type: str | PathLike | object

tools

Module: ncpi/tools.py

  • ensure_module(module_name, package=None, *, version_spec=None, upgrade=False, user=False, quiet=False, extra_pip_args=None, reload_module=False, raise_on_error=False): source
    Verify/install importable dependencies at runtime.
    Parameters
    • module_name import path type: str
    • package pip package name type: str | None
    • version_spec version constraint type: str | None
    • upgrade/user/quiet/extra_pip_args pip behavior type: bool
    • reload_module force reload type: bool
    • raise_on_error raise vs return False. type: bool
  • dynamic_import(module_path, attribute_name=None, package=None, *, default=None, raise_on_error=True, reload_module=False, ensure_type=None, ensure_callable=False): source
    Import modules/attributes dynamically with optional type/callable checks.
    Parameters
    • module_path module import path. type: str
    • attribute_name attribute/class/function name to import from the module. type: str | None
    • package optional package context for relative imports. type: str | None
    • default fallback return value when import fails and raise_on_error=False. type: Any
    • raise_on_error raise exception on failure instead of returning default. type: bool
    • reload_module force module reload before returning attribute/module. type: bool
    • ensure_type optional runtime type check for the imported object. type: type | tuple[type, ...] | None
    • ensure_callable. type: bool
  • record_id_from_api_url(api_url): source
    Extract a Zenodo record ID from API URL text.
    Parameters
    • api_url Zenodo record API URL. type: str
  • ensure_fresh_dir(download_dir): source
    Recreate an empty directory.
    Parameters
    • download_dir target directory path. type: str | PathLike
  • safe_extract_zip(zip_path, outdir): source
    Safely extract ZIP archives with path-traversal checks.
    Parameters
    • zip_path archive file type: str | PathLike
    • outdir extraction folder. type: str | PathLike
  • safe_extract_tar(tar_path, outdir): source
    Safely extract TAR archives with path-traversal checks.
    Parameters
    • tar_path archive file type: str | PathLike
    • outdir extraction folder. type: str | PathLike
  • extract_and_delete_all_archives(outdir, *, verbose=True): source
    Recursively extract ZIP/TAR files and delete each archive after extraction.
    Parameters
    • outdir root folder type: str | PathLike
    • verbose print progress. type: bool | str | int | None
  • get_requests_and_tqdm(): source
    Resolve and return requests and tqdm modules.
  • fetch_record_json(requests, api_url, headers, timeout=60): source
    Request record metadata JSON from Zenodo API.
    Parameters
    • requests requests module/object type: module | object
    • api_url record URL type: str
    • headers HTTP headers type: dict
    • timeout request timeout. type: int | float
  • download_file_streaming(requests, tqdm, file_url, dest_path, *, headers, timeout=120, chunk_size=8192, desc=None): source
    Stream-download a file with progress reporting.
    Parameters
    • requests HTTP client module type: module | object
    • tqdm progress helper type: callable | module
    • file_url source URL type: str
    • dest_path output path type: str | PathLike
    • headers request headers type: dict
    • timeout seconds type: int | float
    • chunk_size transfer chunk bytes type: int
    • desc progress label. type: str | None
  • is_http_403(err): source
    Detect whether an exception corresponds to HTTP 403.
    Parameters
    • err caught exception object. type: Exception
  • download_files_archive_with_curl(record_id, outdir): source
    Fallback downloader using Zenodo files-archive endpoint plus extraction.
    Parameters
    • record_id Zenodo record ID type: str | int
    • outdir destination folder. type: str | PathLike
  • download_zenodo_record(api_url, download_dir='zenodo_files', fallback_files_archive=True): source
    Download and extract all files from one Zenodo record.
    Parameters
    • api_url record API URL type: str
    • download_dir local output folder type: str | PathLike
    • fallback_files_archive use archive fallback when direct downloads fail. type: bool
  • timer(description=None): source
    Decorator to measure and print function execution time.
    Parameters
    • description optional label shown in timing output. type: str | None