diff --git a/CDTools/tools/analysis.py b/CDTools/tools/analysis.py index 9f87a92..09ae5f4 100644 --- a/CDTools/tools/analysis.py +++ b/CDTools/tools/analysis.py @@ -4,8 +4,9 @@ import torch as t import numpy as np from CDTools.tools import cmath +__all__ = ['orthogonalize_probes'] - +from matplotlib import pyplot as plt def orthogonalize_probes(probes): """Orthogonalizes a set of incoherently mixing probes @@ -32,25 +33,27 @@ def orthogonalize_probes(probes): ortho_probe = np.copy(probe) for j, basis in enumerate(bases): coefficients[j,i] = np.sum(basis.conj()*ortho_probe) - ortho_probe -= basis * coefficients[i,j] + ortho_probe -= basis * coefficients[j,i] coefficients[i,i] = np.sqrt(np.sum(np.abs(ortho_probe)**2)) bases.append(ortho_probe / coefficients[i,i]) - density_mat = np.conj(coefficients).transpose().dot(coefficients) + + density_mat = coefficients.dot(np.conj(coefficients).transpose()) eigvals, eigvecs = np.linalg.eigh(density_mat) ortho_probes = [] for i in range(len(eigvals)): coefficients = np.sqrt(eigvals[i]) * eigvecs[:,i] + print(coefficients) probe = np.zeros(bases[0].shape, dtype=np.complex64) for coefficient, basis in zip(coefficients, bases): probe += basis * coefficient ortho_probes.append(probe) - return cmath.complex_to_torch(np.stack(ortho_probes)) + return cmath.complex_to_torch(np.stack(ortho_probes[::-1])) diff --git a/CDTools/tools/image_processing.py b/CDTools/tools/image_processing.py index 44f4eb8..322889f 100644 --- a/CDTools/tools/image_processing.py +++ b/CDTools/tools/image_processing.py @@ -3,6 +3,8 @@ import numpy as np import torch as t from CDTools.tools import cmath +__all__ = ['centroid', 'centroid_sq', 'sinc_subpixel_shift', + 'find_subpixel_shift', 'find_pixel_shift', 'find_shift'] def centroid(im, dims=2): diff --git a/CDTools/tools/initializers.py b/CDTools/tools/initializers.py index d5ad876..33268b1 100644 --- a/CDTools/tools/initializers.py +++ b/CDTools/tools/initializers.py @@ -3,7 +3,7 @@ import numpy as np import torch as t __all__ = ['exit_wave_geometry', 'calc_object_setup', 'gaussian', - 'gaussian_probe'] + 'gaussian_probe', 'SHARP_style_probe'] from CDTools.tools import cmath from CDTools.tools.propagators import inverse_far_field diff --git a/CDTools/tools/interactions.py b/CDTools/tools/interactions.py index c70d6dd..c4437e3 100644 --- a/CDTools/tools/interactions.py +++ b/CDTools/tools/interactions.py @@ -5,6 +5,8 @@ import torch as t import numpy as np +__all__ = ['translations_to_pixel', #'pixel_to_translations', + 'ptycho_2D_round','ptycho_2D_linear','ptycho_2D_sinc'] # # This file will host tools to turn various kinds of model information @@ -12,6 +14,7 @@ import numpy as np # area. # + def translations_to_pixel(basis, translations, surface_normal=t.Tensor([0,0,1])): """Takes real space translations and outputs them in pixel space diff --git a/CDTools/tools/plotting.py b/CDTools/tools/plotting.py index c9fbb47..3d2212a 100644 --- a/CDTools/tools/plotting.py +++ b/CDTools/tools/plotting.py @@ -7,6 +7,10 @@ import matplotlib.pyplot as plt from matplotlib.colors import hsv_to_rgb +__all__ = ['colorize','plot_1D','plot_amplitude','plot_phase', + 'plot_colorized'] + + def colorize(z): """ Returns RGB values for a complex color plot given a complex array This function returns a set of RGB values that can be used directly @@ -34,7 +38,7 @@ def colorize(z): return hsv_to_rgb(np.dstack((h,s,v))) -def plot_1d(arr, fig = None, **kwargs): +def plot_1D(arr, fig = None, **kwargs): """Simple 1D plotter Args: diff --git a/CDTools/tools/projectors.py b/CDTools/tools/projectors.py index a4bb10a..f4f9f8b 100644 --- a/CDTools/tools/projectors.py +++ b/CDTools/tools/projectors.py @@ -4,6 +4,7 @@ import torch as t __all__ = ['modulus', 'support'] + def modulus(wavefront, intensities, mask = None): """Implements the modulus constraint in torch diff --git a/tests/tools/test_analysis.py b/tests/tools/test_analysis.py new file mode 100644 index 0000000..9919b90 --- /dev/null +++ b/tests/tools/test_analysis.py @@ -0,0 +1,43 @@ +from __future__ import division, print_function, absolute_import + +import pytest +import numpy as np +import torch as t +from itertools import combinations + +from CDTools.tools import analysis, cmath + + +from matplotlib import pyplot as plt +def test_orthogonalize_probes(): + + # The test strategy should be to define a few non-orthogonal probes + # and orthogonalize them. Then we can test two features of the results: + + # 1) Are they orthogonal? + # 2) Is the total intensity at each point the same as it was originally? + + probe_xs = np.arange(128) - 64 + probe_ys = np.arange(150) - 75 + probe_Ys, probe_Xs = np.meshgrid(probe_ys, probe_xs) + probe_Rs = np.sqrt(probe_Xs**2 + probe_Ys**2) + + probes = np.array([10*np.exp(-probe_Rs**2 / (2 * 10**2)), + 3*np.exp(-probe_Rs**2 / (2 * 12**2)), + 1*np.exp(-probe_Rs**2 / (2 * 15**2))]).astype(np.complex64) + + ortho_probes = cmath.torch_to_complex(analysis.orthogonalize_probes(probes)) + + for p1,p2 in combinations(ortho_probes,2): + assert np.sum(np.conj(p1)*p2) / np.sum(np.abs(p1)**2) < 1e-6 + + for probe in ortho_probes: + print(np.sum(np.abs(probe)**2)) + + for probe in probes: + print(np.sum(np.abs(probe)**2)) + + probe_intensity = np.sum(np.abs(probes)**2,axis=0) + ortho_probe_intensity = np.sum(np.abs(ortho_probes)**2,axis=0) + + assert np.allclose(probe_intensity,ortho_probe_intensity) diff --git a/tests/tools/test_cmath.py b/tests/tools/test_cmath.py index 8a8cdbe..e39d821 100644 --- a/tests/tools/test_cmath.py +++ b/tests/tools/test_cmath.py @@ -124,3 +124,12 @@ def test_ifftshift(): shifted = cmath.ifftshift(cmath.complex_to_torch(arr),dims=(0,1)) assert np.allclose(ifftshift(arr,axes=(0,1)), cmath.torch_to_complex(shifted)) + + +def test_expi(): + phases = np.random.rand(20,70) * 2 * np.pi + np_result = np.exp(1j * phases) + + torch_result = cmath.expi(t.Tensor(phases)) + + assert np.allclose(np_result, cmath.torch_to_complex(torch_result)) diff --git a/tests/tools/test_image_processing.py b/tests/tools/test_image_processing.py index 038398a..7fcd736 100644 --- a/tests/tools/test_image_processing.py +++ b/tests/tools/test_image_processing.py @@ -39,6 +39,25 @@ def test_centroid_sq(): centroids = image_processing.centroid_sq(ims, comp=True) assert t.allclose(centroids, t.Tensor(np.array(sp_centroids))) + +def test_sinc_subpixel_shift(): + + im = np.zeros((512,512), dtype=np.complex128) + im[256,256] = 1 + + # test it by creating a single pixel object and seeing that it is + # shifted correctly + xs = np.arange(512) - 256 + Ys,Xs = np.meshgrid(xs,xs) + sinc_im = np.sinc(Xs-0.3) * np.sinc(Ys-0.6) + + torch_im = cmath.complex_to_torch(im) + test_im = image_processing.sinc_subpixel_shift(torch_im,(0.3,0.6)) + + # The fidelity isn't great due to the FFT-based approach, so we need + # a pretty relaxed condition + assert np.max(np.abs(sinc_im - cmath.torch_to_complex(test_im))) < 0.005 + def test_find_pixel_shift(): diff --git a/tests/tools/test_interactions.py b/tests/tools/test_interactions.py index d787aa4..11de230 100644 --- a/tests/tools/test_interactions.py +++ b/tests/tools/test_interactions.py @@ -136,4 +136,51 @@ def test_ptycho_2D_linear(single_pixel_probe, random_obj): assert np.isclose(np.sum(obj_shift * obj_section),exit_pixel) # Test for a single translation + + +def test_ptycho_2D_sinc(single_pixel_probe, random_obj): + + + # For this one, I just want to check one translation, but + # I need to check both formats + translations = np.array([[46.7,53.2]]) + translation = np.array([46.7,53.2]) + + exit_waves_probe = interactions.ptycho_2D_sinc( + cmath.complex_to_torch(single_pixel_probe), + cmath.complex_to_torch(random_obj), + t.tensor(translations), + shift_probe=True) + + exit_wave_probe = interactions.ptycho_2D_sinc( + cmath.complex_to_torch(single_pixel_probe), + cmath.complex_to_torch(random_obj), + t.tensor(translation), + shift_probe=True) + + # Check that the outputs match + assert t.allclose(exit_waves_probe[0],exit_wave_probe) + + + # Now we explicitly define what the sinc interpolated array should + # look like + xs = np.arange(256) - 128 + Ys,Xs = np.meshgrid(xs,xs) + sinc_probe = np.sinc(Xs) * np.sinc(Ys) + # Just check that the unshifted probe is correct + assert np.allclose(single_pixel_probe, sinc_probe) + + sinc_shifted_probe = np.sinc(Xs-0.7) * np.sinc(Ys-0.2) + obj_section = random_obj[46:46+256, + 53:53+256] + exit_wave_np = sinc_shifted_probe * obj_section + + exit_wave_torch = cmath.torch_to_complex(exit_wave_probe) + + # The fidelity isn't great due to the FFT-based approach, so we need + # a pretty relaxed condition + assert np.max(np.abs(exit_wave_np-exit_wave_torch)) < 0.005 + + + diff --git a/tests/tools/test_plotting.py b/tests/tools/test_plotting.py index e64e9f3..5fc04ef 100644 --- a/tests/tools/test_plotting.py +++ b/tests/tools/test_plotting.py @@ -9,10 +9,10 @@ import torch as t import scipy.misc import matplotlib.pyplot as plt -def test_plot_1d(show_plot): +def test_plot_1D(show_plot): # Plot simple linear scatter plot arr = np.arange(10) - plotting.plot_1d(arr, title = 'Linear Plot') + plotting.plot_1D(arr, title = 'Linear Plot') if show_plot: plt.show() diff --git a/tests/tools/test_propagators.py b/tests/tools/test_propagators.py index 62041f4..a11537a 100644 --- a/tests/tools/test_propagators.py +++ b/tests/tools/test_propagators.py @@ -86,3 +86,29 @@ def test_near_field(): # Again, 10^-3 is about all the accuracy we can expect assert np.max(np.abs(Emz-Emz_t)) < 1e-3 * np.max(np.abs(Emz)) + + +def test_inverse_near_field(): + + x = (np.arange(800) - 400) * 1.5e-9 + y = (np.arange(1200) - 600) * 1e-9 + Ys,Xs = np.meshgrid(y,x) + Rs = np.sqrt(Xs**2+Ys**2) + + wavelength = 3e-9 #nm + sigma = 20e-9 #nm + z = 1000e-9 #nm + + w0 = np.sqrt(2)*sigma + E0 = np.exp(-Rs**2 / w0**2) + + asp = propagators.generate_angular_spectrum_propagator( + E0.shape,(1.5e-9,1e-9),wavelength,z,dtype=t.float64) + + E0 = cmath.complex_to_torch(E0) + E_prop = propagators.near_field(E0,asp) + + E_backprop = propagators.inverse_near_field(E_prop, asp) + + # We just want to check that it actually is the inverse + assert t.all(t.isclose(E0,E_backprop))