Skip to content
github-actions[bot] edited this page Jul 20, 2026 · 2 revisions

Module Reference

flimkit.PTU - PTU File I/O

reader.py

  • PTUFile(path, verbose=False) - wraps Christoph Gohlke's ptufile and exposes the FLIMFile interface. Pins the TCSPC bin grid, integrates frames, and selects the photon channel.
    • .summed_decay(channel=None) - summed decay histogram
    • .pixel_stack(channel=None, binning=1) - (Y, X, H) histogram stack
    • .raw_pixel_stack(channel=None, binning=1) - (Y, X, H) stack (uint32)
    • .n_bins, .tcspc_res, .time_ns - TCSPC metadata
  • read_pck(path) - reads PicoQuant Check / IRF .pck histograms (ptufile exposes only their tags, so this stays in FLIMKit)

decode.py

  • get_flim_histogram_from_ptufile() - (Y, X, H) stack + metadata for the tile-stitch pipeline
  • create_time_axis() - build time axis from PTU metadata

tools.py

  • signal_from_PTUFile(path, dtype, binning) - load PTU and return an xarray.DataArray with labelled dimensions (Y, X, H) and frequency attribute

stitch.py

  • stitch_flim_tiles(xlif_path, ptu_dir, output_dir, ...) - stitch multi-tile PTU data into a mosaic using XLIF metadata. Three-pass phase-correlation registration (Preibisch et al. 2009): column Y drift, row Y residuals, row X backlash. Nearest-centre ownership for canvas assembly.
  • fit_flim_tiles(...) - full fitting pipeline on a stitched mosaic (two-pass: pooled DE fit → per-pixel NNLS)
  • load_flim_for_fitting(output_dir, load_to_memory) - load previously stitched data

flimkit.FLIM - Reconvolution Fitting

fitters.py

  • fit_summed(decay, tcspc_res, n_bins, irf_prompt, ...) - fit a summed FLIM decay via reconvolution. Pass 1: Differential Evolution global search → Levenberg-Marquardt polish. Returns (best_params, summary_dict).
  • fit_per_pixel(stack, tcspc_res, n_bins, irf_prompt, global_popt, n_exp, ...) - per-pixel fitting with τ values fixed from the global fit. Uses NNLS - fast, convex, unique solution. Pass 2.

Two-pass model:

y(t) = [IRF(t + Shift_IRF) + Bkgr_IRF] ⊗ [Σ αᵢ·exp(−t/τᵢ) + Bkgr]

Pass 1 (summed): DE → LM polish → fixes τ₁...τₙ
Pass 2 (per-pixel): NNLS fits α₁...αₙ and background with fixed τ values

Primary per-pixel output: tau_mean_amp = Σ(fracᵢ × τᵢ) - amplitude-weighted mean lifetime

assemble.py

  • assemble_tile_maps(tile_results, canvas_h, canvas_w, n_exp) - assemble per-tile results into a single canvas
  • derive_global_tau(canvas, n_exp) - ROI-level lifetime statistics from the assembled canvas
  • save_assembled_maps(canvas, global_summary, output_dir, roi_name, n_exp, ...) - save canvas as TIFFs and NPY

irf_tools.py

  • build_machine_irf_from_folder(folder, align_anchor, reducer, ...) - build machine IRF from paired PTU/XLSX files. Aligns to decay peak, aggregates by median, saves as .npy + _meta.json.
  • irf_from_xlsx_analytical(xlsx, ...) - fit the analytical IRF model (Gaussian + exponential tail)
  • gaussian_irf_from_fwhm(n_bins, tcspc_res, fwhm_ns, peak_bin) - generate Gaussian IRF from FWHM

flimkit.phasor - Phasor Analysis

signal.py

  • return_phasor_from_PTUFile(ptu_file) - compute phasor coordinates from a PTU file
  • get_phasor_irf(irf_xlsx) - read IRF from FLIM microscope software Excel export
  • calibrate_signal_with_irf(signal, real, imag, irf_time_ns, irf_counts, frequency) - phase/modulation correction via IRF phasor
  • calibrate_signal_with_machine_irf(signal, real, imag, machine_irf_npy, frequency) - calibrate using a machine IRF .npy. Reads companion _meta.json for time resolution; interpolates onto the signal time axis.

filters.py

  • phasor_filter(real, imag, method, *, mean=None, sigma=1.0, size=3, wavelet='db4', level=1, threshold_mode='soft') - apply a spatial filter to calibrated phasor G/S arrays. When mean is supplied, the phasorpy 0.10 NaN-aware C implementation is used for Gaussian and median; otherwise falls back to scipy. Wavelet denoising uses PyWavelets with a MAD noise estimator. Returns (real_f, imag_f).

interactive.py

  • phasor_cursor_tool(real_cal, imag_cal, mean, frequency, ...) - interactive phasor cursor widget. Works in Jupyter (ipywidgets) and standalone scripts (matplotlib.widgets). Click-to-place elliptic cursors, adjustable radius/angle, per-cursor τ_φ maps, two-component decomposition, Undo/Peaks/Export/Save.

peaks.py

  • find_phasor_peaks(real_cal, imag_cal, mean, frequency, ...) - automatic peak detection on 2-D phasor histograms via Gaussian smoothing and local maxima detection

flimkit.UI - Desktop GUI

gui.py

  • launch_gui() - entry point for the Tkinter GUI
  • FLIMKitApp - main application class. Tabs: Single FOV Fit, Tile Stitch/Fit, Batch ROI Fit, Machine IRF Builder, Phasor Analysis
  • FOVPreviewPanel - right-panel widget showing intensity image and summed decay. Switches to PhasorViewPanel when the Phasor tab is active. Caches the last fitted IRF prompt (_irf_prompt) so per-ROI fits can reuse it.

roi_tools.py

  • RoiManager - stores region geometry and per-region statistics. Serialises to/from JSON for .roi_session.npz persistence.
    • .add_region(name, tool, coords) - register a new region, returns its integer ID
    • .compute_region_mask(region_id, image_shape) - boolean (H×W) mask for a region
    • .to_json() / .from_json(json_str) - serialise/deserialise for session files
  • RoiAnalysisPanel - tab panel for region drawing, statistics display, and per-ROI fitting.
    • Drawing modes: Select, Rectangle, Ellipse, Polygon, Freehand
    • Per-region stats: τ_mean, τ_median, τ_stdev, photon count (all from the loaded lifetime/intensity maps)
    • _fit_roi_decay() - shows the Fit Options dialog, builds a union mask for all selected regions, extracts the summed decay, and runs fit_summed in a background thread. On completion writes τ stats back to each merged region and updates the session file.
    • _show_roi_fit_result(result) / _view_last_fit_result() - open (or reopen from cache) the dark-themed fit result popup with decay plot, residuals, and summary table.
    • Export: CSV (including fit columns), GeoJSON (single or all regions), GeoJSON import
  • _ask_roi_fit_options(params) - modal dialog for overriding n_exp, τ bounds, and cost function before a per-ROI fit. Returns an updated params dict or None if cancelled.

phasor_panel.py

  • PhasorViewPanel(parent, max_cursors=6) - embedded Tkinter widget with FigureCanvasTkAgg. Top axes: FOV intensity image (colourised once cursors are placed); bottom axes: phasor histogram. Controls: Clear, Undo, Save session, Radius slider, Minor/major slider, spatial filter row (method selector, σ/size spinboxes, Apply, Reset).
    • .set_data(real_cal, imag_cal, mean, frequency, display_image, min_photons) - load phasor data; call on main thread
    • .load_session(session, min_photons) - restore a saved .npz session
    • .get_session_dict() - export current state for saving

flimkit.image - Image Utilities

tools.py

  • make_intensity_image(ptu_path, rotate_90_cw, save_image) - 2-D intensity image from PTU
  • make_cell_mask(intensity_image, flow_threshold, cellprob_threshold, resize_to, gpu, ...) - binary cell mask via Cellpose-SAM segmentation (GPU when available, CPU fallback)
  • apply_intensity_threshold(intensity_image, threshold) - boolean mask for photon-count gating
  • pick_intensity_threshold(intensity_image) - interactive slider for visual threshold selection

flimkit.utils - Shared Utilities

plotting.py

  • plot_summed(...) - main summed-fit figure: log-scale decay + model overlay, weighted residuals, parameter table
  • plot_pixel_maps(...) - per-pixel lifetime and amplitude maps
  • plot_lifetime_histogram(...) - lifetime distribution histogram

enhanced_outputs.py

  • save_fit_summary_txt(...) - human-readable fit results text file
  • save_weighted_tau_images(...) - intensity-weighted and amplitude-weighted τ TIFFs with optional display range clipping

lifetime_image.py

  • make_lifetime_image(canvas, output_dir, roi_name, tau_min_ns, tau_max_ns, ...) - colourised lifetime image with NaN-aware smoothing and gamma correction

xlsx_tools.py

  • load_xlsx(path, debug=False) - parse a FLIM microscope FLIM export XLSX. Auto-detects column layout; returns decay_t/c, irf_t/c, fit_t/c, res_t/c.

xml_utils.py

  • parse_xlif_tile_positions(xlif_path, ptu_basename) - tile positions from XLIF (microns)
  • get_pixel_size_from_xlif(xlif_path) - pixel size (m) and pixel count
  • compute_tile_pixel_positions(tiles, pixel_size_m, tile_size) - convert physical positions to pixel coordinates and compute canvas size

Clone this wiki locally