flimkit 0.14.2__tar.gz → 0.14.3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. {flimkit-0.14.2 → flimkit-0.14.3}/PKG-INFO +1 -1
  2. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/UI/gui.py +44 -134
  3. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/UI/phasor_panel.py +31 -13
  4. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/_version.py +2 -1
  5. flimkit-0.14.3/flimkit/batch_cli.py +337 -0
  6. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/cli.py +8 -0
  7. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/interactive.py +2 -0
  8. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/phasor/export.py +2 -10
  9. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/phasor/filters.py +17 -0
  10. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/phasor_launcher.py +6 -0
  11. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit.egg-info/PKG-INFO +1 -1
  12. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit.egg-info/SOURCES.txt +1 -0
  13. {flimkit-0.14.2 → flimkit-0.14.3}/pyproject.toml +0 -1
  14. {flimkit-0.14.2 → flimkit-0.14.3}/LICENSE.md +0 -0
  15. {flimkit-0.14.2 → flimkit-0.14.3}/README.md +0 -0
  16. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/FLIM/__init__.py +0 -0
  17. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/FLIM/assemble.py +0 -0
  18. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/FLIM/batch.py +0 -0
  19. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/FLIM/bg_tools.py +0 -0
  20. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/FLIM/fit_tools.py +0 -0
  21. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/FLIM/fitters.py +0 -0
  22. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/FLIM/irf_tools.py +0 -0
  23. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/FLIM/models.py +0 -0
  24. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/FLIM/nb_freetau.py +0 -0
  25. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/FLIM/nb_freetau_cuda.py +0 -0
  26. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/FLIM/poisson_fit.py +0 -0
  27. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/GPU/__init__.py +0 -0
  28. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/GPU/_base.py +0 -0
  29. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/GPU/cuda.py +0 -0
  30. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/GPU/mlx_backend.py +0 -0
  31. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/GPU/mps.py +0 -0
  32. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/GPU/rocm.py +0 -0
  33. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/GPU/torch_backend.py +0 -0
  34. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/GPU/torch_lm.py +0 -0
  35. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/UI/app_state.py +0 -0
  36. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/UI/controller.py +0 -0
  37. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/UI/expert_settings.py +0 -0
  38. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/UI/fit_help.py +0 -0
  39. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/UI/fov_preview.py +0 -0
  40. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/UI/icon.icns +0 -0
  41. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/UI/icon.ico +0 -0
  42. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/UI/icon.png +0 -0
  43. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/UI/irf_widget.py +0 -0
  44. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/UI/mode_controller.py +0 -0
  45. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/UI/modes/__init__.py +0 -0
  46. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/UI/modes/base.py +0 -0
  47. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/UI/modes/batch_mode.py +0 -0
  48. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/UI/modes/fov_mode.py +0 -0
  49. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/UI/modes/irf_mode.py +0 -0
  50. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/UI/modes/phasor_mode.py +0 -0
  51. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/UI/modes/stitch_mode.py +0 -0
  52. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/UI/progress_window.py +0 -0
  53. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/UI/project_panel.py +0 -0
  54. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/UI/results_panel.py +0 -0
  55. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/UI/roi_tools.py +0 -0
  56. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/UI/utils.py +0 -0
  57. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/__init__.py +0 -0
  58. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/configs.py +0 -0
  59. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/dialogs.py +0 -0
  60. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/formats/BH/__init__.py +0 -0
  61. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/formats/BH/reader.py +0 -0
  62. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/formats/BH/writer.py +0 -0
  63. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/formats/ISS/__init__.py +0 -0
  64. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/formats/ISS/fdflim.py +0 -0
  65. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/formats/ISS/image.py +0 -0
  66. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/formats/ISS/reader.py +0 -0
  67. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/formats/PS/__init__.py +0 -0
  68. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/formats/PS/reader.py +0 -0
  69. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/formats/PTU/__init__.py +0 -0
  70. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/formats/PTU/decode.py +0 -0
  71. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/formats/PTU/phu.py +0 -0
  72. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/formats/PTU/reader.py +0 -0
  73. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/formats/PTU/series.py +0 -0
  74. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/formats/PTU/stitch.py +0 -0
  75. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/formats/PTU/tools.py +0 -0
  76. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/formats/__init__.py +0 -0
  77. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/formats/flim_file.py +0 -0
  78. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/formats/phasor.py +0 -0
  79. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/formats/signal.py +0 -0
  80. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/image/tools.py +0 -0
  81. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/mpl_backend.py +0 -0
  82. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/phasor/__init__.py +0 -0
  83. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/phasor/fret.py +0 -0
  84. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/phasor/interactive.py +0 -0
  85. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/phasor/peaks.py +0 -0
  86. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/phasor/signal.py +0 -0
  87. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/plugins/__init__.py +0 -0
  88. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/plugins/bindings.py +0 -0
  89. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/plugins/builtin/__init__.py +0 -0
  90. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/plugins/builtin/core_tools.py +0 -0
  91. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/plugins/loader.py +0 -0
  92. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/plugins/registry.py +0 -0
  93. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/project.py +0 -0
  94. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/synth.py +0 -0
  95. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/utils/__init__.py +0 -0
  96. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/utils/app_update.py +0 -0
  97. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/utils/apply_settings.py +0 -0
  98. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/utils/batch_fit.py +0 -0
  99. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/utils/config_manager.py +0 -0
  100. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/utils/config_snapshot.py +0 -0
  101. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/utils/crash_handler.py +0 -0
  102. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/utils/display.py +0 -0
  103. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/utils/enhanced_outputs.py +0 -0
  104. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/utils/export_png.py +0 -0
  105. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/utils/fancy.py +0 -0
  106. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/utils/lifetime_image.py +0 -0
  107. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/utils/misc.py +0 -0
  108. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/utils/ome_zarr.py +0 -0
  109. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/utils/plotting.py +0 -0
  110. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/utils/roi.py +0 -0
  111. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/utils/session.py +0 -0
  112. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/utils/update_check.py +0 -0
  113. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/utils/xlsx_tools.py +0 -0
  114. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit/utils/xml_utils.py +0 -0
  115. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit.egg-info/dependency_links.txt +0 -0
  116. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit.egg-info/entry_points.txt +0 -0
  117. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit.egg-info/requires.txt +0 -0
  118. {flimkit-0.14.2 → flimkit-0.14.3}/flimkit.egg-info/top_level.txt +0 -0
  119. {flimkit-0.14.2 → flimkit-0.14.3}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: flimkit
3
- Version: 0.14.2
3
+ Version: 0.14.3
4
4
  Summary: Fluorescence lifetime imaging analysis: reading, fitting, phasors and stitching
5
5
  Author-email: Alex Hunt <alexander.hunt@ed.ac.uk>
6
6
  License-Expression: MIT
@@ -2866,8 +2866,27 @@ Anthropic's Claude AI assisted with parts of the GUI implementation.
2866
2866
  correct_pileup = self.bv_batch_correct_pileup.get()
2867
2867
  tvb_ptu_batch = (self.sv_batch_tvb_ptu.get().strip() or None) if hasattr(self, 'sv_batch_tvb_ptu') else None
2868
2868
  expert_overrides = dict(self._expert_overrides)
2869
- from flimkit.interactive import _run_flim_fit
2869
+ from flimkit.batch_cli import fitFov
2870
2870
  import gc, csv as csv_mod
2871
+ bp = argparse.Namespace(
2872
+ nexp=n_exp, dist_type=_batch_model,
2873
+ dist_n_components=(self.iv_ncomp_dist_batch.get() if _batch_model not in ('discrete', 'tail') else 1),
2874
+ fit_t0=expert_overrides.get('fit_t0', False),
2875
+ tau_min=tau_min, tau_max=tau_max,
2876
+ optimizer=expert_overrides.get('optimizer', cfg['Optimizer']),
2877
+ restarts=expert_overrides.get('lm_restarts', cfg['lm_restarts']),
2878
+ de_population=expert_overrides.get('de_population', cfg['de_population']),
2879
+ de_maxiter=expert_overrides.get('de_maxiter', cfg['de_maxiter']),
2880
+ workers=expert_overrides.get('n_workers', cfg['n_workers']),
2881
+ binning=expert_overrides.get('binning_factor', cfg['binning_factor']),
2882
+ min_photons=expert_overrides.get('min_photons', cfg['MIN_PHOTONS_PERPIX']),
2883
+ channel=expert_overrides.get('channels', cfg['channels']),
2884
+ irf_fwhm=expert_overrides.get('irf_fwhm', cfg['IRF_FWHM']),
2885
+ intensity_threshold=thr, correct_pileup=correct_pileup,
2886
+ machine_irf=mirf, estimate_irf='machine_irf', tvb_ptu=tvb_ptu_batch,
2887
+ save_npy=save_npy,
2888
+ irf_align=expert_overrides.get('irf_align', 'steepest_rise'),
2889
+ irf_shift_bins=expert_overrides.get('irf_shift_bins', 2))
2871
2890
  def task(progress_callback, cancel_event):
2872
2891
  csv_path = Path(out_dir) / 'batch_fov_fit_summary.csv'
2873
2892
  header_written = False
@@ -2882,58 +2901,7 @@ Anthropic's Claude AI assisted with parts of the GUI implementation.
2882
2901
  fov_out.mkdir(parents=True, exist_ok=True)
2883
2902
  print(f'\n{'='*50}\n [{idx+1}/{n_total}] {stem}\n{'='*50}')
2884
2903
  try:
2885
- a = argparse.Namespace(
2886
- ptu=str(ptu_path),
2887
- xlsx=None,
2888
- debug_xlsx=False,
2889
- print_config=False,
2890
- irf=None,
2891
- irf_xlsx=None,
2892
- estimate_irf='machine_irf',
2893
- no_xlsx_irf=True,
2894
- machine_irf=mirf,
2895
- irf_bins=cfg['IRF_BINS'],
2896
- irf_fit_width=cfg['IRF_FIT_WIDTH'],
2897
- irf_fwhm=expert_overrides.get('irf_fwhm', cfg['IRF_FWHM']),
2898
- nexp=n_exp,
2899
- dist_type=_batch_model,
2900
- dist_n_components=(self.iv_ncomp_dist_batch.get() if _batch_model not in ('discrete', 'tail') else 1),
2901
- fit_t0=expert_overrides.get('fit_t0', False),
2902
- tau_min=tau_min,
2903
- tau_max=tau_max,
2904
- mode='both',
2905
- binning=expert_overrides.get('binning_factor', cfg['binning_factor']),
2906
- min_photons=expert_overrides.get('min_photons', cfg['MIN_PHOTONS_PERPIX']),
2907
- optimizer=expert_overrides.get('optimizer', cfg['Optimizer']),
2908
- restarts=expert_overrides.get('lm_restarts', cfg['lm_restarts']),
2909
- de_population=expert_overrides.get('de_population', cfg['de_population']),
2910
- de_maxiter=expert_overrides.get('de_maxiter', cfg['de_maxiter']),
2911
- workers=expert_overrides.get('n_workers', cfg['n_workers']),
2912
- no_polish=False,
2913
- channel=expert_overrides.get('channels', cfg['channels']),
2914
- out=str(fov_out / stem),
2915
- no_plots=True,
2916
- cell_mask=False,
2917
- correct_pileup=correct_pileup,
2918
- intensity_threshold=thr,
2919
- irf_align=expert_overrides.get('irf_align', 'steepest_rise'),
2920
- irf_shift_bins=expert_overrides.get('irf_shift_bins', 2),
2921
- tvb_ptu=tvb_ptu_batch,
2922
- tvb_channel=None,
2923
- )
2924
- result = _run_flim_fit(a)
2925
- summary = result.get('global_summary', {})
2926
- pu_pct = result.get('pileup_pct')
2927
- cr_mhz = result.get('count_rate_mhz')
2928
- if not save_npy:
2929
- for f_ in fov_out.glob('*.npy'):
2930
- if not f_.name.endswith('_time_axis_ns.npy'):
2931
- f_.unlink(missing_ok=True)
2932
- gc.collect()
2933
- row = {'fov': stem, 'status': 'OK',
2934
- 'pileup_pct': pu_pct if pu_pct is not None else '',
2935
- 'count_rate_mhz': cr_mhz if cr_mhz is not None else '',
2936
- **summary}
2904
+ row = fitFov(ptu_path, fov_out, bp)
2937
2905
  print(f' OK: {stem}')
2938
2906
  except Exception as exc:
2939
2907
  import traceback; traceback.print_exc()
@@ -2992,11 +2960,28 @@ Anthropic's Claude AI assisted with parts of the GUI implementation.
2992
2960
  correct_pileup = self.bv_batch_correct_pileup.get()
2993
2961
  tvb_ptu_batch = (self.sv_batch_tvb_ptu.get().strip() or None) if hasattr(self, 'sv_batch_tvb_ptu') else None
2994
2962
  expert_overrides = dict(self._expert_overrides)
2995
- from flimkit.formats.PTU.stitch import fit_flim_tiles
2996
- from flimkit.FLIM.assemble import (derive_global_tau, save_assembled_maps,
2997
- assemble_tile_maps)
2998
- from flimkit.utils.lifetime_image import make_lifetime_image, make_component_rgb_tiff
2963
+ from flimkit.batch_cli import fitRoi
2999
2964
  import gc, csv as csv_mod
2965
+ bp = argparse.Namespace(
2966
+ nexp=n_exp, dist_type=_batch_model,
2967
+ dist_n_components=(self.iv_ncomp_dist_batch.get() if _batch_model not in ('discrete', 'tail') else 1),
2968
+ fit_t0=expert_overrides.get('fit_t0', False),
2969
+ tau_min=tau_min, tau_max=tau_max,
2970
+ optimizer=expert_overrides.get('optimizer', 'de'),
2971
+ restarts=expert_overrides.get('lm_restarts', 1),
2972
+ de_population=expert_overrides.get('de_population', cfg['de_population']),
2973
+ de_maxiter=expert_overrides.get('de_maxiter', cfg['de_maxiter']),
2974
+ workers=expert_overrides.get('n_workers', cfg['n_workers']),
2975
+ binning=expert_overrides.get('binning_factor', 1),
2976
+ min_photons=expert_overrides.get('min_photons', cfg['MIN_PHOTONS_PERPIX']),
2977
+ channel=expert_overrides.get('channels', cfg['channels']),
2978
+ irf_fwhm=expert_overrides.get('irf_fwhm', cfg['IRF_FWHM']),
2979
+ intensity_threshold=thr, correct_pileup=correct_pileup,
2980
+ machine_irf=mirf, estimate_irf='machine_irf', tvb_ptu=tvb_ptu_batch,
2981
+ register=register, reg_shift=reg_shift, rotate_tiles=True,
2982
+ tau_lo=tau_lo, tau_hi=tau_hi, int_max=int_max,
2983
+ tau_weighting=('int' if tau_weighting == 'intensity' else 'amp'),
2984
+ gamma=gamma, save_lifetime=save_lifetime, save_rgb=save_rgb, save_npy=save_npy)
3000
2985
  def task(progress_callback, cancel_event):
3001
2986
  csv_path = Path(out_dir) / 'batch_roi_fit_summary.csv'
3002
2987
  header_written = False
@@ -3012,83 +2997,8 @@ Anthropic's Claude AI assisted with parts of the GUI implementation.
3012
2997
  roi_out.mkdir(parents=True, exist_ok=True)
3013
2998
  print(f'\n{'='*50}\n [{idx+1}/{n_total}] {ptu_basename}\n{'='*50}')
3014
2999
  try:
3015
- fit_args = argparse.Namespace(
3016
- nexp=n_exp, dist_type=_batch_model,
3017
- dist_n_components=(self.iv_ncomp_dist_batch.get() if _batch_model not in ('discrete', 'tail') else 1),
3018
- fit_t0=expert_overrides.get('fit_t0', False),
3019
- tau_min=tau_min, tau_max=tau_max,
3020
- optimizer=expert_overrides.get('optimizer', 'de'),
3021
- restarts=expert_overrides.get('lm_restarts', 1),
3022
- de_population=expert_overrides.get('de_population', cfg['de_population']),
3023
- de_maxiter=expert_overrides.get('de_maxiter', cfg['de_maxiter']),
3024
- workers=expert_overrides.get('n_workers', cfg['n_workers']),
3025
- binning=expert_overrides.get('binning_factor', 1),
3026
- min_photons=expert_overrides.get('min_photons', cfg['MIN_PHOTONS_PERPIX']),
3027
- channel=expert_overrides.get('channels', cfg['channels']),
3028
- irf_fwhm=expert_overrides.get('irf_fwhm', cfg['IRF_FWHM']),
3029
- intensity_threshold=thr,
3030
- correct_pileup=correct_pileup,
3031
- register_tiles=register,
3032
- reg_max_shift_px=reg_shift,
3033
- machine_irf=mirf,
3034
- tau_display_min=tau_lo,
3035
- tau_display_max=tau_hi,
3036
- intensity_display_min=0.0,
3037
- intensity_display_max=None,
3038
- irf_xlsx_dir=None, irf_xlsx_map=None,
3039
- ptu_basename=ptu_basename,
3040
- xlif=str(xlif_path),
3041
- ptu_dir=ptu_dir,
3042
- output_dir=str(roi_out),
3043
- no_plots=True, cell_mask=False,
3044
- debug_xlsx=False, print_config=False,
3045
- irf=None, irf_xlsx=None,
3046
- estimate_irf='machine_irf',
3047
- no_xlsx_irf=True,
3048
- tvb_ptu=tvb_ptu_batch,
3049
- tvb_channel=None,
3050
- )
3051
- (tile_results, canvas_h, canvas_w, _, _, _, _, _, _) = fit_flim_tiles(
3052
- xlif_path=xlif_path, ptu_dir=Path(ptu_dir),
3053
- output_dir=roi_out, args=fit_args,
3054
- ptu_basename=ptu_basename, rotate_tiles=True, verbose=True,
3055
- )
3056
- if not tile_results:
3057
- row = {'roi': ptu_basename, 'status': 'No tiles fitted'}
3058
- else:
3059
- canvas = assemble_tile_maps(tile_results, canvas_h, canvas_w, n_exp)
3060
- del tile_results; gc.collect()
3061
- summary = derive_global_tau(canvas, n_exp=n_exp)
3062
- from flimkit.utils.export_png import xlif_field_area_um2
3063
- area_um2 = xlif_field_area_um2(xlif_path, ptu_basename, (canvas_h, canvas_w), fit_args.binning)
3064
- save_assembled_maps(
3065
- canvas=canvas, global_summary=summary,
3066
- output_dir=roi_out, roi_name=roi_clean, n_exp=n_exp,
3067
- tau_display_min=tau_lo, tau_display_max=tau_hi,
3068
- intensity_display_max=int_max,
3069
- tau_weighting=('int' if tau_weighting == 'intensity' else 'amp'),
3070
- field_area_um2=area_um2,
3071
- )
3072
- if save_lifetime:
3073
- make_lifetime_image(
3074
- canvas=canvas, output_dir=roi_out, roi_name=roi_clean,
3075
- tau_min_ns=tau_lo, tau_max_ns=tau_hi,
3076
- smooth_sigma_px=0.0, gamma=gamma, verbose=False,
3077
- tau_key=tau_key, field_area_um2=area_um2,
3078
- )
3079
- if save_rgb:
3080
- make_component_rgb_tiff(
3081
- canvas=canvas, output_dir=roi_out,
3082
- roi_name=roi_clean, n_exp=n_exp, verbose=False,
3083
- field_area_um2=area_um2,
3084
- )
3085
- if not save_npy:
3086
- for f_ in roi_out.glob('*.npy'):
3087
- if not f_.name.endswith('_time_axis_ns.npy'):
3088
- f_.unlink(missing_ok=True)
3089
- del canvas; gc.collect()
3090
- row = {'roi': ptu_basename, 'status': 'OK', **summary}
3091
- print(f' OK: {ptu_basename}')
3000
+ row = fitRoi(xlif_path, ptu_dir, roi_out, bp)
3001
+ print(f' {row["status"]}: {ptu_basename}')
3092
3002
  except Exception as exc:
3093
3003
  import traceback; traceback.print_exc()
3094
3004
  row = {'roi': ptu_basename,
@@ -45,6 +45,9 @@ class PhasorViewPanel:
45
45
  self._filter_method = tk.StringVar(value='none')
46
46
  self._filter_sigma = tk.DoubleVar(value=1.0)
47
47
  self._filter_size = tk.IntVar(value=3)
48
+ self._filter_wavelet = tk.StringVar(value='db4')
49
+ self._filter_level = tk.IntVar(value=1)
50
+ self._filter_threshold = tk.StringVar(value='soft')
48
51
  self._applied_filter = None
49
52
  self._cursors = []
50
53
  self._cursor_artists = []
@@ -145,6 +148,17 @@ class PhasorViewPanel:
145
148
  ttk.Spinbox(self._filt_size_frame, textvariable=self._filter_size,
146
149
  from_=3, to=15, increment=2, width=4).pack(side='left', padx=(2, 6))
147
150
  self._filt_size_frame.pack_forget()
151
+ from flimkit.phasor.filters import THRESHOLD_MODES, WAVELET_NAMES
152
+ self._filt_wavelet_frame = ttk.Frame(row_filt)
153
+ self._filt_wavelet_frame.pack(side='left')
154
+ ttk.Combobox(self._filt_wavelet_frame, textvariable=self._filter_wavelet,
155
+ values=list(WAVELET_NAMES), width=6).pack(side='left', padx=(2, 4))
156
+ ttk.Label(self._filt_wavelet_frame, text='level:').pack(side='left')
157
+ ttk.Spinbox(self._filt_wavelet_frame, textvariable=self._filter_level,
158
+ from_=1, to=6, increment=1, width=3).pack(side='left', padx=(2, 4))
159
+ ttk.Combobox(self._filt_wavelet_frame, textvariable=self._filter_threshold,
160
+ values=list(THRESHOLD_MODES), state='readonly', width=5).pack(side='left', padx=(0, 6))
161
+ self._filt_wavelet_frame.pack_forget()
148
162
  self._filt_apply_btn = ttk.Button(row_filt, text='Apply', command=self._on_filter_apply)
149
163
  self._filt_apply_btn.pack(side='left', padx=(0, 4))
150
164
  ttk.Button(row_filt, text='Reset',
@@ -175,12 +189,17 @@ class PhasorViewPanel:
175
189
  shown = {'sigma'}
176
190
  elif method == 'median':
177
191
  shown = {'size'}
178
- elif method in ('none', 'wavelet'):
192
+ elif method == 'wavelet':
193
+ shown = {'wavelet'}
194
+ elif method == 'none':
179
195
  shown = set()
180
196
  else:
181
197
  shown = self._plugin_filter_params(method)
182
198
  self._filt_sigma_frame.pack_forget()
183
199
  self._filt_size_frame.pack_forget()
200
+ self._filt_wavelet_frame.pack_forget()
201
+ if 'wavelet' in shown:
202
+ self._filt_wavelet_frame.pack(side='left', before=self._filt_apply_btn)
184
203
  if 'sigma' in shown:
185
204
  self._filt_sigma_frame.pack(side='left', before=self._filt_apply_btn)
186
205
  if 'size' in shown:
@@ -194,7 +213,10 @@ class PhasorViewPanel:
194
213
  return
195
214
  spec = dict(method=method,
196
215
  sigma=float(self._filter_sigma.get()),
197
- size=int(self._filter_size.get()))
216
+ size=int(self._filter_size.get()),
217
+ wavelet=self._filter_wavelet.get(),
218
+ level=int(self._filter_level.get()),
219
+ threshold_mode=self._filter_threshold.get())
198
220
  try:
199
221
  self._apply_filter_spec(spec)
200
222
  except Exception as exc:
@@ -216,23 +238,16 @@ class PhasorViewPanel:
216
238
  if method == 'median':
217
239
  return f"median (size={spec['size']})"
218
240
  if method == 'wavelet':
219
- return 'wavelet (db4)'
241
+ return (f"wavelet ({spec.get('wavelet', 'db4')}, level {spec.get('level', 1)}, "
242
+ f"{spec.get('threshold_mode', 'soft')})")
220
243
  return method
221
244
 
222
245
  def _apply_filter_spec(self, spec):
223
- from flimkit.phasor.filters import phasor_filter
246
+ from flimkit.phasor.filters import filter_kwargs, phasor_filter
224
247
  method = spec['method']
225
- kwargs = {}
226
- if method == 'gaussian':
227
- kwargs['sigma'] = float(spec['sigma'])
228
- elif method == 'median':
229
- kwargs['size'] = int(spec['size'])
230
- elif method != 'wavelet':
231
- kwargs['sigma'] = float(spec['sigma'])
232
- kwargs['size'] = int(spec['size'])
233
248
  self._real, self._imag = phasor_filter(
234
249
  self._real_raw.copy(), self._imag_raw.copy(), method,
235
- mean=self._mean, **kwargs)
250
+ mean=self._mean, **filter_kwargs(spec))
236
251
  self._applied_filter = dict(spec)
237
252
 
238
253
  def _on_filter_reset(self):
@@ -329,6 +344,9 @@ class PhasorViewPanel:
329
344
  if spec.get('method', 'none') not in ('none', '', None):
330
345
  self._filter_sigma.set(float(spec.get('sigma', 1.0)))
331
346
  self._filter_size.set(int(spec.get('size', 3)))
347
+ self._filter_wavelet.set(str(spec.get('wavelet', 'db4')))
348
+ self._filter_level.set(int(spec.get('level', 1)))
349
+ self._filter_threshold.set(str(spec.get('threshold_mode', 'soft')))
332
350
  self._filter_method.set(spec['method'])
333
351
  try:
334
352
  self._apply_filter_spec(spec)
@@ -1,4 +1,4 @@
1
- __version__ = '0.14.2'
1
+ __version__ = '0.14.3'
2
2
  fitter_version = '25'
3
3
  app_name = 'FLIMKitDEV' if '+dev' in __version__ else 'FLIMKit'
4
4
 
@@ -51,5 +51,6 @@ Need to add Phasor once added to the codebase, and update version to 1.0. And ad
51
51
  0.14.0 -> free-tau per-pixel fits run in numba instead of scipy once per pixel, on the CPU and on NVIDIA GPUs through numba.cuda, and on a CUDA or ROCm card through torch as a batched Levenberg-Marquardt, so fitter_version goes to 24. The @fit_backend plugin hook lets an add-on run the per-pixel fits on its own C or CUDA code; flimkit-accelerator-plugin is the worked example and can speed free tau up considerably, though nothing needs it. Fixed two fitting bugs: stitched and batch ROI fits paired each tile's amplitudes with the wrong lifetimes, and CPU free-tau fits used the wrong IRF when the IRF had a fitted tail and the background was fitted. Summed fits report standard errors and, by default, bootstrap errors. Export all, phasor PNG export, an in-app update check and update.py. FLIMKitDEV is built from dev.
52
52
  0.14.1 -> the compiled desktop app starts on Linux again: PIL._tkinter_finder is bundled, so the matplotlib toolbar no longer dies on a missing module. The installation check accepts an add-on fit backend that solves every free-tau pixel itself instead of demanding that some reach the scipy solver. Releases now publish to PyPI on their own: a release created by the build workflow does not trigger the publish workflow, so the build dispatches it. No fitted number changes, so fitter_version stays at 24.
53
53
  0.14.2 -> fixed-tau per-pixel fits with two or more components estimate the amplitudes by Poisson maximum likelihood with a fitted constant offset, so fitter_version goes to 25. The earlier projection stays behind Earlier projection for fixed tau in Expert Settings and --estimator nnls. A fit backend can take the Poisson fit by listing poisson in its estimators attribute. The IRF selector is one dropdown.
54
+ 0.14.3 -> batch tiled ROI and single FOV fits in the terminal UI and as scripts, sharing their code with the GUI batch. The wavelet phasor filter has a wavelet, a level and a threshold setting.
54
55
  1.0.0 -> release version with all core features implemented and tested
55
56
  1.5.0 (or 2.0) -> validation of fitting results with known fluorophores.'''
@@ -0,0 +1,337 @@
1
+ import argparse
2
+ import csv
3
+ import gc
4
+ from pathlib import Path
5
+
6
+ from .configs import (
7
+ n_exp, Tau_min, Tau_max, binning_factor, MIN_PHOTONS_PERPIX, lm_restarts,
8
+ de_population, de_maxiter, n_workers, IRF_BINS, IRF_FIT_WIDTH, IRF_FWHM,
9
+ channels, INTENSITY_THRESHOLD, TAU_DISPLAY_MIN, TAU_DISPLAY_MAX,
10
+ MACHINE_IRF_DEFAULT_PATH)
11
+
12
+
13
+ def _batch_parser(description, input_flag, input_help, need_ptu_dir=True):
14
+ ap = argparse.ArgumentParser(description=description)
15
+ ap.add_argument(input_flag, required=True, help=input_help)
16
+ if need_ptu_dir == True:
17
+ ap.add_argument('--ptu-dir', required=True)
18
+ ap.add_argument('--output-dir', default=None, help='Default: <ptu-dir>/save')
19
+ ap.add_argument('--estimate-irf', default='machine_irf',
20
+ choices=['parametric', 'raw', 'machine_irf', 'machine_irf_sigma_full', 'machine_irf_sigma_half'])
21
+ ap.add_argument('--machine-irf', default=str(MACHINE_IRF_DEFAULT_PATH))
22
+ ap.add_argument('--nexp', type=int, default=n_exp, choices=[1, 2, 3])
23
+ ap.add_argument('--tau-min', type=float, default=Tau_min)
24
+ ap.add_argument('--tau-max', type=float, default=Tau_max)
25
+ ap.add_argument('--binning', type=int, default=binning_factor)
26
+ ap.add_argument('--min-photons', type=int, default=MIN_PHOTONS_PERPIX)
27
+ ap.add_argument('--optimizer', default='de', choices=['lm_multistart', 'de'])
28
+ ap.add_argument('--restarts', type=int, default=lm_restarts)
29
+ ap.add_argument('--de-population', type=int, default=de_population)
30
+ ap.add_argument('--de-maxiter', type=int, default=de_maxiter)
31
+ ap.add_argument('--workers', type=int, default=n_workers)
32
+ ap.add_argument('--channel', type=int, default=channels)
33
+ ap.add_argument('--irf-fwhm', type=float, default=IRF_FWHM)
34
+ ap.add_argument('--intensity-threshold', type=int, default=INTENSITY_THRESHOLD)
35
+ ap.add_argument('--correct-pileup', action='store_true')
36
+ ap.add_argument('--tau-display-min', type=float, default=TAU_DISPLAY_MIN)
37
+ ap.add_argument('--tau-display-max', type=float, default=TAU_DISPLAY_MAX)
38
+ ap.add_argument('--intensity-display-min', type=float, default=None)
39
+ ap.add_argument('--intensity-display-max', type=float, default=None)
40
+ ap.add_argument('--tau-weighting', default='amp', choices=['amp', 'int'])
41
+ ap.add_argument('--fit-t0', action='store_true')
42
+ ap.add_argument('--gamma', type=float, default=0.4)
43
+ ap.add_argument('--no-save-npy', action='store_true')
44
+ return ap
45
+
46
+
47
+ def resolve_out_dir(ptu_dir, output_dir):
48
+ out = Path(output_dir) if output_dir else Path(ptu_dir) / 'save'
49
+ out.mkdir(parents=True, exist_ok=True)
50
+ return out
51
+
52
+
53
+ def write_rows(csv_path, rows):
54
+ keys = []
55
+ for r in rows:
56
+ for k in r:
57
+ if k not in keys:
58
+ keys.append(k)
59
+ with open(csv_path, 'w', newline='') as fh:
60
+ writer = csv.DictWriter(fh, fieldnames=keys)
61
+ writer.writeheader()
62
+ writer.writerows(rows)
63
+
64
+
65
+ def error_row(key, name, exc):
66
+ return {key: name, 'status': f'ERROR: {type(exc).__name__}: {str(exc)[:80]}'}
67
+
68
+
69
+ def _fit_args(p):
70
+ return dict(
71
+ nexp=p.nexp, dist_type=p.dist_type, dist_n_components=p.dist_n_components,
72
+ fit_t0=p.fit_t0, tau_min=p.tau_min, tau_max=p.tau_max, optimizer=p.optimizer,
73
+ restarts=p.restarts, de_population=p.de_population, de_maxiter=p.de_maxiter,
74
+ workers=p.workers, binning=p.binning, min_photons=p.min_photons,
75
+ channel=p.channel, irf_fwhm=p.irf_fwhm, intensity_threshold=p.intensity_threshold,
76
+ correct_pileup=p.correct_pileup, machine_irf=p.machine_irf,
77
+ estimate_irf=p.estimate_irf, no_xlsx_irf=True, irf=None, irf_xlsx=None,
78
+ irf_bins=IRF_BINS, irf_fit_width=IRF_FIT_WIDTH, tvb_ptu=p.tvb_ptu,
79
+ tvb_channel=None, no_plots=True, cell_mask=False, debug_xlsx=False,
80
+ print_config=False)
81
+
82
+
83
+ def fitRoi(xlif_path, ptu_dir, roi_out, p):
84
+ from .formats.PTU.stitch import fit_flim_tiles
85
+ from .FLIM.assemble import derive_global_tau, save_assembled_maps, assemble_tile_maps
86
+ from .utils.lifetime_image import make_lifetime_image, make_component_rgb_tiff
87
+ from .utils.export_png import xlif_field_area_um2
88
+ xlif_path = Path(xlif_path)
89
+ roi_out = Path(roi_out)
90
+ ptu_basename = xlif_path.stem
91
+ roi_clean = ptu_basename.replace(' ', '_')
92
+ tau_key = 'tau_mean_int' if p.tau_weighting == 'int' else 'tau_mean_amp'
93
+ fit_args = argparse.Namespace(
94
+ **_fit_args(p), register_tiles=p.register, reg_max_shift_px=p.reg_shift,
95
+ tau_display_min=p.tau_lo, tau_display_max=p.tau_hi, intensity_display_min=0.0,
96
+ intensity_display_max=None, irf_xlsx_dir=None, irf_xlsx_map=None,
97
+ ptu_basename=ptu_basename, xlif=str(xlif_path), ptu_dir=str(ptu_dir),
98
+ output_dir=str(roi_out))
99
+ (tile_results, canvas_h, canvas_w, _, _, _, _, _, _) = fit_flim_tiles(
100
+ xlif_path=xlif_path, ptu_dir=Path(ptu_dir), output_dir=roi_out, args=fit_args,
101
+ ptu_basename=ptu_basename, rotate_tiles=p.rotate_tiles, verbose=True)
102
+ if not tile_results:
103
+ return {'roi': ptu_basename, 'status': 'No tiles fitted'}
104
+ canvas = assemble_tile_maps(tile_results, canvas_h, canvas_w, p.nexp)
105
+ del tile_results
106
+ gc.collect()
107
+ summary = derive_global_tau(canvas, n_exp=p.nexp)
108
+ area_um2 = xlif_field_area_um2(xlif_path, ptu_basename, (canvas_h, canvas_w), fit_args.binning)
109
+ save_assembled_maps(
110
+ canvas=canvas, global_summary=summary, output_dir=roi_out, roi_name=roi_clean,
111
+ n_exp=p.nexp, tau_display_min=p.tau_lo, tau_display_max=p.tau_hi,
112
+ intensity_display_max=p.int_max, tau_weighting=p.tau_weighting,
113
+ field_area_um2=area_um2)
114
+ if p.save_lifetime == True:
115
+ make_lifetime_image(
116
+ canvas=canvas, output_dir=roi_out, roi_name=roi_clean, tau_min_ns=p.tau_lo,
117
+ tau_max_ns=p.tau_hi, smooth_sigma_px=0.0, gamma=p.gamma, verbose=False,
118
+ tau_key=tau_key, field_area_um2=area_um2)
119
+ if p.save_rgb == True:
120
+ make_component_rgb_tiff(
121
+ canvas=canvas, output_dir=roi_out, roi_name=roi_clean, n_exp=p.nexp,
122
+ verbose=False, field_area_um2=area_um2)
123
+ if p.save_npy == False:
124
+ for f_ in roi_out.glob('*.npy'):
125
+ if f_.name.endswith('_time_axis_ns.npy') == False:
126
+ f_.unlink(missing_ok=True)
127
+ del canvas
128
+ gc.collect()
129
+ return {'roi': ptu_basename, 'status': 'OK', **summary}
130
+
131
+
132
+ def fitFov(ptu_path, fov_out, p):
133
+ from .interactive import _run_flim_fit
134
+ ptu_path = Path(ptu_path)
135
+ fov_out = Path(fov_out)
136
+ stem = ptu_path.stem
137
+ a = argparse.Namespace(
138
+ **_fit_args(p), ptu=str(ptu_path), xlsx=None, mode='both', no_polish=False,
139
+ out=str(fov_out / stem), irf_align=p.irf_align, irf_shift_bins=p.irf_shift_bins)
140
+ result = _run_flim_fit(a)
141
+ if p.save_npy == False:
142
+ for f_ in fov_out.glob('*.npy'):
143
+ if f_.name.endswith('_time_axis_ns.npy') == False:
144
+ f_.unlink(missing_ok=True)
145
+ gc.collect()
146
+ pu_pct = result.get('pileup_pct')
147
+ cr_mhz = result.get('count_rate_mhz')
148
+ return {'fov': stem, 'status': 'OK',
149
+ 'pileup_pct': pu_pct if pu_pct is not None else '',
150
+ 'count_rate_mhz': cr_mhz if cr_mhz is not None else '',
151
+ **result.get('global_summary', {})}
152
+
153
+
154
+ def _batch_params(a):
155
+ return argparse.Namespace(
156
+ nexp=a.nexp, dist_type='discrete', dist_n_components=1, fit_t0=a.fit_t0,
157
+ tau_min=a.tau_min, tau_max=a.tau_max, optimizer=a.optimizer, restarts=a.restarts,
158
+ de_population=a.de_population, de_maxiter=a.de_maxiter, workers=a.workers,
159
+ binning=a.binning, min_photons=a.min_photons, channel=a.channel,
160
+ irf_fwhm=a.irf_fwhm, intensity_threshold=a.intensity_threshold,
161
+ correct_pileup=a.correct_pileup, machine_irf=a.machine_irf,
162
+ estimate_irf=a.estimate_irf, tvb_ptu=None, register=getattr(a, 'register_tiles', True),
163
+ reg_shift=getattr(a, 'reg_max_shift', 120), rotate_tiles=getattr(a, 'rotate_tiles', True),
164
+ tau_lo=a.tau_display_min if a.tau_display_min is not None else 0.0,
165
+ tau_hi=a.tau_display_max if a.tau_display_max is not None else 10.0,
166
+ int_max=a.intensity_display_max, tau_weighting=a.tau_weighting,
167
+ gamma=a.gamma, save_lifetime=True, save_rgb=True, save_npy=a.save_npy,
168
+ irf_align='steepest_rise', irf_shift_bins=2)
169
+
170
+
171
+ def _run_batch(items, out_dir, runner, key, csv_name, label):
172
+ out_dir = Path(out_dir)
173
+ csv_path = out_dir / csv_name
174
+ rows = []
175
+ n_total = len(items)
176
+ for idx, item in enumerate(items):
177
+ name = item.stem
178
+ item_out = out_dir / name.replace(' ', '_')
179
+ item_out.mkdir(parents=True, exist_ok=True)
180
+ print(f"\n{'='*50}\n [{idx + 1}/{n_total}] {name}\n{'='*50}")
181
+ try:
182
+ row = runner(item, item_out)
183
+ except Exception as exc:
184
+ import traceback
185
+ traceback.print_exc()
186
+ row = error_row(key, name, exc)
187
+ gc.collect()
188
+ rows.append(row)
189
+ write_rows(csv_path, rows)
190
+ print(f'\n{label} complete. CSV: {csv_path}')
191
+ return csv_path
192
+
193
+
194
+ def _run_tile_batch(a):
195
+ xlif_files = sorted(Path(a.xlif_dir).glob('*.xlif'))
196
+ if len(xlif_files) == 0:
197
+ raise ValueError(f'No .xlif files found in: {a.xlif_dir}')
198
+ out_dir = resolve_out_dir(a.ptu_dir, a.output_dir)
199
+ p = _batch_params(a)
200
+ return _run_batch(xlif_files, out_dir, lambda x, o: fitRoi(x, a.ptu_dir, o, p),
201
+ 'roi', 'batch_roi_fit_summary.csv', 'Batch')
202
+
203
+
204
+ def _run_fov_batch(a):
205
+ from .formats import supported_extensions
206
+ ptu_files = sorted(f for e in supported_extensions() for f in Path(a.fov_dir).glob('*' + e))
207
+ if len(ptu_files) == 0:
208
+ raise ValueError(f'No FLIM files found in: {a.fov_dir}')
209
+ out_dir = resolve_out_dir(a.ptu_dir, a.output_dir)
210
+ p = _batch_params(a)
211
+ return _run_batch(ptu_files, out_dir, lambda f, o: fitFov(f, o, p),
212
+ 'fov', 'batch_fov_fit_summary.csv', 'Batch FOV')
213
+
214
+
215
+ def _inquire_common(a):
216
+ import inquirer
217
+ from .interactive import yes_no_question
218
+ a.ptu_dir = input('Enter directory containing PTU files: ').strip()
219
+ if Path(a.ptu_dir).is_dir() == False:
220
+ raise ValueError(f'PTU directory not found: {a.ptu_dir}')
221
+ a.output_dir = input('Enter output directory (Enter for <ptu-dir>/save): ').strip() or None
222
+ a.estimate_irf = inquirer.prompt([inquirer.List(
223
+ 'm', message='IRF method',
224
+ choices=['machine_irf', 'machine_irf_sigma_half', 'machine_irf_sigma_full', 'parametric', 'raw'])])['m']
225
+ a.machine_irf = str(MACHINE_IRF_DEFAULT_PATH)
226
+ if a.estimate_irf.startswith('machine_irf'):
227
+ a.machine_irf = input(f'Machine IRF .npy (Enter for default: {a.machine_irf}): ').strip() or a.machine_irf
228
+ if Path(a.machine_irf).exists() == False:
229
+ print(' Warning: machine IRF file not found, falling back to parametric')
230
+ a.estimate_irf = 'parametric'
231
+ a.nexp = int(inquirer.prompt([inquirer.List(
232
+ 'n', message='Number of exponential components', choices=['1', '2', '3'], default='2')])['n'])
233
+ val = input('Min photon intensity per pixel (Enter for none): ').strip() if yes_no_question('Apply intensity threshold?') == 'y' else ''
234
+ a.intensity_threshold = int(val) if val else None
235
+ a.correct_pileup = yes_no_question('Apply pile-up correction?') == 'y'
236
+ return a
237
+
238
+
239
+ def _ask_float(label, default):
240
+ val = input(f' {label} (Enter for {default}): ').strip()
241
+ return float(val) if val else default
242
+
243
+
244
+ def _ask_int(label, default):
245
+ val = input(f' {label} (Enter for {default}): ').strip()
246
+ return int(val) if val else default
247
+
248
+
249
+ def _inquire_display(a):
250
+ import inquirer
251
+ from .interactive import yes_no_question
252
+ a.tau_weighting = 'int' if inquirer.prompt([inquirer.List(
253
+ 'w', message='Lifetime weighting for the tau image',
254
+ choices=['amplitude', 'intensity'])])['w'] == 'intensity' else 'amp'
255
+ if yes_no_question('Set lifetime display range for tau images?') == 'y':
256
+ a.tau_display_min = _ask_float('Min tau (ns)', None)
257
+ a.tau_display_max = _ask_float('Max tau (ns)', None)
258
+ if yes_no_question('Set intensity display range?') == 'y':
259
+ a.intensity_display_min = _ask_float('Min intensity (photons)', None)
260
+ a.intensity_display_max = _ask_float('Max intensity (photons)', None)
261
+ return a
262
+
263
+
264
+ def _inquire_expert(a):
265
+ import inquirer
266
+ from .interactive import yes_no_question
267
+ if yes_no_question('Set expert fit settings?') == 'n':
268
+ return a
269
+ a.tau_min = _ask_float('Min tau for fit (ns)', a.tau_min)
270
+ a.tau_max = _ask_float('Max tau for fit (ns)', a.tau_max)
271
+ a.binning = _ask_int('Binning factor', a.binning)
272
+ a.min_photons = _ask_int('Min photons per pixel', a.min_photons)
273
+ a.optimizer = inquirer.prompt([inquirer.List(
274
+ 'o', message='Optimizer', choices=['de', 'lm_multistart'], default=a.optimizer)])['o']
275
+ a.restarts = _ask_int('LM restarts', a.restarts)
276
+ a.de_population = _ask_int('DE population', a.de_population)
277
+ a.de_maxiter = _ask_int('DE max iterations', a.de_maxiter)
278
+ a.workers = _ask_int('Workers', a.workers)
279
+ a.channel = _ask_int('Channel', a.channel)
280
+ a.irf_fwhm = _ask_float('IRF FWHM (ns)', a.irf_fwhm)
281
+ return a
282
+
283
+
284
+ def tileBatchFit(interactive=False):
285
+ if interactive == True:
286
+ from .interactive import yes_no_question
287
+ a = argparse.Namespace(
288
+ tau_min=Tau_min, tau_max=Tau_max, binning=binning_factor,
289
+ min_photons=MIN_PHOTONS_PERPIX, optimizer='de', restarts=lm_restarts,
290
+ de_population=de_population, de_maxiter=de_maxiter, workers=n_workers,
291
+ channel=channels, irf_fwhm=IRF_FWHM, tau_display_min=TAU_DISPLAY_MIN,
292
+ tau_display_max=TAU_DISPLAY_MAX, reg_max_shift=120, intensity_display_min=None,
293
+ intensity_display_max=None, tau_weighting='amp', fit_t0=False, gamma=0.4, save_npy=True)
294
+ print('\nBatch tiled ROI fit: one fit per .xlif in a folder')
295
+ a.xlif_dir = input('Enter directory containing XLIF files: ').strip()
296
+ if Path(a.xlif_dir).is_dir() == False:
297
+ raise ValueError(f'XLIF directory not found: {a.xlif_dir}')
298
+ _inquire_common(a)
299
+ a.rotate_tiles = yes_no_question('Apply 90 degree clockwise rotation to tiles?') == 'y'
300
+ a.register_tiles = yes_no_question('Register tile columns by phase correlation?') == 'y'
301
+ if a.register_tiles == True:
302
+ a.reg_max_shift = _ask_int('Max registration shift (px)', a.reg_max_shift)
303
+ _inquire_display(a)
304
+ _inquire_expert(a)
305
+ else:
306
+ ap = _batch_parser('Batch per-tile FLIM fit over every .xlif in a folder', '--xlif-dir',
307
+ 'Folder of .xlif files')
308
+ ap.add_argument('--no-rotate', action='store_true')
309
+ ap.add_argument('--no-register', action='store_true')
310
+ ap.add_argument('--reg-max-shift', type=int, default=120)
311
+ a = ap.parse_args()
312
+ a.save_npy = a.no_save_npy == False
313
+ a.rotate_tiles = a.no_rotate == False
314
+ a.register_tiles = a.no_register == False
315
+ return _run_tile_batch(a)
316
+
317
+
318
+ def fovBatchFit(interactive=False):
319
+ if interactive == True:
320
+ a = argparse.Namespace(
321
+ tau_min=Tau_min, tau_max=Tau_max, binning=binning_factor,
322
+ min_photons=MIN_PHOTONS_PERPIX, optimizer='de', restarts=lm_restarts,
323
+ de_population=de_population, de_maxiter=de_maxiter, workers=n_workers,
324
+ channel=channels, irf_fwhm=IRF_FWHM, tau_display_min=TAU_DISPLAY_MIN,
325
+ tau_display_max=TAU_DISPLAY_MAX, intensity_display_min=None,
326
+ intensity_display_max=None, tau_weighting='amp', fit_t0=False, gamma=0.4, save_npy=True)
327
+ print('\nBatch single-FOV fit: one fit per FLIM file in a folder')
328
+ _inquire_common(a)
329
+ _inquire_expert(a)
330
+ a.fov_dir = a.ptu_dir
331
+ else:
332
+ ap = _batch_parser('Batch single-FOV FLIM fit over every FLIM file in a folder', '--fov-dir',
333
+ 'Folder of FLIM files', need_ptu_dir=False)
334
+ a = ap.parse_args()
335
+ a.save_npy = a.no_save_npy == False
336
+ a.ptu_dir = a.fov_dir
337
+ return _run_fov_batch(a)
@@ -44,6 +44,8 @@ def main(fast=False, cli=False, check_updates=False, no_plugins=False, plugin_pa
44
44
  'Just stitch multiple tiles together',
45
45
  'Timelapse batch fit',
46
46
  'Z-stack batch fit',
47
+ 'Batch tiled ROI fit',
48
+ 'Batch single FOV fit',
47
49
  'About',
48
50
  'Exit'
49
51
  ]
@@ -70,6 +72,12 @@ def main(fast=False, cli=False, check_updates=False, no_plugins=False, plugin_pa
70
72
  elif answers['process_option'] == 'Z-stack batch fit':
71
73
  print('Z-stack batch FLIM fitting...')
72
74
  zstack_flim_fit(interactive=True)
75
+ elif answers['process_option'] == 'Batch tiled ROI fit':
76
+ from flimkit.batch_cli import tileBatchFit
77
+ tileBatchFit(interactive=True)
78
+ elif answers['process_option'] == 'Batch single FOV fit':
79
+ from flimkit.batch_cli import fovBatchFit
80
+ fovBatchFit(interactive=True)
73
81
  elif answers['process_option'] == 'About':
74
82
  print('Current version: ' + __version__)
75
83
  try:
@@ -1504,6 +1504,7 @@ def _run_tile_fit(args, progress_callback=None, cancel_event=None, progress_wind
1504
1504
  tau_display_max = getattr(args, 'tau_display_max', None),
1505
1505
  intensity_display_min = getattr(args, 'intensity_display_min', None),
1506
1506
  intensity_display_max = getattr(args, 'intensity_display_max', None),
1507
+ tau_weighting = getattr(args, 'tau_weighting', 'amp'),
1507
1508
  field_area_um2 = tile_area_um2,
1508
1509
  )
1509
1510
  if _cancelled(cancel_event):
@@ -1521,6 +1522,7 @@ def _run_tile_fit(args, progress_callback=None, cancel_event=None, progress_wind
1521
1522
  tau_max_ns = tau_max_img,
1522
1523
  smooth_sigma_px = 2.0,
1523
1524
  verbose = True,
1525
+ tau_key = 'tau_mean_int' if getattr(args, 'tau_weighting', 'amp') == 'int' else 'tau_mean_amp',
1524
1526
  field_area_um2 = tile_area_um2,
1525
1527
  )
1526
1528
  print(f"\n{'='*60}")
@@ -14,17 +14,9 @@ def _filtered_phasor(session):
14
14
  method = spec.get('method') or 'none'
15
15
  if method == 'none':
16
16
  return real, imag, mean
17
- from flimkit.phasor.filters import phasor_filter
18
- kwargs = {}
19
- if method == 'gaussian':
20
- kwargs['sigma'] = float(spec.get('sigma', 1.0))
21
- elif method == 'median':
22
- kwargs['size'] = int(spec.get('size', 3))
23
- elif method != 'wavelet':
24
- kwargs['sigma'] = float(spec.get('sigma', 1.0))
25
- kwargs['size'] = int(spec.get('size', 3))
17
+ from flimkit.phasor.filters import filter_kwargs, phasor_filter
26
18
  try:
27
- real, imag = phasor_filter(real.copy(), imag.copy(), method, mean=mean, **kwargs)
19
+ real, imag = phasor_filter(real.copy(), imag.copy(), method, mean=mean, **filter_kwargs(spec))
28
20
  except Exception as exc:
29
21
  print(f'[Phasor Export] Could not re-apply the saved {method} filter, plotting unfiltered: {exc}')
30
22
  return real, imag, mean
@@ -55,6 +55,23 @@ def phasor_filter(
55
55
  )
56
56
 
57
57
 
58
+ WAVELET_NAMES = ('db4', 'db2', 'db8', 'haar', 'sym4', 'coif1')
59
+ THRESHOLD_MODES = ('soft', 'hard')
60
+
61
+
62
+ def filter_kwargs(spec):
63
+ method = spec.get('method')
64
+ if method == 'gaussian':
65
+ return dict(sigma=float(spec.get('sigma', 1.0)))
66
+ if method == 'median':
67
+ return dict(size=int(spec.get('size', 3)))
68
+ if method == 'wavelet':
69
+ return dict(wavelet=str(spec.get('wavelet', 'db4')),
70
+ level=int(spec.get('level', 1)),
71
+ threshold_mode=str(spec.get('threshold_mode', 'soft')))
72
+ return dict(sigma=float(spec.get('sigma', 1.0)), size=int(spec.get('size', 3)))
73
+
74
+
58
75
  def phasor_filter_methods():
59
76
  from flimkit.plugins import registry
60
77
  return ['gaussian', 'median', 'wavelet'] + [f.id for f in registry.phasor_filters()]
@@ -72,6 +72,9 @@ def save_session(path, *,
72
72
  filter_method=np.array(str(filt.get('method') or 'none')),
73
73
  filter_sigma=np.float64(filt.get('sigma', 1.0)),
74
74
  filter_size=np.int64(filt.get('size', 3)),
75
+ filter_wavelet=np.array(str(filt.get('wavelet', 'db4'))),
76
+ filter_level=np.int64(filt.get('level', 1)),
77
+ filter_threshold=np.array(str(filt.get('threshold_mode', 'soft'))),
75
78
  ptu_file=np.array(ptu_file or ''),
76
79
  irf_file=np.array(irf_file or ''),
77
80
  )
@@ -112,6 +115,9 @@ def load_session(path):
112
115
  method=str(d['filter_method']) if 'filter_method' in d else 'none',
113
116
  sigma=float(d['filter_sigma']) if 'filter_sigma' in d else 1.0,
114
117
  size=int(d['filter_size']) if 'filter_size' in d else 3,
118
+ wavelet=str(d['filter_wavelet']) if 'filter_wavelet' in d else 'db4',
119
+ level=int(d['filter_level']) if 'filter_level' in d else 1,
120
+ threshold_mode=str(d['filter_threshold']) if 'filter_threshold' in d else 'soft',
115
121
  )
116
122
  return dict(
117
123
  real_cal=d['real_cal'],
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: flimkit
3
- Version: 0.14.2
3
+ Version: 0.14.3
4
4
  Summary: Fluorescence lifetime imaging analysis: reading, fitting, phasors and stitching
5
5
  Author-email: Alex Hunt <alexander.hunt@ed.ac.uk>
6
6
  License-Expression: MIT
@@ -3,6 +3,7 @@ README.md
3
3
  pyproject.toml
4
4
  flimkit/__init__.py
5
5
  flimkit/_version.py
6
+ flimkit/batch_cli.py
6
7
  flimkit/cli.py
7
8
  flimkit/configs.py
8
9
  flimkit/dialogs.py
@@ -99,5 +99,4 @@ exclude = ['flimkit_tests*']
99
99
  namespaces = true
100
100
 
101
101
  [tool.setuptools.package-data]
102
- 'flimkit.machine_irf' = ['*.csv', '*.npy', '*.json']
103
102
  'flimkit.UI' = ['*.png', '*.ico', '*.icns']
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes