Event Fitting Functions#
- massphoto.fitting.get_psf_thumbnails(processed_movie, events, thumbnail_size=11, thumbnail_frames=0, exclude_nan=False, return_df=False)[source]#
Extracts valid point spread function (PSF) thumbnails from a processed movie based on the provided coordinates.
Note
Available as both
massphoto.get_psf_thumbnailsandmassphoto.fitting.get_psf_thumbnails.Parameters:#
- processed_movienp.ndarray
A 3D numpy array representing the processed movie with dimensions (frames, height, width).
- eventspd.DataFrame | np.ndarray
DataFrame containing candidate event positions with columns ‘frame’, ‘x’, and ‘y’.
- thumbnail_sizeint, optional
Size of the square thumbnail. Default is 11.
- thumbnail_framesint, optional
Number of frames to extract for each thumbnail. Default is 0. For 0, a 2D thumbnail is returned. For values > 0, a 3D thumbnail is returned.
- exclude_nanbool, optional
Exclude thumbnails containing NaN values. NaNs only occurs when thumbnail_frames > 2*navg+ngap. Default is False.
- return_dfbool, optional
Whether to return a DataFrame of valid thumbnail positions. Default is False.
Returns:#
- np.ndarray
A 4D numpy array of extracted thumbnails with dimensions (number of valid thumbnails, thumbnail_size, thumbnail_size). This is generally only 3D however as we only provide a single frame for index 0, but passing a 4D slice selection would work.
- massphoto.fitting.fit_psf_thumbnails_numba(movie, tyx, fitfun, thumbnail_size=11)[source]#
Low-level thumbnail fitter helper.
Extracts thumbnails at
tyxand runsfitfunon each thumbnail. Most users should callfit_event()orfit()instead.
- massphoto.fitting.fit_event(movie, events, thumbnail_size=11, psf_parameters=None, psf_experimental=None, method='gradient-descent', max_shift=3, keep_invalid=False)[source]#
Fit PSFs to detected events for precise position and contrast determination.
Note
Available as both
massphoto.fit_eventandmassphoto.fitting.fit_event.- Parameters:
movie (np.ndarray) – Input movie array with shape (frames, y, x).
events (pd.DataFrame) – DataFrame with columns ‘frame’, ‘y’, ‘x’ and optionally ‘c’.
thumbnail_size (int, default=11) – Size of square region around each event for fitting.
psf_parameters (dict | None, default=None) – Parameters for the theoretical PSF model. If None, uses defaults from DefaultsStore.
psf_experimental (np.ndarray | None, default=None) – Experimentally determined PSF. Takes precedence over theoretical models.
method (str, default="gradient-descent") –
Fitting method. Options:
”gradient-descent”: Optimized and numba-complied code for PSF fitting
Other scipy.optimize.minimize methods (e.g., “Nelder-Mead”)
max_shift (int, default=3) – Maximum allowed shift from initial position in pixels. Passed to fitting function but not enforced.
keep_invalid (bool, default=False) – If True, the output DataFrame has the same length and index as
events. Rows whose thumbnails fall outside the movie bounds are retained with NaN in all fit columns.
- Returns:
DataFrame with fitted parameters as columns:
frame: Original frame number
x, y: Refined event positions
contrasts: Fitted contrast values
x_det, y_det: Original detection positions
x_fit, y_fit: Position refinement offsets
contrasts_det: Original detection contrasts (if provided)
contrasts_se: Standard error of contrast (gradient-descent only)
r2_fit: R-squared of fit (gradient-descent only)
res_fit: Residual of fit (gradient-descent only)
- Return type:
pd.DataFrame
- massphoto.fitting.fit(movie, events=None, movie_template=None, movie_normalize_frame_means=False, movie_correct_drift=False, return_ratiometric=False, ratiometric_args=None, ratiometric_func=<function calc_ratiometric>, detection_func=<function event_correlation_step>, detection_args=None, fit_func=<function fit_event>, fit_args=None, chunk_overlap=-1, chunk_size=1000, postprocess=(<function apply>, ), scheduler=None, progress_bar=True, attach_record=True, compute_movie_metrics=False)[source]#
Detect events and fit PSFs with chunked (Dask) processing.
Note
Available as both
massphoto.fitandmassphoto.fitting.fit.This is the main high-level entry point for most analyses. By default, it runs a detection step followed by a fitting step using
process(). Defaults can be overridden viamassphoto.defaults(see Managing Defaults).- Parameters:
movie (da.Array | np.ndarray | os.PathLike) – Movie array of shape
(frames, y, x), or a path readable byread_movie().events (pd.DataFrame | np.ndarray | list | None, default=None) – Precomputed detections/candidates with
frame,y, andxfields. When provided, the detection step is skipped and only fitting is run.movie_template (np.ndarray | None, default=None) – Global native reference image used for frame-mean normalization and drift correction. If needed and not supplied, it is computed as the mean image of the input movie.
movie_normalize_frame_means (bool, default=False) – If True, scale each native frame so its mean matches the global frame mean before drift correction, ratiometric conversion, detection, and fitting.
movie_correct_drift (bool, default=False) – If True, apply
correct_drift()before ratiometric conversion / detection.return_ratiometric (bool, default=False) – If True, also return the ratiometric movie used for detection/fitting.
ratiometric_args (dict | None, default=None) – Passed to
ratiometric_func. Defaults are taken frommassphoto.defaults.ratiometric_func (Callable | None, default=:func:~massphoto.movie_process.calc_ratiometric) – Function that converts the native movie to a ratiometric representation.
detection_func (Callable, default=event_correlation_step) – Event detection function. Common choices:
event_correlation_step()(default) orevent_correlation()(faster).detection_args (dict | None, default=None) – Extra kwargs passed to
detection_func.fit_func (Callable, default=fit_event) – PSF fitting function applied to detections (default:
fit_event()).fit_args (dict | None, default=None) – Extra kwargs passed to
fit_func.chunk_overlap (int, default=-1) – Chunk overlap in frames;
-1letsprocess()infer a suitable value from processing args.chunk_size (int, default=1000) – Chunk size in frames; default is 1000.
postprocess (Sequence[Callable[[pd.DataFrame], pd.DataFrame]]) – Post-processing callbacks applied to the final DataFrame. By default, applies
apply()when a calibration is available.scheduler (str | None, default=None) – Dask scheduler name (e.g.
"threads"or"processes").progress_bar (bool, default=True) – If True, display a tqdm progress bar during Dask computation.
attach_record (bool, default=True) – If True, attach an
analysis_recorddictionary toDataFrame.attrscontaining the effective defaults state, origin function, and origin kwargs for reproducible replay withmassphoto.resolve_record().compute_movie_metrics (bool, default=False) – If True, compute per-frame movie metrics (
intensity,sharpness,signal, and drift metrics whenmovie_correct_drift=True) and attach them toDataFrame.attrs["frame_metrics"].
- Returns:
Event table with detection + fit results. If
return_ratiometric=True, also returns the ratiometric movie.- Return type:
pd.DataFrame | tuple[pd.DataFrame, np.ndarray]
Examples
Run end-to-end detection + fitting from a file:
import massphoto events = massphoto.fit( "path/to/data.mp", movie_correct_drift=True, ratiometric_args={"navg": 10, "ngap": 1}, detection_func=massphoto.detection.event_correlation, fit_args={"thumbnail_size": 11}, scheduler="threads", )