flimkit 0.15.0__tar.gz → 0.15.1__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 (121) hide show
  1. {flimkit-0.15.0 → flimkit-0.15.1}/PKG-INFO +2 -2
  2. {flimkit-0.15.0 → flimkit-0.15.1}/README.md +1 -1
  3. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/FLIM/fitters.py +23 -11
  4. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/GPU/_base.py +19 -1
  5. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/GPU/mlx_backend.py +11 -10
  6. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/GPU/torch_backend.py +11 -9
  7. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/UI/fov_preview.py +4 -6
  8. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/UI/gui.py +27 -58
  9. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/UI/phasor_panel.py +4 -0
  10. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/UI/project_panel.py +0 -1
  11. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/UI/roi_tools.py +4 -0
  12. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/UI/utils.py +2 -0
  13. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/_version.py +3 -2
  14. flimkit-0.15.1/flimkit/formats/ICS/__init__.py +1 -0
  15. flimkit-0.15.1/flimkit/formats/ICS/reader.py +266 -0
  16. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/formats/PTU/stitch.py +4 -0
  17. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/formats/flim_file.py +14 -0
  18. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/interactive.py +35 -116
  19. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/project.py +9 -6
  20. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/utils/apply_settings.py +1 -1
  21. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/utils/config_manager.py +6 -10
  22. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/utils/session.py +18 -6
  23. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit.egg-info/PKG-INFO +2 -2
  24. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit.egg-info/SOURCES.txt +2 -0
  25. {flimkit-0.15.0 → flimkit-0.15.1}/LICENSE.md +0 -0
  26. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/FLIM/__init__.py +0 -0
  27. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/FLIM/assemble.py +0 -0
  28. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/FLIM/batch.py +0 -0
  29. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/FLIM/bg_tools.py +0 -0
  30. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/FLIM/fit_tools.py +0 -0
  31. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/FLIM/irf_tools.py +0 -0
  32. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/FLIM/models.py +0 -0
  33. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/FLIM/nb_freetau.py +0 -0
  34. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/FLIM/nb_freetau_cuda.py +0 -0
  35. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/FLIM/poisson_fit.py +0 -0
  36. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/GPU/__init__.py +0 -0
  37. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/GPU/cuda.py +0 -0
  38. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/GPU/mps.py +0 -0
  39. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/GPU/rocm.py +0 -0
  40. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/GPU/torch_lm.py +0 -0
  41. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/UI/app_state.py +0 -0
  42. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/UI/controller.py +0 -0
  43. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/UI/expert_settings.py +0 -0
  44. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/UI/fit_help.py +0 -0
  45. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/UI/icon.icns +0 -0
  46. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/UI/icon.ico +0 -0
  47. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/UI/icon.png +0 -0
  48. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/UI/irf_widget.py +0 -0
  49. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/UI/mode_controller.py +0 -0
  50. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/UI/modes/__init__.py +0 -0
  51. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/UI/modes/base.py +0 -0
  52. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/UI/modes/batch_mode.py +0 -0
  53. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/UI/modes/fov_mode.py +0 -0
  54. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/UI/modes/irf_mode.py +0 -0
  55. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/UI/modes/phasor_mode.py +0 -0
  56. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/UI/modes/stitch_mode.py +0 -0
  57. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/UI/progress_window.py +0 -0
  58. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/UI/results_panel.py +0 -0
  59. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/__init__.py +0 -0
  60. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/batch_cli.py +0 -0
  61. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/cli.py +0 -0
  62. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/configs.py +0 -0
  63. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/dialogs.py +0 -0
  64. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/formats/BH/__init__.py +0 -0
  65. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/formats/BH/reader.py +0 -0
  66. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/formats/BH/writer.py +0 -0
  67. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/formats/ISS/__init__.py +0 -0
  68. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/formats/ISS/fdflim.py +0 -0
  69. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/formats/ISS/image.py +0 -0
  70. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/formats/ISS/reader.py +0 -0
  71. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/formats/PS/__init__.py +0 -0
  72. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/formats/PS/reader.py +0 -0
  73. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/formats/PTU/__init__.py +0 -0
  74. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/formats/PTU/decode.py +0 -0
  75. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/formats/PTU/phu.py +0 -0
  76. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/formats/PTU/reader.py +0 -0
  77. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/formats/PTU/series.py +0 -0
  78. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/formats/PTU/tools.py +0 -0
  79. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/formats/__init__.py +0 -0
  80. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/formats/phasor.py +0 -0
  81. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/formats/signal.py +0 -0
  82. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/image/tools.py +0 -0
  83. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/mpl_backend.py +0 -0
  84. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/phasor/__init__.py +0 -0
  85. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/phasor/export.py +0 -0
  86. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/phasor/filters.py +0 -0
  87. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/phasor/fret.py +0 -0
  88. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/phasor/interactive.py +0 -0
  89. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/phasor/peaks.py +0 -0
  90. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/phasor/signal.py +0 -0
  91. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/phasor_launcher.py +0 -0
  92. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/plugins/__init__.py +0 -0
  93. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/plugins/bindings.py +0 -0
  94. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/plugins/builtin/__init__.py +0 -0
  95. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/plugins/builtin/core_tools.py +0 -0
  96. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/plugins/loader.py +0 -0
  97. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/plugins/registry.py +0 -0
  98. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/synth.py +0 -0
  99. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/utils/__init__.py +0 -0
  100. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/utils/app_update.py +0 -0
  101. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/utils/batch_fit.py +0 -0
  102. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/utils/config_snapshot.py +0 -0
  103. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/utils/crash_handler.py +0 -0
  104. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/utils/display.py +0 -0
  105. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/utils/enhanced_outputs.py +0 -0
  106. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/utils/export_png.py +0 -0
  107. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/utils/fancy.py +0 -0
  108. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/utils/lifetime_image.py +0 -0
  109. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/utils/misc.py +0 -0
  110. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/utils/ome_zarr.py +0 -0
  111. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/utils/plotting.py +0 -0
  112. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/utils/roi.py +0 -0
  113. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/utils/update_check.py +0 -0
  114. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/utils/xlsx_tools.py +0 -0
  115. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit/utils/xml_utils.py +0 -0
  116. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit.egg-info/dependency_links.txt +0 -0
  117. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit.egg-info/entry_points.txt +0 -0
  118. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit.egg-info/requires.txt +0 -0
  119. {flimkit-0.15.0 → flimkit-0.15.1}/flimkit.egg-info/top_level.txt +0 -0
  120. {flimkit-0.15.0 → flimkit-0.15.1}/pyproject.toml +0 -0
  121. {flimkit-0.15.0 → flimkit-0.15.1}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: flimkit
3
- Version: 0.15.0
3
+ Version: 0.15.1
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
@@ -168,7 +168,7 @@ docker run -d \
168
168
  alex1075/flimkit:latest
169
169
  ```
170
170
 
171
- Then open http://localhost:14500 and log in as `flimkit` with that password.
171
+ Then open http://localhost:14500 and log in as `flimkit` with that password. The image won't start without a password.
172
172
 
173
173
  The images are built in [flimkit-docker](https://github.com/FLIMKit/flimkit-docker), which lists the tags (Cellpose, CUDA, ROCm, the noVNC desktop and the headless bridge images), the settings, the compose file for a TrueNAS SCALE custom app, and how to build one yourself.
174
174
 
@@ -104,7 +104,7 @@ docker run -d \
104
104
  alex1075/flimkit:latest
105
105
  ```
106
106
 
107
- Then open http://localhost:14500 and log in as `flimkit` with that password.
107
+ Then open http://localhost:14500 and log in as `flimkit` with that password. The image won't start without a password.
108
108
 
109
109
  The images are built in [flimkit-docker](https://github.com/FLIMKit/flimkit-docker), which lists the tags (Cellpose, CUDA, ROCm, the noVNC desktop and the headless bridge images), the settings, the compose file for a TrueNAS SCALE custom app, and how to build one yourself.
110
110
 
@@ -1501,6 +1501,14 @@ def fit_summed_dist(decay, tcspc_res, n_bins, irf_prompt,
1501
1501
  r = np.sqrt(2.0 * dev)
1502
1502
  r[m < n] *= -1
1503
1503
  return r
1504
+ unit = np.ones(len(lo))
1505
+ unit[:2 * n_components] = TAU_FIT_UNIT_S
1506
+ lo_u, hi_u = np.asarray(lo) / unit, np.asarray(hi) / unit
1507
+ def lm_in_ns(p0, **kw):
1508
+ res = least_squares(lambda q: residuals(q * unit), np.asarray(p0) / unit,
1509
+ bounds=(lo_u, hi_u), method='trf', **kw)
1510
+ res.x = res.x * unit
1511
+ return res
1504
1512
  if optimizer == 'lm_multistart':
1505
1513
  rng = np.random.default_rng(42)
1506
1514
  best_res = None
@@ -1518,8 +1526,7 @@ def fit_summed_dist(decay, tcspc_res, n_bins, irf_prompt,
1518
1526
  fit_tvb=fit_tvb, tvb_init=tvb_init)
1519
1527
  p0[:n_components] = tau_ov
1520
1528
  try:
1521
- res = least_squares(residuals, p0, bounds=(lo, hi), method='trf',
1522
- max_nfev=50000, ftol=1e-13, xtol=1e-13, gtol=1e-13)
1529
+ res = lm_in_ns(p0, max_nfev=50000, ftol=1e-13, xtol=1e-13, gtol=1e-13)
1523
1530
  except Exception as exc:
1524
1531
  print(f' Restart {i:2d}: failed ({exc})')
1525
1532
  continue
@@ -1570,8 +1577,7 @@ def fit_summed_dist(decay, tcspc_res, n_bins, irf_prompt,
1570
1577
  eps = 1e-10
1571
1578
  popt_work = np.clip(popt_work, np.asarray(lo) + eps, np.asarray(hi) - eps)
1572
1579
  try:
1573
- pol = least_squares(residuals, popt_work, bounds=(lo, hi), method='trf',
1574
- max_nfev=5000, ftol=1e-13, xtol=1e-13, gtol=1e-13)
1580
+ pol = lm_in_ns(popt_work, max_nfev=5000, ftol=1e-13, xtol=1e-13, gtol=1e-13)
1575
1581
  popt_work = pol.x
1576
1582
  message += f'; polished cost={pol.cost:.4e}'
1577
1583
  except ValueError as e:
@@ -1880,17 +1886,18 @@ def fit_per_pixel_dist(stack, tcspc_res, n_bins, irf_prompt,
1880
1886
  w_hi_s = widths_g.max() * 5.0
1881
1887
  fit_stack_max = float(stack[..., fit_idx].max())
1882
1888
  amp_hi = fit_stack_max * 10.0
1883
- lo_px = np.array([tau_lo_s] * n_components + [w_lo_s] * n_components + [0.0] * n_components)
1884
- hi_px = np.array([tau_hi_s] * n_components + [w_hi_s] * n_components + [amp_hi] * n_components)
1889
+ unit_px = np.r_[np.full(2 * n_components, TAU_FIT_UNIT_S), np.ones(n_components)]
1890
+ lo_px = np.array([tau_lo_s] * n_components + [w_lo_s] * n_components + [0.0] * n_components) / unit_px
1891
+ hi_px = np.array([tau_hi_s] * n_components + [w_hi_s] * n_components + [amp_hi] * n_components) / unit_px
1885
1892
  p0_px = np.concatenate([tau_centers_g, widths_g,
1886
- np.full(n_components, fit_stack_max / n_components)])
1893
+ np.full(n_components, fit_stack_max / n_components)]) / unit_px
1887
1894
  def _fit_pixel_dist(flat_idx):
1888
1895
  d = flat[flat_idx].astype(np.float64)
1889
1896
  d_fit = d[fit_idx]
1890
1897
  bg = _ebg(d, int(np.argmax(d)))
1891
- wt_fit = np.sqrt(np.maximum(d_fit, 1.0))
1898
+ pos = d_fit > 0
1892
1899
  def _resid(p):
1893
- full_p = np.concatenate([p, [shift]])
1900
+ full_p = np.concatenate([p * unit_px, [shift]])
1894
1901
  if fit_sigma:
1895
1902
  full_p = np.concatenate([full_p, [sigma]])
1896
1903
  if fit_bg:
@@ -1898,12 +1905,17 @@ def fit_per_pixel_dist(stack, tcspc_res, n_bins, irf_prompt,
1898
1905
  m = dist_reconvolution_model(
1899
1906
  full_p, tcspc_res, n_bins, irf_prompt,
1900
1907
  n_components, dist_type, bg, False, False, rep_period_s=rep_period_s)
1901
- return (m[fit_idx] - d_fit) / wt_fit
1908
+ m = np.maximum(m[fit_idx], 1e-10)
1909
+ dev = m - d_fit
1910
+ dev[pos] += d_fit[pos] * np.log(d_fit[pos] / m[pos])
1911
+ r = np.sqrt(2.0 * np.maximum(dev, 0.0))
1912
+ r[m < d_fit] *= -1
1913
+ return r
1902
1914
  try:
1903
1915
  res = least_squares(_resid, p0_px, bounds=(lo_px, hi_px),
1904
1916
  method='trf', max_nfev=500,
1905
1917
  ftol=1e-8, xtol=1e-8, gtol=1e-8)
1906
- return res.x
1918
+ return res.x * unit_px
1907
1919
  except Exception:
1908
1920
  return None
1909
1921
  n_workers = min(ny * nx, max(1, multiprocessing.cpu_count()))
@@ -4,6 +4,25 @@ from ..FLIM.fit_tools import (TAU_FIT_UNIT_S, calibrated_chi2,
4
4
  calibrated_from_terms, chi2_terms)
5
5
  from ..FLIM.models import reconvolution_model
6
6
 
7
+ def subset_solvers(A):
8
+ A = np.asarray(A, dtype=np.float64)
9
+ n_bins, n_cols = A.shape
10
+ masks = [tuple(i for i in range(n_cols) if m & (1 << i)) for m in range(1, 1 << n_cols)]
11
+ solvers = np.zeros((len(masks), n_cols, n_bins))
12
+ for k, cols in enumerate(masks):
13
+ solvers[k, cols, :] = np.linalg.pinv(A[:, cols])
14
+ return solvers.reshape(len(masks) * n_cols, n_bins), A.T @ A
15
+
16
+ def pick_nnls(c, gram):
17
+ n_cols = gram.shape[0]
18
+ c = np.asarray(c, dtype=np.float64).reshape(c.shape[0], -1, n_cols)
19
+ val = np.einsum('psi,psi->ps', c @ gram, c)
20
+ val = np.where(np.all(c >= 0.0, axis=2), val, -np.inf)
21
+ best = np.argmax(val, axis=1)
22
+ rows = np.arange(c.shape[0])
23
+ out = c[rows, best]
24
+ return np.where((val[rows, best] > 0.0)[:, None], out, 0.0)
25
+
7
26
  def fit_window(fit_idx, n_bins):
8
27
  if fit_idx is None:
9
28
  return None
@@ -345,7 +364,6 @@ class _BackendMixin:
345
364
  full_p, tcspc_res, n_bins, irf_array,
346
365
  n_exp, bg_b, False, False, False,
347
366
  n_sync=n_sync_model)
348
- # Poisson deviance residuals (sum of squares = 2 * Poisson negative log-likelihood ratio)
349
367
  m_ = model if win is None else model[win]
350
368
  d_ = decay_b if win is None else decay_b[win]
351
369
  m_ = np.maximum(m_, 1e-12)
@@ -1,5 +1,5 @@
1
1
  import numpy as np
2
- from flimkit.GPU._base import _BackendMixin, fit_window, pixel_blocks
2
+ from flimkit.GPU._base import _BackendMixin, fit_window, pixel_blocks, pick_nnls, subset_solvers
3
3
  from flimkit.FLIM.fit_tools import (calibrated_chi2, distribution_dof,
4
4
  estimate_bg, coates_pileup_correction)
5
5
 
@@ -49,11 +49,16 @@ class MLXBackend(_BackendMixin):
49
49
  B_col = B_col if win is None else B_col[win]
50
50
  A_aug = np.column_stack(
51
51
  [A, B_col, np.ones(A.shape[0], dtype=np.float32)]).astype(np.float32)
52
- A_pinv_mx = mx.linalg.pinv(mx.array(A_aug), stream=mx.cpu)
52
+ flat, gram = subset_solvers(A_aug)
53
53
  else:
54
- A_pinv_mx = mx.linalg.pinv(mx.array(A.astype(np.float32)), stream=mx.cpu)
54
+ flat, gram = subset_solvers(A)
55
+ solvers_mx = mx.array(flat.T.astype(np.float32))
56
+ def nnls(data):
57
+ c_mx = mx.array(data) @ solvers_mx
58
+ mx.eval(c_mx)
59
+ return pick_nnls(np.array(c_mx), gram)
55
60
  n_fit = A.shape[0]
56
- for first, last in pixel_blocks(valid_idx.size, 4 * (2 * n_bins + n_fit + n_exp),
61
+ for first, last in pixel_blocks(valid_idx.size, 4 * (2 * n_bins + n_fit + flat.shape[0]),
57
62
  budget=self.block_bytes()):
58
63
  block = valid_idx[first:last]
59
64
  decay = raw[block].astype(np.float32)
@@ -63,9 +68,7 @@ class MLXBackend(_BackendMixin):
63
68
  if correct_pileup and n_sync_px > 0:
64
69
  for row in range(data_in.shape[0]):
65
70
  data_in[row] = coates_pileup_correction(data_in[row], n_sync_px)
66
- coeffs_mx = mx.maximum(mx.array(data_in) @ A_pinv_mx.T, 0.0)
67
- mx.eval(coeffs_mx)
68
- coeffs = np.array(coeffs_mx)
71
+ coeffs = nnls(data_in)
69
72
  amps = coeffs[:, :n_exp]
70
73
  tvb = coeffs[:, n_exp]
71
74
  bg = coeffs[:, n_exp + 1]
@@ -77,9 +80,7 @@ class MLXBackend(_BackendMixin):
77
80
  if correct_pileup and n_sync_px > 0:
78
81
  for row in range(corrected.shape[0]):
79
82
  corrected[row] = coates_pileup_correction(corrected[row], n_sync_px)
80
- amps_mx = mx.maximum(mx.array(corrected) @ A_pinv_mx.T, 0.0)
81
- mx.eval(amps_mx)
82
- amps = np.array(amps_mx)
83
+ amps = nnls(corrected)
83
84
  tvb = None
84
85
  decay_fit = decay if win is None else decay[:, win]
85
86
  self._scatter_fixed_tau(
@@ -1,7 +1,7 @@
1
1
  import threading
2
2
 
3
3
  import numpy as np
4
- from flimkit.GPU._base import (_BackendMixin, fit_window, pixel_blocks,
4
+ from flimkit.GPU._base import (_BackendMixin, fit_window, pixel_blocks, pick_nnls, subset_solvers,
5
5
  gpu_block_bytes, CUDA_BLOCK_BYTES)
6
6
  from flimkit.FLIM.fit_tools import (TAU_FIT_UNIT_S, calibrated_chi2,
7
7
  calibrated_from_terms, distribution_dof,
@@ -152,17 +152,19 @@ class TorchBackend(_BackendMixin):
152
152
  B_col = B_col if win is None else B_col[win]
153
153
  A_aug = np.column_stack(
154
154
  [A, B_col, np.ones(A.shape[0], dtype=np.float32)]).astype(np.float32)
155
- A_pinv = torch.linalg.pinv(torch.as_tensor(A_aug, device='cpu')).to(self.device)
155
+ flat, gram = subset_solvers(A_aug)
156
156
  else:
157
- A_cpu = torch.as_tensor(A, dtype=torch.float32, device='cpu')
158
- A_pinv = torch.linalg.pinv(A_cpu).to(self.device)
157
+ flat, gram = subset_solvers(A)
158
+ solvers_t = torch.as_tensor(flat.astype(np.float32), device=self.device)
159
+ def nnls(data_t):
160
+ return pick_nnls(self._matmul_full_precision(data_t, solvers_t.T).cpu().numpy(), gram)
159
161
  n_fit = A.shape[0]
160
162
  on_device = (not with_tvb and not (correct_pileup and n_sync_px > 0)
161
163
  and self.device.type == 'cuda')
162
164
  if on_device:
163
165
  A_exact = torch.as_tensor(A, dtype=torch.float64, device=self.device)
164
166
  win_t = None if win is None else torch.as_tensor(win, device=self.device)
165
- for first, last in pixel_blocks(valid_idx.size, 4 * (2 * n_bins + n_fit + n_exp),
167
+ for first, last in pixel_blocks(valid_idx.size, 4 * (2 * n_bins + n_fit + flat.shape[0]),
166
168
  budget=self.block_bytes()):
167
169
  block = valid_idx[first:last]
168
170
  decay = raw[block].astype(np.float32)
@@ -175,8 +177,8 @@ class TorchBackend(_BackendMixin):
175
177
  if win_t is not None:
176
178
  corr_t = corr_t[:, win_t]
177
179
  decay_t = decay_t[:, win_t]
178
- amps_t = torch.clamp(corr_t @ A_pinv.T, min=0.0)
179
- amps = amps_t.cpu().numpy()
180
+ amps = nnls(corr_t)
181
+ amps_t = torch.as_tensor(amps.astype(np.float32), device=self.device)
180
182
  tvb = None
181
183
  decay_fit = None
182
184
  chi2_parts = self._chi2_terms_device(decay_t, amps_t, A_exact, bg_t)
@@ -186,7 +188,7 @@ class TorchBackend(_BackendMixin):
186
188
  for row in range(data_in.shape[0]):
187
189
  data_in[row] = coates_pileup_correction(data_in[row], n_sync_px)
188
190
  data_t = torch.as_tensor(data_in, dtype=torch.float32, device=self.device)
189
- coeffs = torch.clamp(data_t @ A_pinv.T, min=0.0).cpu().numpy()
191
+ coeffs = nnls(data_t)
190
192
  amps = coeffs[:, :n_exp]
191
193
  tvb = coeffs[:, n_exp]
192
194
  bg = coeffs[:, n_exp + 1]
@@ -199,7 +201,7 @@ class TorchBackend(_BackendMixin):
199
201
  for row in range(corrected.shape[0]):
200
202
  corrected[row] = coates_pileup_correction(corrected[row], n_sync_px)
201
203
  data_t = torch.as_tensor(corrected, dtype=torch.float32, device=self.device)
202
- amps = torch.clamp(data_t @ A_pinv.T, min=0.0).cpu().numpy()
204
+ amps = nnls(data_t)
203
205
  tvb = None
204
206
  decay_fit = decay if win is None else decay[:, win]
205
207
  self._scatter_fixed_tau(
@@ -765,9 +765,8 @@ class FOVPreviewPanel:
765
765
  session_file = ptu_path.parent / f'{ptu_path.stem}.roi_session.npz'
766
766
  if not session_file.exists():
767
767
  return
768
- existing_data = np.load(session_file, allow_pickle=True)
769
- session_data = {key: existing_data[key].item() if existing_data[key].ndim == 0 else existing_data[key]
770
- for key in existing_data.files}
768
+ from flimkit.utils.session import load_session_npz
769
+ session_data = {k: v.item() if v.ndim == 0 else v for k, v in load_session_npz(session_file).items()}
771
770
  session_data['fov_color_scale'] = json.dumps(self._flim_color_scale)
772
771
  session_data['fov_intensity_scale'] = json.dumps(self._int_display)
773
772
  np.savez_compressed(session_file, **session_data)
@@ -785,9 +784,8 @@ class FOVPreviewPanel:
785
784
  ptu_path = Path(self._ptu_path)
786
785
  session_file = ptu_path.parent / f'{ptu_path.stem}.roi_session.npz'
787
786
  if session_file.exists():
788
- existing_data = np.load(session_file, allow_pickle=True)
789
- session_data = {key: existing_data[key].item() if existing_data[key].ndim == 0 else existing_data[key]
790
- for key in existing_data.files}
787
+ from flimkit.utils.session import load_session_npz
788
+ session_data = {k: v.item() if v.ndim == 0 else v for k, v in load_session_npz(session_file).items()}
791
789
  else:
792
790
  session_data = {
793
791
  'timestamp': datetime.now().isoformat(),
@@ -51,6 +51,8 @@ from flimkit.UI.utils import (
51
51
  _C,
52
52
  _reconstruct_dict_from_session,
53
53
  _parse_summary,
54
+ load_session_npz,
55
+ plain_array,
54
56
  _Redirect,
55
57
  _FileRedirect,
56
58
  _FileTailer,
@@ -1471,14 +1473,14 @@ Anthropic's Claude AI assisted with parts of the GUI implementation.
1471
1473
  pass
1472
1474
  elif val is not None and not callable(val):
1473
1475
  try:
1474
- session_data[key] = val
1476
+ session_data[key] = plain_array(val)
1475
1477
  except Exception:
1476
1478
  pass
1477
1479
  if summary_rows:
1478
1480
  params, values, units = zip(*summary_rows)
1479
- session_data['summary_params'] = np.array(params, dtype=object)
1480
- session_data['summary_values'] = np.array(values, dtype=object)
1481
- session_data['summary_units'] = np.array(units, dtype=object)
1481
+ session_data['summary_params'] = plain_array(np.array(params, dtype=object))
1482
+ session_data['summary_values'] = plain_array(np.array(values, dtype=object))
1483
+ session_data['summary_units'] = plain_array(np.array(units, dtype=object))
1482
1484
  if self._fov_preview._ptu_path:
1483
1485
  session_data['fov_ptu_path'] = self._fov_preview._ptu_path
1484
1486
  if self._fov_preview._lifetime_map is not None:
@@ -1501,9 +1503,9 @@ Anthropic's Claude AI assisted with parts of the GUI implementation.
1501
1503
  def _load_roi_session(self, session_path: str) -> dict:
1502
1504
  try:
1503
1505
  import numpy as np
1504
- data = np.load(session_path, allow_pickle=True)
1506
+ data = load_session_npz(session_path)
1505
1507
  loaded = {}
1506
- for key in data.files:
1508
+ for key in data:
1507
1509
  val = data[key]
1508
1510
  if isinstance(val, np.ndarray):
1509
1511
  if val.ndim == 0:
@@ -1546,24 +1548,7 @@ Anthropic's Claude AI assisted with parts of the GUI implementation.
1546
1548
  import traceback
1547
1549
  traceback.print_exc()
1548
1550
  try:
1549
- params = session_data.get('summary_params', [])
1550
- values = session_data.get('summary_values', [])
1551
- units = session_data.get('summary_units', [])
1552
- if isinstance(params, np.ndarray):
1553
- params = params.tolist()
1554
- if isinstance(values, np.ndarray):
1555
- values = values.tolist()
1556
- if isinstance(units, np.ndarray):
1557
- units = units.tolist()
1558
- rows = []
1559
- for param, val, unit in zip(params, values, units):
1560
- if isinstance(param, bytes):
1561
- param = param.decode('utf-8')
1562
- if isinstance(val, bytes):
1563
- val = val.decode('utf-8')
1564
- if isinstance(unit, bytes):
1565
- unit = unit.decode('utf-8')
1566
- rows.append((str(param), str(val), str(unit)))
1551
+ rows = self._summary_rows_from_session(session_data)
1567
1552
  if rows:
1568
1553
  self._res.populate_summary(rows)
1569
1554
  if 'fov_regions' in session_data:
@@ -1696,8 +1681,7 @@ Anthropic's Claude AI assisted with parts of the GUI implementation.
1696
1681
  if not session_file.exists():
1697
1682
  return
1698
1683
  print(f'[Auto-Load] Found tile session: {session_file.name}')
1699
- session_data = np.load(session_file, allow_pickle=True)
1700
- loaded = {key: session_data[key] for key in session_data.files}
1684
+ loaded = load_session_npz(session_file)
1701
1685
  if 'form_state_json' in loaded:
1702
1686
  try:
1703
1687
  form_state_str = loaded['form_state_json']
@@ -1709,24 +1693,9 @@ Anthropic's Claude AI assisted with parts of the GUI implementation.
1709
1693
  self._restore_form_state(form_state)
1710
1694
  except Exception as e:
1711
1695
  print(f'[Auto-Load] Could not restore form state: {e}')
1712
- if 'summary_params' in loaded:
1713
- params = loaded['summary_params']
1714
- values = loaded['summary_values']
1715
- units = loaded['summary_units']
1716
- if isinstance(params, np.ndarray):
1717
- params = params.tolist()
1718
- if isinstance(values, np.ndarray):
1719
- values = values.tolist()
1720
- if isinstance(units, np.ndarray):
1721
- units = units.tolist()
1722
- rows = []
1723
- for p, v, u in zip(params, values, units):
1724
- if isinstance(p, bytes): p = p.decode('utf-8')
1725
- if isinstance(v, bytes): v = v.decode('utf-8')
1726
- if isinstance(u, bytes): u = u.decode('utf-8')
1727
- rows.append((str(p), str(v), str(u)))
1728
- if rows:
1729
- self._res.populate_summary(rows)
1696
+ rows = self._summary_rows_from_session(loaded)
1697
+ if rows:
1698
+ self._res.populate_summary(rows)
1730
1699
  if 'fov_color_scale' in loaded:
1731
1700
  try:
1732
1701
  cs = loaded['fov_color_scale']
@@ -1785,9 +1754,9 @@ Anthropic's Claude AI assisted with parts of the GUI implementation.
1785
1754
  def load_roi_fit(self, npz_path: str) -> dict:
1786
1755
  try:
1787
1756
  import numpy as np
1788
- data = np.load(npz_path, allow_pickle=True)
1757
+ data = load_session_npz(npz_path)
1789
1758
  loaded = {}
1790
- for key in data.files:
1759
+ for key in data:
1791
1760
  val = data[key]
1792
1761
  if hasattr(val, 'dtype') and val.dtype == object:
1793
1762
  val = val.tolist()
@@ -1860,18 +1829,7 @@ Anthropic's Claude AI assisted with parts of the GUI implementation.
1860
1829
  if not suppress_popups:
1861
1830
  messagebox.showerror('Load Error', f'Failed to load fitted data from:\n{npz_path}')
1862
1831
  return
1863
- params = fit_result.get('summary_params', [])
1864
- values = fit_result.get('summary_values', [])
1865
- units = fit_result.get('summary_units', [])
1866
- rows = []
1867
- if isinstance(params, np.ndarray): params = params.tolist()
1868
- if isinstance(values, np.ndarray): values = values.tolist()
1869
- if isinstance(units, np.ndarray): units = units.tolist()
1870
- for param, val, unit in zip(params, values, units):
1871
- if isinstance(param, bytes): param = param.decode('utf-8')
1872
- if isinstance(val, bytes): val = val.decode('utf-8')
1873
- if isinstance(unit, bytes): unit = unit.decode('utf-8')
1874
- rows.append((str(param), str(val), str(unit)))
1832
+ rows = self._summary_rows_from_session(fit_result)
1875
1833
  try:
1876
1834
  if rows:
1877
1835
  self._res.populate_summary(rows)
@@ -3238,6 +3196,9 @@ Anthropic's Claude AI assisted with parts of the GUI implementation.
3238
3196
  params['rep_period_ns'] = expert['rep_period_ns']
3239
3197
  if 'channels' in expert:
3240
3198
  params['channel'] = expert['channels']
3199
+ for key in ('fit_start_ns', 'fit_end_ns', 'exclude_ns'):
3200
+ if key in expert:
3201
+ params[key] = expert[key] or None
3241
3202
  return params
3242
3203
 
3243
3204
  def _on_fov_analysis_changed(self):
@@ -4393,6 +4354,14 @@ Anthropic's Claude AI assisted with parts of the GUI implementation.
4393
4354
  if stem:
4394
4355
  self._proj_browser.on_fit_done(stem, output_prefix=prefix)
4395
4356
 
4357
+ def _summary_rows_from_session(self, data):
4358
+ saved = [data.get(k) for k in ('summary_params', 'summary_values', 'summary_units')]
4359
+ if any(v is None for v in saved):
4360
+ return self._extract_summary_rows(_reconstruct_dict_from_session(data, 'global_summary'),
4361
+ data.get('global_popt'))
4362
+ return [tuple(x.decode('utf-8') if isinstance(x, bytes) else str(x) for x in row)
4363
+ for row in zip(*(np.asarray(v).tolist() for v in saved))]
4364
+
4396
4365
  def _extract_summary_rows(self, global_summary: dict, global_popt=None) -> list:
4397
4366
  if not global_summary:
4398
4367
  return []
@@ -915,6 +915,7 @@ class PhasorViewPanel:
915
915
  from flimkit.formats import FLIMFile
916
916
  from flimkit.FLIM.fitters import fit_summed
917
917
  from flimkit.FLIM.fit_tools import resolve_rep_period_ns
918
+ from flimkit.interactive import parse_exclude_ns
918
919
  ptu = FLIMFile(ptu_path, verbose=False)
919
920
  n_bins = ptu.n_bins
920
921
  tcspc_res = ptu.tcspc_res
@@ -962,6 +963,9 @@ class PhasorViewPanel:
962
963
  n_starts = params.get('n_starts'),
963
964
  rep_period_ns = resolve_rep_period_ns(params.get('rep_period_ns'), ptu),
964
965
  fixed_taus_ns = params.get('fixed_taus_ns'),
966
+ fit_start_ns = params.get('fit_start_ns'),
967
+ fit_end_ns = params.get('fit_end_ns'),
968
+ exclude_ns = parse_exclude_ns(params.get('exclude_ns')),
965
969
  )
966
970
  if progress_callback:
967
971
  progress_callback(4, 4)
@@ -94,7 +94,6 @@ class ProjectBrowserPanel:
94
94
  def on_phasor_done(self, stem):
95
95
  if self._project is None:
96
96
  return
97
- self._project.update_after_phasor(stem)
98
97
  self._project.save()
99
98
  self._refresh()
100
99
 
@@ -703,6 +703,7 @@ class RoiAnalysisPanel:
703
703
  from flimkit.formats import FLIMFile
704
704
  from flimkit.FLIM.fitters import fit_summed
705
705
  from flimkit.FLIM.fit_tools import resolve_rep_period_ns
706
+ from flimkit.interactive import parse_exclude_ns
706
707
  ptu = FLIMFile(ptu_path, verbose=False)
707
708
  n_bins = ptu.n_bins
708
709
  tcspc_res = ptu.tcspc_res
@@ -745,6 +746,9 @@ class RoiAnalysisPanel:
745
746
  n_starts=params.get('n_starts'),
746
747
  rep_period_ns=resolve_rep_period_ns(params.get('rep_period_ns'), ptu),
747
748
  fixed_taus_ns=params.get('fixed_taus_ns'),
749
+ fit_start_ns=params.get('fit_start_ns'),
750
+ fit_end_ns=params.get('fit_end_ns'),
751
+ exclude_ns=parse_exclude_ns(params.get('exclude_ns')),
748
752
  )
749
753
  if progress_callback:
750
754
  progress_callback(4, 4)
@@ -13,6 +13,8 @@ from flimkit.utils.session import (
13
13
  _reconstruct_dict_from_session,
14
14
  _safe_array_from_json,
15
15
  _parse_summary,
16
+ load_session_npz,
17
+ plain_array,
16
18
  )
17
19
  try:
18
20
  from tkinterdnd2 import DND_FILES, DND_TEXT
@@ -1,5 +1,5 @@
1
- __version__ = '0.15.0'
2
- fitter_version = '27'
1
+ __version__ = '0.15.1'
2
+ fitter_version = '28'
3
3
  app_name = 'FLIMKitDEV' if '+dev' in __version__ else 'FLIMKit'
4
4
 
5
5
  roadmap = '''Flim program roadmap:
@@ -54,5 +54,6 @@ Need to add Phasor once added to the codebase, and update version to 1.0. And ad
54
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.
55
55
  0.14.4 -> free-tau per-pixel fits fit the Poisson likelihood instead of a chi-squared weighted by the observed counts, which biased the lifetimes at low counts, so fitter_version goes to 26.
56
56
  0.15.0 -> the polish after differential evolution works on log10 of the lifetimes and converges, which takes a tri-exponential fit at 1e6 photons from 6.7 and 7.4% error on the mid and short lifetimes to 2.1 and 3.3%. Below about 1e5 photons the components still cannot be resolved by any fit. DE updates its population the same way on one core or many, so fitter_version goes to 27. When the components are not resolved the summary leads with the mean lifetimes, and ROI and phasor-cursor fits can fix the lifetimes from the image fit. An incomplete-decay term adds the decay left over from earlier pulses, off by default; flimkit-accelerator-plugin 0.3.0 carries it in C and CUDA.
57
+ 0.15.1 -> the fit window, exclusion bands and IRF shift bound reach every fit, where the tail model in stitch then fit, the tile and series fits and the ROI and cursor fits ignored them, and the torch and MLX backends solve the fixed-tau NNLS exactly instead of clamping, so fitter_version goes to 28. Session files load without pickle, project.json and config.json are written atomically and keep a .bak, and the web UI answers only localhost without a password.
57
58
  1.0.0 -> release version with all core features implemented and tested
58
59
  1.5.0 (or 2.0) -> validation of fitting results with known fluorophores.'''
@@ -0,0 +1 @@
1
+ from .reader import ICSFile, read_ics