Package: biopsykit
BioPsyKitA Python package for the analysis of biopsychological data.With this package you have everything you need for analyzing biopsychological data, including:Data processing pipelines for various physiological signals (ECG, EEG, Respiration, Motion, ...).Algorithms and data processing pipelines for sleep/wake prediction and computation of sleep endpoints
based on activity or IMU data.Functions to import and process data from sleep trackers (e.g., Withings Sleep Analyzer)Functions for processing and analysis of salivary biomarker data (cortisol, amylase).Implementation of various psychological and HCI-related questionnaires.Implementation of classes representing different psychological protocols
(e.g., TSST, MIST, Cortisol Awakening Response Assessment, etc.)Functions for easily setting up statistical analysis pipelines.Functions for setting up and evaluating machine learning pipelines.Plotting wrappers optimized for displaying biopsychological data.DetailsAnalysis of Physiological SignalsECG ProcessingBioPsyKitprovides a whole ECG data processing pipeline, consisting of:Loading ECG data from:Generic.csvfilesNilsPod binary (.bin) files (requiresNilsPodLib)Other sensor types (coming soon)Splitting data into single study parts (based on time intervals) that will be analyzed separatelyPerforming ECG processing, including:R peak detection (usingNeurokit)R peak outlier removal and interpolationHRV feature computationECG-derived respiration (EDR) estimation for respiration rate and respiratory sinus arrhythmia (RSA)
(experimental)Instantaneous heart rate resamplingComputing aggregated results (e.g., mean and standard error) per study partCreating plots for visualizing processing resultsQuick Examplefrombiopsykit.signals.ecgimportEcgProcessorfrombiopsykit.example_dataimportget_ecg_exampleecg_data,sampling_rate=get_ecg_example()ep=EcgProcessor(ecg_data,sampling_rate)ep.ecg_process()print(ep.ecg_result)... more biosignals coming soon!Sleep/Wake PredictionBioPsyKitallows to process sleep data collected from IMU or activity sensors (e.g., Actigraphs). This includes:Detection of wear periodsDetection of time spent in bedDetection of sleep and wake phasesComputation of sleep endpoints (e.g., sleep and wake onset, net sleep duration wake after sleep onset, etc.)Quick Exampleimportbiopsykitasbpfrombiopsykit.example_dataimportget_sleep_imu_exampleimu_data,sampling_rate=get_sleep_imu_example()sleep_results=bp.sleep.sleep_processing_pipeline.predict_pipeline_acceleration(imu_data,sampling_rate)sleep_endpoints=sleep_results["sleep_endpoints"]print(sleep_endpoints)Salivary Biomarker AnalysisBioPsyKitprovides several methods for the analysis of salivary biomarkers (e.g. cortisol and amylase), such as:Import data from Excel and csv files into a standardized formatCompute standard features (maximum increase, slope, area-under-the-curve, mean, standard deviation, ...)Quick Exampleimportbiopsykitasbpfrombiopsykit.example_dataimportget_saliva_examplesaliva_data=get_saliva_example(sample_times=[-20,0,10,20,30,40,50])max_inc=bp.saliva.max_increase(saliva_data)# remove the first saliva sample (t=-20) from computing the AUCauc=bp.saliva.auc(saliva_data,remove_s0=True)print(max_inc)print(auc)QuestionnairesBioPsyKitimplements various established psychological (state and trait) questionnaires, such as:Perceived Stress Scale (PSS)Positive and Negative Affect Schedule (PANAS)Self-Compassion Scale (SCS)Big Five Inventory (BFI)State Trait Depression and Anxiety Questionnaire (STADI)Trier Inventory for Chronic Stress (TICS)Primary Appraisal Secondary Appraisal Scale (PASA)...Quick Exampleimportbiopsykitasbpfrombiopsykit.example_dataimportget_questionnaire_exampledata=get_questionnaire_example()pss_data=data.filter(like="PSS")pss_result=bp.questionnaires.pss(pss_data)print(pss_result)List Supported Questionnairesimportbiopsykitasbpprint(bp.questionnaires.utils.get_supported_questionnaires())Psychological ProtocolsBioPsyKitimplements methods for easy handling and analysis of data recorded with several established psychological
protocols, such as:Montreal Imaging Stress Task (MIST)Trier Social Stress Test (TSST)Cortisol Awakening Response Assessment (CAR)...Quick Examplefrombiopsykit.protocolsimportTSSTfrombiopsykit.example_dataimportget_saliva_examplefrombiopsykit.example_dataimportget_hr_subject_data_dict_example# specify TSST structure and the durations of the single phasesstructure={"Pre":None,"TSST":{"Preparation":300,"Talk":300,"Math":300},"Post":None}tsst=TSST(name="TSST",structure=structure)saliva_data=get_saliva_example(sample_times=[-20,0,10,20,30,40,50])hr_subject_data_dict=get_hr_subject_data_dict_example()# add saliva data collected during the whole TSST proceduretsst.add_saliva_data(saliva_data,saliva_type="cortisol")# add heart rate data collected during the "TSST" study parttsst.add_hr_data(hr_subject_data_dict,study_part="TSST")# compute heart rate results: normalize ECG data relative to "Preparation" phase; afterwards, use data from the# "Talk" and "Math" phases and compute the average heart rate for each subject and study phase, respectivelytsst.compute_hr_results(result_id="hr_mean",study_part="TSST",normalize_to=True,select_phases=True,mean_per_subject=True,params={"normalize_to":"Preparation","select_phases":["Talk","Math"]})Statistical AnalysisBioPsyKitimplements methods for simplified statistical analysis of biopsychological data by offering an
object-oriented interface for setting up statistical analysis pipelines, displaying the results, and adding
statistical significance brackets to plots.Quick Exampleimportmatplotlib.pyplotaspltfrombiopsykit.statsimportStatsPipelinefrombiopsykit.plottingimportmulti_feature_boxplotfrombiopsykit.example_dataimportget_stats_exampledata=get_stats_example()# configure statistical analysis pipeline which consists of checking for normal distribution and performing paired# t-tests (within-variable: time) on each questionnaire subscale separately (grouping data by subscale).pipeline=StatsPipeline(steps=[("prep","normality"),("test","pairwise_ttests")],params={"dv":"PANAS","groupby":"subscale","subject":"subject","within":"time"})# apply statistics pipeline on datapipeline.apply(data)# plot data and add statistical significance brackets from statistical analysis pipelinefig,axs=plt.subplots(ncols=3)features=["NegativeAffect","PositiveAffect","Total"]# generate statistical significance bracketsbox_pairs,pvalues=pipeline.sig_brackets("test",stats_effect_type="within",plot_type="single",x="time",features=features,subplots=True)# plot datamulti_feature_boxplot(data=data,x="time",y="PANAS",features=features,group="subscale",order=["pre","post"],stats_kwargs={"box_pairs":box_pairs,"pvalues":pvalues},ax=axs)Machine Learning AnalysisBioPsyKitimplements methods for simplified and systematic evaluation of different machine learning pipelines.Quick Example# Utilsfromsklearn.datasetsimportload_breast_cancer# Preprocessing & Feature Selectionfromsklearn.feature_selectionimportSelectKBestfromsklearn.preprocessingimportMinMaxScaler,StandardScaler# Classificationfromsklearn.neighborsimportKNeighborsClassifierfromsklearn.treeimportDecisionTreeClassifier# Cross-Validationfromsklearn.model_selectionimportKFoldfrombiopsykit.classification.model_selectionimportSklearnPipelinePermuter# load example datasetbreast_cancer=load_breast_cancer()X=breast_cancer.datay=breast_cancer.target# specify estimator combinationsmodel_dict={"scaler":{"StandardScaler":StandardScaler(),"MinMaxScaler":MinMaxScaler()},"reduce_dim":{"SelectKBest":SelectKBest(),},"clf":{"KNeighborsClassifier":KNeighborsClassifier(),"DecisionTreeClassifier":DecisionTreeClassifier(),}}# specify hyperparameter for grid searchparams_dict={"StandardScaler":None,"MinMaxScaler":None,"SelectKBest":{"k":[2,4,"all"]},"KNeighborsClassifier":{"n_neighbors":[2,4],"weights":["uniform","distance"]},"DecisionTreeClassifier":{"criterion":['gini','entropy'],"max_depth":[2,4]},}pipeline_permuter=SklearnPipelinePermuter(model_dict,params_dict)pipeline_permuter.fit(X,y,outer_cv=KFold(5),inner_cv=KFold(5))# print summary of all relevant metrics for the best pipeline for each evaluated pipeline combinationprint(pipeline_permuter.metric_summary())InstallationBioPsyKitrequires Python >=3.8. First, install a compatible version of Python. Then installBioPsyKitvia pip.Installation fromPyPi:pipinstallbiopsykitInstallation fromPyPiwith extras
(e.g.,jupyterto directly install all required dependencies for the use with Jupyter Lab):pipinstall"biopsykit[jupyter]"Installation from local repository copy:gitclonehttps://github.com/mad-lab-fau/BioPsyKit.gitcdBioPsyKit
pipinstall.For DeveloperIf you are a developer and want to contribute toBioPsyKityou can install an editable version of the package from
a local copy of the repository.BioPsyKit usespoetryto manage dependencies and packaging. Once you installed poetry,
run the following commands to clone the repository, initialize a virtual env and install all development dependencies:Without Extrasgitclonehttps://github.com/mad-lab-fau/BioPsyKit.gitcdBioPsyKit
poetryinstallWith all Extras (e.g., extended functionalities for IPython/Jupyter Notebooks)gitclonehttps://github.com/mad-lab-fau/BioPsyKit.gitcdBioPsyKit
poetryinstall-Emne-EjupyterTo run any of the tools required for the development workflow, use thepoecommands of thepoethepoettask runner:$poe
docsBuildthehtmldocsusingSphinx.
formatReformatallfilesusingblack.
format_checkCheck,butnotchange,formattingusingblack.
lintLintallfileswithProspector.testRunPytestwithcoverage.
update_versionBumptheversioninpyproject.tomlandbiopsykit.__init__.
register_ipykernelRegisteranewIPythonkernelnamed`biopsykit`linkedtothevirtualenvironment.
remove_ipykernelRemovetheassociatedIPythonkernel.Some NotesThepoecommands are only available if you are in the virtual environment associated with this project.
You can either activate the virtual environment manually (e.g.,source .venv/bin/activate) or use thepoetry shellcommand to spawn a new shell with the virtual environment activated.In order to use jupyter notebooks with the project you need to register a new IPython
kernel associated with the venv of the project (poe register_ipykernel- see below).
When creating a notebook, make to sure to select this kernel (top right corner of the notebook).In order to build the documentation, you need to additionally installpandoc.See theContributing Guidelinesfor further information.ExamplesSee theExamples Galleryfor example on how to use BioPsyKit.Citing BioPsyKitIf you useBioPsyKitin your work, please report the version you used in the text. Additionally, please also cite the corresponding paper:Richer et al., (2021). BioPsyKit: A Python package for the analysis of biopsychological data. Journal of Open Source Software, 6(66), 3702, https://doi.org/10.21105/joss.03702If you use a specific algorithm please also to make sure you cite the original paper of the algorithm! We recommend the following citation style:We used the algorithm proposed by Author et al. [paper-citation], implemented by the BioPsykit package [biopsykit-citation].