-
Notifications
You must be signed in to change notification settings - Fork 4
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
New Stokes and Mueller module #110
Conversation
Re: GPU implementation, the API between pytorch and numpy seems quite consistent i.e.,
If we find that all the assumptions in the forward model related to polarization transfer can be covered by two properties: a) instrument matrix, and b) sample model, we can use a generic name and specify the assumptions via arguments. I'll think more about this. |
|
I wouldn't be too concerned about NumPy methods. However SciPy signal processing API may have a much lower coverage. Will have to check in detail. |
Using torch is an interesting idea, in that it is 'accelerated' for CPUs too, so in theory the same code can work for CPU and GPU. However in addition to API coverage, lack of optimization/more overhead can be potential issues. |
We don't currently have type checking infra set up, so type hints serves mainly 2 purpose:
I like to write type hints because it helps me code faster (e.g. I get syntax-highlighted and linted types that's copied over so less typos in the docstring type field). But as long as the code is consistent in style and well-documented I think it's all fine. |
@talonchandler, the cell membrane signal from the new orientation image computed with the additional background correction definitely has more contrast and is more continuous signal compared to the earlier version with just measured background correction. Thank you! |
Could you clarify which convention we are discussing here: convention for what is called right vs left circularly polarized light, or convention for axes of orientation, or may be both? |
Let's focus on the model (which is making a lot of sense as I read it), naming convention, and numpy implementation in this PR, and start a separate issue to work on GPU acceleration. We should refactor whole codebase (including deconvolution code) if we change the GPU backend. |
@mattersoflight, I am trying to understand how to read the orientation measurement of cell membrane, if it makes physical sense. The value of orientation changes with new implementation and further background correction, so I was curious. |
Good question...I think we should discuss both. I can think of two paths to take here:
|
Thanks for the comparison @Soorya19Pradeep. Very helpful.
These are the types of knobs that we might provide in the "decoupling" approach: one checkbox/function for "invert orientation" and one for "rotate by 90 degrees". |
Thanks, @Soorya19Pradeep for the examples. It is great that you are taking a close look at FOVs. Seeing the full dynamic range of orientation after correcting background bias is promising! To be sure of the accuracy of the measurement, I suggest finding some patches where you see strong cortical actin bundles. If the background correction in this (arguably challenging) case is accurate, you'd see that orientation is parallel to the actin bundle. Once you have reconstructed retardance and orientation, you can call |
waveorder/stokes.py
Outdated
|
||
1) A forward function group: | ||
|
||
A = A_matrix(swing, scheme="5-State") |
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.
We should use a more descriptive name here: A_matrix
, can be called Instrument_matrix
, Sys_matrix
, or I2Stokes_matrix
.
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.
I just renamed A_matrix
to I2S_matrix
and added a new S2I_matrix
function.
I'm open to more iteration on these names.
waveorder/stokes.py
Outdated
s0, s1, s3, s3 = s0123_CPL_after_ADR(ret, ori, tra, dop) | ||
s0, s1, s2 = s012_CPL_after_AR(ret, ori, dop) |
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.
These names can be more intuitive.
I suggest stokes_ADR(ret,ori,tra,dop, input='CPL')
and stokes_AR(ret,ori,tra, input='CPL')
.
Reading the mnemonics for components in the order in which vectors and matrices multiply is more intuitive. The input can also be a Stokes vector when one wants to use the methods for another purpose, e.g., model non-ideal illumination.
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.
I think adding input="CPL"
is a big improvement!
How do these sound?
stokes_after_ADR(ret,ori,tra,dop, input='CPL')
stokes012_after_AR(ret,ori,tra, input='CPL')
I think it's important to make it clear that these are stokes vectors after an ADR/AR, and I think if we don't return all 4 stokes params then the function name should make that clear.
Reading the mnemonics for components in the order in which vectors and matrices multiply is more intuitive. The input can also be a Stokes vector when one wants to use the methods for another purpose, e.g., model non-ideal illumination.
I'm not sure I understand this. The matched inverse
functions below take Stokes vectors as input...is this what you have in mind?
waveorder/stokes.py
Outdated
ret, ori, tra, dop = inverse_s0123_CPL_after_ADR(s0, s1, s2, s3) | ||
ret, ori, tra = inverse_s012_CPL_after_AR(s0, s1, s2) |
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.
I suggest:
ret, ori, tra, dop = inverse_ADR(s0,s1,s2,s3,input='CPL')
ret, ori, tra = inverese_AR(s0,s1,s2,input='CPL')
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.
Similar to above...how do these sound:
ret, ori, tra, dop = inverse_stokes_after_ADR(s0, s1, s2, s3, input="CPL")
ret, ori, tra = inverse_stokes012_after_AR(s0, s1, s2, input="CPL")
inverse_ADR
alone might make me think that I'm going to get a Mueller matrix.
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.
Further down you suggest estimate_ADR
, and I do like the word estimate
here.
I'm now favoring
ret, ori, tra, dop = estimate_ADR_from_stokes(s0, s1, s2, s3, input="CPL")
ret, ori, tra = estimate_AR_from_stokes012(s0, s1, s2, input="CPL")
waveorder/stokes.py
Outdated
|
||
ret, ori, tra, dop = inverse_s0123_CPL_after_ADR(s0, s1, s2, s3) | ||
ret, ori, tra = inverse_s012_CPL_after_AR(s0, s1, s2) | ||
M = AR_mueller_from_CPL_projection(s0, s1, s2, s3) |
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.
I suggest:
M = mueller_from_projection(s0,s1,s2,s3, model='AR', direction='forward', input='CPL')
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.
Much better!
Thinking more, I also don't think projection
is the right word here. I think:
M = mueller_from_stokes(s0, s1, s2, s3, model="AR", direction="forward", input="CPL")
or possibly mueller_from_measured_stokes
is even clearer.
waveorder/stokes.py
Outdated
|
||
3) A convenience function group: | ||
|
||
M = inv_AR_mueller_from_CPL_projection(s0, s1, s2, s3) |
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.
I suggest:
M = mueller_from_projection(s0,s1,s2,s3, model='AR', direction='inverse', input='CPL')
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.
Overall, this PR is a great step forward towards unifying the polarization algebra in our codebase.
The module currently consists of many small methods. They can be unified by specifying some of the assumptions by parameters.
I've made specific suggestions above. With that, the script can look like this.
# Calculate A and A_inv
A = stokes.instrument_matrix(swing=0.1, scheme="5-State")
A_inv = np.linalg.pinv(A)
# Apply A_inv to background and sample data
S_bg = stokes.mmul(A_inv, cyx_bg_data)
S_sm = stokes.mmul(A_inv, czyx_data)
# Calculate background correction matrix from S_bg
M_inv = stokes.mueller_from_projection(*S_bg. model='AR', direction='inverse', input='CPL')
# Apply background correction to sample data
bg_corr_S_sm = stokes.mmul(M_inv, S_sm)
# Reconstruct parameters
ret, ori, tra, dop = stokes.inverse_ADR(*bg_corr_S_sm, input = 'CPL')
Additional thoughts:
- I think that estimate_ADR is a reasonable substitute for inverse_ADR.
- I went back and forth about how to shape the ND arrays s0, s1, s2, s3. On one hand, they can be combined in one argument with a dimension serving as Stokes dimension. But on the other hand, it may complicate implementation and require expensive transposes. This requires quick discussion in light of Transpose + np.copy() + (fancy indexing and/or
ndarray.copy()
) causes major slowdowns recOrder#322
I can test the example script once the code path is refactored.
I've just completed the renaming/refactoring. @mattersoflight this is ready for your re-review. The latest API (at this level) looks like:
I've also spent some time characterizing the old (green profiles) vs. new algorithms (white profiles). Soorya's cells - retardance on y axis - measured bkg correction only Kazansky target - retardance on y axis - measured bkg correction only Kazansky target - orientation on y axis - measured bkg correction only Timing 1 x 2048 x 2048: 8 x 2048 x 2048: Example comparison script (generates Kaz target comparison above) Full example script (click to expand):
|
I neglected to commit one small change: |
thanks for the offline discussion. Looks great to me! |
* New Stokes and Mueller module (#110) * Initial fwd and inv w/ tests * Add A-matrix and mueller-from-projection functions * Debug AR_mueller * Add convenience functions * Make 4d transposes nd with moveaxis * Add documentation * Improve module docstring * Change `KeyError` to `ValueError` * Improved docs * Remove unnecessary test * Removed "float" from docs * Revert "Removed "float" from docs" This reverts commit d9dd7e3. * Use `assert_almost_equal` * fixed couple of typos * `A` -> `I2S` & new `S2I` * comprehensive renaming * copy `s0` <-> `tra` * `np.array(s0)` so that it always has `.copy()` * Set default to "inverse" --------- Co-authored-by: Shalin Mehta <[email protected]> * PR docs (#111) * Add .git-blame-ignore-revs (#109) * Add #110 pr doc * Phase 2D + 3D refactor (#117) * black formatting * move 2D-to-3D phase recon to phase.py * convert gen_HZ_stack to ZYX * keep existing gpu handling * add 3D_to_3D phase OTF * improve naming consistency in phase_2D_to_3D_OTF * Add kwargs to recon params * change axes for 2D recon preparation * simplify 2D_to_3D recon with kwargs * handle padding and simplify OTFs * add 3D_to_3D recon with kwargs * temporarily remove docs for rewriting * first dependence on torch * move gen_Hz_stack to torch * convert 2d wotf to torch * move gen_Greens_function_z to torch * move important utils to torch * phase3Dto3D complete overhaul * refactor * optics.py to torch * high-level tests * splitt phase.py into models * clean up 3D script * cleaning and notes * phase2Dto3D placeholders * clean tests * use napari in tests * better skipping * reduce dependencies * update tests * maintiain PTI simulation's compatibility revised optics functions * drop pdb * Preserve birefringence recon * fix transpose bug * transpose bug * phase2Dto3D.py example * support padding * empty model for planaraniso * improved names * broad renaming of phase2D_3D and phase3D_3D * updated 2D phase and absorption recon Return the 2D absorption along with phase. Viewing OTFs in napari is very nice. I changed the axis order to be able to compare phase and absorption OTFs at focal plane. * display OTFs with Z-axis as a slider * changes to 2D phase/absorption simulation I suggest changing this example to be simulation and reconstruction of 2D specimens, thinner than the depth of field of the microscope. * rename models to <object-type>_<object-thickness>_<data_shape> * fix isotropic_thin_3d example, include absorption * 2D -> 2d, 3D -> 3d --------- Co-authored-by: Shalin Mehta <[email protected]> * Prepare polarization algorithms for integration with `recOrder` (#118) * black formatting * move 2D-to-3D phase recon to phase.py * convert gen_HZ_stack to ZYX * keep existing gpu handling * add 3D_to_3D phase OTF * improve naming consistency in phase_2D_to_3D_OTF * Add kwargs to recon params * change axes for 2D recon preparation * simplify 2D_to_3D recon with kwargs * handle padding and simplify OTFs * add 3D_to_3D recon with kwargs * temporarily remove docs for rewriting * first dependence on torch * move gen_Hz_stack to torch * convert 2d wotf to torch * move gen_Greens_function_z to torch * move important utils to torch * phase3Dto3D complete overhaul * refactor * optics.py to torch * high-level tests * splitt phase.py into models * clean up 3D script * cleaning and notes * phase2Dto3D placeholders * clean tests * use napari in tests * better skipping * reduce dependencies * update tests * maintiain PTI simulation's compatibility revised optics functions * drop pdb * Preserve birefringence recon * fix transpose bug * transpose bug * phase2Dto3D.py example * support padding * empty model for planaraniso * improved names * broad renaming of phase2D_3D and phase3D_3D * Rename variables in `stokes.py`. * updated 2D phase and absorption recon Return the 2D absorption along with phase. Viewing OTFs in napari is very nice. I changed the axis order to be able to compare phase and absorption OTFs at focal plane. * display OTFs with Z-axis as a slider * changes to 2D phase/absorption simulation I suggest changing this example to be simulation and reconstruction of 2D specimens, thinner than the depth of field of the microscope. * convert stokes to torch * initial draft of planaraniso model * rename models to <object-type>_<object-thickness>_<data_shape> * fix isotropic_thin_3d example, include absorption * 2D -> 2d, 3D -> 3d * calculate background corrections with transfer function * rearrange examples folder * rearrange examples folder * rearrange `isotropic` and `phase` examples * add `inplane_anisotropic` model and example * fix inplane tests * fix maintenance scripts * remove deprecated * use `np.meshgrid` for consistency * minor bug * integration changes --------- Co-authored-by: Shalin Mehta <[email protected]> * Remove kwargs from reconstructions (#119) * remove kwargs * fix estimated background bug * `illumination_wavelength` -> `wavelength_illumination` (#123) * Remove duplicate test (#125) remove duplicate test * Add option for axial flip of `phase_thick_3d` transfer function (#124) * `illumination_wavelength` -> `wavelength_illumination` * add option for axial flip of transfer function * test axial flip --------- Co-authored-by: Ziwen Liu <[email protected]> * Rename model from `anisotropic_thin` to `oriented_thick` (#127) `anisotropic_thin` -> `oriented_thick` * `isotropic_fluorescent_thick_3d` model (#128) * typo * model outline * prototype transfer function * 3d phantom + visualize transfer function * refactor apply_transfer_function * typo * refactor padding (with gpt docs + tests) * complete example * test apply_inverse_transfer_function * TV reconstructions raise NotImplementedError * `pad_zyx` -> `pad_zyx_along_z` * Simplify `data += 10` * Update tests/test_util.py Co-authored-by: Ziwen Liu <[email protected]> --------- Co-authored-by: Ziwen Liu <[email protected]> * Match parameters to simplify `recOrder`-`waveorder` interface (#131) * add axial_flip to `isotropic_thin_3d` * `illumination` -> `emission` for fluorescence * simplify parameters for usage with recOrder * fix test * pin torch>=2.0.0 * `z_position_list` should accept a list --------- Co-authored-by: Shalin Mehta <[email protected]> Co-authored-by: Ziwen Liu <[email protected]>
This PR adds a completely rewritten version of all Stokes- and Mueller-related calculations in
waveorder
.This rewrite was motived by the following questions:
Highlight improvements:
mmul
(Mueller multiply) function that useseinsum
is the key simplifying design choice.What does the new API look like? Here's an example snippet from
/hpc/projects/compmicro/projects/infected_cell_imaging/Image_preprocessing/Exp_2023_02_07_A549MemNucl_PolPhase3D/Background_correction_trial/bg-corr-with-mask.py
Limitations compared to the current
waveorder_reconstructor
implementation:waveorder_reconstructor
class' parallelnp
andcp
implementations seem clunky.I have not removed the existing implementation in the
waveorder_reconstructor
class. My current plan is to discuss the technical parts of this reimplementation and compare with the existing implementation here, then later I can complete the refactor by removing the Stokes parts of thewaveorder_reconstructor
class and updating therecOrder
calls.Note: this PR is to merge into
alg-dev
, so we have a bit more flexibility in the changes. Temporarily breaking changes/suggestions are okay while we iterate.Specific feedback requests:
inverse_s0123_CPL_after_ADR
doesn't roll off the tongue like the earlierPolarization_recon
, but I think it's important to be very specific at this level. Later layers of abstraction can reintroduce more abstract names likesPolarization_recon
if we think they're helpful.