PhotometryPipeline
A highly flexible class for bulk processing photometry data. Supports custom operations and subclasses of PhotometryData and PhotometryExperiment
Example Usage
This example is for an risky decision making task in rats stored in the TDT format with multiple experiments per TDT folder.
Setup
from pyFiberPhotometry import PhotometryExperiment, PhotometryData, PhotometryPipeline, TDTLoader
# --- loader params ---
shared_loader_kwargs = dict(
event_labels = ['Lrg', 'Sml', 'Hsl', 'Zap'],
signal_label = '_465',
isosbestic_label = '_405',
downsample = 10,
annotation_file = 'annotations.json',
annotation_handler = 'json',
)
loader_kwargs = [
dict(box='A', **shared_loader_kwargs),
dict(box='B', **shared_loader_kwargs)
]
# --- preprocess params ---
preprocess_kwargs = dict(
cutoff_frequency = 3.0,
order = 4,
correction_method = 'dF/F',
signal_normalization = 'none',
fit_using = 'OLS',
maxiter = 1000,
c = 3,
artifact_detector = None,
artifact_corrector = None,
)
# --- trial extraction params ---
trial_extraction_kwargs = dict(
align_to = 'Hsl',
center_on = ['Lrg', 'Sml'],
trial_bounds = (-23.0, 5.0),
baseline_bounds = (-5, -1),
event_tolerences = {'Lrg' : (5, 18), 'Sml' : (5, 18), 'Zap': (4.5, 18.5)},
trial_normalization = 'zero',
check_overlap = False,
time_error_threshold = 0.01,
event_conflict_logic = 'first',
)
# --- uid builder ---
def RDT_id_builder(exp: PhotometryExperiment) -> str:
id = (
f"{exp.metadata.get('rat', 'UnknownRat')}_"
f"{exp.metadata.get('current', 'UnknownCurrent')}uA_"
f"Box{exp.metadata.get('box', 'UnknownBox')}_"
f"{exp.metadata.get('stripped_date', 'UnknownDate')}_"
f"{exp.metadata.get('source', 'UnknownSource').split('-')[-1]}"
)
return id
# --- post loading operation ---
# removes last dummy trial
def RDT_post_load(exp: PhotometryExperiment) -> None:
if 'Hsl' in exp.events:
exp.events['Hsl'] = exp.events['Hsl'][:-1]
Run
pipeline = PhotometryPipeline(
data_directory='database/NAc_Young_RDT_Photometry',
target_type='folder',
loader_cls=TDTLoader,
experiment_cls=PhotometryExperiment,
data_cls=PhotometryData,
recursive=False,
pattern='Emely*'
)
result = pipeline.run(
output_dir='/pipeline_RDT',
loader_kwargs=loader_kwargs,
preprocess_kwargs=preprocess_kwargs,
trial_extraction_kwargs=trial_extraction_kwargs,
log_file='pipeline.log',
passdown_metadata=['rat', 'current', 'box', 'source'],
id_builder=RDT_id_builder,
post_load_operation=RDT_post_load,
)
PhotometryPipeline(data_directory, target_type, loader_cls, experiment_cls=PhotometryExperiment, data_cls=PhotometryData, recursive=False, pattern=None)
Initialize a generic directory-level photometry pipeline.
Parameters:
-
data_directory(str | Path) –Root directory containing candidate input files or folders to process.
-
target_type(Literal['file', 'folder']) –File type to treat as a pipeline input. Must be either
'file'or'folder'. -
loader_cls(type[PhotometryLoader]) –Loader class to use.
-
experiment_cls(type[PhotometryExperiment], default:PhotometryExperiment) –Experiment class to use.
-
data_cls(type[PhotometryData], default:PhotometryData) –Trial-data class to use.
-
recursive(bool, default:False) –Whether to recursively search under
data_directorywhen discovering inputs. -
pattern(str | None, default:None) –Optional glob pattern used to filter discovered inputs. If
None, all children underdata_directoryare considered.
Raises:
-
ValueError–If
data_directorydoes not exist or is not a directory.
Source code in pyFiberPhotometry/core/PhotometryPipeline.py
discover_inputs()
Discover candidate inputs under self.data_directory.
Source code in pyFiberPhotometry/core/PhotometryPipeline.py
run(loader_kwargs, preprocess_kwargs, trial_extraction_kwargs, output_dir=None, log_file=None, trial_output_file='trials.h5ad', low_memory_mode=False, passdown_metadata=['source'], id_builder=None, post_load_operation=None, post_preprocess_operation=None, post_trial_extraction_operation=None)
Run the batch processing pipeline over all discovered inputs.
For each discovered input, the pipeline constructs a loader, loads an
experiment, preprocesses the continuous signal, extracts trial-wise
data, optionally applies custom hook operations, passes selected
metadata down into trial_data.obs, and accumulates the resulting
trial-data objects in memory or on disk.
Parameters:
-
output_dir(str | Path | None, default:None) –Directory where outputs should be written. If
None, nothing is saved. -
loader_kwargs(dict[str, Any] | list[dict[str, Any]]) –Keyword arguments passed to
loader_clsfor each job, excluding the discovered input path that the pipeline supplies positionally. Use list of dictionaries creates to create multiple jobs per single input, useful for file formats that contain multiple experiment's data within a single folder/file. -
preprocess_kwargs(dict[str, Any]) –Keyword arguments passed to
PhotometryExperiment.preprocess_signal(). -
trial_extraction_kwargs(dict[str, Any]) –Keyword arguments passed to
PhotometryExperiment.extract_trial_data(). -
log_file(str | None, default:None) –Optional path to a log file. If provided, logging is configured to write to that file. Default
None. -
trial_output_file(str | None, default:'trials.h5ad') –Name of the output
.h5adfile written underoutput_dirfor accumulated trial data. -
low_memory_mode(bool, default:False) –If
True, accumulate trial data directly on disk instead of keeping the full combined object in memory. -
passdown_metadata(list[str] | None, default:['source']) –Metadata keys from
exp.metadatato copy intoexp.trial_data.obsfor each processed experiment. IfNone, no metadata columns are added. -
id_builder(Callable[[type[PhotometryExperiment]], str] | None, default:None) –Optional callable used to construct and assign an experiment ID after loading. Automatically passes the experiment ID to
trial_data.obs. -
post_load_operation(Callable[[type[PhotometryExperiment]], None] | None, default:None) –Optional callable run immediately after an experiment is loaded.
-
post_preprocess_operation(Callable[[type[PhotometryExperiment]], None] | None, default:None) –Optional callable run immediately after preprocessing completes.
-
post_trial_extraction_operation(Callable[[type[PhotometryExperiment]], None] | None, default:None) –Optional callable run immediately after trial extraction completes.
Returns:
-
type[PhotometryData]–type[PhotometryData]: The trial-data object containing all extracted trials.
Raises:
-
TypeError–If provided kwargs do not match the accepted signatures of the loader, preprocessing, or trial-extraction methods.
-
ValueError–If the output configuration is invalid or if no inputs are discovered.
Source code in pyFiberPhotometry/core/PhotometryPipeline.py
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 308 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 | |