From ff252a880199d8bcf16b54a0002f1d83264ca5f5 Mon Sep 17 00:00:00 2001
From: Andrey Aristov <aaristov@pasteur.fr>
Date: Sun, 29 May 2022 13:04:18 +0200
Subject: [PATCH] sequential align

---
 align.py | 73 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 73 insertions(+)
 create mode 100644 align.py

diff --git a/align.py b/align.py
new file mode 100644
index 0000000..4c02f46
--- /dev/null
+++ b/align.py
@@ -0,0 +1,73 @@
+from droplet_growth import mic, register, poisson
+import tifffile as tf
+import os
+import dask.array as da
+from functools import partial
+from zarr_tools import convert
+import yaml
+import fire
+
+def align_multichip(BF_TRITC_2D_path, out_path, concentrations_path, template_path, labels_path, fit_poisson, nmax=10):
+    with open(concentrations_path, 'r') as f:
+        concentrations_dct = (yaml.safe_load(f))
+    concentrations = concentrations_dct['concentrations']
+    unit = concentrations_dct['units']
+    tif_paths = [f'{os.path.dirname(BF_TRITC_2D_path)}/{c}{unit}_aligned.tif' for c in concentrations]
+    data = da.from_zarr(BF_TRITC_2D_path+'/0/')
+    template16 = tf.imread(template_path)
+    big_labels = tf.imread(labels_path)
+
+    fun = partial(
+        align2D, 
+        template16=template16,
+        big_labels=big_labels,
+        unit=unit,
+        fit_poisson=fit_poisson,
+        nmax=nmax )
+    aligned = list(map(lambda x: fun(*x), zip(data, tif_paths,concentrations)) )
+    daligned = da.from_array(aligned)
+    convert.to_zarr(
+        daligned, 
+        path=out_path, 
+        steps=4, 
+        name=['BF','TRITC','mask'], 
+        colormap=['gray','green','blue'],
+        lut=((1000,30000),(440, 600),(0,501)),
+    )
+    return out_path
+
+
+def align2D(stack_dask, path_tif, ab, template16, big_labels, unit='μg_mL', fit_poisson=True, nmax=10):
+    print(ab)
+    try:
+        aligned = tf.imread(path_tif)
+        print(f'already alinged: {path_tif}')
+        return aligned
+    except FileNotFoundError:
+        pass
+        
+    data = stack_dask.compute()
+    aligned, tvec = register.align_stack(
+        data, 
+        path_to_save=path_tif, 
+        template16=template16, 
+        mask2=big_labels, 
+        binnings=(2,16,2)
+    )
+    counts = mic.get_cell_numbers(aligned[1], aligned[2], threshold_abs=2, plot=False, bf=aligned[0])
+    
+    counts.loc[:,'[AB]'] = ab
+    
+    if fit_poisson:
+        l = poisson.fit(
+            counts.query(f'n_cells < {nmax}').n_cells, 
+            title=f"automatic {ab}{unit.replace('_','/')}",
+            save_fig_path=path_tif.replace('.tif', '-counts-hist.png')
+        )
+        counts.loc[:, 'poisson fit'] = l
+
+    counts.to_csv((cp := path_tif.replace('.tif', '-counts.csv')), index=None)
+    return aligned
+
+if __name__ == "__main__":
+    fire.Fire(align_multichip)
-- 
GitLab