1. Usage#

[1]:
%load_ext autoreload
%autoreload 2

import numpy as np
import scipy
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
import skimage
import skimage.io
import seaborn as sb
import tifffile

from nima import nima

cm = plt.cm.inferno_r

fp = "../../tests/data/1b_c16_15.tif"

channels = ["G", "R", "C"]
# dark = io.imread('/home/dati/GBM_persson/analyses/15.02.05_cal-GBM5-pBJclop/dark/dark-25_500.tif')
# flat = io.imread('/home/dati/GBM_persson/analyses/15.02.05_cal-GBM5-pBJclop/flat/flat-C-dark-37bis_500.tif')
[2]:
d_im, n_ch, times = nima.read_tiff(fp, channels)
(4, 512, 512)
[3]:
d_im_bg, bgs, ff, bgv = nima.d_bg(d_im, downscale=(2, 2), kind="li_adaptive")
bgs
[3]:
G R C
0 462.00 249.75 278.00
1 463.50 253.00 280.25
2 464.50 254.75 282.00
3 461.25 252.50 278.00
[4]:
d_im_bg["G"].__sizeof__()
[4]:
8388752
[5]:
scipy.stats.distributions.norm.fit(bgv["C"][1])
[5]:
(284.6376898796607, 36.32323945861521)
[6]:
sb.histplot(bgv["C"][1], kde=True, stat="density")
plt.yscale("log")
../_images/tutorials_usage_6_0.png
[7]:
ff["C"][1][0]
[7]:
../_images/tutorials_usage_7_0.png
[8]:
for i in range(4):
    plt.hist(bgv["C"][i], histtype="step", bins=32, log=1)
../_images/tutorials_usage_8_0.png
[9]:
nima.d_mask_label(
    d_im_bg, threshold_method="yen", min_size=2000, channels=channels, watershed=0
)
d_im_bg.keys()
[9]:
dict_keys(['G', 'R', 'C', 'mask', 'labels'])
[10]:
f = nima.d_show(d_im_bg)
../_images/tutorials_usage_10_0.png
[11]:
meas, pr = nima.d_meas_props(d_im_bg)
f = nima.d_plot_meas(bgs, meas, channels=channels)
../_images/tutorials_usage_11_0.png
[12]:
plt.subplot(1, 2, 1)
skimage.io.imshow(d_im_bg["r_cl"][2], vmin=0.0, vmax=1.1)
plt.subplot(1, 2, 2)
skimage.io.imshow(d_im_bg["r_pH"][2], vmin=7.3, vmax=10.7)
/home/docs/checkouts/readthedocs.org/user_builds/nima/envs/tut2/lib/python3.11/site-packages/skimage/io/_plugins/matplotlib_plugin.py:149: UserWarning: Float image out of standard range; displaying image with stretched contrast.
  lo, hi, cmap = _get_display_range(image)
[12]:
<matplotlib.image.AxesImage at 0x7f448dba1210>
../_images/tutorials_usage_12_2.png
[13]:
c0 = d_im["C"][0]
g0 = d_im["G"][0]
r0 = d_im["R"][0]
tifffile.imshow(1 / c0 / c0)
[13]:
(<Figure size 988.8x604.8 with 2 Axes>,
 <Axes: >,
 <matplotlib.image.AxesImage at 0x7f448fbc4390>)
../_images/tutorials_usage_13_1.png
[14]:
background_channel1 = skimage.restoration.rolling_ball(c0, radius=160)
tifffile.imshow(background_channel1)
[14]:
(<Figure size 988.8x604.8 with 2 Axes>,
 <Axes: >,
 <matplotlib.image.AxesImage at 0x7f448d04a8d0>)
../_images/tutorials_usage_14_1.png
[15]:
plt.plot(background_channel1[200])
[15]:
[<matplotlib.lines.Line2D at 0x7f448d0bb150>]
../_images/tutorials_usage_15_1.png

1.1. background, AF, target cells#

[16]:
import aicsimageio
[17]:
aicsim = aicsimageio.AICSImage(
    "/home/dati/GBM_persson/data/15.02.05_cal-GBM5-pBJclop/ph633/1_20_40.tif"
)
---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
Cell In[17], line 1
----> 1 aicsim = aicsimageio.AICSImage(
      2     "/home/dati/GBM_persson/data/15.02.05_cal-GBM5-pBJclop/ph633/1_20_40.tif"
      3 )

File ~/checkouts/readthedocs.org/user_builds/nima/envs/tut2/lib/python3.11/site-packages/aicsimageio/aics_image.py:277, in AICSImage.__init__(self, image, reader, reconstruct_mosaic, fs_kwargs, **kwargs)
    267 def __init__(
    268     self,
    269     image: types.ImageLike,
   (...)
    273     **kwargs: Any,
    274 ):
    275     if reader is None:
    276         # Determine reader class and create dask delayed array
--> 277         ReaderClass = self.determine_reader(image, fs_kwargs=fs_kwargs, **kwargs)
    278     else:
    279         # Init reader
    280         ReaderClass = reader

File ~/checkouts/readthedocs.org/user_builds/nima/envs/tut2/lib/python3.11/site-packages/aicsimageio/aics_image.py:176, in AICSImage.determine_reader(image, fs_kwargs, **kwargs)
    174 # Try reader detection based off of file path extension
    175 if isinstance(image, (str, Path)):
--> 176     _, path = pathlike_to_fs(image, enforce_exists=True, fs_kwargs=fs_kwargs)
    178     # Check for extension in FORMAT_IMPLEMENTATIONS
    179     for format_ext, readers in FORMAT_IMPLEMENTATIONS.items():

File ~/checkouts/readthedocs.org/user_builds/nima/envs/tut2/lib/python3.11/site-packages/aicsimageio/utils/io_utils.py:56, in pathlike_to_fs(uri, enforce_exists, fs_kwargs)
     54 if enforce_exists:
     55     if not fs.exists(path):
---> 56         raise FileNotFoundError(f"{fs.protocol}://{path}")
     58 # Get and store details
     59 # We do not return an AbstractBufferedFile (i.e. fs.open) as we do not want to have
     60 # any open file buffers _after_ any API call. API calls must themselves call
     61 # fs.open and complete their function during the context of the opened buffer.
     62 return fs, path

FileNotFoundError: file:///home/dati/GBM_persson/data/15.02.05_cal-GBM5-pBJclop/ph633/1_20_40.tif
[18]:
aicsim.ome_metadata
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[18], line 1
----> 1 aicsim.ome_metadata

NameError: name 'aicsim' is not defined
[19]:
import nima_io.read as ir
---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
Cell In[19], line 1
----> 1 import nima_io.read as ir

ModuleNotFoundError: No module named 'nima_io'
[20]:
md, wr = ir.read(
    "/home/dati/GBM_persson/data/15.02.05_cal-GBM5-pBJclop/ph633/1_20_40.tif"
)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[20], line 1
----> 1 md, wr = ir.read(
      2     "/home/dati/GBM_persson/data/15.02.05_cal-GBM5-pBJclop/ph633/1_20_40.tif"
      3 )

NameError: name 'ir' is not defined
[21]:
md.full
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[21], line 1
----> 1 md.full

NameError: name 'md' is not defined
[22]:
channels3 = ["G", "R", "C", "G2"]
dim3, _, _ = nima.read_tiff(
    "/home/dati/GBM_persson/data/15.02.05_cal-GBM5-pBJclop/ph633/1_20_40.tif", channels3
)
dim3, bgm3, _, bgv3 = nima.d_bg(dim3, downscale=(2, 2), kind="li_adaptive")
c = dim3["C"]
g = dim3["G"]
r = dim3["R"]

bc = bgv3["C"][3]
bg = bgv3["G"][3]
br = bgv3["R"][3]
---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
/tmp/ipykernel_1066/1316661724.py in ?()
      1 channels3 = ["G", "R", "C", "G2"]
----> 2 dim3, _, _ = nima.read_tiff(
      3     "/home/dati/GBM_persson/data/15.02.05_cal-GBM5-pBJclop/ph633/1_20_40.tif", channels3
      4 )
      5 dim3, bgm3, _, bgv3 = nima.d_bg(dim3, downscale=(2, 2), kind="li_adaptive")

~/checkouts/readthedocs.org/user_builds/nima/envs/tut2/lib/python3.11/site-packages/nima/nima.py in ?(fp, channels)
     90     (3, 4)
     91
     92     """
     93     n_channels = len(channels)
---> 94     with tifffile.TiffFile(fp) as tif:
     95         im = tif.asarray()
     96         axes = tif.series[0].axes
     97     idx = axes.rfind("T")

~/checkouts/readthedocs.org/user_builds/nima/envs/tut2/lib/python3.11/site-packages/tifffile/tifffile.py in ?(self, file, mode, name, offset, size, omexml, _multifile, _useframes, _parent, **is_flags)
   3929
   3930         if mode not in (None, 'r', 'r+', 'rb', 'r+b'):
   3931             raise ValueError(f'invalid mode {mode!r}')
   3932
-> 3933         fh = FileHandle(file, mode=mode, name=name, offset=offset, size=size)
   3934         self._fh = fh
   3935         self._multifile = True if _multifile is None else bool(_multifile)
   3936         self._files = {fh.name: self}

~/checkouts/readthedocs.org/user_builds/nima/envs/tut2/lib/python3.11/site-packages/tifffile/tifffile.py in ?(self, file, mode, name, offset, size)
  13631         self._offset = -1 if offset is None else offset
  13632         self._size = -1 if size is None else size
  13633         self._close = True
  13634         self._lock = NullContext()
> 13635         self.open()
  13636         assert self._fh is not None

~/checkouts/readthedocs.org/user_builds/nima/envs/tut2/lib/python3.11/site-packages/tifffile/tifffile.py in ?(self)
  13646         if isinstance(self._file, str):
  13647             # file name
  13648             self._file = os.path.realpath(self._file)
  13649             self._dir, self._name = os.path.split(self._file)
> 13650             self._fh = open(self._file, self._mode)  # type: ignore
  13651             self._close = True
  13652             if self._offset < 0:
  13653                 self._offset = 0

FileNotFoundError: [Errno 2] No such file or directory: '/home/dati/GBM_persson/data/15.02.05_cal-GBM5-pBJclop/ph633/1_20_40.tif'

c = d_im_bg[‘C’] g = d_im_bg[‘G’] r = d_im_bg[‘R’]

bc = bgv[‘C’][2] bg = bgv[‘G’][3] br = bgv[‘R’][3]

[23]:
skimage.io.imshow(dim3["R"][1])
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[23], line 1
----> 1 skimage.io.imshow(dim3["R"][1])

NameError: name 'dim3' is not defined
[24]:
plt.plot(dim3["R"][1][80, 30:])
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[24], line 1
----> 1 plt.plot(dim3["R"][1][80, 30:])

NameError: name 'dim3' is not defined
[25]:
mmin = min(len(bc), len(bg), len(br))

print("c =", len(bc))
print("g =", len(bg))
print("r =", len(br))

plt.figure(figsize=(7.5, 6))

plt.subplot(2, 2, 1)
mmin = min(len(bc), len(bg))
plt.hexbin(bg[:mmin], bc[:mmin], bins="log", cmap=plt.cm.viridis_r)
cb = plt.colorbar()
plt.xlabel("green")
plt.ylabel("cyan")

plt.subplot(2, 2, 2)
mmin = min(len(bc), len(br))
plt.hexbin(br[:mmin], bc[:mmin], bins="log", cmap=plt.cm.viridis_r)
cb = plt.colorbar()
plt.xlabel("red")
plt.ylabel("cyan")

ax = plt.subplot(2, 2, 4)
mmin = min(len(br), len(bg))
plt.hexbin(br[:mmin], bg[:mmin], bins="log", cmap=plt.cm.viridis_r)
cb = plt.colorbar()
plt.xlabel("red")
plt.ylabel("green")
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[25], line 1
----> 1 mmin = min(len(bc), len(bg), len(br))
      3 print("c =", len(bc))
      4 print("g =", len(bg))

NameError: name 'bc' is not defined
[26]:
from mpl_toolkits.axes_grid1.inset_locator import mark_inset

plt.figure(figsize=(10, 8))
plt.subplot(2, 2, 1)
plt.hexbin(g.ravel(), c.ravel(), bins="log", cmap=plt.cm.viridis_r)
cb = plt.colorbar()
plt.xlabel("green")
plt.ylabel("cyan")

plt.subplot(2, 2, 2)
plt.hexbin(r.ravel(), c.ravel(), bins="log", cmap=plt.cm.viridis_r)
cb = plt.colorbar()
plt.xlabel("red")
plt.ylabel("cyan")

ax = plt.subplot(2, 2, 4)
plt.hexbin(r.ravel(), g.ravel(), bins="log", cmap=plt.cm.viridis_r)
cb = plt.colorbar()
plt.xlabel("red")
plt.ylabel("green")

axins = plt.axes([0.2, 0.12, 0.28, 0.28])
axins.hexbin(
    r.ravel(), g.ravel(), extent=(0, 80, 0, 150), bins="log", cmap=plt.cm.viridis_r
)

mark_inset(ax, axins, loc1=1, loc2=4, fc="none", ec="0.5")
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[26], line 5
      3 plt.figure(figsize=(10, 8))
      4 plt.subplot(2, 2, 1)
----> 5 plt.hexbin(g.ravel(), c.ravel(), bins="log", cmap=plt.cm.viridis_r)
      6 cb = plt.colorbar()
      7 plt.xlabel("green")

NameError: name 'g' is not defined
../_images/tutorials_usage_28_1.png
[27]:
import statsmodels.api as sm


# import pylab
def qqplot(v1, v2):
    ml = min(len(v1), len(v2))
    sm.qqplot_2samples(v1[:ml], v2[:ml])
    # pylab.show()


qqplot(bgv3["R"][2], bgv3["G"][2])
qqplot(bgv3["C"][3], bgv3["R"][1])
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[27], line 11
      7     sm.qqplot_2samples(v1[:ml], v2[:ml])
      8     # pylab.show()
---> 11 qqplot(bgv3["R"][2], bgv3["G"][2])
     12 qqplot(bgv3["C"][3], bgv3["R"][1])

NameError: name 'bgv3' is not defined

1.2. flat image correction#

[28]:
g1a = nima.read_tiff("/home/dati/dt-clop3/data/210917/3alpha/c1_2.tf8", channels)[0][
    "G"
][2]
g2a = nima.read_tiff("/home/dati/dt-clop3/data/210917/3alpha/c2_2.tf8", channels)[0][
    "G"
][2]
g3a = nima.read_tiff("/home/dati/dt-clop3/data/210917/3alpha/c3_2.tf8", channels)[0][
    "G"
][2]
g1 = nima.read_tiff("/home/dati/dt-clop3/data/210917/3/c1_2.tf8", channels)[0]["G"][2]
g2 = nima.read_tiff("/home/dati/dt-clop3/data/210917/3/c2_2.tf8", channels)[0]["G"][2]
g3 = nima.read_tiff("/home/dati/dt-clop3/data/210917/3/c3_2.tf8", channels)[0]["G"][2]
---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
/tmp/ipykernel_1066/4145832345.py in ?()
----> 1 g1a = nima.read_tiff("/home/dati/dt-clop3/data/210917/3alpha/c1_2.tf8", channels)[0][
      2     "G"
      3 ][2]
      4 g2a = nima.read_tiff("/home/dati/dt-clop3/data/210917/3alpha/c2_2.tf8", channels)[0][

~/checkouts/readthedocs.org/user_builds/nima/envs/tut2/lib/python3.11/site-packages/nima/nima.py in ?(fp, channels)
     90     (3, 4)
     91
     92     """
     93     n_channels = len(channels)
---> 94     with tifffile.TiffFile(fp) as tif:
     95         im = tif.asarray()
     96         axes = tif.series[0].axes
     97     idx = axes.rfind("T")

~/checkouts/readthedocs.org/user_builds/nima/envs/tut2/lib/python3.11/site-packages/tifffile/tifffile.py in ?(self, file, mode, name, offset, size, omexml, _multifile, _useframes, _parent, **is_flags)
   3929
   3930         if mode not in (None, 'r', 'r+', 'rb', 'r+b'):
   3931             raise ValueError(f'invalid mode {mode!r}')
   3932
-> 3933         fh = FileHandle(file, mode=mode, name=name, offset=offset, size=size)
   3934         self._fh = fh
   3935         self._multifile = True if _multifile is None else bool(_multifile)
   3936         self._files = {fh.name: self}

~/checkouts/readthedocs.org/user_builds/nima/envs/tut2/lib/python3.11/site-packages/tifffile/tifffile.py in ?(self, file, mode, name, offset, size)
  13631         self._offset = -1 if offset is None else offset
  13632         self._size = -1 if size is None else size
  13633         self._close = True
  13634         self._lock = NullContext()
> 13635         self.open()
  13636         assert self._fh is not None

~/checkouts/readthedocs.org/user_builds/nima/envs/tut2/lib/python3.11/site-packages/tifffile/tifffile.py in ?(self)
  13646         if isinstance(self._file, str):
  13647             # file name
  13648             self._file = os.path.realpath(self._file)
  13649             self._dir, self._name = os.path.split(self._file)
> 13650             self._fh = open(self._file, self._mode)  # type: ignore
  13651             self._close = True
  13652             if self._offset < 0:
  13653                 self._offset = 0

FileNotFoundError: [Errno 2] No such file or directory: '/home/dati/dt-clop3/data/210917/3alpha/c1_2.tf8'
[29]:
plt.subplot(1, 2, 1)
skimage.io.imshow(
    skimage.filters.gaussian(np.max([g1, g2, g3, g1a, g2a, g3a], axis=0), sigma=500)
)
plt.subplot(1, 2, 2)
skimage.io.imshow(skimage.filters.gaussian(np.max([g1, g2, g3], axis=0), sigma=500))
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[29], line 3
      1 plt.subplot(1, 2, 1)
      2 skimage.io.imshow(
----> 3     skimage.filters.gaussian(np.max([g1, g2, g3, g1a, g2a, g3a], axis=0), sigma=500)
      4 )
      5 plt.subplot(1, 2, 2)
      6 skimage.io.imshow(skimage.filters.gaussian(np.max([g1, g2, g3], axis=0), sigma=500))

NameError: name 'g1' is not defined
../_images/tutorials_usage_32_1.png

Run simulazion to identify best algorithm for FLAT calculation.

(Do we need to simulate a fluorophore solution sample?)

Compare to external image simulator.

[30]:
phantom = skimage.io.imread(
    "/home/dan/2024-02-05_15h-38m-58s_image_all_tif/final/final.tif"
)
---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
/tmp/ipykernel_1066/4096004834.py in ?()
----> 1 phantom = skimage.io.imread(
      2     "/home/dan/2024-02-05_15h-38m-58s_image_all_tif/final/final.tif"
      3 )

~/checkouts/readthedocs.org/user_builds/nima/envs/tut2/lib/python3.11/site-packages/skimage/io/_io.py in ?(fname, as_gray, plugin, **plugin_args)
     49         if fname.lower().endswith(('.tiff', '.tif')):
     50             plugin = 'tifffile'
     51
     52     with file_or_url_context(fname) as fname:
---> 53         img = call_plugin('imread', fname, plugin=plugin, **plugin_args)
     54
     55     if not hasattr(img, 'ndim'):
     56         return img

~/checkouts/readthedocs.org/user_builds/nima/envs/tut2/lib/python3.11/site-packages/skimage/io/manage_plugins.py in ?(kind, *args, **kwargs)
    201             func = [f for (p, f) in plugin_funcs if p == plugin][0]
    202         except IndexError:
    203             raise RuntimeError(f'Could not find the plugin "{plugin}" for {kind}.')
    204
--> 205     return func(*args, **kwargs)

~/checkouts/readthedocs.org/user_builds/nima/envs/tut2/lib/python3.11/site-packages/skimage/io/_plugins/tifffile_plugin.py in ?(fname, **kwargs)
     70     """
     71     if 'img_num' in kwargs:
     72         kwargs['key'] = kwargs.pop('img_num')
     73
---> 74     return tifffile_imread(fname, **kwargs)

~/checkouts/readthedocs.org/user_builds/nima/envs/tut2/lib/python3.11/site-packages/tifffile/tifffile.py in ?(files, aszarr, key, series, level, squeeze, maxworkers, mode, name, offset, size, pattern, axesorder, categories, imread, sort, container, chunkshape, dtype, axestiled, ioworkers, chunkmode, fillvalue, zattrs, multiscales, omexml, out, out_inplace, _multifile, _useframes, **kwargs)
   1036
   1037         if isinstance(files, str) or not isinstance(
   1038             files, collections.abc.Sequence
   1039         ):
-> 1040             with TiffFile(
   1041                 files,
   1042                 mode=mode,
   1043                 name=name,

~/checkouts/readthedocs.org/user_builds/nima/envs/tut2/lib/python3.11/site-packages/tifffile/tifffile.py in ?(self, file, mode, name, offset, size, omexml, _multifile, _useframes, _parent, **is_flags)
   3929
   3930         if mode not in (None, 'r', 'r+', 'rb', 'r+b'):
   3931             raise ValueError(f'invalid mode {mode!r}')
   3932
-> 3933         fh = FileHandle(file, mode=mode, name=name, offset=offset, size=size)
   3934         self._fh = fh
   3935         self._multifile = True if _multifile is None else bool(_multifile)
   3936         self._files = {fh.name: self}

~/checkouts/readthedocs.org/user_builds/nima/envs/tut2/lib/python3.11/site-packages/tifffile/tifffile.py in ?(self, file, mode, name, offset, size)
  13631         self._offset = -1 if offset is None else offset
  13632         self._size = -1 if size is None else size
  13633         self._close = True
  13634         self._lock = NullContext()
> 13635         self.open()
  13636         assert self._fh is not None

~/checkouts/readthedocs.org/user_builds/nima/envs/tut2/lib/python3.11/site-packages/tifffile/tifffile.py in ?(self)
  13646         if isinstance(self._file, str):
  13647             # file name
  13648             self._file = os.path.realpath(self._file)
  13649             self._dir, self._name = os.path.split(self._file)
> 13650             self._fh = open(self._file, self._mode)  # type: ignore
  13651             self._close = True
  13652             if self._offset < 0:
  13653                 self._offset = 0

FileNotFoundError: [Errno 2] No such file or directory: '/home/dan/2024-02-05_15h-38m-58s_image_all_tif/final/final.tif'
[31]:
skimage.io.imshow(phantom[14])
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[31], line 1
----> 1 skimage.io.imshow(phantom[14])

NameError: name 'phantom' is not defined
[32]:
sb.histplot(phantom[1].flatten(), kde=True)
plt.yscale("log")
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[32], line 1
----> 1 sb.histplot(phantom[1].flatten(), kde=True)
      2 plt.yscale("log")

NameError: name 'phantom' is not defined

1.3. utils.bg#

[33]:
mmap24 = tifffile.memmap(
    "/home/dati/dt-clop3/data/210917/3/c1_2.tf8", mode="r", page=24
)
mmap25 = tifffile.memmap(
    "/home/dati/dt-clop3/data/210917/3/c1_2.tf8", mode="r", page=25
)
mmap26 = tifffile.memmap(
    "/home/dati/dt-clop3/data/210917/3/c1_2.tf8", mode="r", page=26
)
skimage.io.imshow(mmap25)
---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
/tmp/ipykernel_1066/2917330543.py in ?()
----> 1 mmap24 = tifffile.memmap(
      2     "/home/dati/dt-clop3/data/210917/3/c1_2.tf8", mode="r", page=24
      3 )
      4 mmap25 = tifffile.memmap(

~/checkouts/readthedocs.org/user_builds/nima/envs/tut2/lib/python3.11/site-packages/tifffile/tifffile.py in ?(filename, shape, dtype, page, series, level, mode, **kwargs)
   1342             raise ValueError('image data are not memory-mappable')
   1343         offset = result[0]
   1344     else:
   1345         # use existing file
-> 1346         with TiffFile(filename, **kwargs) as tif:
   1347             if page is None:
   1348                 tiffseries = tif.series[series].levels[level]
   1349                 if tiffseries.dataoffset is None:

~/checkouts/readthedocs.org/user_builds/nima/envs/tut2/lib/python3.11/site-packages/tifffile/tifffile.py in ?(self, file, mode, name, offset, size, omexml, _multifile, _useframes, _parent, **is_flags)
   3929
   3930         if mode not in (None, 'r', 'r+', 'rb', 'r+b'):
   3931             raise ValueError(f'invalid mode {mode!r}')
   3932
-> 3933         fh = FileHandle(file, mode=mode, name=name, offset=offset, size=size)
   3934         self._fh = fh
   3935         self._multifile = True if _multifile is None else bool(_multifile)
   3936         self._files = {fh.name: self}

~/checkouts/readthedocs.org/user_builds/nima/envs/tut2/lib/python3.11/site-packages/tifffile/tifffile.py in ?(self, file, mode, name, offset, size)
  13631         self._offset = -1 if offset is None else offset
  13632         self._size = -1 if size is None else size
  13633         self._close = True
  13634         self._lock = NullContext()
> 13635         self.open()
  13636         assert self._fh is not None

~/checkouts/readthedocs.org/user_builds/nima/envs/tut2/lib/python3.11/site-packages/tifffile/tifffile.py in ?(self)
  13646         if isinstance(self._file, str):
  13647             # file name
  13648             self._file = os.path.realpath(self._file)
  13649             self._dir, self._name = os.path.split(self._file)
> 13650             self._fh = open(self._file, self._mode)  # type: ignore
  13651             self._close = True
  13652             if self._offset < 0:
  13653                 self._offset = 0

FileNotFoundError: [Errno 2] No such file or directory: '/home/dati/dt-clop3/data/210917/3/c1_2.tf8'
[34]:
sb.histplot(mmap24.ravel())
plt.yscale("log")
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[34], line 1
----> 1 sb.histplot(mmap24.ravel())
      2 plt.yscale("log")

NameError: name 'mmap24' is not defined
[35]:
from nima import utils
[36]:
bg24, sd24 = utils.bg(mmap24, bgmax=114950000000000000000000000000)
bg25, sd25 = utils.bg(mmap25)
bg26, sd26 = utils.bg(mmap26)
bg24, sd24, bg25, sd25, bg26, sd26
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[36], line 1
----> 1 bg24, sd24 = utils.bg(mmap24, bgmax=114950000000000000000000000000)
      2 bg25, sd25 = utils.bg(mmap25)
      3 bg26, sd26 = utils.bg(mmap26)

NameError: name 'mmap24' is not defined
[37]:
sb.histplot(mmap25[(utils.prob(mmap25, bg25, sd25) > 0.00033)])
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[37], line 1
----> 1 sb.histplot(mmap25[(utils.prob(mmap25, bg25, sd25) > 0.00033)])

NameError: name 'mmap25' is not defined
[38]:
skimage.io.imshow(utils.prob(mmap25, bg25, sd25) > 0.033)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[38], line 1
----> 1 skimage.io.imshow(utils.prob(mmap25, bg25, sd25) > 0.033)

NameError: name 'mmap25' is not defined
[39]:
bg = mmap24[(utils.prob(mmap24, bg24, sd24) > 0.00033)]
br = mmap25[(utils.prob(mmap25, bg25, sd25) > 0.00000033)]
bc = mmap26[(utils.prob(mmap26, bg26, sd26) > 0.00000033)]

mmin = min(len(bc), len(bg), len(br))

print("c =", len(bc))
print("g =", len(bg))
print("r =", len(br))

plt.figure(figsize=(7.5, 6))

plt.subplot(2, 2, 1)
mmin = min(len(bc), len(bg))
plt.hexbin(bg[:mmin], bc[:mmin], bins="log", cmap=plt.cm.viridis_r)
cb = plt.colorbar()
plt.xlabel("green")
plt.ylabel("cyan")

plt.subplot(2, 2, 2)
mmin = min(len(bc), len(br))
plt.hexbin(br[:mmin], bc[:mmin], bins="log", cmap=plt.cm.viridis_r)
cb = plt.colorbar()
plt.xlabel("red")
plt.ylabel("cyan")

ax = plt.subplot(2, 2, 4)
mmin = min(len(br), len(bg))
plt.hexbin(br[:mmin], bg[:mmin], bins="log", cmap=plt.cm.viridis_r)
cb = plt.colorbar()
plt.xlabel("red")
plt.ylabel("green")
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[39], line 1
----> 1 bg = mmap24[(utils.prob(mmap24, bg24, sd24) > 0.00033)]
      2 br = mmap25[(utils.prob(mmap25, bg25, sd25) > 0.00000033)]
      3 bc = mmap26[(utils.prob(mmap26, bg26, sd26) > 0.00000033)]

NameError: name 'mmap24' is not defined
[40]:
with tifffile.TiffFile("/home/dati/dt-clop3/data/210917/3alpha/c1_2.tf8") as tif:
    im = tif.asarray()
    axes = tif.series[0].axes
    print(axes)
---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
/tmp/ipykernel_1066/4212848427.py in ?()
----> 1 with tifffile.TiffFile("/home/dati/dt-clop3/data/210917/3alpha/c1_2.tf8") as tif:
      2     im = tif.asarray()
      3     axes = tif.series[0].axes
      4     print(axes)

~/checkouts/readthedocs.org/user_builds/nima/envs/tut2/lib/python3.11/site-packages/tifffile/tifffile.py in ?(self, file, mode, name, offset, size, omexml, _multifile, _useframes, _parent, **is_flags)
   3929
   3930         if mode not in (None, 'r', 'r+', 'rb', 'r+b'):
   3931             raise ValueError(f'invalid mode {mode!r}')
   3932
-> 3933         fh = FileHandle(file, mode=mode, name=name, offset=offset, size=size)
   3934         self._fh = fh
   3935         self._multifile = True if _multifile is None else bool(_multifile)
   3936         self._files = {fh.name: self}

~/checkouts/readthedocs.org/user_builds/nima/envs/tut2/lib/python3.11/site-packages/tifffile/tifffile.py in ?(self, file, mode, name, offset, size)
  13631         self._offset = -1 if offset is None else offset
  13632         self._size = -1 if size is None else size
  13633         self._close = True
  13634         self._lock = NullContext()
> 13635         self.open()
  13636         assert self._fh is not None

~/checkouts/readthedocs.org/user_builds/nima/envs/tut2/lib/python3.11/site-packages/tifffile/tifffile.py in ?(self)
  13646         if isinstance(self._file, str):
  13647             # file name
  13648             self._file = os.path.realpath(self._file)
  13649             self._dir, self._name = os.path.split(self._file)
> 13650             self._fh = open(self._file, self._mode)  # type: ignore
  13651             self._close = True
  13652             if self._offset < 0:
  13653                 self._offset = 0

FileNotFoundError: [Errno 2] No such file or directory: '/home/dati/dt-clop3/data/210917/3alpha/c1_2.tf8'

1.4. BIAS and FLAT#

TODO: - pytest - build a function callable from both the library and the CLI