mirror of
https://github.com/cdtools-developers/cdtools.git
synced 2026-11-27 15:37:49 +01:00
remove useless old examples, and update the examples and docs to be useful for the current version
This commit is contained in:
1 parent
46b00807c8
commit
7b2509cfe1
22 files changed
+311
-551
No files matched your search
+3
-3
@@ -20,13 +20,13 @@ sys.path.insert(0, os.path.abspath('../..'))
|
||||
# -- Project information -----------------------------------------------------
|
||||
|
||||
project = 'CDTools'
|
||||
copyright = '2019-2021, Abraham Levitan'
|
||||
copyright = '2019-2024, Abraham Levitan'
|
||||
author = 'Abraham Levitan'
|
||||
|
||||
# The short X.Y version
|
||||
version = '0.1'
|
||||
version = '0.2'
|
||||
# The full version, including alpha/beta/rc tags
|
||||
release = '0.1.0'
|
||||
release = '0.2.0'
|
||||
|
||||
|
||||
# -- General configuration ---------------------------------------------------
|
||||
|
||||
+60
-58
@@ -1,98 +1,100 @@
|
||||
Examples
|
||||
========
|
||||
|
||||
Included with the repository are a number of example scripts that demonstrate how various aspects of CDTools work. It is recommended to read through at least a few of them before continuing to the tutorial, to get a feel for how the ptychography scripts work.
|
||||
Included with the repository are a number of example scripts that demonstrate how various aspects of CDTools work. It is recommended to read through at least a few of them before continuing to the tutorial.
|
||||
|
||||
All the datasets used in these example scripts are included in the repository, and the scripts should be runnable as soon as CDTools is installed
|
||||
|
||||
|
||||
Inspect Dataset
|
||||
---------------
|
||||
|
||||
We have some ptychography data in a .cxi file. How do we look at it, confirm that it looks like you expect, hasn't been corrupted, etc? This script demonstrates how to load and look at your data, if it's stored as a compliant .cxi file.
|
||||
The first example loads and visualizes ptychography data stored in a .cxi file.
|
||||
|
||||
.. literalinclude:: ../../examples/inspect_dataset.py
|
||||
|
||||
First, data is read into a Ptycho2DDataset object, which is a subclass of a pytorch dataset. This dataset, unsurprisingly, is for 2D ptycho scan data. Calling :code:`dataset.inspect` generates a plot showing an overview of the ptychography scan data, with a nanomap of integrated detector intensity on the left and detector images on the right.
|
||||
First, data is read into a Ptycho2DDataset object, which is a subclass of a pytorch dataset that knows a bit about the structure of ptychography data. Calling :code:`dataset.inspect` generates a plot showing an overview of the ptychography scan data. On the left is a scatter plot showing the integrated detector intensity at each probe location. On the right, raw detector images are shown. The dataset can be navigated by clicking around the scatter plot on the left.
|
||||
|
||||
|
||||
Simple Ptycho
|
||||
-------------
|
||||
|
||||
This script runs a ptychography reconstruction using the SimplePtycho model. This model implements a straightforward transmission ptychography geometry, with no position refinement, incoherent modes, or other doodads (only a background model).
|
||||
This script runs a ptychography reconstruction using the SimplePtycho model, a bare-bones ptychography model for the transmission geometry.
|
||||
|
||||
The purpose of the SimplePtycho model is pedagogical: there are very few situations where it would preferred to the FancyPtycho model which will be introduced later.
|
||||
|
||||
Because of it's simplicity, the definition of this model is much simpler than the definition of FancyPtycho, and it is therefore a good first model to look at to learn how to implement a custom ptychography model in CDTools.
|
||||
|
||||
.. literalinclude:: ../../examples/simple_ptycho.py
|
||||
|
||||
Because this script only runs ten iterations, the quality of the reconstruction is relatively poor - however, on this particular dataset, running 75 or so iterations will lead to a surprisingly good reconstruction. On other datasets, however, it will often fail to converge, even in some cases where there is little error in the data.
|
||||
When reading this script, note the basic workflow. After the data is loaded, a model is created to match the geometry stored in the dataset with a sensible default initialization for all the parameters.
|
||||
|
||||
When reading this script, note the basic workflow. After the data is loaded, a model is created to match the geometry stored in the dataset, with a default initialization for all the parameters. Next, a reconstruction is run (and the progress reported out). Finally, the finished reconstruction is plotted.
|
||||
Next, the model is moved to the GPU using the :code:`model.to` function. Any device understood by :code:`torch.Tensor.to` can be specified here. The next line is a bit more subtle - the dataset is told to move patterns to the GPU before passing them to the model using the :code:`dataset.get_as` function. This function does not move the stored patterns to the GPU. If there is sufficient GPU memory, the patterns can also be pre-moved to the GPU using :code:`dataset.to`, but the speedup is empirically quite small.
|
||||
|
||||
Once the device is selected, a reconstruction is run using :code:`model.Adam_optimize`. This is a generator function which will yield at every epoch, to allow some monitoring code to be run.
|
||||
|
||||
Finally, the results can be studied using :code:`model.inspect(dataet)`, which creates or updates a set of plots showing the current state of the model parameters. :code:`model.compare(dataset)` is also called, which shows how the simulated diffraction patterns compare to the measured diffraction patterns in the dataset.
|
||||
|
||||
|
||||
Gold Balls Ptycho
|
||||
-----------------
|
||||
Fancy Ptycho
|
||||
------------
|
||||
|
||||
This script uses the FancyPtycho model to perform a reconstruction from the classic `gold balls <http://www.cxidb.org/id-65.html>`_ dataset. The FancyPtycho model is the workhorse model for 2D Ptychographic reconstructions, and has the option to enable correction for a variety of potential sources of error.
|
||||
This script runs a reconstruction on the same data, but using the workhorse FancyPtycho model, demonstrating some of it's more commonly used features
|
||||
|
||||
.. literalinclude:: ../../examples/fancy_ptycho.py
|
||||
|
||||
The :code:`FancyPtycho.from_dataset` factory function has many keyword arguments which can turn on or modify various mixins. In this case, we perform a reconstruction with:
|
||||
|
||||
- 3 incoherently mixing probe modes (in the vein of doi:10.1038/nature11806)
|
||||
- A probe array expanded by a factor of 2 in real space, i.e. simulated on a 2x2 upsampled grid in Fourier space (in the vein of doi:10.1103/PhysRevA.87.053850)
|
||||
- A circular finite support constraint applied to the probe
|
||||
- An initial guess for the probe which has been propagated from its focus position
|
||||
|
||||
By default, FancyPtycho will also optimize over the following model parameters, each of which corrects for a specific source of errror:
|
||||
|
||||
:code:`model.background`
|
||||
A frame-independent detector background
|
||||
|
||||
:code:`model.weights`
|
||||
A frame-to-frame variation in the incoming probe intensity
|
||||
|
||||
:code:`model.translation_offsets`
|
||||
A frame-independent detector background
|
||||
|
||||
These corrections can be turned off (on) by calling :code:`model.<parameter>.requires_grad = False #(True)`.
|
||||
|
||||
|
||||
Gold Ball Ptycho
|
||||
----------------
|
||||
|
||||
This script shows how the FancyPtycho model might be used in a realistic situation, to perform a reconstruction on the classic `gold balls <http://www.cxidb.org/id-65.html>`_ dataset. This script also shows how to save results!
|
||||
|
||||
.. literalinclude:: ../../examples/gold_ball_ptycho.py
|
||||
|
||||
A number of things are changed about this script. The first difference is the section where we transfer the data and the model to the GPU. This is an important step if we would like to get a reconstruction anytime soon!
|
||||
Note, in particular, the use of :code:`model.save_on_exception` and :code:`model.save_to_h5` to save the results of the reconstruction. If a different file format is required, :code:`model.save_results` will save to a pure-python dictionary.
|
||||
|
||||
Next, note that we can liveplot the results by calling :code:`model.inspect` within the reconstruction loop. In fact, we could put any code we wanted here to look at the state of the model, and it would be executed after each epoch.
|
||||
|
||||
Finally, note that we take the time to save the results of this reconstruction. This is handled by pickling the dictionary produced by :code:`model.save_results`, which contains all the parameters which were reconstructed by the model.
|
||||
|
||||
There are a number of things going on behind the scenes as well, just because we decided to use the FancyPtycho model. This reconstruction, in addition to using two incoherently mixing modes, is also performing position annealing and reconstructing any instabilities in the probe flux that might have occured.
|
||||
Finally, note that there are several small adjustments made to the script to counteract particular sources of error that are present in this dataset, for example the raster grid pathology caused by the scan pattern used. Also note that not every mixin is needed every time - in this case, we turn off optimization of the :code:`weights` parameter.
|
||||
|
||||
|
||||
MIT BNL Logo
|
||||
------------
|
||||
|
||||
Next, we look at an example showing a more involved reconstruction from a dataset that has some serious errors in it. This is a dataset we collected at the CSX beamline of NSLS-II in 2016 from a target that said "MIT BNL" on it, using a defocused zone plate.
|
||||
|
||||
.. literalinclude:: ../../examples/MIT_BNL_logo.py
|
||||
|
||||
The first new thing that pops out at us is the choice to remove part of the diffraction patterns stored in the dataset. In this case, that data is noisy, and in any case, it's masked off with the mask stored in the .cxi file. We can simply edit all the patterns like we would any other pytorch or numpy array, taking care to crop the mask as well to match.
|
||||
|
||||
The next thing we note is that a few more options are being taken advantage of during the model construction. First of all, we introduce the :code:`translation_scale` option, which sets the aggressiveness of the position reconstruction. A small number like 1 (the default) is often too mild when there are large errors, whereas numbers above 10 are often too agressive to lead to convergence.
|
||||
|
||||
In this case, the :code:`propagation_distance` option tells us how far to propagate the naive initial guess of the probe. This data was taken from a very defocused zone plate, which is a classic difficult-to-reconstruct probe. The standard probe initialization, however, is generally quite good at generating a good guess of the focal point of any zone-plate-like optics. This option lets us start with a guess of that probe, which has already been propagated from it's focal point by a known distance.
|
||||
|
||||
Next, note that we can start to play a bit with the reconstruction procedure in response to the kinds of error that exist in the data. In this case, we actually perform three rounds of reconstruction, in serial, with different parameters! First, we we turn off the position reconstruction, and run the reconstruction with an explicitly chosen batch size which was found to work well with this dataset. Next, we turn position reconstruction back on, and continue the reconstruction. Finally, we improve the reconstruction quality by running ten iterations at a smaller learning rate (the default is set to a sensible 0.005).
|
||||
|
||||
|
||||
Specular Ptycho
|
||||
Gold Ball Split
|
||||
---------------
|
||||
|
||||
This file demonstrates a reconstruction from an experiment in the specular reflection geometry.
|
||||
It is very common to run reconstructions on two disjoint subsets of the same dataset, as well as the full dataset. This is primarily done to estimate the resolution of a reconstruction via the Fourier ring correlation (FRC).
|
||||
|
||||
.. literalinclude:: ../../examples/specular_ptycho.py
|
||||
.. literalinclude:: ../../examples/gold_ball_split.py
|
||||
|
||||
While the reconstruction itself is simple this time, a few new parameters have been set in the model definition. First, the :code:`randomize_ang` parameter was set. This seeds the object with phase noise spanning a given angular range, rather than a constant. Second, the :code:`scattering_mode` parameter is set. When set, it will override any information in the .cxi file about the sample orientation, and define the orientation based on the detector geometry.
|
||||
|
||||
In this case, the 'reflection' geometry knows to set the sample normal parallel to the scattering vector defined by an outgoing ray which intersects the detector at a perpendicular, and an incoming ray along the positive z-direction (as defined in the cxi specification). The other options, 'transmision', assumes that the surface normal of your sample is parallel to the incoming light ray. If this is left unset, it will use any information stored in the .cxi file, and will default to a transmission geometry if no data exists.
|
||||
This script simply divides the dataset in two, and then performs the same reconstruction on both halves of the dataset, as well as the full dataset.
|
||||
|
||||
|
||||
Ensemble Reconstruction
|
||||
-----------------------
|
||||
Gold Ball Synthesize
|
||||
--------------------
|
||||
|
||||
One important check when working with ptychography is performing multiple independently seeded reconstructions from the same data, to understand to what extent they converge to the same solution. This script demonstrates how to run an ensemble of reconstructions
|
||||
Once we have a set of three reconstructions - two half data reconstructions and a full data reconstruction, we need to calculate the resolution metrics. This script shows how that is done.
|
||||
|
||||
.. literalinclude:: ../../examples/ensemble_reconstruction.py
|
||||
|
||||
Note that essentially all that's different here is that the reconstructions are performed within a loop, with each reconstruction added to a list. Importantly, the :code:`randomize_ang` parameter is set, so that the reconstructions are seeded with a different pattern of noise.
|
||||
|
||||
|
||||
|
||||
Ensemble Analysis
|
||||
-----------------
|
||||
|
||||
This file inspects the results from the ensemble reconstruction
|
||||
|
||||
.. literalinclude:: ../../examples/ensemble_analysis.py
|
||||
|
||||
After loading the results and manipulating them a bit using regular python, two analysis functions from CDTools are used to glean information from the ensemble.
|
||||
|
||||
First is :code:`analysis.synthesize_reconstructions`. This function takes a stack of reconstructed probes and objects, corrects each reconstruction to account for the various ambiguities (phase ramps, translation offsets, etc.), and sums them into a single synthesized probe and object. Once the reconstructions are synthesized, this final synthesized probe and object can be plotted
|
||||
|
||||
Second is :code:`analysis.calc_consistency_prtf`. This function compares the power into various spatial frequencies between a stack of individual reconstructions and a synthesized reconstruction, in analogy with the phase retrieval transfer function. It then outputs a curve analogous to the PRTF, that shows at what spatial frequencies the reconstructions have converged consistently. This result is then plotted as well.
|
||||
.. literalinclude:: ../../examples/gold_ball_synthesize.py
|
||||
|
||||
|
||||
Transmission RPI
|
||||
----------------
|
||||
|
||||
CDTools also contains a forward model for randomized probe imaging (RPI, doi:10.1364/OE.397421). This is currently not documented fully, but hopefully will be soon
|
||||
@@ -1,6 +1,8 @@
|
||||
Tutorial
|
||||
========
|
||||
|
||||
WARNING: THE FOLLOWING TUTORIAL IS OUT OF DATE! It has some helpful information, but it is not trustworthy. Please rely on the examples, which are current as of February 2024.
|
||||
|
||||
This tutorial builds on the examples, leading to a more complete understanding of how to use CDTools and - importantly - how to extend it. First, we will cover the details of writing a useful reconstruction script for a particular experiment. Next, we will discuss how to implement a new dataset type for different kinds of coherent diffraction. Finally, we will go over how to make new models to cover specific types of ptychography which aren't described by any of the built-in models.
|
||||
|
||||
|
||||
|
||||
@@ -1,51 +0,0 @@
|
||||
import cdtools
|
||||
from matplotlib import pyplot as plt
|
||||
|
||||
|
||||
# This file is too large to be distributed via Github.
|
||||
# Please contact Abe Levitan (alevitan@mit) if you would like access
|
||||
filename = '79511_p.cxi'
|
||||
dataset = cdtools.datasets.Ptycho2DDataset.from_cxi(filename)
|
||||
|
||||
# In this dataset, the edges of the patterns are masked off anyway
|
||||
# We can easily just remove this data instead of leaving it to float.
|
||||
dataset.patterns = dataset.patterns[:,70:-70,70:-70]
|
||||
dataset.mask = dataset.mask[70:-70,70:-70]
|
||||
|
||||
# This model definition includes lots of tweaks, described below.
|
||||
#
|
||||
# randomize_ang defines the initial random phase noise's extent
|
||||
# translations_scale defines how aggressive the position reconstruction is
|
||||
# n_modes is the number of incoherent modes
|
||||
# propagation_distance is the distance to propagate from the SHARP-style guess of the probe's focal spot (in this case, the value comes from knowledge of the experimental geometry).
|
||||
model = cdtools.models.FancyPtycho.from_dataset(dataset,
|
||||
translation_scale = 4,
|
||||
n_modes=2,
|
||||
propagation_distance=73e-6)
|
||||
|
||||
# Move to the GPU
|
||||
model.to(device='cuda')
|
||||
dataset.get_as(device='cuda')
|
||||
|
||||
|
||||
# We turn off position reconstruction for the first phase
|
||||
model.translation_offsets.requires_grad = False
|
||||
for loss in model.Adam_optimize(10, dataset, batch_size=15):
|
||||
model.inspect(dataset)
|
||||
print(model.report())
|
||||
|
||||
# And we turn it on for the second phase
|
||||
model.translation_offsets.requires_grad = True
|
||||
for loss in model.Adam_optimize(20, dataset, batch_size=15):
|
||||
model.inspect(dataset)
|
||||
print(model.report())
|
||||
|
||||
# The third phase lowers the rate further
|
||||
for loss in model.Adam_optimize(10, dataset, batch_size=15, lr=0.0005):
|
||||
model.inspect(dataset)
|
||||
print(model.report())
|
||||
|
||||
|
||||
model.inspect(dataset)
|
||||
model.compare(dataset)
|
||||
plt.show()
|
||||
@@ -1,45 +0,0 @@
|
||||
|
||||
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
import torch.nn as nn
|
||||
import torch.optim as optim
|
||||
|
||||
from torch.nn.parallel import DistributedDataParallel as DDP
|
||||
|
||||
class ToyModel(nn.Module):
|
||||
def __init__(self):
|
||||
super(ToyModel, self).__init__()
|
||||
self.net1 = nn.Linear(10, 10)
|
||||
self.relu = nn.ReLU()
|
||||
self.net2 = nn.Linear(10, 5)
|
||||
|
||||
def forward(self, x):
|
||||
return self.net2(self.relu(self.net1(x)))
|
||||
|
||||
|
||||
def demo_basic():
|
||||
dist.init_process_group("nccl")
|
||||
rank = dist.get_rank()
|
||||
print(f"Start running basic DDP example on rank {rank}.")
|
||||
|
||||
# create model and move it to GPU with id rank
|
||||
device_id = rank % torch.cuda.device_count()
|
||||
model = ToyModel().to(device_id)
|
||||
ddp_model = DDP(model, device_ids=[device_id])
|
||||
|
||||
loss_fn = nn.MSELoss()
|
||||
optimizer = optim.SGD(ddp_model.parameters(), lr=0.001)
|
||||
|
||||
for i in range(100):
|
||||
print(i)
|
||||
optimizer.zero_grad()
|
||||
outputs = ddp_model(torch.randn(20, 10))
|
||||
mat = torch.rand([3,3], dtype=torch.complex64)
|
||||
inv_mat = torch.inverse(mat)
|
||||
labels = torch.randn(20, 5).to(device_id)
|
||||
loss_fn(outputs, labels).backward()
|
||||
optimizer.step()
|
||||
|
||||
if __name__ == "__main__":
|
||||
demo_basic()
|
||||
@@ -1,39 +0,0 @@
|
||||
from matplotlib import pyplot as plt
|
||||
from scipy import io
|
||||
|
||||
from cdtools.tools import plotting
|
||||
from cdtools.tools import analysis
|
||||
|
||||
|
||||
|
||||
dataset = io.loadmat('example_reconstructions/gold_balls_ensemble.mat')
|
||||
|
||||
|
||||
# Now we synthesize an average reconstruction
|
||||
synth_probe, synth_obj, aligned_objs = analysis.synthesize_reconstructions(
|
||||
dataset['probe'], dataset['obj'])
|
||||
|
||||
# And then we calculate the consistency PRTF from this
|
||||
freqs, prtf = analysis.calc_consistency_prtf(synth_obj, aligned_objs, dataset['basis'][0])
|
||||
|
||||
# Plot the first mode in detail
|
||||
plotting.plot_phase(synth_probe[0],basis=dataset['basis'][0])
|
||||
plotting.plot_amplitude(synth_probe[0],basis=dataset['basis'][0])
|
||||
plotting.plot_colorized(synth_probe[0],basis=dataset['basis'][0])
|
||||
|
||||
# Just plot the colorized version of the subdominant modes
|
||||
plotting.plot_colorized(synth_probe[1],basis=dataset['basis'][0])
|
||||
plotting.plot_colorized(synth_probe[2],basis=dataset['basis'][0])
|
||||
|
||||
# And now we plot the object
|
||||
plotting.plot_amplitude(synth_obj,basis=dataset['basis'][0])
|
||||
plotting.plot_colorized(synth_obj,basis=dataset['basis'][0])
|
||||
plotting.plot_phase(synth_obj,basis=dataset['basis'][0])
|
||||
|
||||
# Finally, plot the consistency PRTF
|
||||
plt.figure()
|
||||
plt.plot(freqs*1e-6, prtf)
|
||||
plt.xlabel('Spatial Frequency (cycles/um)')
|
||||
plt.ylabel('Consistency Based PRTF')
|
||||
|
||||
plt.show()
|
||||
@@ -1,41 +0,0 @@
|
||||
import cdtools
|
||||
import numpy as np
|
||||
from scipy import io
|
||||
|
||||
# Load the data
|
||||
filename = 'example_data/AuBalls_700ms_30nmStep_3_6SS_filter.cxi'
|
||||
dataset = cdtools.datasets.Ptycho2DDataset.from_cxi(filename)
|
||||
|
||||
results = []
|
||||
n = 25
|
||||
|
||||
for idx in range(n):
|
||||
print('Starting Reconstruction', idx+1, 'of',n)
|
||||
|
||||
# Create a new model each time
|
||||
model = cdtools.models.FancyPtycho.from_dataset(dataset,n_modes=3,
|
||||
randomize_ang=0.1*np.pi)
|
||||
|
||||
# Work on the GPU
|
||||
model.to(device='cuda')
|
||||
dataset.get_as(device='cuda')
|
||||
|
||||
# Run the reconstruction
|
||||
for loss in model.Adam_optimize(30, dataset, batch_size=100):
|
||||
print(model.report(), end='\r')
|
||||
|
||||
# Print a summary that won't be overwritten by the next line
|
||||
print('Finished:',model.report())
|
||||
|
||||
# And add the results to the ensemble dictionary
|
||||
results.append(model.save_results(dataset))
|
||||
|
||||
# This converts from a list of dictionaries to a dictionary of lists
|
||||
# It's safe to assume that all elements have the same set of keys
|
||||
# After this, e.g. dataset['probe'] will return a list of all probes.
|
||||
results = {key: np.array([element[key] for element in results])
|
||||
for key in results[0].keys()}
|
||||
|
||||
print(results['probe'].shape)
|
||||
# Save out the ensemble
|
||||
io.savemat('example_reconstructions/gold_balls_ensemble.mat', results)
|
||||
Binary file not shown.
+12
-10
@@ -1,22 +1,18 @@
|
||||
import cdtools
|
||||
from matplotlib import pyplot as plt
|
||||
import torch as t
|
||||
from torch.utils import data as torchdata
|
||||
import time
|
||||
|
||||
# First, we load an example dataset from a .cxi file
|
||||
filename = 'example_data/lab_ptycho_data.cxi'
|
||||
dataset = cdtools.datasets.Ptycho2DDataset.from_cxi(filename)
|
||||
|
||||
# Next, we create a ptychography model from the dataset
|
||||
# FancyPtycho is the workhorse model
|
||||
model = cdtools.models.FancyPtycho.from_dataset(
|
||||
dataset,
|
||||
n_modes=3, # Use 3 incoherently mixing probe modes
|
||||
oversampling=2, # Simulate the probe on a 2xlarger real-space array
|
||||
probe_support_radius=120, # Force the probe to 0 outside a radius of 120 pix
|
||||
propagation_distance=5e-3, # Propagate the initial probe guess by 5 mm
|
||||
translation_scale=2, # Increase the strength of the position refinement
|
||||
units='mm', # Set the units for the live plots
|
||||
obj_view_crop=-50, # Expands the field of view in the object plot by 50 pix
|
||||
)
|
||||
|
||||
device = 'cuda'
|
||||
@@ -26,16 +22,22 @@ dataset.get_as(device=device)
|
||||
# The learning rate parameter sets the alpha for Adam.
|
||||
# The beta parameters are (0.9, 0.999) by default
|
||||
# The batch size sets the minibatch size
|
||||
for loss in model.Adam_optimize(50, dataset, lr=0.02,batch_size=10):
|
||||
for loss in model.Adam_optimize(50, dataset, lr=0.02, batch_size=10):
|
||||
print(model.report())
|
||||
model.inspect(dataset)
|
||||
# Plotting is expensive, so we only do it every tenth epoch
|
||||
if model.epoch % 10 == 0:
|
||||
model.inspect(dataset)
|
||||
|
||||
# It's totally okay to chain several different reconstructions. Here, we
|
||||
# It's common to chain several different reconstruction loops. Here, we
|
||||
# started with an aggressive refinement to find the probe, and now we
|
||||
# polish the reconstruction with a lower learning rate and larger minibatch
|
||||
for loss in model.Adam_optimize(50, dataset, lr=0.005, batch_size=50):
|
||||
print(model.report())
|
||||
model.inspect(dataset)
|
||||
if model.epoch % 10 == 0:
|
||||
model.inspect(dataset)
|
||||
|
||||
# This orthogonalizes the recovered probe modes
|
||||
model.tidy_probes()
|
||||
|
||||
model.inspect(dataset)
|
||||
model.compare(dataset)
|
||||
|
||||
@@ -1,36 +1,81 @@
|
||||
import cdtools
|
||||
from matplotlib import pyplot as plt
|
||||
from scipy import io
|
||||
import torch as t
|
||||
|
||||
# First, we load an example dataset from a .cxi file
|
||||
filename = 'example_data/AuBalls_700ms_30nmStep_3_6SS_filter.cxi'
|
||||
dataset = cdtools.datasets.Ptycho2DDataset.from_cxi(filename)
|
||||
|
||||
# We pad the dataset with 10 pixels of zeroes around the edge. This
|
||||
# data gets masked off, so it is not used for the reconstruction. This padding
|
||||
# helps prevent aliasing when the probe and object get multiplied. It's a
|
||||
# helpful step when there is signal present out to the edge of the detector,
|
||||
# and is usually set to the radius of the probe's Fourier transform (in pixels)
|
||||
pad = 10
|
||||
dataset.pad(pad)
|
||||
|
||||
dataset.inspect()
|
||||
|
||||
# Next, we create a ptychography model from the dataset
|
||||
# Note that we explicitly ask for two incoherent probe modes
|
||||
# When the dataset is padded with zeroes and masked, the probe reconstruction
|
||||
# becomes very unstable, and often develops noise at these high-frequency,
|
||||
# masked off frequencies. To combat this, we simulate the probe at lower
|
||||
# resolution, using the probe_fourier_crop argument. This is good practice
|
||||
# in general when padding the dataset
|
||||
model = cdtools.models.FancyPtycho.from_dataset(
|
||||
dataset,
|
||||
n_modes=2,
|
||||
n_modes=3,
|
||||
probe_support_radius=50,
|
||||
propagation_distance=2e-6,
|
||||
units='um',
|
||||
probe_fourier_crop=pad
|
||||
)
|
||||
|
||||
# Let's do this reconstruction on the GPU, shall we?
|
||||
#model.to(device='cuda')
|
||||
#dataset.get_as(device='cuda')
|
||||
# This is a trick that my grandmother taught me, to combat the raster grid
|
||||
# pathology: we randomze the our initial guess of the probe positions.
|
||||
# The units here are pixels in the object array.
|
||||
# Try running this script with and without this line to see the difference!
|
||||
model.translation_offsets.data += 0.7 * t.randn_like(model.translation_offsets)
|
||||
|
||||
with model.save_on_exit('example_reconstructions/gold_balls.h5', dataset):
|
||||
# Now, we run a short reconstruction from the dataset
|
||||
for loss in model.Adam_optimize(10, dataset, batch_size=50):
|
||||
# And we liveplot the updates to the model as they happen
|
||||
# Not much probe intensity instability in this dataset, no need for this
|
||||
model.weights.requires_grad = False
|
||||
|
||||
device = 'cuda'
|
||||
model.to(device=device)
|
||||
dataset.get_as(device=device)
|
||||
|
||||
# This will save out the intermediate results if an exception is thrown
|
||||
# during the reconstruction
|
||||
with model.save_on_exception(
|
||||
'example_reconstructions/gold_balls_earlyexit.h5', dataset):
|
||||
|
||||
for loss in model.Adam_optimize(20, dataset, lr=0.005, batch_size=50):
|
||||
print(model.report())
|
||||
model.inspect(dataset)
|
||||
if model.epoch % 10 == 0:
|
||||
model.inspect(dataset)
|
||||
|
||||
# This orthogonalizes the incoherent probe modes
|
||||
model.tidy_probes()
|
||||
for loss in model.Adam_optimize(50, dataset, lr=0.002, batch_size=100):
|
||||
print(model.report())
|
||||
if model.epoch % 10 == 0:
|
||||
model.inspect(dataset)
|
||||
|
||||
# We can often reset our guess of the probe positions once we have a
|
||||
# good guess of probe and object, but in this case it causes the
|
||||
# raster grid pathology to return.
|
||||
# model.translation_offsets.data[:] = 0
|
||||
|
||||
# Setting schedule=True automatically lowers the learning rate if
|
||||
# the loss fails to improve after 10 epochs
|
||||
for loss in model.Adam_optimize(100, dataset, lr=0.001, batch_size=100,
|
||||
schedule=True):
|
||||
print(model.report())
|
||||
if model.epoch % 10 == 0:
|
||||
model.inspect(dataset)
|
||||
|
||||
|
||||
model.tidy_probes()
|
||||
|
||||
# This saves the final result
|
||||
model.save_to_h5('example_reconstructions/gold_balls.h5', dataset)
|
||||
|
||||
# Finally, we plot the results
|
||||
model.inspect(dataset)
|
||||
model.compare(dataset)
|
||||
plt.show()
|
||||
+43
-25
@@ -1,36 +1,54 @@
|
||||
import cdtools
|
||||
from matplotlib import pyplot as plt
|
||||
from scipy import io
|
||||
import torch as t
|
||||
|
||||
# First, we load an example dataset from a .cxi file
|
||||
filename = 'example_data/AuBalls_700ms_30nmStep_3_6SS_filter.cxi'
|
||||
dataset = cdtools.datasets.Ptycho2DDataset.from_cxi(filename)
|
||||
|
||||
datasets = dataset.split()
|
||||
pad = 10
|
||||
dataset.pad(pad)
|
||||
|
||||
for idx, dataset in enumerate(datasets):
|
||||
# This splits the dataset into a pseudorandomly chosen set of two disjoint
|
||||
# datasets. The partitioning is drawn from a saved list, so the split is
|
||||
# deterministic
|
||||
dataset_1, dataset_2 = dataset.split()
|
||||
|
||||
print(f'Working on half {idx}')
|
||||
# Next, we create a ptychography model from the dataset
|
||||
# Note that we explicitly ask for two incoherent probe modes
|
||||
model = cdtools.models.FancyPtycho.from_dataset(dataset, n_modes=2)
|
||||
datasets = [dataset_1, dataset_2, dataset]
|
||||
labels = ['half_1', 'half_2', 'full']
|
||||
|
||||
for label, dataset in zip(labels, datasets):
|
||||
print(f'Working on dataset {label}')
|
||||
|
||||
model = cdtools.models.FancyPtycho.from_dataset(
|
||||
dataset,
|
||||
n_modes=3,
|
||||
probe_support_radius=50,
|
||||
propagation_distance=2e-6,
|
||||
units='um',
|
||||
probe_fourier_crop=pad
|
||||
)
|
||||
|
||||
model.translation_offsets.data += \
|
||||
0.7 * t.randn_like(model.translation_offsets)
|
||||
|
||||
# Let's do this reconstruction on the GPU, shall we?
|
||||
#model.to(device='cuda')
|
||||
#dataset.get_as(device='cuda')
|
||||
model.weights.requires_grad = False
|
||||
|
||||
with model.save_on_exit(f'example_reconstructions/gold_balls_half{idx}.mat',
|
||||
dataset):
|
||||
# Now, we run a short reconstruction from the dataset
|
||||
for loss in model.Adam_optimize(10, dataset, batch_size=50):
|
||||
# And we liveplot the updates to the model as they happen
|
||||
print(model.report())
|
||||
model.inspect(dataset)
|
||||
device = 'cuda'
|
||||
model.to(device=device)
|
||||
dataset.get_as(device=device)
|
||||
|
||||
# This orthogonalizes the incoherent probe modes
|
||||
model.tidy_probes()
|
||||
# For batched reconstructions like this, there's no need to live-plot
|
||||
# the progress
|
||||
for loss in model.Adam_optimize(20, dataset, lr=0.005, batch_size=50):
|
||||
print(model.report())
|
||||
|
||||
# Finally, we plot the results
|
||||
model.inspect(dataset)
|
||||
model.compare(dataset)
|
||||
plt.show()
|
||||
for loss in model.Adam_optimize(50, dataset, lr=0.002, batch_size=100):
|
||||
print(model.report())
|
||||
|
||||
for loss in model.Adam_optimize(100, dataset, lr=0.001, batch_size=100,
|
||||
schedule=True):
|
||||
print(model.report())
|
||||
|
||||
|
||||
model.tidy_probes()
|
||||
|
||||
model.save_to_h5(f'example_reconstructions/gold_balls_{label}.h5', dataset)
|
||||
@@ -0,0 +1,53 @@
|
||||
import cdtools
|
||||
from cdtools.tools import plotting as p
|
||||
from matplotlib import pyplot as plt
|
||||
import numpy as np
|
||||
|
||||
# We load all three reconstructions
|
||||
half_1 = cdtools.tools.data.h5_to_nested_dict(
|
||||
f'example_reconstructions/gold_balls_half_1.h5')
|
||||
half_2 = cdtools.tools.data.h5_to_nested_dict(
|
||||
f'example_reconstructions/gold_balls_half_2.h5')
|
||||
full = cdtools.tools.data.h5_to_nested_dict(
|
||||
f'example_reconstructions/gold_balls_full.h5')
|
||||
|
||||
# This defines the region of recovered object to use for the analysis.
|
||||
pad = 260
|
||||
window = np.s_[pad:-pad, pad:-pad]
|
||||
|
||||
# This brings all three reconstructions to a common basis, correcting for
|
||||
# possible global phase offsets, position shifts, and phase ramps. It also
|
||||
# calculates a Fourier ring correlation and spectral signal-to-noise ratio
|
||||
# estimate from the two half reconstructions.
|
||||
results = cdtools.tools.analysis.standardize_reconstruction_set(
|
||||
half_1,
|
||||
half_2,
|
||||
full,
|
||||
window=window,
|
||||
nbins=40, # The number of bins to use for the FRC calculation
|
||||
)
|
||||
|
||||
# We plot the normalized object images
|
||||
p.plot_amplitude(results['obj_half_1'][window], basis=results['obj_basis'])
|
||||
p.plot_phase(results['obj_half_1'][window], basis=results['obj_basis'])
|
||||
p.plot_amplitude(results['obj_half_2'][window], basis=results['obj_basis'])
|
||||
p.plot_phase(results['obj_half_2'][window], basis=results['obj_basis'])
|
||||
p.plot_amplitude(results['obj_full'][window], basis=results['obj_basis'])
|
||||
p.plot_phase(results['obj_full'][window], basis=results['obj_basis'])
|
||||
|
||||
# We plot the calculated Fourier ring correlation
|
||||
plt.figure()
|
||||
plt.plot(1e-6*results['frc_freqs'], results['frc'])
|
||||
plt.plot(1e-6*results['frc_freqs'], results['frc_threshold'], 'k--')
|
||||
plt.xlabel('Frequency (cycles / um)')
|
||||
plt.ylabel('Fourier Ring Correlation')
|
||||
plt.legend(['FRC', 'threshold'])
|
||||
|
||||
# We plot the calculated spectral signal-to-noise ratio
|
||||
plt.figure()
|
||||
plt.semilogy(1e-6*results['frc_freqs'], results['ssnr'])
|
||||
plt.xlabel('Frequency (cycles / um)')
|
||||
plt.ylabel('Spectral signal-to-noise ratio')
|
||||
plt.grid('on')
|
||||
|
||||
plt.show()
|
||||
@@ -1,38 +0,0 @@
|
||||
import cdtools
|
||||
from matplotlib import pyplot as plt
|
||||
from scipy import io
|
||||
|
||||
#
|
||||
# This is the testing dataset for the Bragg ptychography code, that was
|
||||
# collected with our optical setup using a low NA zone plate illuminating
|
||||
# a reflective diffraction grating with writing on it.
|
||||
#
|
||||
|
||||
# This file is too large to be distributed via Github.
|
||||
# Please contact Abe Levitan (alevitan@mit) if you would like access
|
||||
filename = 'example_data/Zone Plate Bragg 633.cxi'
|
||||
dataset = cdtools.datasets.Ptycho2DDataset.from_cxi(filename)
|
||||
|
||||
#dataset.inspect()
|
||||
|
||||
model = cdtools.models.Bragg2DPtycho.from_dataset(
|
||||
dataset,
|
||||
probe_support_radius=60,
|
||||
correct_tilt=False,
|
||||
units='mm',
|
||||
)
|
||||
|
||||
#model.to(device='cuda')
|
||||
#dataset.get_as(device='cuda')
|
||||
|
||||
|
||||
model.translation_offsets.requires_grad = False
|
||||
for loss in model.Adam_optimize(100, dataset):
|
||||
model.inspect(dataset)
|
||||
print(model.report())
|
||||
|
||||
#io.savemat('example_reconstructions/lab_bragg_2d_ptycho.mat',
|
||||
# model.save_results(dataset))
|
||||
|
||||
model.compare(dataset)
|
||||
plt.show()
|
||||
@@ -1,32 +0,0 @@
|
||||
import cdtools
|
||||
from matplotlib import pyplot as plt
|
||||
from scipy import io
|
||||
|
||||
|
||||
# A simple dataset collected from our optical setup
|
||||
filename = 'example_data/lab_ptycho_data.cxi'
|
||||
dataset = cdtools.datasets.Ptycho2DDataset.from_cxi(filename)
|
||||
|
||||
dataset.inspect(units='mm')
|
||||
plt.show()
|
||||
|
||||
model = cdtools.models.FancyPtycho.from_dataset(dataset, oversampling=2,
|
||||
probe_support_radius=90,
|
||||
n_modes=2,
|
||||
dm_rank=0,units='mm')
|
||||
model.to(device='cuda')
|
||||
dataset.get_as(device='cuda')
|
||||
|
||||
|
||||
model.translation_offsets.requires_grad = False
|
||||
for loss in model.Adam_optimize(50, dataset):
|
||||
model.inspect(dataset)
|
||||
print(model.report())
|
||||
|
||||
model.tidy_probes()
|
||||
|
||||
io.savemat('example_reconstructions/lab_ptycho.mat',
|
||||
model.save_results(dataset))
|
||||
|
||||
model.compare(dataset)
|
||||
plt.show()
|
||||
@@ -1,83 +0,0 @@
|
||||
import cdtools
|
||||
import torch as t
|
||||
from cdtools.models.complex_adam import MyAdam
|
||||
from torch.utils import data as torchdata
|
||||
import time
|
||||
import torch.distributed as dist
|
||||
from torch.nn.parallel import DistributedDataParallel as DDP
|
||||
|
||||
|
||||
def demo():
|
||||
# First, we load an example dataset from a .cxi file
|
||||
filename = 'example_data/lab_ptycho_data.cxi'
|
||||
dataset = cdtools.datasets.Ptycho2DDataset.from_cxi(filename)
|
||||
|
||||
# Next, we create a ptychography model from the dataset
|
||||
model = cdtools.models.SimplePtycho.from_dataset(dataset)
|
||||
|
||||
|
||||
print(dist.is_torchelastic_launched())
|
||||
dist.init_process_group(backend="nccl", init_method='env://')
|
||||
rank = dist.get_rank()
|
||||
print(f"Start running basic DDP example on rank {rank}.")
|
||||
device_id = rank % t.cuda.device_count()
|
||||
print('device id', device_id)
|
||||
model = model.to(device_id)
|
||||
ddp_model = DDP(model, device_ids=[device_id])
|
||||
print(model.loss_train)
|
||||
print(model.Adam_optimize)
|
||||
print(ddp_model.Adam_optimize)
|
||||
|
||||
sampler = torchdata.distributed.DistributedSampler(dataset)
|
||||
# Make a dataloader
|
||||
#data_loader = torchdata.DataLoader(dataset, batch_size=20,
|
||||
# shuffle=True, num_workers=0)
|
||||
data_loader = torchdata.DataLoader(dataset, batch_size=20,
|
||||
shuffle=False, sampler=sampler)
|
||||
|
||||
device = 'cuda:'+str(device_id)
|
||||
dataset.get_as(device=device)
|
||||
|
||||
# Define the optimizer
|
||||
#optimizer = MyAdam(model.parameters(), lr=0.01)
|
||||
optimizer = t.optim.Adam(model.parameters(), lr=0.01)
|
||||
|
||||
normalization=0
|
||||
for inputs, patterns in dataset:#data_loader:
|
||||
normalization += t.sum(patterns)
|
||||
|
||||
dist.all_reduce(normalization)
|
||||
|
||||
for it in range(10):
|
||||
print(it)
|
||||
sampler.set_epoch(it)
|
||||
loss = 0
|
||||
N = 0
|
||||
t0 = time.time()
|
||||
for inputs, patterns in data_loader:
|
||||
#print(inputs)
|
||||
N += 1
|
||||
def closure():
|
||||
optimizer.zero_grad()
|
||||
|
||||
sim_patterns = model.forward(*inputs)
|
||||
|
||||
if hasattr(model, 'mask'):
|
||||
loss = model.loss(patterns,sim_patterns, mask=model.mask)
|
||||
else:
|
||||
loss = model.loss(patternss,sim_patterns)
|
||||
|
||||
loss.backward()
|
||||
return loss.detach()
|
||||
|
||||
loss += optimizer.step(closure)#.cpu().numpy()
|
||||
#dist.all_reduce(loss)
|
||||
#loss = dist.all_reduce(loss)
|
||||
#print(it, 'time', time.time()-t0)
|
||||
#print(loss / normalization)
|
||||
if rank==0:
|
||||
model.inspect()
|
||||
return loss#.cpu().numpy()
|
||||
|
||||
if __name__=='__main__':
|
||||
demo()
|
||||
@@ -1,26 +1,26 @@
|
||||
import cdtools
|
||||
from matplotlib import pyplot as plt
|
||||
import torch as t
|
||||
from torch.utils import data as torchdata
|
||||
import time
|
||||
|
||||
# First, we load an example dataset from a .cxi file
|
||||
# We load an example dataset from a .cxi file
|
||||
filename = 'example_data/lab_ptycho_data.cxi'
|
||||
dataset = cdtools.datasets.Ptycho2DDataset.from_cxi(filename)
|
||||
|
||||
# Next, we create a ptychography model from the dataset
|
||||
# We create a ptychography model from the dataset
|
||||
model = cdtools.models.SimplePtycho.from_dataset(dataset)
|
||||
|
||||
# We move the model to the GPU
|
||||
device = 'cuda'
|
||||
model.to(device=device)
|
||||
dataset.get_as(device=device)
|
||||
|
||||
# We run the actual reconstruction
|
||||
for loss in model.Adam_optimize(100, dataset, batch_size=10):
|
||||
# We print a quick report of the optimization status
|
||||
print(model.report())
|
||||
# And we liveplot the updates to the model as they happen
|
||||
# And liveplot the updates to the model as they happen
|
||||
model.inspect(dataset)
|
||||
|
||||
# We study the results
|
||||
model.inspect(dataset)
|
||||
model.compare(dataset)
|
||||
plt.show()
|
||||
@@ -1,36 +0,0 @@
|
||||
import cdtools
|
||||
from matplotlib import pyplot as plt
|
||||
import numpy as np
|
||||
|
||||
|
||||
# This file is too large to be distributed via Github.
|
||||
# Please contact Abe Levitan (alevitan@mit) if you would like access
|
||||
filename = '/media/Data Bank/CSX_10_18/Processed_CXIs/110531_p.cxi'
|
||||
dataset = cdtools.datasets.Ptycho2DDataset.from_cxi(filename)
|
||||
|
||||
|
||||
# This model definition includes lots of tweaks, described below.
|
||||
#
|
||||
# randomize_ang defines the initial random phase noise's extent
|
||||
# translations_scale defines how aggressive the position reconstruction is
|
||||
# scattering_mode overrides any sample normal information stored in the .cxi file
|
||||
model = cdtools.models.FancyPtycho.from_dataset(dataset,
|
||||
randomize_ang = np.pi/4,
|
||||
translation_scale=10,
|
||||
scattering_mode='reflection')
|
||||
|
||||
|
||||
# Move to the GPU
|
||||
model.to(device='cuda')
|
||||
dataset.get_as(device='cuda')
|
||||
|
||||
|
||||
# Run the reconstruction
|
||||
for i, loss in enumerate(model.Adam_optimize(100, dataset,batch_size=5)):
|
||||
print(i,loss)
|
||||
model.inspect(dataset)
|
||||
|
||||
|
||||
model.inspect(dataset)
|
||||
model.compare(dataset)
|
||||
plt.show()
|
||||
@@ -1,37 +0,0 @@
|
||||
import cdtools
|
||||
from matplotlib import pyplot as plt
|
||||
from scipy import io
|
||||
|
||||
|
||||
filename = 'example_data/lab_ptycho_data.cxi'
|
||||
dataset = cdtools.datasets.Ptycho2DDataset.from_cxi(filename)
|
||||
|
||||
#dataset.inspect(units='mm')
|
||||
#plt.show()
|
||||
|
||||
# dm_rank=-1 tells it to use a full-rank unified mode approximation
|
||||
model = CDTools.models.FancyPtycho.from_dataset(dataset, oversampling=1,n_modes=3, dm_rank=-1)
|
||||
|
||||
|
||||
model.to(device='cuda')
|
||||
dataset.get_as(device='cuda')
|
||||
|
||||
model.translation_offsets.requires_grad = False
|
||||
for loss in model.Adam_optimize(200, dataset):
|
||||
model.inspect(dataset)
|
||||
print(model.report())
|
||||
|
||||
model.tidy_probes()
|
||||
|
||||
for loss in model.Adam_optimize(200, dataset, lr=0.0001):
|
||||
model.inspect(dataset)
|
||||
print(model.report())
|
||||
|
||||
model.tidy_probes(normalize=True)
|
||||
model.inspect(dataset)
|
||||
|
||||
io.savemat('example_reconstructions/unified_modes.mat',
|
||||
model.save_results(dataset))
|
||||
|
||||
model.compare(dataset)
|
||||
plt.show()
|
||||
@@ -284,3 +284,47 @@ class Ptycho2DDataset(CDataset):
|
||||
return dataset_1, dataset_2
|
||||
|
||||
|
||||
def pad(self, to_pad, value=0, mask=True):
|
||||
"""Pads all the diffraction patterns by a speficied amount
|
||||
|
||||
This is useful for scenarios where the diffraction is strong, even
|
||||
near the edge of the detector. In this scenario, the discrete version
|
||||
of the ptychography model will alias. Padding the diffraction patterns
|
||||
to increase their size and masking off the outer region can account
|
||||
for this effect.
|
||||
|
||||
If to_pad is an integer, the patterns will be padded on all sides by
|
||||
this value. If it is a tuple of length 2, then the patterns will be
|
||||
padded (left/right, top/bottom, left/right). If a tuple of length 4,
|
||||
the padding is done as (left, right, top, bottom), following the
|
||||
convention for torch.nn.functional.pad
|
||||
|
||||
Any mask and background data which is stored with the dataset will be
|
||||
padded along with the diffraction patterns
|
||||
|
||||
Parameters
|
||||
----------
|
||||
to_pad : int or tuple(int)
|
||||
The number of pixels to pad by.
|
||||
value : float
|
||||
Optional, the fill value to pad with. Default is 0
|
||||
mask : bool
|
||||
Optional, whether to mask off the new pixels. Default is True
|
||||
"""
|
||||
|
||||
# Convert the padding to a common format
|
||||
if not hasattr(to_pad, "__len__"):
|
||||
to_pad = (to_pad,) * 4
|
||||
elif len(to_pad) == 2:
|
||||
to_pad = ((to_pad[0],) * 2) + ((to_pad[1],) * 2)
|
||||
|
||||
self.patterns = t.nn.functional.pad(self.patterns, to_pad, value=value)
|
||||
if self.mask is not None:
|
||||
if mask:
|
||||
self.mask = t.nn.functional.pad(self.mask, to_pad, value=False)
|
||||
else:
|
||||
self.mask = t.nn.functional.pad(self.mask, to_pad, value=True)
|
||||
if self.background is not None:
|
||||
self.background = t.nn.functional.pad(self.background, to_pad)
|
||||
|
||||
|
||||
@@ -60,7 +60,7 @@ class CDIModel(t.nn.Module):
|
||||
|
||||
self.loss_history = []
|
||||
self.training_history = ''
|
||||
self.iteration_count = 0
|
||||
self.epoch = 0
|
||||
|
||||
def from_dataset(self, dataset):
|
||||
raise NotImplementedError()
|
||||
@@ -178,6 +178,7 @@ class CDIModel(t.nn.Module):
|
||||
return {
|
||||
'state_dict': state_dict,
|
||||
'loss_history': np.array(self.loss_history),
|
||||
'epoch': self.epoch,
|
||||
'training_history': self.training_history,
|
||||
'loss_function': self.loss.__name__,
|
||||
}
|
||||
@@ -352,7 +353,7 @@ class CDIModel(t.nn.Module):
|
||||
scheduler.step(loss)
|
||||
|
||||
self.loss_history.append(loss)
|
||||
epoch_idx = len(self.loss_history)
|
||||
self.epoch = len(self.loss_history)
|
||||
self.latest_iteration_time = time.time() - t0
|
||||
self.training_history += self.report() + '\n'
|
||||
return loss
|
||||
|
||||
@@ -297,9 +297,11 @@ class FancyPtycho(CDIModel):
|
||||
obj = t.stack([obj,] + [0.05*t.ones_like(obj),]*(n_obj_modes-1))
|
||||
|
||||
if obj_view_crop is None:
|
||||
obj_view_crop = min(probe.shape[-2], probe.shape[-1]) // 2
|
||||
obj_view_crop = (min(probe.shape[-2], probe.shape[-1]) // 2
|
||||
+ probe_fourier_crop)
|
||||
if obj_view_crop < 0:
|
||||
obj_view_crop += min(probe.shape[-2], probe.shape[-1]) // 2
|
||||
obj_view_crop += (min(probe.shape[-2], probe.shape[-1]) // 2
|
||||
+ probe_fourier_crop)
|
||||
obj_view_crop += obj_padding
|
||||
|
||||
det_geo = dataset.detector_geometry
|
||||
@@ -747,7 +749,7 @@ class FancyPtycho(CDIModel):
|
||||
('Corrected Translations',
|
||||
lambda self, fig, dataset: p.plot_translations(self.corrected_translations(dataset), fig=fig, units=self.units)),
|
||||
('Background',
|
||||
lambda self, fig: plt.figure(fig.number) and plt.imshow(self.background.detach().cpu().numpy()**2))
|
||||
lambda self, fig: p.plot_amplitude(self.background**2, fig=fig))
|
||||
]
|
||||
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@ import numpy as np
|
||||
from cdtools.tools import image_processing as ip
|
||||
from scipy import linalg as sla
|
||||
from scipy import special
|
||||
from scipy import optimize as opt
|
||||
|
||||
__all__ = ['orthogonalize_probes', 'standardize', 'synthesize_reconstructions',
|
||||
'calc_consistency_prtf', 'calc_deconvolved_cross_correlation',
|
||||
@@ -476,7 +477,7 @@ def calc_frc(im1, im2, basis, im_slice=None, nbins=None, snr=1., limit='side'):
|
||||
basis : array
|
||||
The basis for the images, defined as is standard for datasets
|
||||
im_slice : slice
|
||||
Default is from 3/8 to 5/8 across the image, a slice to use in the processing.
|
||||
Default is the full image
|
||||
nbins : int
|
||||
Number of bins to break the FRC up into
|
||||
snr : float
|
||||
@@ -507,8 +508,7 @@ def calc_frc(im1, im2, basis, im_slice=None, nbins=None, snr=1., limit='side'):
|
||||
basis = t.tensor(basis)
|
||||
|
||||
if im_slice is None:
|
||||
im_slice = np.s_[(im1.shape[0]//8)*3:(im1.shape[0]//8)*5,
|
||||
(im1.shape[1]//8)*3:(im1.shape[1]//8)*5]
|
||||
im_slice = np.s_[:,:]
|
||||
|
||||
if nbins is None:
|
||||
nbins = np.max(im1[im_slice].shape) // 8
|
||||
@@ -1053,12 +1053,13 @@ def standardize_reconstruction_set(
|
||||
half_2,
|
||||
full,
|
||||
correct_phase_offset=True,
|
||||
remove_phase_ramp=True,
|
||||
remove_amplitude_exponent=False,
|
||||
correct_phase_ramp=True,
|
||||
correct_amplitude_exponent=False,
|
||||
window=np.s_[:,:],
|
||||
nbins=50
|
||||
nbins=50,
|
||||
frc_limit='side',
|
||||
):
|
||||
"""Normalizes and analyses a set of 50/50/100% reconstructions
|
||||
"""Standardizes and analyses a set of 50/50/100% reconstructions
|
||||
|
||||
It's very common to split a ptychography dataset into two sub-datasets,
|
||||
each with 50% of the exposures, so that the difference between the two
|
||||
@@ -1102,7 +1103,7 @@ def standardize_reconstruction_set(
|
||||
obj, probe, weights = full['obj'], full['probe'], full['weights']
|
||||
|
||||
|
||||
if remove_phase_ramp:
|
||||
if correct_phase_ramp:
|
||||
obj_1, probe_1 = remove_phase_ramp(
|
||||
half_1['obj'], window, probe=half_1['probe'])
|
||||
obj_2, probe_2 = remove_phase_ramp(
|
||||
@@ -1110,7 +1111,7 @@ def standardize_reconstruction_set(
|
||||
obj, probe = remove_phase_ramp(
|
||||
full['obj'], window, probe=full['probe'])
|
||||
|
||||
if remove_amplitude_exponent:
|
||||
if correct_amplitude_exponent:
|
||||
obj_1, probe_1, weights_1 = remove_amplitude_exponent(
|
||||
obj_1, window, probe=probe_1,
|
||||
weights=half_1['weights'],
|
||||
@@ -1127,36 +1128,30 @@ def standardize_reconstruction_set(
|
||||
basis=full['basis'],
|
||||
translations=full['translations'])
|
||||
|
||||
|
||||
if correct_phase_offset:
|
||||
obj_1 = np.exp(-1j* np.angle(np.sum(obj_1[window]))) * obj_1
|
||||
obj_2 = np.exp(-1j* np.angle(np.sum(obj_2))) * obj_2
|
||||
obj = np.exp(-1j* np.angle(np.sum(obj))) * obj
|
||||
|
||||
|
||||
# TODO calculate the illumination map using the corrected probes and
|
||||
# the appropriately shifted translations, so that all the maps are
|
||||
# directly comparable
|
||||
illumination_map_1 = make_illumination_map(half_1, total_probe_intensity=total_probe_intensity)
|
||||
illumination_map_2 = make_illumination_map(half_2, total_probe_intensity=total_probe_intensity)
|
||||
illumination_map = make_illumination_map(full, total_probe_intensity=total_probe_intensity)
|
||||
|
||||
# Todo update the translations to account for the determined shift
|
||||
shift_1 = cdtools.tools.image_processing.find_shift(
|
||||
shift_1 = ip.find_shift(
|
||||
t.as_tensor(ip.hann_window(np.abs(obj[window]))),
|
||||
t.as_tensor(ip.hann_window(np.abs(obj_1[window]))))
|
||||
obj_1 = cdtools.tools.image_processing.sinc_subpixel_shift(
|
||||
obj_1 = ip.sinc_subpixel_shift(
|
||||
t.as_tensor(obj_1), shift_1).numpy()
|
||||
|
||||
shift_2 = cdtools.tools.image_processing.find_shift(
|
||||
shift_2 = ip.find_shift(
|
||||
t.as_tensor(ip.hann_window(np.abs(obj[window]))),
|
||||
t.as_tensor(ip.hann_window(np.abs(obj_2[window]))))
|
||||
obj_2 = cdtools.tools.image_processing.sinc_subpixel_shift(
|
||||
obj_2 = ip.sinc_subpixel_shift(
|
||||
t.as_tensor(obj_2), shift_2).numpy()
|
||||
|
||||
freqs, frc, threshold = cdtools.tools.analysis.calc_frc(
|
||||
freqs, frc, threshold = calc_frc(
|
||||
ip.hann_window(obj_1[window]),
|
||||
ip.hann_window(obj_2[window]),
|
||||
half_1['basis'], nbins=nbins, limit='corner')
|
||||
full['obj_basis'], nbins=nbins, limit=frc_limit)
|
||||
|
||||
# The correct formulation when the final output is the full reconstruction
|
||||
ssnr = 2 * frc / (1 - frc)
|
||||
@@ -1167,21 +1162,19 @@ def standardize_reconstruction_set(
|
||||
'weights_half_1': weights_1,
|
||||
'translations_half_1': half_1['translations'],
|
||||
'background_1': half_1['background'],
|
||||
'illumination_map_1': illumination_map_1,
|
||||
'obj_half_2': obj_2,
|
||||
'probe_half_2': probe_2,
|
||||
'weights_half_2': weights_2,
|
||||
'translations_half_2': half_2['translations'],
|
||||
'background_2': half_2['background'],
|
||||
'illumination_map_2': illumination_map_2,
|
||||
'obj_full': obj,
|
||||
'probe_full': probe,
|
||||
'weights_full': weights,
|
||||
'translations_full': full['translations'],
|
||||
'background_full': full['background'],
|
||||
'illumination_map_full': illumination_map,
|
||||
'wavelength': full['wavelength'],
|
||||
'basis': full['basis'],
|
||||
'obj_basis': full['obj_basis'],
|
||||
'probe_basis': full['probe_basis'],
|
||||
'frc_freqs': freqs,
|
||||
'frc': frc,
|
||||
'frc_threshold': threshold,
|
||||
|
||||
Reference in new issue
Block a user