mirror of
https://github.com/cdtools-developers/cdtools.git
synced 2026-11-30 00:47:47 +01:00
Add the frantic work over the past few weeks, next challenge is to organize and test it
This commit is contained in:
1 parent
ace81cc66d
commit
bf8dbe086a
14 files changed
+815
-25
No files matched your search
@@ -10,3 +10,4 @@ from CDTools.tools import projectors
|
||||
from CDTools.tools import interactions
|
||||
from CDTools.tools import propagators
|
||||
from CDTools.tools import measurements
|
||||
from CDTools.tools import analysis
|
||||
@@ -0,0 +1,56 @@
|
||||
from __future__ import division, print_function
|
||||
|
||||
import torch as t
|
||||
import numpy as np
|
||||
from CDTools.tools import cmath
|
||||
|
||||
|
||||
|
||||
def orthogonalize_probes(probes):
|
||||
"""Orthogonalizes a set of incoherently mixing probes
|
||||
|
||||
The strategy is to define a reduced orthogonal basis that spans
|
||||
all of the retrieved probes, and then build the density matrix
|
||||
defined by the probes in that basis. After diagonalization, the
|
||||
eigenvectors can be recast into the original basis and returned
|
||||
|
||||
Args:
|
||||
probes (t.Tensor) : n x (image) size tensor, a stack of probes
|
||||
|
||||
Returns:
|
||||
(t.Tensor) : n x (image) size tensor, a stack of probes
|
||||
"""
|
||||
|
||||
try:
|
||||
probes = cmath.torch_to_complex(probes.detach().cpu())
|
||||
except:
|
||||
pass
|
||||
|
||||
bases = []
|
||||
coefficients = np.zeros((probes.shape[0],probes.shape[0]), dtype=np.complex64)
|
||||
for i, probe in enumerate(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]
|
||||
|
||||
|
||||
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)
|
||||
eigvals, eigvecs = np.linalg.eigh(density_mat)
|
||||
|
||||
ortho_probes = []
|
||||
for i in range(len(eigvals)):
|
||||
coefficients = np.sqrt(eigvals[i]) * eigvecs[:,i]
|
||||
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))
|
||||
|
||||
|
||||
|
||||
@@ -57,6 +57,33 @@ def centroid_sq(im, dims=2, comp=False):
|
||||
return centroid(im_sq, dims=dims)
|
||||
|
||||
|
||||
def sinc_subpixel_shift(im, shift):
|
||||
"""Performs a subpixel shift with sinc interpolation on the given tensor
|
||||
|
||||
The subpixel shift is done circularly via a multiplication with a linear
|
||||
phase mask in Fourier space.
|
||||
|
||||
Args:
|
||||
im (torch.Tensor) : A complex-valued tensor to perform the subpixel shift on
|
||||
shift (array_like) : A length-2 array_like object describing the shift to perform, in pixels
|
||||
|
||||
Returns:
|
||||
(torch.Tensor) : The subpixel shifted tensor
|
||||
"""
|
||||
i = t.arange(im.shape[0]) - im.shape[0]//2
|
||||
j = t.arange(im.shape[1]) - im.shape[1]//2
|
||||
I,J = t.meshgrid(i,j)
|
||||
I = 2 * np.pi * I.to(t.float32) / im.shape[0]
|
||||
J = 2 * np.pi * J.to(t.float32) / im.shape[1]
|
||||
I = I.to(dtype=im.dtype,device=im.device)
|
||||
J = J.to(dtype=im.dtype,device=im.device)
|
||||
|
||||
fft_im = cmath.fftshift(t.fft(im, 2))
|
||||
shifted_fft_im = cmath.cmult(fft_im, cmath.expi(-shift[0]*I - shift[1]*J))
|
||||
return t.ifft(cmath.ifftshift(shifted_fft_im),2)
|
||||
|
||||
|
||||
|
||||
def find_subpixel_shift(im1, im2, search_around=(0,0), resolution=10):
|
||||
"""Calculates the subpixel shift between two images by maximizing the autocorrelation
|
||||
|
||||
@@ -91,7 +118,8 @@ def find_subpixel_shift(im1, im2, search_around=(0,0), resolution=10):
|
||||
# Not sure if this is more or less stable than just the correlation
|
||||
# maximum - requires some testing
|
||||
cor = t.ifft(cor_fft / cmath.cabs(cor_fft)[:,:,None],2)
|
||||
|
||||
|
||||
|
||||
# Now, I need to shift the array to pull out a contiguous window
|
||||
# around the correlation maximum
|
||||
try:
|
||||
@@ -149,7 +177,7 @@ def find_pixel_shift(im1, im2):
|
||||
# Not sure if this is more or less stable than just the correlation
|
||||
# maximum - requires some testing
|
||||
cor = cmath.cabs(t.ifft(cor_fft / cmath.cabs(cor_fft)[:,:,None],2))
|
||||
#cor = cmath.cabs(t.ifft(cor_fft,2))
|
||||
|
||||
|
||||
sh = t.tensor(cor.shape).to(device=im1.device)
|
||||
cormax = t.tensor([t.argmax(cor) // sh[1],
|
||||
|
||||
@@ -56,6 +56,7 @@ def exit_wave_geometry(det_basis, det_shape, wavelength, distance, center=None,
|
||||
|
||||
if opt_for_fft:
|
||||
full_shape = t.Tensor([next_fast_len(dim) for dim in full_shape]).to(t.int32)
|
||||
|
||||
# Then, generate a slice that pops the actual detector from the full
|
||||
# detector shape
|
||||
full_center = full_shape // 2
|
||||
@@ -64,9 +65,10 @@ def exit_wave_geometry(det_basis, det_shape, wavelength, distance, center=None,
|
||||
int(full_center[1]-center[1]):
|
||||
int(full_center[1]-center[1]+det_shape[1])]
|
||||
|
||||
|
||||
# Finally, generate the basis for the exit wave in real space
|
||||
# I believe this calculation is incorrect for non-rectangular
|
||||
# detectors, because the real space basis shoud be related to the
|
||||
# detectors, because the real space basis should be related to the
|
||||
# dual of the original basis. Leaving this for now since
|
||||
# non-rectangular detectors are not a pressing concern.
|
||||
basis_dirs = det_basis / t.norm(det_basis, dim=0)
|
||||
@@ -75,7 +77,8 @@ def exit_wave_geometry(det_basis, det_shape, wavelength, distance, center=None,
|
||||
|
||||
# Finally, convert the shape back to a torch.Size
|
||||
full_shape = t.Size([dim for dim in full_shape])
|
||||
|
||||
|
||||
|
||||
return real_space_basis, full_shape, det_slice
|
||||
|
||||
|
||||
@@ -245,6 +248,10 @@ def SHARP_style_probe(dataset, shape, det_slice):
|
||||
# Now we remove the central pixel
|
||||
|
||||
center = np.array(probe_guess.shape) // 2
|
||||
|
||||
|
||||
# I had to remove this because it put some intensity outside of
|
||||
# the detector region that caused issues
|
||||
|
||||
probe_guess[center[0], center[1]]=np.mean([
|
||||
probe_guess[center[0]-1, center[1]],
|
||||
|
||||
@@ -178,7 +178,7 @@ def ptycho_2D_linear(probe, obj, translations, shift_probe=True):
|
||||
|
||||
|
||||
|
||||
#TODO: Implement a sinc-interpolated shift using a fourier space shifting op
|
||||
|
||||
def ptycho_2D_sinc(probe, obj, translations, shift_probe=True, padding=10):
|
||||
"""Returns a stack of exit waves accounting for subpixel shifts
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@ import numpy as np
|
||||
__all__ = ['intensity', 'incoherent sum', 'quadratic_background']
|
||||
|
||||
|
||||
def intensity(wavefield, detector_slice=None, epsilon=1e-7):
|
||||
def intensity(wavefield, detector_slice=None, epsilon=1e-7, saturation=None):
|
||||
"""Returns the intensity of a wavefield
|
||||
|
||||
The intensity is defined as the magnitude squared of the
|
||||
@@ -22,20 +22,25 @@ def intensity(wavefield, detector_slice=None, epsilon=1e-7):
|
||||
Args:
|
||||
wavefield (torch.Tensor) : A JxMxNx2 stack of complex wavefields
|
||||
detector_slice (slice) : Optional, a slice or tuple of slices defining a section of the simulation to return
|
||||
saturation (float) : Optional, a maximum saturation value to clamp the resulting intensities to
|
||||
|
||||
Returns:
|
||||
torch.Tensor : A real MxN array storing the wavefield's intensities
|
||||
"""
|
||||
if detector_slice is None:
|
||||
return cmath.cabssq(wavefield) + epsilon
|
||||
output = cmath.cabssq(wavefield) + epsilon
|
||||
else:
|
||||
if wavefield.dim() == 3:
|
||||
return cmath.cabssq(wavefield[detector_slice]) + epsilon
|
||||
output = cmath.cabssq(wavefield[detector_slice]) + epsilon
|
||||
else:
|
||||
return cmath.cabssq(wavefield[(np.s_[:],) + detector_slice]) + epsilon
|
||||
output = cmath.cabssq(wavefield[(np.s_[:],) + detector_slice]) + epsilon
|
||||
if saturation is None:
|
||||
return output
|
||||
else:
|
||||
return t.clamp(output,0,saturation)
|
||||
|
||||
|
||||
def incoherent_sum(wavefields, detector_slice=None, epsilon=1e-7):
|
||||
def incoherent_sum(wavefields, detector_slice=None, epsilon=1e-7, saturation=None):
|
||||
"""Returns the incoherent sum of the intensities of the wavefields
|
||||
|
||||
The intensity is defined as the sum of the magnitudes squared of
|
||||
@@ -50,22 +55,27 @@ def incoherent_sum(wavefields, detector_slice=None, epsilon=1e-7):
|
||||
Args:
|
||||
wavefields (torch.Tensor) : A JxLxMxNx2 stack of complex wavefields
|
||||
detector_slice (slice) : Optional, a slice or tuple of slices defining a section of the simulation to return
|
||||
saturation (float) : Optional, a maximum saturation value to clamp the resulting intensities to
|
||||
|
||||
Returns:
|
||||
torch.Tensor : A real MxN array storing the incoherently summed intensities
|
||||
"""
|
||||
# This syntax just adds an axis to the slice to preserve the J direction
|
||||
if detector_slice is None:
|
||||
return t.sum(cmath.cabssq(wavefields),dim=-3) + epsilon
|
||||
output = t.sum(cmath.cabssq(wavefields),dim=-3) + epsilon
|
||||
else:
|
||||
if wavefields.dim() == 4:
|
||||
return t.sum(cmath.cabssq(wavefields[(np.s_[:],)+detector_slice]),dim=-3) + epsilon
|
||||
output = t.sum(cmath.cabssq(wavefields[(np.s_[:],)+detector_slice]),dim=0) + epsilon
|
||||
else:
|
||||
return t.sum(cmath.cabssq(wavefields[(np.s_[:],np.s_[:])+detector_slice]),dim=-3) + epsilon
|
||||
output = t.sum(cmath.cabssq(wavefields[(np.s_[:],np.s_[:])+detector_slice]),dim=0) + epsilon
|
||||
|
||||
if saturation is None:
|
||||
return output
|
||||
else:
|
||||
return t.clamp(output,0,saturation)
|
||||
|
||||
|
||||
def quadratic_background(wavefield, background, detector_slice=None, measurement=intensity, epsilon=1e-7):
|
||||
def quadratic_background(wavefield, background, detector_slice=None, measurement=intensity, epsilon=1e-7, saturation=None):
|
||||
"""Returns the intensity of a wavefield plus a background
|
||||
|
||||
The intensity is calculated via the given measurment function
|
||||
@@ -78,13 +88,18 @@ def quadratic_background(wavefield, background, detector_slice=None, measurement
|
||||
background (torch.Tensor) : An tensor storing the square root of the detector background
|
||||
detector_slice (slice) : Optional, a slice or tuple of slices defining a section of the simulation to return
|
||||
measurement (function) : Optional, the measurement function to use. The default is measurements.intensity
|
||||
saturation (float) : Optional, a maximum saturation value to clamp the resulting intensities to
|
||||
|
||||
Returns:
|
||||
torch.Tensor : A real MxN array storing the wavefield's intensities
|
||||
"""
|
||||
if detector_slice is None:
|
||||
return measurement(wavefield, epsilon=epsilon) + background**2
|
||||
output = measurement(wavefield, epsilon=epsilon) + background**2
|
||||
else:
|
||||
return measurement(wavefield, detector_slice, epsilon=epsilon) \
|
||||
output = measurement(wavefield, detector_slice, epsilon=epsilon) \
|
||||
+ background**2
|
||||
|
||||
if saturation is None:
|
||||
return output
|
||||
else:
|
||||
return t.clamp(output,0,saturation)
|
||||
@@ -64,7 +64,7 @@ def plot_amplitude(im, fig = None, basis = np.array([[0,-1], [-1,0], [0,0]]), **
|
||||
if fig is None:
|
||||
fig = plt.figure()
|
||||
ax = fig.add_subplot(111, **kwargs)
|
||||
basis_norm = np.linalg.norm(basis, axis = -1)
|
||||
basis_norm = np.linalg.norm(basis, axis = 0)
|
||||
if isinstance(im, t.Tensor):
|
||||
absolute = cmath.cabs(im).detach().cpu().numpy()
|
||||
else:
|
||||
@@ -93,7 +93,7 @@ def plot_phase(im, fig = None, basis = np.array([[0,-1], [-1,0], [0,0]]), **kwa
|
||||
phase = cmath.cphase(im).detach().cpu().numpy()
|
||||
else:
|
||||
phase = np.angle(im)
|
||||
basis_norm = np.linalg.norm(basis, axis = -1)
|
||||
basis_norm = np.linalg.norm(basis, axis = 0)
|
||||
try: plt.imshow(phase, cmap = 'twilight', extent = [0, phase.shape[-1]*basis_norm[1], 0, phase.shape[-2]*basis_norm[0]])
|
||||
except: plt.imshow(phase, cmap = 'hsv', extent = [0, phase.shape[-1]*basis_norm[1], 0, phase.shape[-2]*basis_norm[0]])
|
||||
plt.colorbar()
|
||||
@@ -119,7 +119,7 @@ def plot_colorized(im, fig = None, basis = np.array([[0,-1], [-1,0], [0,0]]), *
|
||||
ax = fig.add_subplot(111, **kwargs)
|
||||
if isinstance(im, t.Tensor):
|
||||
im = cmath.torch_to_complex(im.detach().cpu())
|
||||
basis_norm = np.linalg.norm(basis, axis = -1)
|
||||
basis_norm = np.linalg.norm(basis, axis = 0)
|
||||
colorized = colorize(im)
|
||||
plt.imshow(colorized, extent = [0, im.shape[-1]*basis_norm[1], 0, im.shape[-2]*basis_norm[0]])
|
||||
return fig
|
||||
Reference in new issue
Block a user