biopsykit.protocols package¶
Module with classes representing different psychological protocols.
- class biopsykit.protocols.CAR(name=None, **kwargs)[source]¶
Bases:
BaseProtocolClass representing psychological protocols for assessing the cortisol awakening response (CAR).
- Parameters
name (str, optional) – name of CAR study or
Noneto use default name (“CAR”). Default:None**kwargs –
additional parameters to be passed to
CARand its superclass,BaseProtocol, such as:car_saliva_plot_params: parameters to stylecar_saliva_plot()
- car_plot_params¶
Plot parameters to style
car_saliva_plot().
- car_saliva_plot(saliva_type='cortisol', **kwargs)[source]¶
Plot CAR saliva data as lineplot.
- Parameters
saliva_type (str, optional) – type of saliva data to plot. Default:
cortisol**kwargs (optional arguments to be passed to
lineplot()) –
- Returns
- Return type
See also
lineplot()draw line plot with error bars
- class biopsykit.protocols.CFT(name=None, structure=None, **kwargs)[source]¶
Bases:
BaseProtocolClass representing the Cold Face Test (CFT) and data collected while conducting the CFT.
The typical structure of the CFT consists of three phases:
“Baseline”: Time at rest before applying cold face stimulus
“CFT”: Application of cold face stimulus
“Recovery”: Time at rest after applying cold face stimulus
- Parameters
name (str) – name of protocol or
Noneto use “CFT” as default name. Default:Nonestructure (dict, optional) –
nested dictionary specifying the structure of the CFT.
The typical structure of the CFT consists of three phases:
”Baseline”: Time at rest before applying cold face stimulus
”CFT”: Application of cold face stimulus
”Recovery”: Time at rest after applying cold face stimulus
The duration of each phase is specified in seconds. Typical durations are: 60s for Baseline, 120s for CFT, 60s for Recovery
The start and duration of the CFT Exposure (
cft_startandcft_duration) will be automatically extracted from the structure dictionary.**kwargs –
additional parameters to be passed to
CFTand its superclass,BaseProcessor, such as:cft_plot_params: dictionary with parameters to stylecft_plot()
Examples
>>> from biopsykit.protocols import CFT >>> # Example: CFT procedure consisting of three parts. >>> >>> structure = { >>> "Baseline": 60, >>> "CFT": 120, >>> "Recovery": 60 >>> } >>> CFT(name="CFT", structure=structure)
- cft_start: int¶
Start of Cold Face Exposure in seconds. It is assumed that the time between the beginning of the recording and the start of the Cold Face Exposure is the Baseline. Default: 60 seconds
- compute_cft_parameter(data, index=None, return_dict=False)[source]¶
Compute CFT parameter.
This function computes the following CFT parameter and returns the result in a dataframe (or, optionally, as dictionary):
Baseline Heart Rate (see
baseline_hr()for further information)CFT Onset (see
onset()for further information)Peak Bradycardia (see
peak_bradycardia()for further information)Mean Bradycardia (see
mean_bradycardia()for further information)Polynomial Fit on CFT Reaction (see
poly_fit()for further information)
- Parameters
- Returns
dataframe or dictionary with CFT parameter
- Return type
DataFrameor dict
- baseline_hr(data)[source]¶
Compute mean heart rate during Baseline Interval.
The Baseline Interval is data in the interval [
0,cft_start].Warning
If
cft_startis 0, it is assumed that no Baseline is present and the first heart rate value in the dataframe is used as CFT Baseline.- Parameters
data (
DataFrame) – input data- Returns
mean heart rate during Baseline Interval
- Return type
- Raises
FeatureComputationError – if data is shorter than the expected duration of the Baseline interval
- extract_cft_interval(data)[source]¶
Extract interval during which CFT was applied.
This function extracts only the part of the data during the “actual” Cold Face Test, i.e., the time during which the cold face stimulus was applied.
- onset(data, is_cft_interval=False, compute_baseline=True, hr_baseline=None)[source]¶
Compute CFT onset.
The CFT onset is defined as the time point after beginning of the CFT Interval where three consecutive heart beats are lower than the Baseline heart rate (typically the Interval directly before the CFT).
This function computes the following CFT onset parameter:
onset: location of CFT onset. This value is the same datatype as the index ofdata(i.e., either a absolute datetime timestamp or a relative timestamp in time since recording).onset_latency: CFT onset latency, i.e., the duration between beginning of the CFT Interval and CFT onset in seconds.onset_idx: location of CFT onset as array indexonset_hr: heart rate at CFT onset in bpmonset_hr_brady_percent: bradycardia at CFT onset, i.e., relative change of CFT onset heart rate compared to Baseline heart rate in percent.onset_slope: Slope between Baseline heart rate and CFT onset heart rate, computed as: onset_slope = (onset_hr - baseline_hr) / onset_latency
- Parameters
data (
DataFrame) – input datais_cft_interval (bool, optional) –
Trueif the heart rate data passed viadatacontains only the CFT Interval,Falseif it contains the data during the whole CFT procedure. Default:Falsecompute_baseline (bool, optional) –
Trueif Baseline Interval is included in data passed viadataand Baseline heart rate should be computed orFalseif Baseline heart rate is passed separately viahr_baseline. Default:Truehr_baseline (float, optional) – mean heart rate during Baseline Interval or
Noneif Baseline interval is present indataand Baseline heart rate is computed from there. Default:None
- Returns
dictionary with CFT onset parameter
- Return type
- peak_bradycardia(data, is_cft_interval=False, compute_baseline=True, hr_baseline=None)[source]¶
Compute CFT peak bradycardia.
The CFT peak bradycardia is defined as the maximum bradycardia (i.e., the minimum heart rate) during the CFT Interval.
This function computes the following CFT peak bradycardia parameter:
peak_brady: location of CFT peak bradycardia. This value is the same datatype as the index ofdata(i.e., either a absolute datetime timestamp or a relative timestamp in time since recording).peak_brady_latency: CFT peak bradycardia latency, i.e., the duration between beginning of the CFT Interval and CFT peak bradycardia in seconds.peak_brady_idx: location of CFT peak bradycardia as array indexpeak_brady_bpm: CFT peak bradycardia in bpmpeak_brady_percent: Relative change of CFT peak bradycardia heart rate compared to Baseline heart rate in percent.peak_brady_slope: Slope between Baseline heart rate and CFT peak bradycardia heart rate, computed as:peak_brady_slope = (peak_brady_bpm - baseline_hr) / peak_brady_latency
- Parameters
data (
DataFrame) – input datais_cft_interval (bool, optional) –
Trueif the heart rate data passed viadatacontains only the CFT Interval,Falseif it contains the data during the whole CFT procedure. Default:Falsecompute_baseline (bool, optional) –
Trueif Baseline Interval is included in data passed viadataand Baseline heart rate should be computed orFalseif Baseline heart rate is passed separately viahr_baseline. Default:Truehr_baseline (float, optional) – mean heart rate during Baseline Interval or
Noneif Baseline interval is present indataand Baseline heart rate is computed from there. Default:None
- Returns
dictionary with CFT peak bradycardia parameter
- Return type
- mean_bradycardia(data, is_cft_interval=False, compute_baseline=True, hr_baseline=None)[source]¶
Compute CFT mean bradycardia.
The CFT mean bradycardia is defined as the mean bradycardia (i.e., the mean decrease of heart rate) during the CFT Interval.
This function computes the following CFT mean bradycardia parameter:
mean_hr_bpm: average heart rate during CFT Interval in bpmmean_brady_bpm: average bradycardia during CFT Interval, computed as:mean_brady_bpm = mean_hr_bpm - hr_baselinemean_brady_percent: relative change of CFT mean bradycardia heart rate compared to Baseline heart rate in percent
- Parameters
data (
DataFrame) – input datais_cft_interval (bool, optional) –
Trueif the heart rate data passed viadatacontains only the CFT Interval,Falseif it contains the data during the whole CFT procedure. Default:Falsecompute_baseline (bool, optional) –
Trueif Baseline Interval is included in data passed viadataand Baseline heart rate should be computed orFalseif Baseline heart rate is passed separately viahr_baseline. Default:Truehr_baseline (float, optional) – mean heart rate during Baseline Interval or
Noneif Baseline interval is present indataand Baseline heart rate is computed from there. Default:None
- Returns
dictionary with CFT mean bradycardia parameter
- Return type
- poly_fit(data, is_cft_interval=False, compute_baseline=True, hr_baseline=None)[source]¶
Compute CFT polynomial fit.
The CFT polynomial fit is computed by applying a 2nd order least-squares polynomial fit to the heart rate during the CFT Interval because the CFT-induced bradycardia and the following recovery is assumed to follow a polynomial function.
This function computes the following CFT polynomial fit parameter:
poly_fit_a{0-2}: constants of the polynomialp(x) = p[2] * x**deg + p[1]* x + p[0]
- Parameters
data (
DataFrame) – input datais_cft_interval (bool, optional) –
Trueif the heart rate data passed viadatacontains only the CFT Interval,Falseif it contains the data during the whole CFT procedure. Default:Falsecompute_baseline (bool, optional) –
Trueif Baseline Interval is included in data passed viadataand Baseline heart rate should be computed orFalseif Baseline heart rate is passed separately viahr_baseline. Default:Truehr_baseline (float, optional) – mean heart rate during Baseline Interval or
Noneif Baseline interval is present indataand Baseline heart rate is computed from there. Default:None
- Returns
dictionary with CFT polynomial fit parameter
- Return type
- cft_plot(data, **kwargs)[source]¶
Draw Cold Face Test (CFT) plot.
- Parameters
data (
DataFrame) – input data**kwargs (dict, optional) –
optional parameters to be passed to the plot, such as:
time_baseline: duration of Baseline Interval to include in plot orNoneto include the whole Baseline Interval in the plot.time_recovery: duration of Recovery Interval to include in plot orNoneto include the whole Recovery Interval in the plot.plot_datetime_index:Trueto plot x axis with absolute time (DatetimeIndex), orFalseto plot data with relative time (starting from second 0). Default:Falseax: pre-existing axes for the plot. Otherwise, a new figure and axes object is created and returned.figsize: tuple specifying figure dimensionsylims: list to manually specify y axis limits, float to specify y axis margin (seematplotlib.axes.Axes.margins()for further information), orNoneto automatically infer y axis limits.plot_onset: whether to plot CFT onset annotations or not: Default:Trueplot_peak_brady: whether to plot CFT peak bradycardia annotations or not: Default:Trueplot_mean: whether to plot CFT mean bradycardia annotations or not. Default:Trueplot_baseline: whether to plot heart rate baseline annotations or not. Default:Trueplot_poly_fit: whether to plot CFT polynomial fit annotations or not. Default:True
- Returns
- Return type
- class biopsykit.protocols.MIST(name=None, structure=None, **kwargs)[source]¶
Bases:
BaseProtocolClass representing the Montreal Imaging Stress Task (MIST) protocol and data collected within a MIST study.
The general structure of the MIST can be specified by passing a
structuredict to the constructor.Up to three nested structure levels are supported:
1st level:
study part: Different parts of the study where the MIST was conducted, such as: “Pre”, “MIST”, and “Post”2nd level:
phase: Different MIST phases that belong to the same study part, such as: “MIST1”, “MIST2”, “MIST3” (for study part “MIST”) or “Questionnaires”, “Rest”, “Training” (for study part “Pre”)3rd level:
subphase: Different MIST subphases that belong to the same phase, such as: “Baseline”, “Arithmetic Task”, “Feedback”
- Parameters
name (str, optional) – name of protocol or
Noneto use “MIST” as default name. Default:Nonestructure (dict, optional) –
nested dictionary specifying the structure of the MIST study.
Up to three nested structure levels are supported:
1st level:
study part: Different parts of the study where the MIST was conducted, such as: “Pre”, MIST”, and “Post”2nd level:
phase: Different MIST phases that belong to the same study part, such as: “MIST1”, “MIST2”, “MIST3” (for study part “MIST”) or “Questionnaires”, “Rest”, “Training” (for study part “Pre”)3rd level:
subphase: Different MIST subphases that belong to the same phase, such as: “Baseline”, “Arithmetic Task”, “Feedback”
If a study part has no division into finer phases (or a phase has no division into finer subphases) the dictionary value can be set to
None.**kwargs –
additional parameters to be passed to
MISTand its superclass,BaseProtocol, such as:saliva_plot_params: dictionary with parameters to stylesaliva_plot()hr_mean_plot_params: dictionary with parameters to stylehr_mean_plot()hr_ensemble_plot_params: dictionary with parameters to stylehr_ensemble_plot()
Examples
>>> from biopsykit.protocols import MIST >>> # Example: MIST study consisting of three parts. Only the MIST part consists of different >>> # phases and subphases >>> structure = { >>> "Before": None, >>> "MIST": { >>> "MIST1": {"BL": 60, "AT": 240, "FB": 120}, >>> "MIST2": {"BL": 60, "AT": 240, "FB": 120}, >>> "MIST3": {"BL": 60, "AT": 240, "FB": 120} >>> }, >>> "After": None >>> } >>> MIST(name="MIST", structure=structure)
References
Dedovic, K., Renwick, R., Mahani, N. K., Engert, V., Lupien, S. J., & Pruessner, J. C. (2005). The Montreal Imaging Stress Task: Using functional imaging to investigate the effects of perceiving and processing psychosocial stress in the human brain. Journal of Psychiatry and Neuroscience, 30(5), 319-325.
- hr_ensemble_plot(ensemble_id, subphases=None, **kwargs)[source]¶
Draw heart rate ensemble plot.
- Parameters
ensemble_id (str) – identifier of the ensemble data to be plotted. Ensemble data needs to be computed using
compute_hr_ensemble()first.subphases (dict, optional) – dictionary with phases (keys) and subphases (values - dict with subphase names and subphase durations) or
Noneto retrieve MIST information fromstructuredict. When passingNone, it is assumed that the study part containing the MIST is namedMIST.**kwargs (dict, optional) – optional arguments for plot configuration to be passed to
hr_ensemble_plot().
- Returns
fig (
matplotlib.figure.Figure) – figure objectax (
matplotlib.axes.Axes) – axes object
- Return type
See also
compute_hr_ensemble()compute heart rate ensemble data
hr_ensemble_plot()Heart rate ensemble plot
- class biopsykit.protocols.TSST(name=None, structure=None, **kwargs)[source]¶
Bases:
BaseProtocolClass representing the Trier Social Stress Test (TSST).
The general structure of the TSST can be specified by passing a
structuredict to the constructor.- Up to three nested structure levels are supported:
1st level:
study part: Different parts of the study where the TSST was conducted, such as: “Pre”, “TSST”, and “Post”.2nd level:
phase: Different TSST phases that belong to the same study part, such as: “Preparation”, “Talk”, “Math” (for study part “TSST”) or “Questionnaires”, “Rest” (for study part “Pre”).3rd level:
subphase: Different TSST subphases that belong to the same phase.
- Parameters
name (str) – name of protocol or
Noneto use “TSST” as default name. Default:Nonestructure (dict, optional) –
nested dictionary specifying the structure of the TSST study.
Up to three nested structure levels are supported:
1st level:
study part: Different parts of the study where the TSST was conducted, such as: “Pre”, “TSST”, and “Post”.2nd level:
phase: Different TSST phases that belong to the same study part, such as: “Preparation”, “Talk”, “Math” (for study part “TSST”) or “Questionnaires”, “Rest” (for study part “Pre”).3rd level:
subphase: Different TSST subphases that belong to the same phase.
If a study part has no division into finer phases (or a phase has no division into finer subphases) the dictionary value can be set to
None.**kwargs –
additional parameters to be passed to
MISTand its superclass,BaseProtocol, such as:saliva_plot_params: dictionary with parameters to stylesaliva_plot()hr_mean_plot_params: dictionary with parameters to stylehr_mean_plot()hr_ensemble_plot_params: dictionary with parameters to stylehr_ensemble_plot()
Examples
>>> from biopsykit.protocols import TSST >>> # Example: TSST study consisting of three parts. Only the TSST part consists of different phases >>> structure = { >>> "Pre": None, >>> "TSST": { >>> "Preparation": 300, >>> "Talk": 300, >>> "Math": 300 >>> }, >>> "Post": None >>> } >>> TSST(name="TSST", structure=structure)
References
Kirschbaum, C., Pirke, K.-M., & Hellhammer, D. H. (1993). The “Trier Social Stress Test” - A Tool for Investigating Psychobiological Stress Responses in a Laboratory Setting. Neuropsychobiology, 28, 76-81. https://doi.org/10.1159/000119004
- class biopsykit.protocols.BaseProtocol(name, structure=None, test_times=None, **kwargs)[source]¶
Bases:
objectClass representing a base class for psychological protocols and data collected within a study.
The general structure of the protocol can be specified by passing a
structuredict to the constructor ofBaseProtocol.Up to three nested structure levels are supported:
1st level:
study part: Different parts of the study, such as: “Preface”, “Test”, and “Questionnaires”2nd level:
phase: Different phases of the psychological protocol that belong to the same study part, such as: “Preparation”, “Stress”, “Recovery”3rd level:
subphase: Different subphases that belong to the same phase, such as: “Baseline”, “Arithmetic Task”, “Feedback”
Note
Duration of phases and/or subphases are expected in seconds.
- Parameters
name (str) – name of protocol
structure (dict, optional) –
nested dictionary specifying the structure of the protocol. Up to three nested structure levels are supported:
1st level:
study_part: Different parts of the study, such as: “Preface”, “Test”, and “Questionnaires”2nd level:
phase: Different phases of the psychological protocol that belong to the same study part, such as: “Preparation”, “Stress”, “Recovery”3rd level:
subphase: Different subphases that belong to the same phase, such as: “Baseline”, “Arithmetic Task”, “Feedback”
If a study part has no division into finer phases (or a phase has no division into finer subphases) the dictionary value can be set to
None. If the whole study has no division into different parts, thestructuredict can be set toNone. Default:Nonetest_times (list, optional) – start and end time of psychological test (in minutes) or
Noneif the protocol has no particular test.test_timesis then internally set to [0, 0]. Default:None**kwargs –
additional parameters to be passed to
BaseProtocol, such as:saliva_plot_params: dictionary with parameters to stylesaliva_plot()hr_mean_plot_params: dictionary with parameters to stylehr_mean_plot()hr_ensemble_plot_params: dictionary with parameters to stylehr_ensemble_plot()
Examples
>>> from biopsykit.protocols import BaseProtocol >>> # Example 1: study with three parts, no finer division into phases >>> structure = { >>> "Preface": None, >>> "Test": None, >>> "Questionnaires": None >>> } >>> BaseProtocol(name="Base", structure=structure) >>> # Example 2: study with three parts, all parts have different phases with specific durations >>> structure = { >>> "Preface": {"Questionnaires": 240, "Baseline": 60}, >>> "Test": {"Preparation": 120, "Test": 240, "Recovery": 120}, >>> "Recovery": {"Part1": 240, "Part2": 240} >>> } >>> BaseProtocol(name="Base", structure=structure) >>> # Example 3: only certain study parts have different phases (example: TSST) >>> structure = { >>> "Before": None, >>> "TSST": {"Preparation": 300, "Talk": 300, "Math": 300}, >>> "After": None >>> } >>> BaseProtocol(name="Base", structure=structure) >>> # Example 4: study with phases and subphases, only certain study parts have different phases (example: MIST) >>> structure = { >>> "Before": None, >>> "MIST": { >>> "MIST1": {"BL": 60, "AT": 240, "FB": 120}, >>> "MIST2": {"BL": 60, "AT": 240, "FB": 120}, >>> "MIST3": {"BL": 60, "AT": 240, "FB": 120} >>> }, >>> "After": None >>> } >>> BaseProtocol(name="Base", structure=structure)
- structure: dict[str, Any]¶
Structure of protocol, i.e., whether protocol is divided into different parts, phases, or subphases.
If protocol is not divided into different parts
protocol_structureis set toNone.
- test_times: Sequence[int]¶
Start and end time of psychological test (in minutes).
If no psychological test was performed in the protocol
test_timesis set to [0, 0].
- sample_times: dict[str, collections.abc.Sequence[int]]¶
Dictionary with sample times of saliva samples (in minutes).
Sample times are either provided explicitly using the
sample_timesparameter inadd_saliva_data()or by extracting it from the saliva data (if atimecolumn is present).
- saliva_data: dict[str, biopsykit.utils.dtypes._BiomarkerRawDataFrame | pandas.core.frame.DataFrame]¶
Dictionary with saliva data collected during the study.
Data in
SalivaRawDataFrameformat can be added usingadd_saliva_data().
- hr_data: dict[str, dict[str, dict[str, biopsykit.utils.dtypes._HeartRateDataFrame | pandas.core.frame.DataFrame]] | dict[str, dict[str, dict[str, biopsykit.utils.dtypes._HeartRateDataFrame | pandas.core.frame.DataFrame]]]]¶
Dictionary with heart rate data collected during the study. If the study consists of multiple study parts each part has its own
HeartRateSubjectDataDict. If the study has no individual study parts (only different phases), the name of the one and only study part defaults toStudy(to ensure consistent dictionary structure).Data in
HeartRateSubjectDataDictformat can be added usingadd_hr_data().
- rpeak_data: dict[str, dict[str, dict[str, pandas.core.frame.DataFrame]]]¶
Dictionary with R peak data collected during the study. If the study consists of multiple study parts each part has its own
SubjectDataDict. If the study has no individual study parts (only different phases), the name of the one and only study part defaults toStudy(to ensure consistent dictionary structure).Data in
SubjectDataDictformat can be added usingadd_hr_data().
- hr_results: dict[str, pandas.core.frame.DataFrame]¶
Dictionary with heart rate results.
Dict keys are the identifiers that are specified when computing results from
hr_datausingcompute_hr_results().
- hr_above_baseline_results: dict[str, pandas.core.frame.DataFrame]¶
Dictionary with heart rate above baseline results.
Dict keys are the identifiers that are specified when computing results from
hr_datausingcompute_hr_above_baseline().
- hrv_results: dict[str, pandas.core.frame.DataFrame]¶
Dictionary with heart rate variability ensemble.
Dict keys are the identifiers that are specified when computing ensemble from
rpeak_datausingcompute_hrv_results().
- hrv_above_baseline_results: dict[str, pandas.core.frame.DataFrame]¶
Dictionary with heart rate variability above baseline results.
Dict keys are the identifiers that are specified when computing results from
rpeak_datausingcompute_hrv_above_baseline().
- hr_ensemble: dict[str, dict[str, pandas.core.frame.DataFrame]]¶
Dictionary with merged heart rate data for heart rate ensemble plot.
Dict keys are the identifiers that are specified when computing ensemble HR data from
hr_datausingcompute_hr_ensemble().See also
hr_ensemble_plot()heart rate ensemble plot
- saliva_plot_params: dict[str, Any]¶
Plot parameters for customizing the general saliva plot for a specific psychological protocol.
See also
saliva_plot()saliva plot
- hr_mean_plot_params: dict[str, Any]¶
Plot parameters for customizing the general HR mean plot for a specific psychological protocol.
See also
hr_mean_plot()HR mean plot
- hr_ensemble_plot_params: dict[str, Any]¶
Plot parameters for customizing the general HR ensemble plot for a specific psychological protocol.
See also
hr_ensemble_plot()HR ensemble plot
- to_file(file_path)[source]¶
Serialize
Protocolobject and export as file.This function converts the basic information of this object (
name,structure,test_times) to a JSON object and saves the serialized object to a JSON file.- Parameters
file_path (
Pathor str) – file path to export
- classmethod from_file(file_path)[source]¶
Load serialized
Protocolobject from file.- Parameters
file_path (
Pathor str) – file path to export- Returns
Protocolinstance- Return type
instance of
BaseProtocol
- add_saliva_data(saliva_data, saliva_type=None, sample_times=None, test_times=None, sample_times_absolute=False)[source]¶
Add saliva data collected during psychological protocol to
Protocolinstance.- Parameters
saliva_data (
SalivaRawDataFrameor dict) – saliva data (or dict of such) to be added to this protocol.saliva_type (str or list of str, optional) – saliva type (or list of such) of saliva data. Not needed if
saliva_datais a dictionary, then the saliva types are inferred from the dictionary keys.sample_times (list of int or dict, optional) – list of sample times in minutes. Sample times are either expected to be provided relative to the psychological test in the protocol (if present) or as absolute sample times. If passed as relative sample times (
sample_times_absolute'' is ``False), a sample collected directly before the test should, per convention, be denoted as \(t = -1\) while a sample collected directly after the test was collected at time point :math`t = 0`.test_times (list of int, optional) – list with start and end time of psychological test in minutes. Per convention, the start of the test should be at time point \(t = 0\).
test_timesis also used to compute the absolute sample timessample_times_absolute (bool, optional) –
Trueif sample times are provided as absolute time points orFalseif sample times are provided as relative time points to the psychological test. Default:False
- add_hr_data(hr_data, rpeak_data=None, study_part=None)[source]¶
Add time-series heart rate data collected during psychological protocol to
Protocolinstance.- Parameters
hr_data (
HeartRateSubjectDataDict) – dictionary with heart rate data of all subjects collected during the protocol.rpeak_data (
SubjectDataDict, optional) – dictionary with rpeak data of all subjects collected during the protocol. Needed if heart rate variability should be computed.study_part (str, optional) – string indicating to which study part data belongs to or
Noneif data has no individual study parts. Default:None
- compute_hr_results(result_id, study_part=None, resample_sec=True, normalize_to=False, select_phases=False, split_into_subphases=False, mean_per_subject=True, add_conditions=False, reindex=False, params=None)[source]¶
Compute heart rate data results from one study part.
The different processing steps can be enabled or disabled by setting the function parameters to
TrueorFalse, respectively. Parameters that are required for a specific processing step can be provided in theparamsdict. The dict key must match the name of the processing step.- Parameters
result_id (str) – Result ID, a descriptive name of the results that were computed. This ID will also be used as key to store the computed results in the
hr_resultsdictionary.study_part (str, optional) – study part the data which should be processed belongs to or
Noneif data has no individual study parts. Default:Noneresample_sec (bool, optional) –
Trueto apply resampling. Instantaneous heart rate data will then be resampled to 1 Hz. Default:Truenormalize_to (bool, optional) –
Trueto normalize heart rate data per subject. Data will then be the heart rate increase relative to the average heart rate in the phase. The name of the phase (or a dataframe containing heart rate data to normalize to) is specified in theparamsdictionary (key:normalize_to). Default:Falseselect_phases (bool, optional) –
Trueto only select specific phases for further processing,Falseto use all data fromstudy_part. The phases to be selected are specified in theparamsdictionary (key:select_phases). Default:Falsesplit_into_subphases (bool, optional) –
Trueto further split phases into subphases,Falseotherwise. The subphases are provided as dictionary (keys: subphase names, values: subphase durations in seconds) in theparamsdictionary (key:split_into_subphases). Default:Falsemean_per_subject (bool, optional) –
Trueto compute the mean heart rate per phase (and subphase, if present) for each subject and combine results into one dataframe. The resulting index level names of the dataframe can be provided as list in theparamsdictionary (key:mean_per_subject). By default, the index level names are [“subject”, “phase”]. Default:Trueadd_conditions (bool, optional) –
Trueto add subject conditions to dataframe data. Information on which subject belongs to which condition can be provided asSubjectConditionDataFrameorSubjectConditionDictin theparamsdictionary (key:add_conditions). Default:Falsereindex (bool, optional) –
Trueto reindex index levels of the resulting dataframe. Reindex index levels can be provided in theparamsdictionary as a dictionary with index levels as keys and index orders as values (key:reindex). Default:Falseparams (dict, optional) – dictionary with parameters provided to the different processing steps
- compute_hrv_results(result_id, study_part=None, select_phases=False, split_into_subphases=False, dict_levels=None, hrv_params=None, add_conditions=False, params=None)[source]¶
Compute heart rate variability ensemble from one study part.
The different processing steps can be enabled or disabled by setting the function parameters to
TrueorFalse, respectively. Parameters that are required for a specific processing step can be provided in theparamsdict. The dict key must match the name of the processing step.- Parameters
result_id (str) – Result ID, a descriptive name of the ensemble that were computed. This ID will also be used as key to store the computed ensemble in the
hrv_resultsdictionary.study_part (str, optional) – study part the data which should be processed belongs to or
Noneif data has no individual study parts. Default:Noneselect_phases (bool, optional) –
Trueto only select specific phases for further processing,Falseto use all data fromstudy_part. The phases to be selected are specified in theparamsdictionary (key:select_phases). Default:Falsesplit_into_subphases (bool, optional) –
Trueto further split phases into subphases,Falseotherwise. The subphases are provided as dictionary (keys: subphase names, values: subphase durations in seconds) in theparamsdictionary (key:split_into_subphases). Default:Falsedict_levels (list, optional) – list with names of dictionary levels which will also be the index level names of the resulting dataframe or
Noneto use default level names: [“subject”, “phase”] (ifsplit_into_subphasesisFalse) or [“subject”, “phase”, “subphase”] (ifsplit_into_subphasesisTrue).hrv_params (dict, optional) – dictionary with parameters to configure HRV processing or
Noneto use default parameter. Seehrv_process()for an overview on available parameters.add_conditions (bool, optional) –
Trueto add subject conditions to dataframe data. Information on which subject belongs to which condition can be provided asSubjectConditionDataFrameorSubjectConditionDictin theparamsdictionary (key:add_conditions). Default:Falseparams (dict, optional) – dictionary with parameters provided to the different processing steps.
- compute_hr_ensemble(ensemble_id, study_part=None, resample_sec=True, normalize_to=True, select_phases=False, cut_phases=True, merge_dict=True, add_conditions=False, params=None)[source]¶
Compute heart rate ensemble data from one study part.
Heart rate ensemble data are time-series data where data from all subjects within one phase have the same length and can thus be overlaid as mean ± standard error in a plot.
The different processing steps can be enabled or disabled by setting the function parameters to
TrueorFalse, respectively. Parameters that are required for a specific processing step can be provided in theparamsdict. The dict key must match the name of the processing step.- Parameters
ensemble_id (str) – ensemble identifier, a descriptive name of the ensemble data that were computed. This ID will also be used as key to store the computed ensemble data in the
hr_ensembledictionary.study_part (str, optional) – study part the data which should be processed belongs to or
Noneif data has no individual study parts. Default:Noneresample_sec (bool, optional) –
Trueto apply resampling. Instantaneous heart rate data will then be resampled to 1 Hz. Default:Truenormalize_to (bool, optional) –
Trueto normalize heart rate data per subject. Data will then be the heart rate increase relative to the average heart rate in the phase. The name of the phase (or a dataframe containing heart rate data to normalize to) is specified in theparamsdictionary (key:normalize_to). Default:Falseselect_phases (bool, optional) –
Trueto only select specific phases for further processing,Falseto use all data fromstudy_part. The phases to be selected are specified in theparamsdictionary (key:select_phases). Default:Falsecut_phases (bool, optional) –
Trueto cut time-series data to shortest duration of a subject in each phase,Falseotherwise. Default:Truemerge_dict (bool, optional) –
Trueto convertStudyDataDictintoMergedStudyDataDict, i.e., merge dictionary data from individual subjects into one dataframe for each phase. Default:Trueadd_conditions (bool, optional) –
Trueto add subject conditions to dataframe data. Information on which subject belongs to which condition can be provided asSubjectConditionDataFrameorSubjectConditionDictin theparamsdictionary (key:add_conditions). Default:Falseparams (dict, optional) – dictionary with parameters provided to the different processing steps
See also
hr_ensemble_plot()Heart rate ensemble plot
- compute_hr_above_baseline(result_id, baseline_phase, study_part=None, select_phases=False, split_into_subphases=False, add_conditions=False, params=None)[source]¶
Compute the relative amount of heart rate above a specified baseline.
The different processing steps can be enabled or disabled by setting the function parameters to
TrueorFalse, respectively. Parameters that are required for a specific processing step can be provided in theparamsdict. The dict key must match the name of the processing step.- Parameters
result_id (str) – Result ID, a descriptive name of the results that were computed. This ID will also be used as key to store the computed results in the
hr_above_baseline_resultsdictionary.baseline_phase (str) – string indicating the name of the phase that should be used as baseline for computing the relative amount above the baseline.
study_part (str, optional) – study part the data which should be processed belongs to or
Noneif data has no individual study parts. Default:Noneselect_phases (bool, optional) –
Trueto only select specific phases for further processing,Falseto use all data fromstudy_part. The phases to be selected are specified in theparamsdictionary (key:select_phases). Default:Falsesplit_into_subphases (bool, optional) –
Trueto further split phases into subphases,Falseotherwise. The subphases are provided as dictionary (keys: subphase names, values: subphase durations in seconds) in theparamsdictionary (key:split_into_subphases). Default:Falseadd_conditions (bool, optional) –
Trueto add subject conditions to dataframe data. Information on which subject belongs to which condition can be provided asSubjectConditionDataFrameorSubjectConditionDictin theparamsdictionary (key:add_conditions). Default:Falseparams (dict, optional) – dictionary with parameters provided to the different processing steps
- compute_hrv_above_baseline(result_id, baseline_phase, continuous_hrv_data, select_phases=False, split_into_subphases=False, add_conditions=False, hrv_columns=None, params=None)[source]¶
Compute the relative amount of heart rate variability above a specified baseline.
The different processing steps can be enabled or disabled by setting the function parameters to
TrueorFalse, respectively. Parameters that are required for a specific processing step can be provided in theparamsdict. The dict key must match the name of the processing step.- Parameters
result_id (str) – Result ID, a descriptive name of the results that were computed. This ID will also be used as key to store the computed results in the
hrv_above_baseline_resultsdictionary.baseline_phase (str) – string indicating the name of the phase that should be used as baseline for computing the relative amount above the baseline.
continuous_hrv_data (
SubjectDataDict) – dictionary with continuous HRV of all subjects collected during the protocol.select_phases (bool, optional) –
Trueto only select specific phases for further processing,Falseto use all data fromstudy_part. The phases to be selected are specified in theparamsdictionary (key:select_phases). Default:Falsesplit_into_subphases (bool, optional) –
Trueto further split phases into subphases,Falseotherwise. The subphases are provided as dictionary (keys: subphase names, values: subphase durations in seconds) in theparamsdictionary (key:split_into_subphases). Default:Falseadd_conditions (bool, optional) –
Trueto add subject conditions to dataframe data. Information on which subject belongs to which condition can be provided asSubjectConditionDataFrameorSubjectConditionDictin theparamsdictionary (key:add_conditions). Default:Falsehrv_columns (list of str) – selected column names for computing or
Noneto compute relative amount above baseline for all columns. Default:Noneparams (dict, optional) – dictionary with parameters provided to the different processing steps
- get_hr_results(result_id)[source]¶
Return heart rate processing results.
Heart rate results can be computed by calling
compute_hr_results().- Parameters
result_id (str) – identifier of result parameters specified when computing results via
compute_hr_results()- Returns
heart rate processing results
- Return type
- add_hrv_results(result_id, results)[source]¶
Add existing heart rate variability processing ensemble.
- export_hr_above_baseline_results(base_path, prefix=None)[source]¶
Export all heart rate above baseline results to csv files.
- export_hr_ensemble(base_path, prefix=None)[source]¶
Export all heart rate ensemble data to Excel files.
- export_hrv_results(base_path, prefix=None)[source]¶
Export all heart rate variability results to csv files.
- export_hrv_above_baseline_results(base_path, prefix=None)[source]¶
Export all heart rate variability above baseline results to csv files.
- get_hrv_results(result_id)[source]¶
Return heart rate variability processing ensemble.
Heart rate variability ensemble can be computed by calling
compute_hrv_results().- Parameters
result_id (str) – identifier of result parameters specified when computing ensemble via
compute_hrv_results()- Returns
heart rate variability processing ensemble
- Return type
- add_hr_ensemble(ensemble_id, ensemble)[source]¶
Add existing heart rate ensemble data.
- Parameters
ensemble_id (str) – identifier of ensemble parameters used to store dictionary in
hr_ensembledictionaryensemble (
MergedStudyDataDict) – ensemble data asMergedStudyDataDict
- get_hr_ensemble(ensemble_id)[source]¶
Return heart rate ensemble data.
- Parameters
ensemble_id (str) – identifier of ensemble parameters specified when computing ensemble parameters via
compute_hr_ensemble()- Returns
heart rate ensemble ensemble
- Return type
- saliva_plot(saliva_type='cortisol', **kwargs)[source]¶
Plot saliva data during psychological protocol as mean ± standard error.
- Parameters
saliva_type ({"cortisol", "amylase", "il6"}, optional) – saliva type to be plotted. If a dict is passed and
saliva_typeisNonethe saliva types are inferred from dict keys. Default:cortisol**kwargs – additional parameters to be passed to
saliva_plot().
- Returns
fig (
matplotlib.figure.Figure) – figure objectax (
matplotlib.axes.Axes) – axes object
- Return type
tuple[matplotlib.figure.Figure, matplotlib.axes._axes.Axes] | None
See also
saliva_plot()Plot saliva data during a psychological protocol
- static saliva_plot_combine_legend(fig, ax, saliva_types, **kwargs)[source]¶
Combine multiple legends of
saliva_plot()into one legend outside plot.If data from multiple saliva types are combined into one plot (e.g., by calling
saliva_plot()on the same plot twice) then two separate legend are created. This function can be used to combine the two legends into one.- Parameters
fig (
Figure) – figure objectax (
Axes) – axes objectsaliva_types (list) – list of saliva types in plot
**kwargs – additional arguments to customize plot that are passed to
saliva_plot_combine_legend()
- saliva_feature_boxplot(x, saliva_type, feature=None, stats_kwargs=None, **kwargs)[source]¶
Draw a boxplot with significance brackets, specifically designed for saliva features.
This is a wrapper of
saliva_feature_boxplot()that directly uses the saliva data added to thisProtocolinstance.- Parameters
x (str) – column of x axis in
datasaliva_type (str) – type of saliva data to plot
feature (str, optional) – name of feature to plot or
Nonestats_kwargs (dict, optional) – dictionary with arguments for significance brackets
**kwargs – additional arguments that are passed to
saliva_feature_boxplot()
- Returns
fig (
matplotlib.figure.Figure) – figure objectax (
matplotlib.axes.Axes) – axes object
- Return type
See also
saliva_feature_boxplot()plot saliva features as boxplot without
Protocolinstancefeature_boxplot()plot features as boxplot
- static saliva_multi_feature_boxplot(data, saliva_type, features, hue=None, stats_kwargs=None, **kwargs)[source]¶
Draw multiple features as boxplots with significance brackets, specifically designed for saliva features.
This is a wrapper of
saliva_multi_feature_boxplot().- Parameters
data (
SalivaFeatureDataFrame) – saliva feature dataframesaliva_type (str) – type of saliva data to plot
hue (str, optional) – column name of grouping variable. Default:
Nonefeatures (list of str or dict of str) – features to plot. If
featuresis a list, each entry must correspond to one feature category in the index level specified bygroup. A separate subplot will be created for each feature. If similar features (i.e., different slope or AUC parameters) should be combined into one subplot,featurescan be provided as dictionary. Then, the dict keys specify the feature category (a separate subplot will be created for each category) and the dict values specify the feature (or list of features) that are combined into the subplots.stats_kwargs (dict, optional) – nested dictionary with arguments for significance brackets. See
feature_boxplot()for further information
- Returns
fig (
matplotlib.figure.Figure) – figure objectaxs (list of
matplotlib.axes.Axes) – list of subplot axes objects
- Return type
tuple[matplotlib.figure.Figure, collections.abc.Iterable[matplotlib.axes._axes.Axes]]
See also
saliva_multi_feature_boxplot()plot multiple saliva features as boxplots without instantiating a
ProtocolinstanceStatsPipeline()class to create statistical analysis pipelines and get parameter for plotting significance brackets
- hr_ensemble_plot(ensemble_id, subphases=None, **kwargs)[source]¶
Draw heart rate ensemble plot.
- Parameters
ensemble_id (str) – identifier of the ensemble data to be plotted. Ensemble data needs to be computed using
compute_hr_ensemble()firstsubphases (dict, optional) – dictionary with phases (keys) and subphases (values - dict with subphase names and subphase durations) or
Noneif no subphases are present. Default:None**kwargs (dict, optional) –
additional parameters to be passed to
hr_ensemble_plot()for plot configuration, such as:ax: pre-existing axes for the plot. Otherwise, a new figure and axes object is created and returned.palette: color palette to plot data from different phases. Ifpaletteis a str then it is assumed to be the name of afau_colorspalette (fau_colors.cmaps._fields).figsize: tuple specifying figure dimensionsensemble_alpha: transparency value for ensemble plot errorband (around mean). Default: 0.3background_alpha: transparency value for background spans (if subphases are present). Default: 0.2linestyle: list of line styles for ensemble plots. Must match the number of phases to plotphase_text: string pattern to customize phase name shown in legend with placeholder for subphase name. Default: “{}”
To style axes:
is_relative: boolean indicating whether heart rate data is relative (in % relative to baseline) or absolute (in bpm). Default:Truexlabel: label of x axis. Default: “\(Time [s]\)”xaxis_minor_tick_locator: locator object to style x axis minor ticks. Default: 60 secylabel: label of y axis. Default: “\(\Delta HR [\%]\)”ylims: y axis limits. Default:Noneto automatically infer limits
To style the annotations at the end of each phase:
end_phase_text: string pattern to customize text at the end of phase with placeholder for phase name. Default: “{}”end_phase_line_color: line color of vertical lines used to indicate end of phase. Default: “#e0e0e0”end_phase_line_width: line width of vertical lines used to indicate end of phase. Default: 2.0
To style legend:
legend_loc: location of legend. Default: “lower right”legend_bbox_to_anchor: box that is used to position the legend in conjunction withlegend_loc
- Returns
fig (
matplotlib.figure.Figure) – figure objectax (
matplotlib.axes.Axes) – axes object
- Return type
See also
compute_hr_ensemble()compute heart rate ensemble data
hr_ensemble_plot()Heart rate ensemble plot
- hr_mean_plot(result_id, **kwargs)[source]¶
Plot course of heart rate as mean ± standard error over phases (and subphases) of a psychological protocol.
The correct plot is automatically inferred from the provided data:
only
phaseindex level: plot phases over x axisphaseandsubphaseindex levels: plot subphases over x axis, highlight phases as vertical spansadditionally:
conditionlevel: plot data of different conditions individually (corresponds tohueparameter inbiopsykit.plotting.lineplot())
- Parameters
result_id (str) – identifier of the heart rate result data to be plotted
**kwargs –
additional parameters to be passed to
hr_mean_plot()for plot configuration, such as:ax: pre-existing axes for the plot. Otherwise, a new figure and axes object is created and returned.figsize: tuple specifying figure dimensionspalette: color palette to plot data from different conditions. Ifpaletteis a str then it is assumed to be the name of afau_colorspalette (fau_colors.cmaps._fields).is_relative: boolean indicating whether heart rate data is relative (in % relative to baseline) or absolute (in bpm). Default:Falseorder: list specifying the order of categorical values (i.e., conditions) along the x axis.x_offset: offset value to move different groups along the x axis for better visualization. Default: 0.05xlabel: label of x axis. Default: “Subphases” (if subphases are present) or “Phases” (if only phases are present)ylabel: label of y axis. Default: “\(\Delta HR [%]\)”ylims: list to manually specify y axis limits, float to specify y axis margin (seemargin()for further information), orNoneto automatically infer y axis limitsmarker: string or list of strings to specify marker style. Ifmarkeris a string, then marker of each line will have the same style. Ifmarkeris a list, then marker of each line will have a different style.linestyle: string or list of strings to specify line style. Iflinestyleis a string, then each line will have the same style. Iflinestyleis a list, then each line will have a different style.
- Returns
fig (
matplotlib.figure.Figure) – figure objectax (
matplotlib.axes.Axes) – axes object
- Return type
See also
hr_mean_plot()Plot heart rate data as lineplot with mean and standard error
lineplot()Plot generic data as lineplot with mean and standard error
- class biopsykit.protocols.CftFeatureExtraction(*, start_baseline_sec=0, duration_baseline_sec=0, duration_cft_sec=120, duration_recovery_sec=0, group_level, error_handling='warn')[source]¶
Bases:
AlgorithmExtract Cold Face Test features from heartbeat-level heart-rate data.
- Parameters
- output_: DataFrame¶
- group_level: str_t¶
Submodules¶
- biopsykit.protocols.base module
BaseProtocolBaseProtocol.nameBaseProtocol.structureBaseProtocol.saliva_typesBaseProtocol.test_timesBaseProtocol.sample_timesBaseProtocol.saliva_dataBaseProtocol.hr_dataBaseProtocol.rpeak_dataBaseProtocol.hr_resultsBaseProtocol.hr_above_baseline_resultsBaseProtocol.hrv_resultsBaseProtocol.hrv_above_baseline_resultsBaseProtocol.hr_ensembleBaseProtocol.saliva_plot_paramsBaseProtocol.hr_mean_plot_paramsBaseProtocol.hr_ensemble_plot_paramsBaseProtocol.to_file()BaseProtocol.from_file()BaseProtocol.add_saliva_data()BaseProtocol.add_hr_data()BaseProtocol.compute_hr_results()BaseProtocol.compute_hrv_results()BaseProtocol.compute_hr_ensemble()BaseProtocol.compute_hr_above_baseline()BaseProtocol.compute_hrv_above_baseline()BaseProtocol.add_hr_results()BaseProtocol.get_hr_results()BaseProtocol.add_hrv_results()BaseProtocol.export_hr_results()BaseProtocol.export_hr_above_baseline_results()BaseProtocol.export_hr_ensemble()BaseProtocol.export_hrv_results()BaseProtocol.export_hrv_above_baseline_results()BaseProtocol.get_hrv_results()BaseProtocol.add_hr_ensemble()BaseProtocol.get_hr_ensemble()BaseProtocol.saliva_plot()BaseProtocol.saliva_plot_combine_legend()BaseProtocol.saliva_feature_boxplot()BaseProtocol.saliva_multi_feature_boxplot()BaseProtocol.hr_ensemble_plot()BaseProtocol.hr_mean_plot()
- biopsykit.protocols.car module
CARCAR.car_plot_paramsCAR.car_saliva_plot()CAR.nameCAR.structureCAR.saliva_typesCAR.test_timesCAR.sample_timesCAR.saliva_dataCAR.hr_dataCAR.rpeak_dataCAR.hr_resultsCAR.hr_above_baseline_resultsCAR.hrv_resultsCAR.hrv_above_baseline_resultsCAR.hr_ensembleCAR.saliva_plot_paramsCAR.hr_mean_plot_paramsCAR.hr_ensemble_plot_params
- biopsykit.protocols.cft module
CFTCFT.cft_startCFT.cft_durationCFT.cft_plot_paramsCFT.compute_cft_parameter()CFT.baseline_hr()CFT.extract_cft_interval()CFT.onset()CFT.peak_bradycardia()CFT.mean_bradycardia()CFT.poly_fit()CFT.cft_plot()CFT.nameCFT.structureCFT.saliva_typesCFT.test_timesCFT.sample_timesCFT.saliva_dataCFT.hr_dataCFT.rpeak_dataCFT.hr_resultsCFT.hr_above_baseline_resultsCFT.hrv_resultsCFT.hrv_above_baseline_resultsCFT.hr_ensembleCFT.saliva_plot_paramsCFT.hr_mean_plot_paramsCFT.hr_ensemble_plot_params
CftFeatureExtractionCftFeatureExtraction.cft_parameterCftFeatureExtraction.output_CftFeatureExtraction.start_baseline_secCftFeatureExtraction.duration_baseline_secCftFeatureExtraction.duration_cft_secCftFeatureExtraction.duration_recovery_secCftFeatureExtraction.group_levelCftFeatureExtraction.error_handlingCftFeatureExtraction.extract()
- biopsykit.protocols.mist module
- biopsykit.protocols.plotting module
- biopsykit.protocols.tsst module