PhotometryExperiment
This class is used to process and slice photometry experiments, with support for both dual and single channel experiments.
The two main APIs:
-
preprocess_signal()applies a low-pass filter, fits a reference trace, and applies correction methods, with optionally functionality to detect and correct movement artifacts. -
extract_trial_data()uses the events timestamps in the.eventsattribute to slice, align, and pass down trial-relative event timesteps to a 2DPhotometryDataobject.
Example Usage
Dual channel preprocessing
exp.preprocess_signal(
# lowpass butterworth params
cutoff_frequency=3,
order=4,
# correction method and isosbestic fit params
correction_method='dF/F',
fit_using='IRLS',
maxiter=1000,
c=2,
)
Single channel preprocessing
# import artifact handlers
from pyFiberPhotometry.analysis.artifact import ODS_Detector, Spline_Corrector
# instantiate artifact detector and corrector
detector = ODS_Detector(
score_threshold=5,
jump_score_threshold=10,
expand_sec=(0.5, 2),
buffer_sec=1.5,
n_chunks=20,
)
corrector = Spline_Corrector(
anchor_sec=(0.2, 0.2),
correct_spikes=True,
correct_jumps=True,
)
exp.preprocess_signal(
cutoff_frequency=3,
order=4,
correction_method='dB/B',
fit_using='IRLS',
maxiter=1000,
c=2,
# pass in artifact handlers
artifact_detector=detector,
artifact_corrector=corrector,
)
Trial extraction
exp.extract_trial_data(
# what event should we consider the "start" of a trial
align_to='event',
# what events do we want to center on
center_on=['lever1', 'lever2'],
# how long in seconds should our trials be relative to "center_on"
trial_bounds=(-10, 10),
# expected range of our events relative to "align_to"
event_tolerences={
'lever1':(2, 10),
'lever2':(2, 10),
'loud_noise':(2, 12),
},
# which trial-wise normalization should be preformed
trial_normalization='none',
# if multiple of the same event are within tolerences which should be picked
event_conflict_logic='first',
# should an error be thrown if multiple "center_on" event are present in the same trial
check_overlap=True,
)
PhotometryExperiment(raw_signal, raw_isosbestic, time, events={}, metadata={}, frequency=None)
Handle processing of raw photometry data.
Initialize a photometry experiment.
Parameters:
-
raw_signal(ndarray) –Raw signal channel values.
-
raw_isosbestic(ndarray) –Raw isosbestic channel values. If
None, experiment is assumed to be single channel. -
time(ndarray) –Time points corresponding to the raw signals.
-
events(dict, default:{}) –Mapping of event labels to timestamp arrays. Defaults to
{}. -
metadata(dict, default:{}) –Additional experiment metadata. Defaults to
{}. -
frequency(float | None, default:None) –Sampling frequency in Hz. If
None(default), it is estimated fromraw_signalandtime.
Source code in pyFiberPhotometry/core/PhotometryExperiment.py
load_TDT(data_folder, box, event_labels, signal_label, isosbestic_label, downsample=10)
classmethod
Load photometry data from TDT format.
Parameters:
-
data_folder(str) –Path to the TDT block folder.
-
box(str) –TDT box identifier used in stream and epoc labels.
-
event_labels(list[str]) –Event labels to extract from epocs.
-
signal_label(str) –Base label for the signal channel.
-
isosbestic_label(str) –Base label for the isosbestic channel.
-
downsample(int, default:10) –Downsampling factor for the raw streams (mean pooling). Defaults to
10.
Returns:
-
PhotometryExperiment(PhotometryExperiment) –Loaded experiment instance.
Source code in pyFiberPhotometry/core/PhotometryExperiment.py
run_pipeline()
Run the full processing pipeline for one experiment.
This method is intended to be implemented by child classes.
Returns:
-
None–None
preprocess_signal(cutoff_frequency=3.0, order=4, signal_normalization='none', correction_method='dF/F', fit_using='IRLS', maxiter=1000, c=3, artifact_detector=None, artifact_corrector=None)
Low-pass filter and preprocess the signal using isosbestic fitting.
Parameters:
-
cutoff_frequency(float, default:3.0) –Low-pass cutoff frequency in Hz. Values between 1 and 5 recommended. Defaults to
3.0. -
order(int, default:4) –Butterworth filter order. Values >3 are recommended. Defaults to
4. -
correction_method(Literal['dF/F', 'dF', 'dB/B', 'dB', 'none'] | Callable, default:'dF/F') –Reference trace correction method:
*'dF/F'and'dB/B= (signal - fitted reference) / fitted reference *'dF'and'dB'= (signal - fitted reference) For dual channel experiments the reference is the isosbestic, for single channel it is a fit photobleaching curve. Use'dF/F'or'dF'for dual channel and'dB/B'or'dB'for single channel. A custom function that takes in the positional arguementssignal,fitted_referenceand returns a 1Dnp.ndarraycan also be passed. Defaults to'dF/F'. -
signal_normalization(Literal['zscore', 'nullZ', 'none'] | Callable, default:'none') –Method for whole-signal normalization;
'none'for dF/F and'zscore'for dF is recommended. A custom function that takes in the positional arguementssignaland returns a 1Dnp.ndarraycan also be passed. Defaults to'none'. -
fit_using(Literal['OLS', 'IRLS', 'IRLS_no_intercept', 'OLS_no_intercept'] | Callable, default:'IRLS') –Model used to fit isosbestic to experimental signal. IRLS methods recommended. Use a no intercept type model if large global change is present in the experimental signal. A custom function that takes in the positional arguements
signal,isosbesticand returns a 1Dnp.ndarrayand a sequence of params can also be passed. Note custom functions will only apply to isosbestic fits (i.e. dual channel experiments). Defaults to'IRLS'. -
maxiter(int, default:1000) –Maximum iterations of the IRLS isosbestic fit. Defaults to
1000. -
c(float | None, default:3) –Constant for IRLS fits; smaller values mean more agressive downweighting.
1.4 <= c <= 3is recommended unless there is large global drift in the experimental signal, in which case large values (>5) are better. Defaults to3. -
artifact_detector(ArtifactDetector | None, default:None) –Detector object with method
.detect(signal, reference, time)used to detect artifacts. IfNone, detection is skipped. Defaults toNone. -
artifact_corrector(ArtifactCorrector | None, default:None) –Corrector object with method
.correct(signal, time, artifacts)used to correct artifacts. IfNone, correction is skipped. Defaults toNone.
Returns:
-
None–None
Raises:
-
ValueError–- If
correction_methodis incompatible withself.channel_mode - If
artifact_correctorspecified but notartifact_detector
- If
Source code in pyFiberPhotometry/core/PhotometryExperiment.py
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 | |
extract_trial_data(align_to, center_on, trial_bounds, baseline_bounds=None, event_tolerences={}, trial_normalization='none', check_overlap=True, time_error_threshold=0.1, window_alignment='nearest', invalid_window_policy='drop', event_conflict_logic='first')
Build trial-wise windows, normalize, and store trial data.
Parameters:
-
align_to(str) –Event label used to align and identify trial, should be one per trial.
-
center_on(list[str]) –Event labels to center trial windows on. Events should be mutually exclusive (i.e. lever press choice). If no
center_onevents are present within an identified trial,align_towill be centered on. -
trial_bounds(tuple[float, float]) –Trial window bounds relative to
center_onevents. -
baseline_bounds(tuple[float, float] | None, default:None) –Baseline window bounds relative to
align_toevent used for per-trial normalizations. Defaults toNone. -
event_tolerences(dict[str, tuple[float, float]], default:{}) –Time tolerances for event annotation, relative to
align_to. Defaults to{}. -
trial_normalization(Literal['zscore', 'zero', 'mad', 'amp', 'none'] | Callable, default:'none') –Normalization method for trial signals based on baselines. A custom function that takes in the positional arguements
trial_signals,baseline_signalsand returns a 2Dnp.ndarrayof shape (n_trials, n_times) can also be passed. Defaults to'none'. -
check_overlap(bool, default:True) –Whether to throw an error when multiple
center_onevents are found in the same trial. Defaults toTrue. -
time_error_threshold(float, default:0.1) –Maximum allowed mean timing error. Defaults to
0.1. -
window_alignment(Literal['nearest', 'interp'], default:'nearest') –Stategy for aligning trial times. In
'nearest'mode, events times are rounded to the nearest sampling times, giving a maximum event alignment error of +/- 0.5/frequency. In'interp'mode, signals are linearly interpolated to an exact event-centered time grid, removing event alignment error but introduction signal interpolation error. Use'nearest'if event times are already locked to time sampling points. -
invalid_window_policy(Literal['drop', 'error'], default:'drop') –Policy for handling trials whose windows extend outside the signal bounds.
'drop'drops the invalid windows while'error'raises an error if any invalid windows are present. -
event_conflict_logic(Literal['first', 'last', 'mean'], default:'first') –Logic for choosing center-on event timestamps if multiple of the same event are present. Defaults to
'first'.
Returns:
-
None–None
Raises:
-
ValueError–If
baseline_boundsisNoneandtrial_normalizationrequires baselines.
Source code in pyFiberPhotometry/core/PhotometryExperiment.py
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 | |
low_frequency_pass_butter(signal, sample_frequency, cutoff_frequency=30.0, order=4, axis=0)
Apply a low-pass Butterworth filter to a signal.
Parameters:
-
signal(ndarray) –Input signal array.
-
sample_frequency(float) –Sampling frequency in Hz.
-
cutoff_frequency(float, default:30.0) –Low-pass cutoff frequency in Hz. Defaults to
30.0. -
order(int, default:4) –Butterworth filter order. Defaults to
4. -
axis(int, default:0) –Axis of the array to perform a low-pass on. Defaults to
0.
Returns:
-
ndarray–np.ndarray: Filtered signal.
Source code in pyFiberPhotometry/core/PhotometryExperiment.py
fit_isosbestic_to_signal(signal, isosbestic, fit_using='IRLS', maxiter=1000, c=None)
Fit the isosbestic channel to the signal.
Parameters:
-
signal(ndarray) –Filtered signal trace.
-
isosbestic(ndarray) –Filtered isosbestic trace.
-
fit_using(Literal['OLS', 'IRLS', 'IRLS_no_intercept', 'OLS_no_intercept'] | Callable, default:'IRLS') –Model used to fit isosbestic. Defaults to
'IRLS'. -
maxiter(int, default:1000) –Maximum iterations of IRLS isosbestic fit. Defaults to
1000. -
c(float | None, default:None) –Constant for IRLS fits; smaller values mean more agressive downweighting.
1.4 <= c <= 3is recommended. Defaults toNone.
Returns:
-
tuple[ndarray, float, Any]–tuple[np.ndarray, float, Any]: Fitted isosbestic, R-squared value, and fit coefficients.
Source code in pyFiberPhotometry/core/PhotometryExperiment.py
fit_photobleaching_curve(signal, window_dur=5)
Fit a curve with a negative bi-exponential photobleaching model. Uses a soft_l1 least squares to fit to the sliding-window median downsampled signal.
Parameters:
-
signal(ndarray) –Signal array to fit the photobleaching curve to.
-
window_dur(float, default:5) –Length of the window in seconds used for sliding-window median downsampling. Defaults to
5.
Returns:
-
ndarray–tuple[np.ndarray, list[float]]: Fitted curve and fitted parameter
-
float–values.
Source code in pyFiberPhotometry/core/PhotometryExperiment.py
median_centered_abs_max_check(trial_signal, threshold=0.075)
Check whether a trial signal should be flagged as poor quality
Tests a threshold for minimum MAD (robust Z-score). Threshold needs to be tuned for specific experiments. Generally not recommended.
Parameters:
-
trial_signal(ndarray) –Trial-by-time signal array.
-
threshold(float, default:0.075) –Mean absolute-max threshold applied after median centering. Defaults to
0.075.
Returns:
-
is_poor_signal(bool) –Trueif the signal is classified as poor quality.
Source code in pyFiberPhotometry/core/PhotometryExperiment.py
dashboard(save=None, downsample=20)
Plot a quick dashboard for the experiment.
Plots the raw, fitted, and, if .preprocess_signal() has been run,
processed signal, isosbestic trace, and the fitted photobleaching curve
if available.
Parameters:
-
save(str | None, default:None) –Path to save the figure. If
None, the figure is not saved. Defaults toNone. -
downsample(int | optional, default:20) –Downsample factor for signals before plotting. Defaults to 20.
Returns:
-
None–None