get tests working

This commit is contained in:
Abe Levitan committed 2021-06-21 16:55:34 -04:00
1 parent 8f58242efe
commit 76e6d5efae
18 files changed
+291 -1072

No files matched your search

-1
View File
@@ -5,7 +5,6 @@ or numpy arrays, so they can be used either directly after reconstructions
on the attributes of the models themselves, or after-the-fact once the
data has been stored in numpy arrays.
"""
from __future__ import division, print_function
import torch as t
import numpy as np
+1 -1
View File
@@ -7,7 +7,7 @@ Appendix C. doi: 10.1007/978-1-4419-6533-2_11
They are actually taken from https://github.com/LeBeauGroup/pyMultislicer
written by Jim LeBeau, but above is the original reference.
"""
from __future__ import division, print_function, absolute_import
import numpy as np
import torch as t
from scipy import fftpack
-1
View File
@@ -5,7 +5,6 @@ specific desired information from a .cxi file. These functions should
handle all the needed conversions between standard formats (for example,
transposes of the basis arrays, shifting from object to probe motion, etc).
"""
from __future__ import division, print_function, absolute_import
import h5py
import numpy as np
@@ -7,7 +7,6 @@ kind of tools perform common image manipulations on torch tensors, in such
a way that it is safe to include them in automatic differentiation models.
"""
from __future__ import division, print_function, absolute_import
import numpy as np
import torch as t
from CDTools.tools import propagators
@@ -139,6 +138,7 @@ def find_subpixel_shift(im1, im2, search_around=(0,0), resolution=10):
shift : torch.Tensor
The relative shift (i,j) needed to best map im1 onto im2
"""
#
# Here's my approach, perhaps it's a little unconventional. I will first
# calculate the phase correlation function as found in ____ (cite a paper
@@ -159,7 +159,7 @@ def find_subpixel_shift(im1, im2, search_around=(0,0), resolution=10):
try:
search_around = search_around.cpu()
except:
search_around = t.tensor(search_around)
search_around = t.as_tensor(search_around)
window_size = 15
shift_zero = tuple(-search_around + t.tensor([window_size,window_size]))
@@ -178,6 +178,7 @@ def find_subpixel_shift(im1, im2, search_around=(0,0), resolution=10):
# And we extract the shift from the window
print(upsampled.shape)
sh = t.as_tensor(upsampled.shape, device=upsampled.device)
cormax = t.as_tensor([t.div(t.argmax(upsampled), sh[1],
rounding_mode='floor'),
@@ -185,6 +186,9 @@ def find_subpixel_shift(im1, im2, search_around=(0,0), resolution=10):
device=upsampled.device)
sh_over_2 = t.div(sh,2,rounding_mode='floor')
print(cormax.shape)
print(sh.shape)
print(sh_over_2.shape)
subpixel_shift = ((cormax + sh_over_2) % sh - sh_over_2).to(dtype=upsampled.dtype)
return search_around.to(device=upsampled.device, dtype=upsampled.dtype) + \
@@ -301,7 +305,9 @@ def convolve_1d(image, kernel, dim=0, fftshift_kernel=True):
return conv_im
def fourier_upsample(ims):
def fourier_upsample(ims, preserve_mean=False):
# If preserve_mean is true, it preserves the mean pixel intensity
# otherwise, it preserves the total summed intensity
upsampled = t.zeros(ims.shape[:-2]+(2*ims.shape[-2],2*ims.shape[-1]),
dtype=ims.dtype,
device=ims.device)
@@ -310,6 +316,8 @@ def fourier_upsample(ims):
ims.shape[-1]//2+ims.shape[-1]]
upsampled[...,left[0]:right[0],left[1]:right[1]] = propagators.far_field(ims)
if preserve_mean:
upsampled *= 2
return propagators.inverse_far_field(upsampled)
+114 -16
View File
@@ -4,22 +4,22 @@ The functions in this module both do the geometric calculations needed to
initialize the reconstrucions, and the heuristic calculations for
geierating sensible initializations for the probe guess.
"""
from __future__ import division, print_function, absolute_import
import numpy as np
import torch as t
__all__ = ['exit_wave_geometry', 'calc_object_setup', 'gaussian',
'gaussian_probe', 'SHARP_style_probe', 'RPI_spectral_init',
'generate_subdominant_modes']
from CDTools.tools.propagators import *
from CDTools.tools.analysis import orthogonalize_probes
from CDTools.tools import image_processing
from scipy.fftpack import next_fast_len
from scipy.sparse import linalg as spla
from torch.nn.functional import pad
import numpy as np
from functools import *
__all__ = ['exit_wave_geometry', 'calc_object_setup', 'gaussian',
'gaussian_probe', 'SHARP_style_probe', 'STEM_style_probe',
'RPI_spectral_init',
'generate_subdominant_modes']
def exit_wave_geometry(det_basis, det_shape, wavelength, distance, center=None, opt_for_fft=True, padding=0, oversampling=1):
"""Returns an exit wave basis and shape, as well as a detector slice for the given detector geometry
@@ -378,6 +378,104 @@ def SHARP_style_probe(dataset, shape, det_slice, propagation_distance=None, over
return final_probe
def STEM_style_probe(dataset, shape, det_slice, convergence_semiangle, propagation_distance=None, oversampling=1):
"""Generates a STEM style probe guess from a dataset
What we call the "STEM" style probe guess is a probe generated by
a uniform aperture in Fourier space, with no optical aberrations.
This is the kind of probe than an ideal, aberration-corrected STEM
with perfect coherence would produce, so it is a good starting
guess for STEM datasets.
We set the initial intensity of the probe with relation to the
diffraction patterns so that a typical object will have an intensity
of around 1. We also set the initial phase ramp of the probe such that
the undiffracted probe has a centroid on the detector which matches the
centroid of the diffraction patterns
Parameters
----------
dataset : Ptycho_2D_Dataset
The dataset to work from
shape : torch.Size
The size of the probe array to simulate
det_slice : slice
A slice or tuple of slices corresponding to the detector region in Fourier space
convergence_angle : float
The convergence angle of the probe, in mrad.
propagation_distance : float
Default is no propagation, an amount to propagate the guessed probe from it's focal point
oversampling : int
Default 1, the width of the region of pixels in the wavefield to bin into a single detector pixel
Returns
-------
torch.Tensor
The complex-style tensor storing the probe guess
"""
# The basis in the dataset should describe the basis of the probe's
# Fourier transform, even if the probe is simulated on larger stage than
# the detector. The only issue is if the probe is oversampled in
# Fourier space (simulated on a larger stage in real space). That factor
# is defined by oversampling.
probe_basis = dataset.detector_geometry['basis'] / oversampling
mean_im = t.mean(dataset.patterns,dim=0)
center = image_processing.centroid(mean_im)
Is = t.arange(shape[0], dtype=t.float32) - center[0]
Js = t.arange(shape[1], dtype=t.float32) - center[1]
Is,Js = t.meshgrid(Is,Js)
Rs = t.tensordot(probe_basis,t.stack([Is,Js]),dims=1)
forward = t.Tensor([0,0,1])
Rs = (forward * dataset.detector_geometry['distance'])[:,None,None] + Rs
dirs = Rs / t.linalg.norm(Rs,dim=(0,))
angles = t.acos(t.tensordot(forward,dirs,dims=1)) * 1000 #in mrad
probe_fft = t.zeros(shape,dtype=t.complex64)
probe_fft[angles<convergence_semiangle] = 1
probe_mean = t.mean(t.abs(probe_fft)**2)
diff_mean = t.mean(mean_im)
probe_fft = probe_fft * t.sqrt(diff_mean / probe_mean)
probe_guess = inverse_far_field(probe_fft)
if propagation_distance is not None:
# It's probably worth checking if this is correct when oversampling
# is not 1
probe_shape = t.as_tensor(tuple(probe_guess.shape))
# Start by recalculating the probe basis from the given information
det_basis = t.as_tensor(dataset.detector_geometry['basis'])
basis_dirs = det_basis / t.norm(det_basis, dim=0)
distance = dataset.detector_geometry['distance']
probe_basis = basis_dirs * dataset.wavelength * distance / \
(probe_shape * t.norm(det_basis,dim=0))
# Then package everything as it's needed
probe_spacing = t.norm(probe_basis,dim=0).numpy()
probe_shape = probe_shape.numpy().astype(np.int32)
# And generate the propagator
AS_prop = generate_angular_spectrum_propagator(probe_shape, probe_spacing, dataset.wavelength, propagation_distance)
probe_guess = near_field(probe_guess,AS_prop)
# Finally, place this probe in a full-sized array if there is oversampling
final_probe = t.zeros(shape,dtype=t.complex64)
left = shape[0]//2 - probe_guess.shape[0] // 2
top = shape[1]//2 - probe_guess.shape[1] // 2
final_probe[left:left+probe_guess.shape[0],
top:top+probe_guess.shape[1]] = probe_guess
return final_probe
def RPI_spectral_init(pattern, probe, obj_shape, n_modes=1, mask=None, background=None):
# First, check if the probe is a single mode or many modes.
@@ -495,27 +593,27 @@ def generate_subdominant_modes(dominant_mode, n_modes, circular=True):
dominant_fft = far_field(dominant_mode)
shape = dominant_mode.shape
center = ((shape[-3]-1)//2, (shape[-2]-1)//2)
center = ((shape[-2]-1)//2, (shape[-1]-1)//2)
i, j = np.mgrid[:shape[-3], :shape[-2]]
i, j = np.mgrid[:shape[-2], :shape[-1]]
i = t.tensor(i - center[0]).to(dtype=dominant_fft.dtype,
device=dominant_fft.device)
j = t.tensor(j - center[1]).to(dtype=dominant_fft.dtype,
device=dominant_fft.device)
if circular:
a = t.stack((i,j),dim=-1)
b = t.stack((i,-j),dim=-1)
a = i + 1j * j
b = i - 1j * j
else:
a = t.stack((i,t.zeros_like(i)),dim=-1)
b = t.stack((j,t.zeros_like(j)),dim=-1)
a = i
b = j
probe_norm = t.sum(cmath.cabssq(dominant_mode))
probe_norm = t.sum(t.abs(dominant_mode)**2)
# Then we need to multiply that FFT by various phase masks and IFFT
probes = []
for a_order,b_order in make_orders(n_modes):
mask = reduce(cmath.cmult,[a]*a_order+[b]*b_order)
new_probe = inverse_far_field(cmath.cmult(mask,dominant_fft))
probes.append(new_probe * (probe_norm / t.sum(cmath.cabs(new_probe))))
mask = reduce(t.mul,[a]*a_order+[b]*b_order)
new_probe = inverse_far_field(mask * dominant_fft)
probes.append(new_probe * (probe_norm / t.sum(t.abs(new_probe))))
return t.stack(probes)
+18 -15
View File
@@ -5,11 +5,9 @@ function simulates some aspect of an interaction model that can be used
for ptychographic reconstruction.
"""
from __future__ import division, print_function, absolute_import
import torch as t
import numpy as np
from CDTools.tools import propagators
from CDTools.tools import propagators, image_processing
__all__ = ['translations_to_pixel', 'pixel_to_translations',
'project_translations_to_sample',
@@ -225,7 +223,7 @@ def project_translations_to_sample(sample_basis, translations):
def ptycho_2D_round(probe, obj, translations, multiple_modes=False):
def ptycho_2D_round(probe, obj, translations, multiple_modes=False, upsample_obj=False):
"""Returns a stack of exit waves without accounting for subpixel shifts
This function returns a collection of exit waves, with the first
@@ -265,10 +263,20 @@ def ptycho_2D_round(probe, obj, translations, multiple_modes=False):
integer_translations = t.round(translations).to(dtype=t.int32)
selections = t.stack([obj[tr[0]:tr[0]+probe.shape[-2],
if upsample_obj:
selections = t.stack([obj[tr[0]:tr[0]+probe.shape[-2]//2,
tr[1]:tr[1]+probe.shape[-1]//2]
for tr in integer_translations])
selections = image_processing.fourier_upsample(selections,
preserve_mean=True)
else:
selections = t.stack([obj[tr[0]:tr[0]+probe.shape[-2],
tr[1]:tr[1]+probe.shape[-1]]
for tr in integer_translations])
if multiple_modes:
# if the probe dimension is 4, then this hasn't yet been broadcast
# over the translation dimensions
@@ -445,26 +453,22 @@ def ptycho_2D_sinc(probe, obj, translations, shift_probe=True, padding=10, multi
-subpixel_translations[:,1,None,None]*J))
fft_probe = t.fft.fftshift(t.fft.fft2(probe),dim=(-1,-2))
if probe.dim == 3: # Multi-mode probe
shifted_fft_probe = fft_probe * phase_masks[:,None,:,:]
if multiple_modes: # Multi-mode probe
shifted_fft_probe = fft_probe * phase_masks[...,None,:,:]
else:
shifted_fft_probe = fft_probe * phase_masks
shifted_probe = t.fft.ifft2(t.fft.ifftshift(shifted_fft_probe,
dim=(-1,-2)))
print('p',probe.shape)
print('fftp',fft_probe.shape)
print('sp',shifted_probe.shape)
print('sel',selections.shape)
if probe.dim == 3: # Multi-mode probe
output = shifted_probe * selections[:,None,:,:]
if multiple_modes: # Multi-mode probe
output = shifted_probe * selections[...,None,:,:]
else:
output = shifted_probe * selections
else:
raise NotImplementedError('Object shift not yet implemented')
print(output.shape)
if single_translation:
return output[0]
else:
@@ -532,7 +536,6 @@ def ptycho_2D_sinc_s_matrix(probe, s_matrix, translations, shift_probe=True, pad
J = 2 * np.pi * J.to(t.float32) / probe.shape[-1]
I = I.to(dtype=probe.dtype,device=probe.device)
J = J.to(dtype=probe.dtype,device=probe.device)
print('hi')
for tr, sp in zip(integer_translations,
subpixel_translations):
+1 -2
View File
@@ -5,9 +5,8 @@ that returns the mean squared intensity error, and one that returns the
maximum likelihood metric for a system with Poisson statistics.
"""
from __future__ import division, print_function, absolute_import
import torch as t
import torch as t
__all__ = ['amplitude_mse', 'intensity_mse', 'poisson_nll']
@@ -5,8 +5,6 @@ model. There exist tools to simulate detectors with finite saturation
thresholds, backgrounds, and more.
"""
from __future__ import division, print_function, absolute_import
import torch as t
import numpy as np
from torch.nn.functional import avg_pool2d
-2
View File
@@ -6,8 +6,6 @@ and for after-the-fact analysis. Utilities for plotting complex valued
images exist, as well as plotting scan patterns and nanomaps
"""
from __future__ import division, print_function, absolute_import
import torch as t
import numpy as np
import matplotlib.pyplot as plt
+23 -13
View File
@@ -3,7 +3,6 @@
All the functions here are designed for use in an automatic differentiation
ptychography model. Each function implements a different propagator.
"""
from __future__ import division, print_function, absolute_import
import torch as t
from torch.nn.functional import grid_sample
@@ -316,11 +315,9 @@ def high_NA_far_field(wavefront, k_map, intensity_map=None):
def generate_angular_spectrum_propagator(shape, spacing, wavelength, z, *args, remove_z_phase=False, bandlimit=None, **kwargs):
"""Generates an angular-spectrum based near-field propagator from experimental quantities
This function generates an angular-spectrum based near field
propagator that will work on torch Tensors. The function is structured
this way - to generate the propagator first - because the
@@ -335,7 +332,7 @@ def generate_angular_spectrum_propagator(shape, spacing, wavelength, z, *args, r
to zero beyond an explicit bandlimiting frequency. This is helpful if the
propagator will be used in a repeated multiply/propagate framework such
as a multislice algorithm, where it helps to prevent aliasing.
Parameters
----------
shape : array
@@ -358,13 +355,20 @@ def generate_angular_spectrum_propagator(shape, spacing, wavelength, z, *args, r
"""
# Internally, the generalized propagation function is used, so we start
# by creating an appropriate basis
basis = t.zeros([3,2], **kwargs).real
# This creates a real-valued tensor which matches the kind of complex
# number dtype requested in **kwargs
if 'dtype' in kwargs:
basis = t.real(t.zeros([3,2], **kwargs))
else:
basis = t.zeros([3,2], dtype=t.float32)
spacing = t.as_tensor(spacing, dtype=basis.dtype)
basis[1,0] = -spacing[0]
basis[0,1] = -spacing[1]
# And similarly, the offset is just z along the z direction
offset = t.zeros([3],**kwargs).real
offset = t.zeros([3], dtype=basis.dtype)
offset[2] = z
# And we call the generalized function!
propagator = generate_generalized_angular_spectrum_propagator(shape, basis,
wavelength, offset,
@@ -478,6 +482,7 @@ def generate_generalized_angular_spectrum_propagator(shape, basis, wavelength, o
# First we calculate a dual basis for the real space grid
inv_basis = t.linalg.pinv(basis).transpose(0,1)
# Then we calculate the frequencies in (i,j) space
ki = 2 * np.pi * t.fft.fftfreq(shape[0], dtype=inv_basis.dtype)
kj = 2 * np.pi * t.fft.fftfreq(shape[1], dtype=inv_basis.dtype)
@@ -487,10 +492,16 @@ def generate_generalized_angular_spectrum_propagator(shape, basis, wavelength, o
# These frequencies span the 2D plane of the input wavefield,
# hence K_ip for "in-plane"
K_ip = t.tensordot(inv_basis, K_ij, dims=1)
# Now, we need to generate the out-of-plane direction, so we can
# expand these Ks to the full Ks in 3D reciprocal space.
perpendicular_dir = t.cross(basis[:,1],basis[:,0])
# THis is broken down into steps to avoid floating point underflow
# which was a real problem that showed up for electron ptycho
b1_dir = basis[:,0] / t.linalg.norm(basis[:,0])
b2_dir = basis[:,1] / t.linalg.norm(basis[:,1])
perpendicular_dir = t.cross(b1_dir,b2_dir)
perpendicular_dir /= t.linalg.norm(perpendicular_dir)
# We set the sign of the propagation direction appropriately
@@ -514,7 +525,7 @@ def generate_generalized_angular_spectrum_propagator(shape, basis, wavelength, o
# Now, we have accurate in-plane values for K, so we can calculate the
# out-of-plane part. We start by calculating it's squared magnitude
K_oop_squared = (2*np.pi/wavelength)**2 - t.linalg.norm(K_ip,dim=0)**2
# Then, we take the square root and assign it the appropriate direction,
# adding to get the full 3D wavevectors. Note that we convert to complex
# before the square root to appropriately map negative numbers to
@@ -522,7 +533,7 @@ def generate_generalized_angular_spectrum_propagator(shape, basis, wavelength, o
K = K_ip + perpendicular_dir[:,None,None] \
* t.sqrt(t.complex(K_oop_squared,t.zeros_like(K_oop_squared)))
#
#
# In this section, we take the inner product of the calcualted
# wavevectors with the offset vector, to get the phase shift
# experienced by each plane wave.
@@ -535,7 +546,6 @@ def generate_generalized_angular_spectrum_propagator(shape, basis, wavelength, o
# experienced by K_0 to 0. K_0 will already have been set to 0 if
# there was no propagation vector set.
K_m_K_0 = K - K_0[:,None,None]
# We actually calculate the phase mask
phase_mask = t.tensordot(offset_vector,K_m_K_0, dims=1)