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.
Simulationconfigures, runs, and organizes neural circuit simulations.FieldPotentialtransforms simulated neural activity into CDM, LFP, EEG, and MEG signals using biophysical kernels, forward models, or proxies.Featuresextracts quantitative and interpretable features from simulated or empirical electrophysiological signals.Inferencetrains inverse models and estimates neural circuit parameters from extracted features.Analysisprovides statistical testing and visualization tools for features, predictions, and simulation results.EphysDatasetParserconverts heterogeneous electrophysiological datasets into a consistent tabular representation for downstream processing.toolscontains 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.
Parametersscript_pathscript filename type: str | PathLikeparam_pathparameter filename type: str | PathLikeoutput_folderdestination 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.
Parametersparam_folderparams directory type: str | PathLikepython_folderscripts directory type: str | PathLikeoutput_folderoutput directory (created if missing). type: str | PathLike
-
Simulation.network(script_path, param_path): source
Execute network-generation stage.
Parametersscript_pathscript underpython_foldertype: str | PathLikeparam_pathparams underparam_folder. type: str | PathLike
-
Simulation.simulate(script_path, param_path): source
Execute simulation stage with the same path semantics asnetwork.
Parametersscript_pathsimulation script filename relative topython_folder(or absolute path) type: str | PathLikeparam_pathparameter filename relative toparam_folder(or absolute path). type: str | PathLike
-
Simulation.analysis(script_path, param_path): source
Execute analysis stage with the same path semantics asnetwork. -
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.
Parametersoutput_folderfolder to bundle type: str | PathLikeoutput_filenamebundle name type: strremove_source_filesdelete source pickle files after bundling. type: bool
-
Simulation.bundle_outputs(output_filename='simulation.pkl', remove_source_files=False): source
Convenience wrapper aroundbundle_output_folderusing the instance output folder.
Parametersoutput_filenamename of the bundled pickle written insideoutput_foldertype: strremove_source_filesremove 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.
Parametersarrinput array type: np.ndarrayshiftpositive/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.
ParametersMC_foldermodel folder type: str | PathLikeparamsnetwork parameter object/module type: object | module | dictbiophysbiophysical setup list type: list[dict]dt/tstopsimulation timing type: floatoutput_sim_pathoptional path to simulation outputs for inferred rates/resting state type: str | PathLike | NoneelectrodeParametersLFP probe settings type: dict | NoneCDMinclude CDM probe type: boolprobesdirect probe override type: object | list | Nonecdm_probeCDM probe class/name type: str | object | Nonemean_nu_X/Vrestmanual alternatives when no output path is provided type: array-like | Nonet_X/tau/g_eff/n_ext/weightskernel 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.
Parameterskernelskernel dictionary type: dictspike_timesspikes by population type: dict[str, array-like]dt/tstopoutput grid type: floatpopulation_sizesoptional normalization type: dict | Nonetransientdiscard pre-window type: floatprobeprobe key type: strcomponentdipole component selection type: intmodeconvolution mode type: strscalescalar multiplier type: floataggregateoptional 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.
ParametersCDMdipole time series (single or multi-dipole) type: np.ndarray | array-likedipole_locationsdipole positions type: array-like | Nonesensor_locationssensor positions (non-NYHead models) type: array-like | Nonemodelforward model name type: str | Nonemodel_kwargsconstructor args type: dict | Nonealign_to_surfaceNYHead 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).
Parametersmethodproxy key type: strsim_datarequired simulation arrays map type: dictsim_steptimestep in ms (mandatory for delayed proxies) type: floatexcitatory_onlykey-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.
Parametersmethodone ofcatch22,specparam,dfa,fEI,hctsa. type: strparamsmethod-specific options dictionary (e.g.,{'normalize': True}). type: dict | None
-
Features.catch22(sample): source
Compute the 22 canonical catch22 features from a 1D sample.
Parameterssampleinput 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.
Parameterssampletime-domain signal (mutually exclusive withfreqs/power_spectrum) type: np.ndarrayfreqsfrequency axis type: np.ndarray | Nonepower_spectrumPSD values type: np.ndarray | Nonefssampling frequency (whensampleused) type: float | Nonefreq_rangefit range type: tuple[float, float] | Nonewelch_kwargsPSD options type: dict | Nonemodel_kwargsspectral-model options type: dict | Noneselect_peakpeak selection strategy type: str | Nonedebugenable debug output type: bool | Nonemetric_thresholdsfit-quality thresholds type: dict | Nonemetric_policythreshold 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.
Parameterssample1D/2D input type: np.ndarraysampling_frequencyHz type: float | Nonefit_interval/compute_intervalDFA windows type: tuple[float, float] | Noneoverlapoverlapping windows flag type: bool | Nonefrequency_rangeband mode type: tuple[float, float] | Nonespectrum_rangespectrum mode type: tuple[float, float] | Nonebad_idxeschannel exclusions type: array-like[int] | Noneinput_is_envelopeenvelope flag type: bool | Nonefilter_kwargsMNE filter settings type: dict | Nonetrim_secondsedge trim type: float | Nonehilbert_n_fftHilbert 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.
Parameterssample1D/2D input type: np.ndarraysampling_frequencyHz type: float | Nonewindow_size_sec/window_overlapfEI window config type: float | Nonedfa_valueoptional precomputed DFA type: float | Nonedfa_thresholdminimum DFA threshold type: float | Nonedfa_fit_interval/dfa_compute_interval/dfa_overlapinternal DFA settings type: tuple[float, float] | Nonefrequency_range/spectrum_rangeband mode type: tuple[float, float] | Nonebad_idxeschannel indices to exclude. type: array-like[int] | Noneinput_is_envelopeset to True if the input already is an amplitude envelope. type: bool | Nonefilter_kwargsextra filtering options passed to MNE filtering utilities. type: dict | Nonetrim_secondsseconds trimmed from each edge after filtering/Hilbert transform. type: float | Nonehilbert_n_fft. type: int | None
-
Features.hctsa(samples, hctsa_folder, workers=None, return_meta=False): source
Run MATLAB-based hctsa feature extraction.
Parameterssamplescollection of 1D series type: list[np.ndarray] | np.ndarrayhctsa_folderHCTSA installation path type: str | PathLikeworkersMATLAB worker count type: int | Nonereturn_metainclude 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.
Parameterssampleslist/array of 1D signals type: list[np.ndarray] | np.ndarrayn_jobsworker count type: int | Nonechunksizedispatch chunk size type: int | Nonestart_methodmultiprocessing method type: strprogress_callbackprogress hook type: callable | Nonelog_callbacklog hook. type: callable | None
Inference
Module: ncpi/Inference.py
-
Inference.__init__(model, hyperparams=None): source
Initialize sklearn or SBI backend based onmodel.
Parametersmodelregressor name or SBI key (NPE/NLE/NRE) type: str | Nonehyperparamsbackend-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.
Parametersfeaturesfeature matrix/vector type: array-likeparameterstarget matrix/vector type: array-likeappendconcatenate to existing data type: boolcopyforce copying. type: bool
-
Inference.initialize_sbi(hyperparams): source
Build an SBI inference object and estimator configuration.
Parametershyperparamsdict including requiredpriorand optionalinference_kwargstype: dict | Noneestimatoroptional SBI estimator identifier/constructor override. type: str | callable | Noneestimator_kwargsextra keyword arguments passed to the SBI estimator builder. type: dict | Nonebuild_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.
Parametersparam_gridoptional hyperparameter candidates type: list[dict] | Nonen_splits/n_repeatsrepeated CV settings type: inttrain_paramsextra SBI train args type: dict | Noneresult_dirartifact output folder type: str | PathLikescalertransformer or bool flag type: bool | objectseedreproducibility seed type: intsklearn_verbosedefault estimator verbosity type: int | bool | Nonesbi_eval_sampling_kwargsposterior-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.
Parametersfeaturesinput feature rows type: array-likeresult_dirartifact location type: str | PathLikescalerwhether to apply saved scaler type: bool | objectn_jobs/chunksize/start_methodsklearn parallelism settings type: int | Nonesbi_eval_sampling_kwargsposterior sampling controls. type: dict | None
Analysis
Module: ncpi/Analysis.py
-
extract_variables(formula): source
Tokenize an R-style formula and extract variable-like terms.
Parametersformulaexpression likeY ~ group * epoch + (1|id). type: str
-
PosthocConfig: source
Configuration object for post-hoc testing inAnalysis.lmer_tests.
Fieldsadjustp-value adjustment method passed to emmeans/contrast/test. type: strpairwise_methodall-pairs comparison backend (pairsorcontrast). type: strpairwise_contrast_methodcontrast method used whenpairwise_method='contrast'. type: strtreatment_methodtreatment-vs-control contrast method. type: strtreatment_refoptional control/reference-level override. type: str | int | None
-
LmerTestsResult: source
Return object used byAnalysis.lmer_testswhen likelihood-ratio tests or model metadata are requested.
Fieldsposthocpost-hoc result DataFrames keyed by spec. type: dict[str, pandas.DataFrame]lrtlikelihood-ratio test table, if requested. type: pandas.DataFrame | Nonemodel_infooptional model-selection metadata. type: dict | None
-
Analysis.__init__(data): source
Store an analysis data object (typically a pandas DataFrame for statistical methods).
Parametersdatasource 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.
Parametersmodelsformula(s) type: str | list[str]group_colgroup field type: str | Nonecontrol_groupcontrol level type: str | Nonenumericnumeric variables type: list[str] | Nonespecspost-hoc specs type: list[str] | Noneposthocpost-hoc policy/config type: dict | bool | Noneprint_infoprint diagnostics type: boollrtrun likelihood-ratio test type: boollrt_dropreduced-model terms type: list[str] | Nonereturn_model_infoinclude 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.
Parametersfull_modelstarting formula type: strnumericnumeric variable list type: list[str] | Nonecritsingle criterion override type: str | Nonerandom_critrandom-effects criterion type: strfixed_critfixed-effects criterion type: strincludeforced terms type: list[str] | Noneprint_infoprint 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.
Parameterscontrol_groupbaseline level type: str | Nonedata_colmeasurement column type: strdata_indexelement index for sequence-valued rows type: intgroup_colgroup column type: str | Nonesensor_colsensor column type: strmin_nminimum per-group samples type: intdrop_zerosremove 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 fromself.data.
Parametersvalues/ch_namesexplicit map input (or infer from data columns) type: array-like | Noneposition_offsetmandatory (y,z) offset type: tuple[float, float]sensor_col/data_col/data_indexDataFrame mapping type: strmontage/ch_typechannel geometry type: strsphere/cmap/vmin/vmaxstyle and limits type: float | tuplecolorbar*colorbar controls type: Anysensors/outlines/contours/res/extrapolate/image_interpMNE topomap options type: bool | str | Noneaxes/show/title/namesdisplay 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.
Parametersvalues/ch_namesexplicit parcel values and names (or infer fromself.data) type: array-like | Nonesensor_col/data_col/data_indexDataFrame mapping used whenvaluesis omitted type: str | int | Noneatlasparcellation name type: strsubject/subjects_dirsource anatomy type: strsurface/hemisphere/viewsviewing geometry type: strcmap/vmin/vmax/center/alpha/smoothing_stepsrendering style type: strcolorbar/colorbar_kwargscolor scale type: boolcortex/background/sizescene styling type: strshow/axesmatplotlib target behavior type: boolauto_fetchauto-download fsaverage type: boolhcp_acceptHCP-MMP license acceptance type: boolbackendrendering backend selector. type: strverboseMNE verbosity type: bool | str | int | Nonebrain_kwargsadditional Brain constructor args. type: dict
EphysDatasetParser
Module: ncpi/EphysDatasetParser.py
-
CanonicalFields: source
Declarative locator map for canonical parsed fields.
Fieldsdatasignal accessor (array-like expected). type: DataFrame | Anyfssampling-frequency accessor in Hz. type: float | Nonech_nameschannel-name accessor/list. type: list[str] | Nonetimetime-axis accessor. type: field spec | Nonedata_domaindomain label accessor (time/frequency). type: field spec | Nonefreqsfrequency-axis accessor for spectral inputs. type: np.ndarray | Nonespectral_kindspectral representation accessor. type: field spec | Noneepochepoch index accessor. type: field spec | Nonemetadataextra metadata accessor/map. type: dict | callable | Nonetable_layouttabular layout selector. type: str | Nonechannel_columnschannel columns for wide tables. type: list[str] | Nonelong_channel_colchannel-name column for long tables. type: str | Nonelong_value_colvalue column for long tables. type: str | Nonelong_time_coltime column for long tables. type: str | Nonearray_axes. type: tuple | list | None
-
ParseConfig: source
Parser behavior configuration for loading, segmentation, epoching, normalization, and aggregation.
Fieldsfieldscanonical field locator configuration. type: CanonicalFieldsepoch_length_sepoch length in seconds. type: float | Noneepoch_step_sepoch step in seconds. type: float | Nonesegment_t0_soptional segment start time (seconds). type: float | Nonesegment_t1_soptional segment end time (seconds). type: float | Nonepreloadwhether to preload source data into memory. type: boolpick_typeschannel-picking rules. type: dict | Nonemax_secondsoptional maximum duration to keep from each recording. type: float | Nonedrop_badsdrop channels marked as bad. type: boolzscoreapply z-score normalization. type: boolzscore_after_epochapply z-score after epoching. type: boolexclude_last_epochdrop incomplete last epoch. type: boolalign_epoch_count_to_minimumalign all channels to minimum epoch count. type: boolaggregate_overaxes to aggregate over (e.g., sensor). type: tuple[str, ...] | Noneaggregate_methodaggregation operation name. type: straggregate_labelscustom labels for aggregated outputs. type: dict | Nonewarn_unimplemented. type: bool
-
EphysDatasetParser.__init__(config=None): source
Construct a parser instance with explicit configuration.
ParametersconfigoptionalParseConfig(defaults applied when omitted). type: ParseConfig | None
-
EphysDatasetParser.parse(source): source
Parse in-memory objects or file paths into canonical DataFrame rows.
Parameterssourcepath 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.
Parametersmodule_nameimport path type: strpackagepip package name type: str | Noneversion_specversion constraint type: str | Noneupgrade/user/quiet/extra_pip_argspip behavior type: boolreload_moduleforce reload type: boolraise_on_errorraise 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.
Parametersmodule_pathmodule import path. type: strattribute_nameattribute/class/function name to import from the module. type: str | Nonepackageoptional package context for relative imports. type: str | Nonedefaultfallback return value when import fails and raise_on_error=False. type: Anyraise_on_errorraise exception on failure instead of returning default. type: boolreload_moduleforce module reload before returning attribute/module. type: boolensure_typeoptional runtime type check for the imported object. type: type | tuple[type, ...] | Noneensure_callable. type: bool
-
record_id_from_api_url(api_url): source
Extract a Zenodo record ID from API URL text.
Parametersapi_urlZenodo record API URL. type: str
-
ensure_fresh_dir(download_dir): source
Recreate an empty directory.
Parametersdownload_dirtarget directory path. type: str | PathLike
-
safe_extract_zip(zip_path, outdir): source
Safely extract ZIP archives with path-traversal checks.
Parameterszip_patharchive file type: str | PathLikeoutdirextraction folder. type: str | PathLike
-
safe_extract_tar(tar_path, outdir): source
Safely extract TAR archives with path-traversal checks.
Parameterstar_patharchive file type: str | PathLikeoutdirextraction folder. type: str | PathLike
-
extract_and_delete_all_archives(outdir, *, verbose=True): source
Recursively extract ZIP/TAR files and delete each archive after extraction.
Parametersoutdirroot folder type: str | PathLikeverboseprint progress. type: bool | str | int | None
-
get_requests_and_tqdm(): source
Resolve and returnrequestsandtqdmmodules. -
fetch_record_json(requests, api_url, headers, timeout=60): source
Request record metadata JSON from Zenodo API.
Parametersrequestsrequests module/object type: module | objectapi_urlrecord URL type: strheadersHTTP headers type: dicttimeoutrequest 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.
ParametersrequestsHTTP client module type: module | objecttqdmprogress helper type: callable | modulefile_urlsource URL type: strdest_pathoutput path type: str | PathLikeheadersrequest headers type: dicttimeoutseconds type: int | floatchunk_sizetransfer chunk bytes type: intdescprogress label. type: str | None
-
is_http_403(err): source
Detect whether an exception corresponds to HTTP 403.
Parameterserrcaught exception object. type: Exception
-
download_files_archive_with_curl(record_id, outdir): source
Fallback downloader using Zenodo files-archive endpoint plus extraction.
Parametersrecord_idZenodo record ID type: str | intoutdirdestination 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.
Parametersapi_urlrecord API URL type: strdownload_dirlocal output folder type: str | PathLikefallback_files_archiveuse archive fallback when direct downloads fail. type: bool
-
timer(description=None): source
Decorator to measure and print function execution time.
Parametersdescriptionoptional label shown in timing output. type: str | None