-
Notifications
You must be signed in to change notification settings - Fork 1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
PSF and attenuation #33
Merged
Merged
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
001a6b3
Compensate for beam PSF
CHrlS98 e11f476
[WIP] Port z-attenuation correction scripts
CHrlS98 89eb51a
Add args to linum_compensate_for_psf.py
CHrlS98 f8ef4ff
Fix PSF correction, use extended vermeer model for attn, cast outputs…
CHrlS98 4a015ac
Update workflow
CHrlS98 be1b4f2
Add n_processes arg to linum_create_mosaic_grid_3d.py
CHrlS98 0783e32
Update .gitignore
CHrlS98 bc2288e
Merge remote-tracking branch 'upstream/main' into psf-and-attenuation
CHrlS98 fc0d9bf
PEP8
CHrlS98 0f820c2
PEP8
CHrlS98 912bbb4
Answer review comments
CHrlS98 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -171,6 +171,10 @@ workflows/work/ | |
# Macos | ||
.DS_Store | ||
|
||
# files | ||
# Data files | ||
*.zarr | ||
*.nii.gz | ||
*.sif | ||
|
||
# Config files | ||
*.ini |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,145 @@ | ||
import numpy as np | ||
from linumpy.preproc.xyzcorr import findTissueInterface | ||
from linumpy.preproc.icorr import confocalPSF, fit_TissueConfocalModel | ||
|
||
from scipy.ndimage import binary_dilation, binary_fill_holes, gaussian_filter | ||
from scipy.stats import zscore | ||
from skimage.filters import threshold_li | ||
from skimage.morphology import disk | ||
|
||
|
||
# TODO: Fine-tune default values for 10x microscope or give heuristic | ||
# for fixing them. | ||
def extract_psfParametersFromMosaic( | ||
vol, f=0.01, nProfiles=10, zr_0=610.0, res=6.5, nIterations=15 | ||
CHrlS98 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
): | ||
"""Computes the confocal PSF from a slice | ||
|
||
Parameters | ||
---------- | ||
vol : ndarray | ||
A stitched tissue slice with axes in order (x, y, z). | ||
f : float | ||
Smoothing factor (in fraction of image size). | ||
nProfiles : int | ||
Number of intensity profile to use. | ||
zr_0 : float | ||
Initial Rayleigh length to use in micron (default=%(default)s for a 3X objective) | ||
res : float | ||
Z resolution (in micron). | ||
|
||
Returns | ||
------- | ||
(2,) tuple | ||
Focal depth (zf) and Rayleigh length (zr) in micron | ||
|
||
""" | ||
|
||
nx, ny, nz = vol.shape | ||
k = int(0.5 * f * (nx + ny)) | ||
aip = vol.mean(axis=2) | ||
|
||
# Compute water-tissue interface | ||
interface = findTissueInterface(vol).astype(int) | ||
|
||
# Compute the agarose mask with the li thresholding method | ||
thresh = threshold_li(aip) | ||
mask_tissue = binary_fill_holes(aip > thresh) | ||
mask_agarose = ~binary_fill_holes(binary_dilation(mask_tissue, disk(k))) | ||
mask_agarose[aip == 0] = 0 | ||
del mask_tissue | ||
|
||
# Get min and max interface depth for the agarose | ||
zmin = np.percentile(interface[mask_agarose], 2.5) | ||
|
||
# Get the average iProfile / interface depth | ||
profilePerInterfaceDepth = np.zeros((nProfiles, nz)) | ||
for ii in range(nProfiles): | ||
for z in range(nz): | ||
profilePerInterfaceDepth[ii, z] = np.mean( | ||
vol[:, :, z][mask_agarose * (interface == zmin + ii)] | ||
) | ||
|
||
# Detect outliers | ||
iProfile_gradient = np.abs( | ||
gaussian_filter(profilePerInterfaceDepth, sigma=(0, 2), order=1) | ||
) | ||
profile_mask = np.abs(zscore(iProfile_gradient, axis=1)) <= 1.0 | ||
for ii in range(nProfiles): | ||
profile_mask[ii, 0:int(zmin + ii)] = 0 | ||
|
||
z = np.linspace(0, nz * res, nz) | ||
zf_list = list() | ||
zr_list = list() | ||
total_err = list() | ||
for z0 in range(nProfiles): | ||
# Find the coarse alignment of the focus based on | ||
# pre-established Rayleigh length from thorlab | ||
errList = list() | ||
for zf in range(nz): | ||
a = profilePerInterfaceDepth[z0, zf] | ||
synthetic_signal = confocalPSF(z, zf, zr_0, a) | ||
err = np.abs(synthetic_signal - profilePerInterfaceDepth[z0, :]) | ||
err = np.mean(err[profile_mask[z0, :]]) | ||
errList.append(err) | ||
|
||
errList = np.array(errList) | ||
zf = np.argmin(errList) * res | ||
a = profilePerInterfaceDepth[z0, int(zf / res)] | ||
|
||
if not (np.isnan(a)): | ||
last_zr = zr_0 | ||
for _ in range(nIterations): | ||
# Optimize the model (without using attenuation) | ||
iProfile = profilePerInterfaceDepth[z0, :] | ||
output = fit_TissueConfocalModel( | ||
iProfile, | ||
int(z0 + zmin), | ||
last_zr, | ||
res, | ||
returnParameters=True, | ||
return_fullModel=True, | ||
useBumpModel=True, | ||
) | ||
zf = output["parameters"]["zf"] | ||
zr = output["parameters"]["zr"] | ||
last_zr = zr | ||
|
||
zf_list.append(zf) | ||
zr_list.append(zr) | ||
err_fit = (output["tissue_psf"] - profilePerInterfaceDepth[z0, :]) ** 2.0 | ||
total_err.append(np.mean(err_fit)) | ||
|
||
min_err = np.argmin(total_err) | ||
zf_final = zf_list[min_err] | ||
zr_final = zr_list[min_err] | ||
|
||
return zf_final, zr_final | ||
|
||
|
||
def get_3dPSF(zf, zr, res, volshape): | ||
"""Generate a 3D PSF based on Gaussian beam parameters. | ||
|
||
Parameters | ||
---------- | ||
zf : float | ||
Focal depth in microns | ||
zr : float | ||
Rayleigh length in microns | ||
res : float | ||
Axial resolution in micron / pixel | ||
volshape : (3,) list of int | ||
Output volume shape in pixel | ||
|
||
Returns | ||
------- | ||
ndarray | ||
3D PSF of shape 'volshape' | ||
""" | ||
# TODO: Invert axes to agree with OME-zarr convention? | ||
nx, ny, nz = volshape[0:3] | ||
z = np.linspace(0, res * nz, nz) | ||
psf = confocalPSF(z, zf, zr) | ||
psf = np.tile(np.reshape(psf, (1, 1, nz)), (nx, ny, 1)) | ||
|
||
return psf |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
#!/usr/bin/env python | ||
# -*- coding: utf-8 -*- | ||
""" | ||
Compensate the tissue attenuation using a precomputed attenuation | ||
bias field. | ||
""" | ||
|
||
import argparse | ||
from pathlib import Path | ||
import dask.array as da | ||
|
||
from linumpy.io.zarr import save_zarr, read_omezarr | ||
|
||
|
||
def _build_arg_parser(): | ||
p = argparse.ArgumentParser( | ||
description=__doc__, formatter_class=argparse.RawTextHelpFormatter) | ||
p.add_argument("input", | ||
help="Input volume (.ome.zarr)") | ||
p.add_argument("bias", | ||
help="Attenuation bias field (.ome.zarr)") | ||
p.add_argument("output", | ||
help="Compensated volume (.ome.zarr)") | ||
|
||
return p | ||
|
||
|
||
def main(): | ||
# Parse arguments | ||
p = _build_arg_parser() | ||
args = p.parse_args() | ||
|
||
# Load volume and bias field | ||
vol, res = read_omezarr(args.input, level=0) | ||
bias, _ = read_omezarr(args.bias, level=0) | ||
chunks = vol.chunks | ||
|
||
# Apply correction | ||
vol_dask = da.from_zarr(vol) | ||
bias_dask = da.from_zarr(bias) | ||
vol_dask /= bias_dask | ||
|
||
# Save the output | ||
save_zarr(vol_dask.astype(da.float32), args.output, scales=res, chunks=chunks) | ||
|
||
|
||
if __name__ == "__main__": | ||
main() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,65 @@ | ||
#!/usr/bin/env python3 | ||
# -*- coding: utf-8 -*- | ||
import argparse | ||
import numpy as np | ||
from linumpy.io.zarr import read_omezarr, save_zarr | ||
from linumpy.psf.psf_estimator import extract_psfParametersFromMosaic, get_3dPSF | ||
|
||
|
||
def _build_arg_parser(): | ||
p = argparse.ArgumentParser() | ||
p.add_argument('in_zarr', | ||
help='Input stitched 3D slice (OME-zarr).') | ||
p.add_argument('out_zarr', | ||
help='Output volume corrected for beam PSF (OME-zarr).') | ||
p.add_argument('--out_psf', | ||
help='Optional output PSF filename.') | ||
p.add_argument('--nz', type=int, default=25, | ||
help='The "nz" first voxels belonging to background [%(default)s].') | ||
p.add_argument('--n_profiles', type=int, default=10, | ||
help='Number of intensity profiles to use [%(default)s].') | ||
p.add_argument('--n_iterations', type=int, default=15, | ||
help='Number of iterations [%(default)s].') | ||
p.add_argument('--smooth', type=float, default=0.01, | ||
help='Smoothing factor as a fraction of volume depth [%(default)s].') | ||
return p | ||
|
||
|
||
def main(): | ||
parser = _build_arg_parser() | ||
args = parser.parse_args() | ||
|
||
# 1. load stitched tissue slice | ||
vol, res = read_omezarr(args.in_zarr, level=0) | ||
chunks = vol.chunks | ||
vol = np.moveaxis(vol, (0, 1, 2), (2, 1, 0)) | ||
res = res[::-1] | ||
res_axial_microns = res[2] * 1000 | ||
|
||
# 2. estimate psf | ||
zf, zr = extract_psfParametersFromMosaic(vol, nProfiles=args.n_profiles, | ||
res=res_axial_microns, f=args.smooth, | ||
nIterations=args.n_iterations) | ||
psf_3d = get_3dPSF(zf, zr, res_axial_microns, vol.shape) | ||
|
||
# Compensate by the PSF | ||
background = np.mean(vol[..., :args.nz]) | ||
output = (vol - background) / psf_3d + background | ||
|
||
# remove negative values | ||
output -= output.min() | ||
|
||
# TODO: Use dask arrays | ||
output = np.moveaxis(output, (0, 1, 2), (2, 1, 0)) | ||
res = res[::-1] | ||
|
||
if args.out_psf: | ||
psf_3d = np.moveaxis(psf_3d, (0, 1, 2), (2, 1, 0)) | ||
# when there are too many levels it'll break the viewer for some reason | ||
save_zarr(psf_3d.astype(np.float32), args.out_psf, scales=res, chunks=chunks) | ||
|
||
save_zarr(output.astype(np.float32), args.out_zarr, scales=res, chunks=chunks) | ||
|
||
|
||
if __name__ == '__main__': | ||
main() |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
New issue #35 to solve units mismatch issue.