Managing Defaults#
This page documents massphoto.defaults, backed by
massphoto.defaults_store.DefaultsStore, which provides centralized,
reproducible configuration for processing pipelines, detection filters, and calibration.
User Guide: Analysis Configuration#
massphoto.defaults allows setting parameters once and having them automatically
injected across the analysis pipeline.
Common Configuration Parameters#
Key |
Type |
Default |
Description / Physical Context |
|---|---|---|---|
|
|
|
Temporal half-window (frames) for ratiometric background suppression. |
|
|
|
Square thumbnail size (pixels) used for PSF cross-correlation and fitting. |
|
|
(see below) |
Interferometric PSF parameters ( |
|
|
|
|
|
|
|
Detection thresholds: |
|
|
|
Number of frames per chunk for parallel Dask execution. |
Default PSF parameters on import:
{
"psf_params": {
"a12": -6.3337259134,
"w": 2.1370299329,
"s": 5.0425755943,
"r_mask": 1.5 * 2.5e-3,
"r_aperture": 8.52e-3,
},
"psf_fun": None,
"psf_size": 11,
"psf_cache_divider": 128,
"psf_cache_interpolate": True,
"mass_calibration": None,
}
Setting and Querying Defaults#
Use set() and get()
to inspect and modify parameters. Keys fall into two categories:
Global keys apply across every pipeline stage that accepts that parameter:
import massphoto as mp
# Set calibration and averaging window globally
mp.defaults.set("mass_calibration", (-5.2, 31000.0))
mp.defaults.set("navg", 15)
# Query current value
current_navg = mp.defaults.get("navg")
Function-specific keys use the <function_name>.<parameter> format to target a specific stage
without affecting others. Function-specific keys always take precedence over global keys.
For example, to configure detection thresholds for event_correlation_step():
# Set detection thresholds: [step_correlation, spatial_PSF_correlation, contrast]
mp.defaults.set("event_correlation_step.thresholds", [0.55, 0.45, 0.0008])
# Query current thresholds
thresholds = mp.defaults.get("event_correlation_step.thresholds")
Similarly, execution chunks for parallel processing can be configured via mp.defaults.set("fit.chunk_size", 500).
Scoped Temporary Overrides#
To test parameters on a single movie without altering global defaults, use the context manager:
with mp.defaults.context({
"fit.chunk_size": 500,
"event_correlation_step.thresholds": [0.55, 0.45, 0.0008],
}):
events = mp.fit("movie.mp")
When the context block exits, previous settings are restored automatically.
Saving and Loading Configurations#
Persist settings to a YAML file for reproducible sharing across lab workstations:
# Save to file
mp.defaults.save("lab_instrument_defaults.yml")
# Restore on another machine
mp.defaults.load("lab_instrument_defaults.yml")
Advanced Developer Reference#
This section documents internal mechanics, function decorators, and worker state serialization for developers and advanced pipeline customizers who want to equip their own functions with automatic defaults injection.
API Methods#
Common methods on massphoto.defaults:
Decorators for Custom Functions#
Functions can be decorated to automatically register their parameters and inject defaults:
from massphoto import defaults
@defaults.sync_defaults(prefix='test')
def fn(a=1, psf_size=11):
"""Registers defaults from signature but does not inject at call-time."""
return a, psf_size
@defaults.sync_apply_defaults(prefix='test')
def fn2(a=1, psf_size=11):
"""Registers defaults and injects values from the store at call-time."""
return a, psf_size
# After updating the store, fn2 will pick up the value automatically
defaults.set('test.psf_size', 15)
assert fn2() == (1, 15)
Removing keys and un-shadowing defaults:
# Raises KeyError if 'some_key' is absent
prev = massphoto.defaults.pop('some_key')
# Returns the supplied default instead of raising
prev = massphoto.defaults.pop('some_key', None)
Worker-friendly callable wrapping:
# Prepare a callable for a worker and include a snapshot of the state
wrapped = defaults.wrap_callable(some_function, state=defaults.get_state(copy=True))
Notes and tips
saveandloaddefault to YAML’s safe dumper/loader; it can be necessary to useunsafe=Truewhen python objects are stored in the defaults (e.g. a callable PSF function). Only use for files of trusted origin.The
sync_apply_defaultsdecorator uses function-specific (func.param), prefix (prefix.param) and global (param) keys with the following precedence (highest-first): explicit call args >func.param>prefix.param> globalparam> signature default.With an explicit prefix, registration uses
prefix.paraminstead offunc.paramexcept for parameters promoted to global keys. Existing function-name keys still take precedence during lookup.
DefaultsStore API
Global defaults registry: Shared configuration across the package.
- class massphoto.defaults_store.DefaultsStore[source]#
Bases:
objectGlobal defaults registry
- Features:
Centralised dictionary store
Import-time default registration via decorators
Run-time injection of configuration into functions
Picklable wrappers for Dask/Multiprocessing workers
YAML import/export
Context manager for temporary overrides
Note
All public methods return shallow copies unless
copy=Trueis specified.Thread-safe for concurrent access.
- classmethod pop(key, *args)[source]#
Remove
keyfrom the store and return its previous value.Behaves like
dict.pop():If a default is supplied (
pop('x', default)) it is returned when the key is missing.If no default is supplied (
pop('x')) aKeyErroris raised when the key is missing.
Example:
# raises KeyError if 'x' is absent massphoto.defaults.pop('x') # returns None instead of raising massphoto.defaults.pop('x', None)
- classmethod sync_defaults(*, prefix=None, overwrite=False, exclude=None, promote=None)[source]#
Decorator: Registers signature defaults at import time. Does NOT modify runtime behavior.
- Parameters:
prefix (str | None)
overwrite (bool)
exclude (Collection[str] | None)
promote (Collection[str] | None)
- classmethod apply_defaults(*, prefix=None)[source]#
Decorator: Injects store values at runtime. Use
functools.wraps(): to preserve function metadata (introspection, Sphinx, type-checkers). Store _injector on the wrapper for pickling support.- Parameters:
prefix (str | None)
- classmethod sync_apply_defaults(*, prefix=None, overwrite=False, exclude=None, promote=None)[source]#
Decorator: Registers defaults AND injects store values at runtime. Combines sync_defaults and apply_defaults.
- Parameters:
prefix (str | None)
overwrite (bool)
exclude (Collection[str] | None)
promote (Collection[str] | None)
- classmethod wrap_callable(func, state=None, copy=True)[source]#
Prepare a callable for a worker process (Dask/Multiprocessing). Ensures the worker initializes the store with ‘state’ (or current state) before execution.
- classmethod context(overrides=None, *, copy=True, load=None, unsafe=False)[source]#
Temporarily override store values within a context block.
- Parameters:
overrides (Mapping[str, Any] | None, optional) – Mapping of keys and values to override in the store.
copy (bool, default=True) – If True, overrides and state snapshots are deep-copied into the context.
load (os.PathLike | None, optional) – Optional path to a YAML file to load into the context.
unsafe (bool, default=False) – If True, use PyYAML’s unsafe loader when loading from YAML.
- Yields:
type[DefaultsStore] – The DefaultsStore class with temporary overrides active.
Examples
>>> with mp.defaults.context({"fit.threshold": 0.005}): ... events = mp.fit("movie.mp")
>>> mp.defaults.set("navg", 15) ... print(mp.defaults.get("navg")) # 15 ... with mp.defaults.context({"navg": 5}): ... print(mp.defaults.get("navg")) # 5
… print(mp.defaults.get(“navg”)) # 15
- class massphoto.defaults_store.FunctionInjector(func, *, prefix=None)[source]#
Bases:
Generic[P,R]Callable wrapper that injects configuration values from DefaultsStore at call time.
The wrapper behaves like the wrapped function for introspection (signature, docstring, annotations) so that inspect and Sphinx autodoc treat it as a normal function.
- get_args(*args, **kwargs)[source]#
Get bound arguments with defaults injected from the store. See
__call__()for the injection order.- Parameters:
*args (~P) – Arguments to bind.
**kwargs (~P) – Arguments to bind.
- Returns:
Bound arguments with injected defaults.
- Return type:
- __call__(*args, **kwargs)[source]#
Call the wrapped function with defaults injected.
Argument resolution order (highest precedence first):
Explicit arguments supplied by the caller.
Function-specific defaults:
<function_name>.<parameter>Prefix defaults (if a prefix is configured):
<prefix>.<parameter>Global defaults:
<parameter>The original default value from the function signature.
*argsand**kwargsparameters are never injected.- Parameters:
args (~P)
kwargs (~P)
- Return type:
R