mirror of
https://github.com/cdtools-developers/cdtools.git
synced 2026-11-30 16:57:47 +01:00
merge updates to master
This commit is contained in:
commit
ab7048e375
47 files changed
+3206
-1770
No files matched your search
@@ -4,9 +4,11 @@ import warnings
|
||||
warnings.filterwarnings("ignore",
|
||||
message='To copy construct from a tensor, ')
|
||||
|
||||
__all__ = ['tools', 'datasets', 'models']
|
||||
__all__ = ['tools', 'datasets', 'models', 'reconstructors']
|
||||
|
||||
from ._version import __version__
|
||||
|
||||
from cdtools import tools
|
||||
from cdtools import datasets
|
||||
from cdtools import models
|
||||
|
||||
from cdtools import reconstructors
|
||||
@@ -0,0 +1 @@
|
||||
__version__ = "0.3.1.dev"
|
||||
@@ -34,10 +34,16 @@ class CDataset(torchdata.Dataset):
|
||||
needed to allow for easy mixing of data on the CPU and GPU.
|
||||
"""
|
||||
|
||||
def __init__(self, entry_info=None, sample_info=None,
|
||||
wavelength=None,
|
||||
detector_geometry=None, mask=None,
|
||||
background=None):
|
||||
def __init__(
|
||||
self,
|
||||
entry_info=None,
|
||||
sample_info=None,
|
||||
wavelength=None,
|
||||
detector_geometry=None,
|
||||
mask=None,
|
||||
qe_mask=None,
|
||||
background=None,
|
||||
):
|
||||
|
||||
"""The __init__ function allows construction from python objects.
|
||||
|
||||
@@ -73,6 +79,12 @@ class CDataset(torchdata.Dataset):
|
||||
self.mask = t.tensor(mask, dtype=t.bool)
|
||||
else:
|
||||
self.mask = None
|
||||
|
||||
if qe_mask is not None:
|
||||
self.qe_mask = t.as_tensor(qe_mask, dtype=t.float32)
|
||||
else:
|
||||
self.qe_mask = None
|
||||
|
||||
if background is not None:
|
||||
self.background = t.tensor(background, dtype=t.float32)
|
||||
else:
|
||||
@@ -98,6 +110,8 @@ class CDataset(torchdata.Dataset):
|
||||
|
||||
if self.mask is not None:
|
||||
self.mask = self.mask.to(*args,**mask_kwargs)
|
||||
if self.qe_mask is not None:
|
||||
self.qe_mask = self.qe_mask.to(*args,**kwargs)
|
||||
if self.background is not None:
|
||||
self.background = self.background.to(*args,**kwargs)
|
||||
|
||||
@@ -193,12 +207,17 @@ class CDataset(torchdata.Dataset):
|
||||
'basis' : basis,
|
||||
'corner' : corner}
|
||||
mask = cdtdata.get_mask(cxi_file)
|
||||
qe_mask = cdtdata.get_qe_mask(cxi_file)
|
||||
dark = cdtdata.get_dark(cxi_file)
|
||||
return cls(entry_info = entry_info,
|
||||
sample_info = sample_info,
|
||||
wavelength=wavelength,
|
||||
detector_geometry=detector_geometry,
|
||||
mask=mask, background=dark)
|
||||
return cls(
|
||||
entry_info=entry_info,
|
||||
sample_info=sample_info,
|
||||
wavelength=wavelength,
|
||||
detector_geometry=detector_geometry,
|
||||
mask=mask,
|
||||
qe_mask=qe_mask,
|
||||
background=dark,
|
||||
)
|
||||
|
||||
|
||||
def to_cxi(self, cxi_file):
|
||||
@@ -236,6 +255,8 @@ class CDataset(torchdata.Dataset):
|
||||
corner = corner)
|
||||
if self.mask is not None:
|
||||
cdtdata.add_mask(cxi_file, self.mask)
|
||||
if self.qe_mask is not None:
|
||||
cdtdata.add_qe_mask(cxi_file, self.qe_mask)
|
||||
if self.background is not None:
|
||||
cdtdata.add_dark(cxi_file, self.background)
|
||||
|
||||
|
||||
@@ -1,15 +1,16 @@
|
||||
import warnings
|
||||
from copy import copy, deepcopy
|
||||
import pathlib
|
||||
|
||||
import h5py
|
||||
import numpy as np
|
||||
import torch as t
|
||||
from copy import copy
|
||||
import h5py
|
||||
import pathlib
|
||||
|
||||
from cdtools.datasets import CDataset
|
||||
from cdtools.datasets.random_selection import random_selection
|
||||
from cdtools.tools import data as cdtdata
|
||||
from cdtools.tools import plotting
|
||||
from matplotlib import pyplot as plt
|
||||
from cdtools.tools import analysis
|
||||
from copy import deepcopy
|
||||
|
||||
__all__ = ['Ptycho2DDataset']
|
||||
|
||||
@@ -77,6 +78,7 @@ class Ptycho2DDataset(CDataset):
|
||||
self.intensities = t.as_tensor(intensities, dtype=t.float32)
|
||||
else:
|
||||
self.intensities = None
|
||||
|
||||
|
||||
def __len__(self):
|
||||
return self.patterns.shape[0]
|
||||
@@ -123,9 +125,9 @@ class Ptycho2DDataset(CDataset):
|
||||
self.translations = self.translations.to(*args, **kwargs)
|
||||
self.patterns = self.patterns.to(*args, **kwargs)
|
||||
|
||||
|
||||
# It sucks that I can't reuse the base factory method here,
|
||||
# perhaps there is a way but I couldn't figure it out.
|
||||
|
||||
@classmethod
|
||||
def from_cxi(cls, cxi_file, cut_zeros=True, load_patterns=True):
|
||||
"""Generates a new Ptycho2DDataset from a .cxi file directly
|
||||
@@ -147,7 +149,7 @@ class Ptycho2DDataset(CDataset):
|
||||
"""
|
||||
# If a bare string is passed
|
||||
if isinstance(cxi_file, str) or isinstance(cxi_file, pathlib.Path):
|
||||
with h5py.File(cxi_file,'r') as f:
|
||||
with h5py.File(cxi_file, 'r') as f:
|
||||
return cls.from_cxi(f, cut_zeros=cut_zeros, load_patterns=load_patterns)
|
||||
|
||||
# Generate a base dataset
|
||||
@@ -163,10 +165,15 @@ class Ptycho2DDataset(CDataset):
|
||||
patterns, axes = cdtdata.get_data(cxi_file, cut_zeros=cut_zeros)
|
||||
dataset.patterns = t.as_tensor(patterns)
|
||||
if dataset.patterns.dtype == t.float64:
|
||||
raise NotImplementedError('64-bit floats are not supported and precision will not be retained in reconstructions! Please explicitly convert your data to 32-bit or submit a pull request')
|
||||
|
||||
# If the data is 64-bit, we need to convert it to 32-bit
|
||||
# because 64-bit floats are not supported in reconstructions
|
||||
dataset.patterns = dataset.patterns.to(dtype=t.float32)
|
||||
warnings.warn(
|
||||
"64-bit floats are not supported and precision will not be retained in reconstructions and were converted to t.float32! "
|
||||
"If you would like to have 64-bit support, please open an issue or submit a pull request."
|
||||
)
|
||||
dataset.axes = axes
|
||||
|
||||
|
||||
if dataset.mask is None:
|
||||
dataset.mask = t.ones(dataset.patterns.shape[-2:]).to(dtype=t.bool)
|
||||
|
||||
@@ -175,9 +182,8 @@ class Ptycho2DDataset(CDataset):
|
||||
dataset.intensities = t.as_tensor(intensities, dtype=t.float32)
|
||||
except KeyError:
|
||||
dataset.intensities = None
|
||||
|
||||
return dataset
|
||||
|
||||
return dataset
|
||||
|
||||
def to_cxi(self, cxi_file):
|
||||
"""Saves out a Ptycho2DDataset as a .cxi file
|
||||
@@ -269,9 +275,12 @@ class Ptycho2DDataset(CDataset):
|
||||
"""Plots the mean diffraction pattern across the dataset
|
||||
|
||||
The output is normalized so that the summed intensity on the
|
||||
detector is equal to the total intensity of light that passed
|
||||
detector is roughly equal to the total intensity of light that passed
|
||||
through the sample within each detector conjugate field of view.
|
||||
|
||||
If the scan points are colinear (which causes issues for this
|
||||
estimation), the mean pattern is displayed unscaled.
|
||||
|
||||
The plot is plotted as log base 10 of the output plus log_offset.
|
||||
By default, log_offset is set equal to 1, which is a good level for
|
||||
shot-noise limited data captured in units of photons. More
|
||||
@@ -372,10 +381,19 @@ class Ptycho2DDataset(CDataset):
|
||||
equal to the sum of a <factor> x <factor> region of pixels in the
|
||||
input pattern. This summation is done by pytorch.functional.avg_pool2d.
|
||||
|
||||
Any mask and background data which is stored with the dataset is
|
||||
downsampled with the data. The background is downsampled using the same
|
||||
method as the data. The mask is expanded so that any output pixel
|
||||
containing a masked pixel will be masked.
|
||||
Any mask, quantum efficiency, and background data which is stored with
|
||||
the dataset is downsampled with the data. The background is downsampled
|
||||
using the same method as the data.
|
||||
|
||||
If there is no quantum efficiency mask, then the mask is downsampled so
|
||||
that any output pixel containing a masked pixel will be masked. If there
|
||||
is a quantum efficiency mask, then the quantum efficiency mask is
|
||||
downsampled using the same method as the data, and the mask is
|
||||
downsampled to include any pixels for which there is at least one valid
|
||||
pixel.
|
||||
|
||||
To avoid leakage of data from masked pixels, the data is first
|
||||
multiplied by the mask before downsampling.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
@@ -383,17 +401,41 @@ class Ptycho2DDataset(CDataset):
|
||||
Default 2, the factor to downsample by
|
||||
|
||||
"""
|
||||
self.patterns = t.nn.functional.avg_pool2d(
|
||||
self.patterns.unsqueeze(0), factor, divisor_override=1)[0]
|
||||
self.mask = t.logical_not(t.nn.functional.max_pool2d(
|
||||
(1-self.mask.to(dtype=t.uint8)).unsqueeze(0).unsqueeze(0),
|
||||
factor
|
||||
)[0,0].to(dtype=t.bool))
|
||||
if hasattr(self, 'mask') and self.mask is not None:
|
||||
self.patterns = t.nn.functional.avg_pool2d(
|
||||
(self.mask * self.patterns).unsqueeze(0),
|
||||
factor, divisor_override=1)[0]
|
||||
else:
|
||||
self.patterns = t.nn.functional.avg_pool2d(
|
||||
self.patterns.unsqueeze(0),
|
||||
factor, divisor_override=1)[0]
|
||||
|
||||
|
||||
# If we have a QE mask, we want to include all pixels for which at
|
||||
# least one of the input pixels was unmasked, because we can account
|
||||
# for the masked pixels through quantum efficiency
|
||||
if hasattr(self, 'qe_mask') and self.qe_mask is not None:
|
||||
self.qe_mask = t.nn.functional.avg_pool2d(
|
||||
(self.mask * self.qe_mask).unsqueeze(0).unsqueeze(0),
|
||||
factor)[0,0]
|
||||
self.mask = t.nn.functional.max_pool2d(
|
||||
self.mask.to(dtype=t.uint8).unsqueeze(0).unsqueeze(0),
|
||||
factor)[0,0].to(dtype=t.bool)
|
||||
|
||||
# But if there is no QE mask, we need to only preserve pixels for
|
||||
# which all input pixels were unmasked
|
||||
elif hasattr(self, 'mask') and self.mask is not None:
|
||||
self.mask = t.logical_not(t.nn.functional.max_pool2d(
|
||||
(1-self.mask.to(dtype=t.uint8)).unsqueeze(0).unsqueeze(0),
|
||||
factor
|
||||
)[0,0].to(dtype=t.bool))
|
||||
|
||||
self.detector_geometry['basis'] = \
|
||||
self.detector_geometry['basis'] * factor
|
||||
|
||||
if self.background is not None:
|
||||
|
||||
|
||||
if hasattr(self, 'background') and self.background is not None:
|
||||
self.background = t.nn.functional.avg_pool2d(
|
||||
self.background.unsqueeze(0).unsqueeze(0),
|
||||
factor,
|
||||
|
||||
+153
-312
@@ -40,6 +40,10 @@ import time
|
||||
from scipy import io
|
||||
from contextlib import contextmanager
|
||||
from cdtools.tools.data import nested_dict_to_h5, h5_to_nested_dict, nested_dict_to_numpy, nested_dict_to_torch
|
||||
from cdtools.reconstructors import AdamReconstructor, LBFGSReconstructor, SGDReconstructor
|
||||
from cdtools.datasets import CDataset
|
||||
from typing import List, Union, Tuple
|
||||
import os
|
||||
|
||||
__all__ = ['CDIModel']
|
||||
|
||||
@@ -316,202 +320,23 @@ class CDIModel(t.nn.Module):
|
||||
|
||||
self.current_checkpoint_id += 1
|
||||
|
||||
|
||||
|
||||
def AD_optimize(self, iterations, data_loader, optimizer,\
|
||||
scheduler=None, regularization_factor=None, thread=True,
|
||||
calculation_width=10):
|
||||
"""Runs a round of reconstruction using the provided optimizer
|
||||
|
||||
This is the basic automatic differentiation reconstruction tool
|
||||
which all the other, algorithm-specific tools, use. It is a
|
||||
generator which yields the average loss each epoch, ending after
|
||||
the specified number of iterations.
|
||||
|
||||
By default, the computation will be run in a separate thread. This
|
||||
is done to enable live plotting with matplotlib during a reconstruction.
|
||||
If the computation was done in the main thread, this would freeze
|
||||
the plots. This behavior can be turned off by setting the keyword
|
||||
argument 'thread' to False.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
iterations : int
|
||||
How many epochs of the algorithm to run
|
||||
data_loader : torch.utils.data.DataLoader
|
||||
A data loader loading the CDataset to reconstruct
|
||||
optimizer : torch.optim.Optimizer
|
||||
The optimizer to run the reconstruction with
|
||||
scheduler : torch.optim.lr_scheduler._LRScheduler
|
||||
Optional, a learning rate scheduler to use
|
||||
regularization_factor : float or list(float)
|
||||
Optional, if the model has a regularizer defined, the set of parameters to pass the regularizer method
|
||||
thread : bool
|
||||
Default True, whether to run the computation in a separate thread to allow interaction with plots during computation
|
||||
calculation_width : int
|
||||
Default 10, how many translations to pass through at once for each round of gradient accumulation. This does not affect the result, but may affect the calculation speed.
|
||||
|
||||
Yields
|
||||
------
|
||||
loss : float
|
||||
The summed loss over the latest epoch, divided by the total diffraction pattern intensity
|
||||
"""
|
||||
|
||||
def run_epoch(stop_event=None):
|
||||
"""Runs one full epoch of the reconstruction."""
|
||||
# First, initialize some tracking variables
|
||||
normalization = 0
|
||||
loss = 0
|
||||
N = 0
|
||||
t0 = time.time()
|
||||
|
||||
# The data loader is responsible for setting the minibatch
|
||||
# size, so each set is a minibatch
|
||||
for inputs, patterns in data_loader:
|
||||
normalization += t.sum(patterns).cpu().numpy()
|
||||
N += 1
|
||||
def closure():
|
||||
optimizer.zero_grad()
|
||||
|
||||
# We further break up the minibatch into a set of chunks.
|
||||
# This lets us use larger minibatches than can fit
|
||||
# on the GPU at once, while still doing batch processing
|
||||
# for efficiency
|
||||
input_chunks = [[inp[i:i + calculation_width]
|
||||
for inp in inputs]
|
||||
for i in range(0, len(inputs[0]),
|
||||
calculation_width)]
|
||||
pattern_chunks = [patterns[i:i + calculation_width]
|
||||
for i in range(0, len(inputs[0]),
|
||||
calculation_width)]
|
||||
|
||||
total_loss = 0
|
||||
for inp, pats in zip(input_chunks, pattern_chunks):
|
||||
# This check allows for graceful exit when threading
|
||||
if stop_event is not None and stop_event.is_set():
|
||||
exit()
|
||||
|
||||
# Run the simulation
|
||||
sim_patterns = self.forward(*inp)
|
||||
|
||||
# Calculate the loss
|
||||
if hasattr(self, 'mask'):
|
||||
loss = self.loss(pats,sim_patterns, mask=self.mask)
|
||||
else:
|
||||
loss = self.loss(pats,sim_patterns)
|
||||
|
||||
# And accumulate the gradients
|
||||
loss.backward()
|
||||
total_loss += loss.detach()
|
||||
|
||||
# If we have a regularizer, we can calculate it separately,
|
||||
# and the gradients will add to the minibatch gradient
|
||||
if regularization_factor is not None \
|
||||
and hasattr(self, 'regularizer'):
|
||||
loss = self.regularizer(regularization_factor)
|
||||
loss.backward()
|
||||
|
||||
return total_loss
|
||||
|
||||
# This takes the step for this minibatch
|
||||
loss += optimizer.step(closure).detach().cpu().numpy()
|
||||
|
||||
|
||||
loss /= normalization
|
||||
|
||||
# We step the scheduler after the full epoch
|
||||
if scheduler is not None:
|
||||
scheduler.step(loss)
|
||||
|
||||
self.loss_history.append(loss)
|
||||
self.epoch = len(self.loss_history)
|
||||
self.latest_iteration_time = time.time() - t0
|
||||
self.training_history += self.report() + '\n'
|
||||
return loss
|
||||
|
||||
# We store the current optimizer as a model parameter so that
|
||||
# it can be saved and loaded for checkpointing
|
||||
self.current_optimizer = optimizer
|
||||
|
||||
# If we don't want to run in a different thread, this is easy
|
||||
if not thread:
|
||||
for it in range(iterations):
|
||||
if self.skip_computation():
|
||||
self.epoch = self.epoch + 1
|
||||
if len(self.loss_history) >= 1:
|
||||
yield self.loss_history[-1]
|
||||
else:
|
||||
yield float('nan')
|
||||
continue
|
||||
|
||||
yield run_epoch()
|
||||
|
||||
|
||||
# But if we do want to thread, it's annoying:
|
||||
else:
|
||||
# Here we set up the communication with the computation thread
|
||||
result_queue = queue.Queue()
|
||||
stop_event = threading.Event()
|
||||
def target():
|
||||
try:
|
||||
result_queue.put(run_epoch(stop_event))
|
||||
except Exception as e:
|
||||
# If something bad happens, put the exception into the
|
||||
# result queue
|
||||
result_queue.put(e)
|
||||
|
||||
# And this actually starts and monitors the thread
|
||||
for it in range(iterations):
|
||||
if self.skip_computation():
|
||||
self.epoch = self.epoch + 1
|
||||
if len(self.loss_history) >= 1:
|
||||
yield self.loss_history[-1]
|
||||
else:
|
||||
yield float('nan')
|
||||
continue
|
||||
|
||||
calc = threading.Thread(target=target, name='calculator', daemon=True)
|
||||
try:
|
||||
calc.start()
|
||||
while calc.is_alive():
|
||||
if hasattr(self, 'figs'):
|
||||
self.figs[0].canvas.start_event_loop(0.01)
|
||||
else:
|
||||
calc.join()
|
||||
|
||||
except KeyboardInterrupt as e:
|
||||
stop_event.set()
|
||||
print('\nAsking execution thread to stop cleanly - please be patient.')
|
||||
calc.join()
|
||||
raise e
|
||||
|
||||
res = result_queue.get()
|
||||
|
||||
# If something went wrong in the thead, we'll get an exception
|
||||
if isinstance(res, Exception):
|
||||
raise res
|
||||
|
||||
yield res
|
||||
|
||||
# And finally, we unset the current optimizer:
|
||||
self.current_optimizer = None
|
||||
|
||||
|
||||
def Adam_optimize(
|
||||
self,
|
||||
iterations,
|
||||
dataset,
|
||||
batch_size=15,
|
||||
lr=0.005,
|
||||
betas=(0.9, 0.999),
|
||||
schedule=False,
|
||||
amsgrad=False,
|
||||
subset=None,
|
||||
regularization_factor=None,
|
||||
iterations: int,
|
||||
dataset: CDataset,
|
||||
batch_size: int = 15,
|
||||
lr: float = 0.005,
|
||||
betas: Tuple[float] = (0.9, 0.999),
|
||||
schedule: bool = False,
|
||||
amsgrad: bool = False,
|
||||
subset: Union[int, List[int]] = None,
|
||||
regularization_factor: Union[float, List[float]] = None,
|
||||
thread=True,
|
||||
calculation_width=10
|
||||
):
|
||||
"""Runs a round of reconstruction using the Adam optimizer
|
||||
"""
|
||||
Runs a round of reconstruction using the Adam optimizer from
|
||||
cdtools.reconstructors.AdamReconstructor.
|
||||
|
||||
This is generally accepted to be the most robust algorithm for use
|
||||
with ptychography. Like all the other optimization routines,
|
||||
@@ -521,125 +346,132 @@ class CDIModel(t.nn.Module):
|
||||
Parameters
|
||||
----------
|
||||
iterations : int
|
||||
How many epochs of the algorithm to run
|
||||
How many epochs of the algorithm to run.
|
||||
dataset : CDataset
|
||||
The dataset to reconstruct against
|
||||
The dataset to reconstruct against.
|
||||
batch_size : int
|
||||
Optional, the size of the minibatches to use
|
||||
Optional, the size of the minibatches to use.
|
||||
lr : float
|
||||
Optional, The learning rate (alpha) to use. Defaultis 0.005. 0.05 is typically the highest possible value with any chance of being stable
|
||||
betas : tuple
|
||||
Optional, The learning rate (alpha) to use. Defaultis 0.005.
|
||||
0.05 is typically the highest possible value with any chance
|
||||
of being stable.
|
||||
betas : tuple(float)
|
||||
Optional, the beta_1 and beta_2 to use. Default is (0.9, 0.999).
|
||||
schedule : float
|
||||
Optional, whether to use the ReduceLROnPlateau scheduler
|
||||
schedule : bool
|
||||
Optional, whether to use the ReduceLROnPlateau scheduler.
|
||||
amsgrad : bool
|
||||
Optional, whether to use the AMSGrad variant of this algorithm.
|
||||
subset : list(int) or int
|
||||
Optional, a pattern index or list of pattern indices to use
|
||||
regularization_factor : float or list(float)
|
||||
Optional, if the model has a regularizer defined, the set of parameters to pass the regularizer method
|
||||
regularization_factor : float or list(float).
|
||||
Optional, if the model has a regularizer defined, the set of
|
||||
parameters to pass the regularizer method.
|
||||
thread : bool
|
||||
Default True, whether to run the computation in a separate thread to allow interaction with plots during computation
|
||||
Default True, whether to run the computation in a separate thread
|
||||
to allow interaction with plots during computation.
|
||||
calculation_width : int
|
||||
Default 10, how many translations to pass through at once for each round of gradient accumulation. Does not affect the result, only the calculation speed
|
||||
|
||||
Default 10, how many translations to pass through at once for
|
||||
each round of gradient accumulation. Does not affect the result,
|
||||
only the calculation speed.
|
||||
|
||||
"""
|
||||
|
||||
self.training_history += (
|
||||
f'Planning {iterations} epochs of Adam, with a learning rate = '
|
||||
f'{lr}, batch size = {batch_size}, regularization_factor = '
|
||||
f'{regularization_factor}, and schedule = {schedule}.\n'
|
||||
reconstructor = AdamReconstructor(
|
||||
model=self,
|
||||
dataset=dataset,
|
||||
subset=subset,
|
||||
)
|
||||
|
||||
|
||||
if subset is not None:
|
||||
# if subset is just one pattern, turn into a list for convenience
|
||||
if type(subset) == type(1):
|
||||
subset = [subset]
|
||||
dataset = torchdata.Subset(dataset, subset)
|
||||
|
||||
# Make a dataloader
|
||||
data_loader = torchdata.DataLoader(dataset,
|
||||
batch_size=batch_size,
|
||||
shuffle=True)
|
||||
|
||||
# Define the optimizer
|
||||
optimizer = t.optim.Adam(
|
||||
self.parameters(),
|
||||
lr = lr,
|
||||
# Run some reconstructions
|
||||
return reconstructor.optimize(
|
||||
iterations=iterations,
|
||||
batch_size=batch_size,
|
||||
lr=lr,
|
||||
betas=betas,
|
||||
amsgrad=amsgrad)
|
||||
schedule=schedule,
|
||||
amsgrad=amsgrad,
|
||||
regularization_factor=regularization_factor, # noqa
|
||||
thread=thread,
|
||||
calculation_width=calculation_width,
|
||||
)
|
||||
|
||||
# Define the scheduler
|
||||
if schedule:
|
||||
scheduler = t.optim.lr_scheduler.ReduceLROnPlateau(optimizer, factor=0.2,threshold=1e-9)
|
||||
else:
|
||||
scheduler = None
|
||||
|
||||
return self.AD_optimize(iterations, data_loader, optimizer,
|
||||
scheduler=scheduler,
|
||||
regularization_factor=regularization_factor,
|
||||
thread=thread,
|
||||
calculation_width=calculation_width)
|
||||
|
||||
|
||||
def LBFGS_optimize(self, iterations, dataset,
|
||||
lr=0.1,history_size=2, subset=None,
|
||||
regularization_factor=None, thread=True,
|
||||
calculation_width=10, line_search_fn=None):
|
||||
"""Runs a round of reconstruction using the L-BFGS optimizer
|
||||
def LBFGS_optimize(self,
|
||||
iterations: int,
|
||||
dataset: CDataset,
|
||||
lr: float = 0.1,
|
||||
history_size: int = 2,
|
||||
subset: Union[int, List[int]] = None,
|
||||
regularization_factor: Union[float, List[float]] =None,
|
||||
thread: bool = True,
|
||||
calculation_width: int = 10,
|
||||
line_search_fn: str = None):
|
||||
"""
|
||||
Runs a round of reconstruction using the L-BFGS optimizer from
|
||||
cdtools.reconstructors.LBFGSReconstructor.
|
||||
|
||||
This algorithm is often less stable that Adam, however in certain
|
||||
situations or geometries it can be shockingly efficient. Like all
|
||||
the other optimization routines, it is defined as a generator
|
||||
function which yields the average loss each epoch.
|
||||
|
||||
Note: There is no batch size, because it is a usually a bad idea to use
|
||||
NOTE: There is no batch size, because it is a usually a bad idea to use
|
||||
LBFGS on anything but all the data at onece
|
||||
|
||||
Parameters
|
||||
----------
|
||||
iterations : int
|
||||
How many epochs of the algorithm to run
|
||||
How many epochs of the algorithm to run.
|
||||
dataset : CDataset
|
||||
The dataset to reconstruct against
|
||||
The dataset to reconstruct against.
|
||||
lr : float
|
||||
Optional, the learning rate to use
|
||||
Optional, the learning rate to use.
|
||||
history_size : int
|
||||
Optional, the length of the history to use.
|
||||
subset : list(int) or int
|
||||
Optional, a pattern index or list of pattern indices to ues
|
||||
Optional, a pattern index or list of pattern indices to use.
|
||||
regularization_factor : float or list(float)
|
||||
Optional, if the model has a regularizer defined, the set of parameters to pass the regularizer method
|
||||
Optional, if the model has a regularizer defined, the set of
|
||||
parameters to pass the regularizer method.
|
||||
thread : bool
|
||||
Default True, whether to run the computation in a separate thread to allow interaction with plots during computation.
|
||||
|
||||
Default True, whether to run the computation in a separate thread
|
||||
to allow interaction with plots during computation.
|
||||
calculation_width : int
|
||||
Default 10, how many translations to pass through at once for each
|
||||
round of gradient accumulation. Does not affect the result, only
|
||||
the calculation speed.
|
||||
"""
|
||||
if subset is not None:
|
||||
# if just one pattern, turn into a list for convenience
|
||||
if type(subset) == type(1):
|
||||
subset = [subset]
|
||||
dataset = torchdata.Subset(dataset, subset)
|
||||
|
||||
# Make a dataloader. This basically does nothing but load all the
|
||||
# data at once
|
||||
data_loader = torchdata.DataLoader(dataset, batch_size=len(dataset))
|
||||
|
||||
|
||||
# Define the optimizer
|
||||
optimizer = t.optim.LBFGS(self.parameters(),
|
||||
lr = lr, history_size=history_size,
|
||||
line_search_fn=line_search_fn)
|
||||
|
||||
return self.AD_optimize(iterations, data_loader, optimizer,
|
||||
regularization_factor=regularization_factor,
|
||||
thread=thread,
|
||||
calculation_width=calculation_width)
|
||||
|
||||
|
||||
def SGD_optimize(self, iterations, dataset, batch_size=None,
|
||||
lr=0.01, momentum=0, dampening=0, weight_decay=0,
|
||||
nesterov=False, subset=None, regularization_factor=None,
|
||||
thread=True, calculation_width=10):
|
||||
"""Runs a round of reconstruction using the SGD optimizer
|
||||
reconstructor = LBFGSReconstructor(
|
||||
model=self,
|
||||
dataset=dataset,
|
||||
subset=subset,
|
||||
)
|
||||
|
||||
# Run some reconstructions
|
||||
return reconstructor.optimize(
|
||||
iterations=iterations,
|
||||
lr=lr,
|
||||
history_size=history_size,
|
||||
regularization_factor=regularization_factor, # noqa
|
||||
thread=thread,
|
||||
calculation_width=calculation_width,
|
||||
line_search_fn=line_search_fn,
|
||||
)
|
||||
|
||||
def SGD_optimize(self,
|
||||
iterations: int,
|
||||
dataset: CDataset,
|
||||
batch_size: int = None,
|
||||
lr: float = 2e-7,
|
||||
momentum: float = 0,
|
||||
dampening: float = 0,
|
||||
weight_decay: float = 0,
|
||||
nesterov: bool = False,
|
||||
subset: Union[int, List[int]] = None,
|
||||
regularization_factor: Union[float, List[float]] = None,
|
||||
thread: bool = True,
|
||||
calculation_width: int = 10):
|
||||
"""
|
||||
Runs a round of reconstruction using the SGD optimizer from
|
||||
cdtools.reconstructors.SGDReconstructor.
|
||||
|
||||
This algorithm is often less stable that Adam, but it is simpler
|
||||
and is the basic workhorse of gradience descent.
|
||||
@@ -647,51 +479,54 @@ class CDIModel(t.nn.Module):
|
||||
Parameters
|
||||
----------
|
||||
iterations : int
|
||||
How many epochs of the algorithm to run
|
||||
How many epochs of the algorithm to run.
|
||||
dataset : CDataset
|
||||
The dataset to reconstruct against
|
||||
The dataset to reconstruct against.
|
||||
batch_size : int
|
||||
Optional, the size of the minibatches to use
|
||||
Optional, the size of the minibatches to use.
|
||||
lr : float
|
||||
Optional, the learning rate to use
|
||||
Optional, the learning rate to use.
|
||||
momentum : float
|
||||
Optional, the length of the history to use.
|
||||
dampening : float
|
||||
Optional, dampening for the momentum.
|
||||
weight_decay : float
|
||||
Optional, weight decay (L2 penalty).
|
||||
nesterov : bool
|
||||
Optional, enables Nesterov momentum. Only applicable when momentum
|
||||
is non-zero.
|
||||
subset : list(int) or int
|
||||
Optional, a pattern index or list of pattern indices to use
|
||||
Optional, a pattern index or list of pattern indices to use.
|
||||
regularization_factor : float or list(float)
|
||||
Optional, if the model has a regularizer defined, the set of parameters to pass the regularizer method
|
||||
Optional, if the model has a regularizer defined, the set of
|
||||
parameters to pass the regularizer method.
|
||||
thread : bool
|
||||
Default True, whether to run the computation in a separate thread to allow interaction with plots during computation
|
||||
Default True, whether to run the computation in a separate thread
|
||||
to allow interaction with plots during computation.
|
||||
calculation_width : int
|
||||
Default 1, how many translations to pass through at once for each round of gradient accumulation
|
||||
Default 10, how many translations to pass through at once for each
|
||||
round of gradient accumulation.
|
||||
|
||||
"""
|
||||
reconstructor = SGDReconstructor(
|
||||
model=self,
|
||||
dataset=dataset,
|
||||
subset=subset,
|
||||
)
|
||||
|
||||
if subset is not None:
|
||||
# if just one pattern, turn into a list for convenience
|
||||
if type(subset) == type(1):
|
||||
subset = [subset]
|
||||
dataset = torchdata.Subset(dataset, subset)
|
||||
|
||||
# Make a dataloader
|
||||
if batch_size is not None:
|
||||
data_loader = torchdata.DataLoader(dataset, batch_size=batch_size,
|
||||
shuffle=True)
|
||||
else:
|
||||
data_loader = torchdata.DataLoader(dataset)
|
||||
|
||||
|
||||
# Define the optimizer
|
||||
optimizer = t.optim.SGD(self.parameters(),
|
||||
lr = lr, momentum=momentum,
|
||||
dampening=dampening,
|
||||
weight_decay=weight_decay,
|
||||
nesterov=nesterov)
|
||||
|
||||
return self.AD_optimize(iterations, data_loader, optimizer,
|
||||
regularization_factor=regularization_factor,
|
||||
thread=thread,
|
||||
calculation_width=calculation_width)
|
||||
# Run some reconstructions
|
||||
return reconstructor.optimize(
|
||||
iterations=iterations,
|
||||
batch_size=batch_size,
|
||||
lr=lr,
|
||||
momentum=momentum,
|
||||
dampening=dampening,
|
||||
weight_decay=weight_decay,
|
||||
nesterov=nesterov,
|
||||
regularization_factor=regularization_factor, # noqa
|
||||
thread=thread,
|
||||
calculation_width=calculation_width,
|
||||
)
|
||||
|
||||
|
||||
def report(self):
|
||||
@@ -872,7 +707,13 @@ class CDIModel(t.nn.Module):
|
||||
updating = True if len(axes[0].images) >= 1 else False
|
||||
|
||||
inputs, output = dataset[idx:idx+1]
|
||||
sim_data = self.forward(*inputs).detach().cpu().numpy()[0]
|
||||
sim_data = self.forward(*inputs).detach().cpu().numpy()
|
||||
# The length of sim_data.shape changes when you're doing
|
||||
# either a ptycho (3) or an RPI (2) reconstruction.
|
||||
# We need to make sure that sim_data is 2D.
|
||||
if len(sim_data.shape) > 2:
|
||||
sim_data = sim_data[0]
|
||||
|
||||
meas_data = output.detach().cpu().numpy()[0]
|
||||
if hasattr(self, 'mask') and self.mask is not None:
|
||||
mask = self.mask.detach().cpu().numpy()
|
||||
|
||||
@@ -28,6 +28,7 @@ class FancyPtycho(CDIModel):
|
||||
probe_fourier_shifts=None,
|
||||
mask=None,
|
||||
weights=None,
|
||||
qe_mask=None,
|
||||
translation_scale=1,
|
||||
saturation=None,
|
||||
probe_support=None,
|
||||
@@ -109,7 +110,18 @@ class FancyPtycho(CDIModel):
|
||||
else:
|
||||
self.register_buffer('mask',
|
||||
t.as_tensor(mask, dtype=t.bool))
|
||||
|
||||
|
||||
|
||||
if qe_mask is None:
|
||||
self.qe_mask = None
|
||||
else:
|
||||
self.qe_mask = t.nn.Parameter(
|
||||
t.as_tensor(qe_mask, dtype=dtype))
|
||||
# I want the ability to optimize over this, but experience shows
|
||||
# that it is wildly unstable, so I think it's best to keep
|
||||
# gradients turned off by default
|
||||
self.qe_mask.requires_grad=False
|
||||
|
||||
probe_guess = t.as_tensor(probe_guess, dtype=t.complex64)
|
||||
obj_guess = t.as_tensor(obj_guess, dtype=t.complex64)
|
||||
|
||||
@@ -224,6 +236,7 @@ class FancyPtycho(CDIModel):
|
||||
dm_rank=None,
|
||||
translation_scale=1,
|
||||
saturation=None,
|
||||
use_qe_mask=False,
|
||||
probe_support_radius=None,
|
||||
probe_fourier_crop=None,
|
||||
propagation_distance=None,
|
||||
@@ -454,6 +467,14 @@ class FancyPtycho(CDIModel):
|
||||
else:
|
||||
mask = None
|
||||
|
||||
if use_qe_mask:
|
||||
if hasattr(dataset, 'qe_mask') and dataset.qe_mask is not None:
|
||||
qe_mask = t.as_tensor(dataset.qe_mask, dtype=t.float32)
|
||||
else:
|
||||
qe_mask = t.ones(dataset.patterns.shape[-2:], dtype=t.float32)
|
||||
else:
|
||||
qe_mask = None
|
||||
|
||||
if probe_support_radius is not None:
|
||||
probe_support = t.zeros(probe[0].shape, dtype=t.bool)
|
||||
xs, ys = np.mgrid[:probe.shape[-2], :probe.shape[-1]]
|
||||
@@ -479,13 +500,15 @@ class FancyPtycho(CDIModel):
|
||||
weights=Ws,
|
||||
mask=mask,
|
||||
background=background,
|
||||
qe_mask=qe_mask,
|
||||
translation_scale=translation_scale,
|
||||
saturation=saturation,
|
||||
probe_basis=probe_basis,
|
||||
probe_support=probe_support,
|
||||
fourier_probe=fourier_probe,
|
||||
oversampling=oversampling,
|
||||
loss=loss, units=units,
|
||||
loss=loss,
|
||||
units=units,
|
||||
probe_fourier_shifts=probe_fourier_shifts,
|
||||
simulate_probe_translation=simulate_probe_translation,
|
||||
simulate_finite_pixels=simulate_finite_pixels,
|
||||
@@ -620,6 +643,7 @@ class FancyPtycho(CDIModel):
|
||||
wavefields,
|
||||
self.background,
|
||||
measurement=tools.measurements.incoherent_sum,
|
||||
qe_mask=self.qe_mask,
|
||||
saturation=self.saturation,
|
||||
oversampling=self.oversampling,
|
||||
simulate_finite_pixels=self.simulate_finite_pixels,
|
||||
@@ -696,15 +720,40 @@ class FancyPtycho(CDIModel):
|
||||
|
||||
|
||||
def center_probes(self, iterations=4):
|
||||
"""Centers the probes
|
||||
"""Centers the probes in real space
|
||||
|
||||
Takes the current guess of the illumination function and centers it
|
||||
using a shift with periodic boundary conditions. It uses
|
||||
cdtools.tools.image_processing.center internally to do the centering.
|
||||
Multiple iterations of an algorithm are run, which is helpful if the
|
||||
illumination is reconstructed near the corners and "wraps around" the
|
||||
probe field of view.
|
||||
|
||||
Note that the centering is always performed in real space, even if
|
||||
the probe array is defined in Fourier space.
|
||||
|
||||
Note that this does not compensate for the centering by adjusting
|
||||
Note also that this does not compensate for the centering by adjusting
|
||||
the object, so it's a good idea to reset the object after centering
|
||||
the probes
|
||||
|
||||
Parameters
|
||||
----------
|
||||
iterations : int
|
||||
Default 4, how many iterations of the centering algorithm to run
|
||||
"""
|
||||
centered_probe = tools.image_processing.center(
|
||||
self.probe.data.cpu(), iterations=iterations)
|
||||
self.probe.data = centered_probe.to(device=self.probe.data.device)
|
||||
if self.fourier_probe:
|
||||
prs = tools.propagators.inverse_far_field(self.probe.detach()).cpu()
|
||||
else:
|
||||
prs = self.probe.detach().cpu()
|
||||
|
||||
centered_prs = tools.image_processing.center(prs, iterations=iterations)
|
||||
|
||||
if self.fourier_probe:
|
||||
self.probe.data = tools.propagators.far_field(
|
||||
centered_prs.to(device=self.probe.data.device))
|
||||
else:
|
||||
self.probe.data = centered_prs.to(device=self.probe.data.device)
|
||||
|
||||
|
||||
|
||||
def tidy_probes(self):
|
||||
@@ -840,6 +889,28 @@ class FancyPtycho(CDIModel):
|
||||
**kwargs),
|
||||
|
||||
|
||||
def plot_translations_and_originals(self, fig, dataset):
|
||||
"""Only used to make a plot for the plot list."""
|
||||
p.plot_translations(
|
||||
dataset.translations,
|
||||
fig=fig,
|
||||
units=self.units,
|
||||
label='original translations',
|
||||
color='#CCCCCC',
|
||||
marker='o',
|
||||
)
|
||||
p.plot_translations(
|
||||
self.corrected_translations(dataset),
|
||||
fig=fig,
|
||||
units=self.units,
|
||||
clear_fig=False,
|
||||
label='refined translations',
|
||||
color='k',
|
||||
marker='.'
|
||||
)
|
||||
plt.legend()
|
||||
|
||||
|
||||
plot_list = [
|
||||
('',
|
||||
lambda self, fig, dataset: self.plot_wavefront_variation(
|
||||
@@ -937,9 +1008,12 @@ class FancyPtycho(CDIModel):
|
||||
lambda self: self.exponentiate_obj),
|
||||
|
||||
('Corrected Translations',
|
||||
lambda self, fig, dataset: p.plot_translations(self.corrected_translations(dataset), fig=fig, units=self.units)),
|
||||
lambda self, fig, dataset: self.plot_translations_and_originals(fig, dataset)),
|
||||
('Background',
|
||||
lambda self, fig: p.plot_amplitude(self.background**2, fig=fig))
|
||||
lambda self, fig: p.plot_amplitude(self.background**2, fig=fig)),
|
||||
('Quantum Efficiency Mask',
|
||||
lambda self, fig: p.plot_amplitude(self.qe_mask, fig=fig),
|
||||
lambda self: (hasattr(self, 'qe_mask') and self.qe_mask is not None))
|
||||
]
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
"""
|
||||
Module `cdtools.tools.reconstructors` contains the `Reconstructor` class and
|
||||
subclasses which run the ptychography reconstructions on a given model and
|
||||
dataset.
|
||||
|
||||
The reconstructors are designed to resemble so-called 'Trainer' classes that
|
||||
(in the language of the AI/ML folks) handles the 'training' of a model given
|
||||
some dataset and optimizer.
|
||||
"""
|
||||
|
||||
# We define __all__ to be sure that import * only imports what we want
|
||||
__all__ = [
|
||||
'Reconstructor',
|
||||
'AdamReconstructor',
|
||||
'LBFGSReconstructor',
|
||||
'SGDReconstructor'
|
||||
]
|
||||
|
||||
from cdtools.reconstructors.base import Reconstructor
|
||||
from cdtools.reconstructors.adam import AdamReconstructor
|
||||
from cdtools.reconstructors.lbfgs import LBFGSReconstructor
|
||||
from cdtools.reconstructors.sgd import SGDReconstructor
|
||||
@@ -0,0 +1,178 @@
|
||||
"""This module contains the AdamReconstructor subclass for performing
|
||||
optimization ('reconstructions') on ptychographic/CDI models using
|
||||
the Adam optimizer.
|
||||
|
||||
The Reconstructor class is designed to resemble so-called
|
||||
'Trainer' classes that (in the language of the AI/ML folks) handles
|
||||
the 'training' of a model given some dataset and optimizer.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import torch as t
|
||||
from typing import Tuple, List, Union
|
||||
from cdtools.reconstructors import Reconstructor
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from cdtools.models import CDIModel
|
||||
from cdtools.datasets.ptycho_2d_dataset import Ptycho2DDataset
|
||||
|
||||
__all__ = ['AdamReconstructor']
|
||||
|
||||
|
||||
class AdamReconstructor(Reconstructor):
|
||||
"""
|
||||
The Adam Reconstructor subclass handles the optimization ('reconstruction')
|
||||
of ptychographic models and datasets using the Adam optimizer.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
model: CDIModel
|
||||
Model for CDI/ptychography reconstruction.
|
||||
dataset: Ptycho2DDataset
|
||||
The dataset to reconstruct against.
|
||||
subset : list(int) or int
|
||||
Optional, a pattern index or list of pattern indices to use.
|
||||
schedule : bool
|
||||
Optional, create a learning rate scheduler
|
||||
(torch.optim.lr_scheduler._LRScheduler).
|
||||
|
||||
Important attributes:
|
||||
- **model** -- Always points to the core model used.
|
||||
- **optimizer** -- This class by default uses `torch.optim.Adam` to perform
|
||||
optimizations.
|
||||
- **scheduler** -- A `torch.optim.lr_scheduler` that is defined during the
|
||||
`optimize` method.
|
||||
- **data_loader** -- A torch.utils.data.DataLoader that is defined by
|
||||
calling the `setup_dataloader` method.
|
||||
"""
|
||||
def __init__(self,
|
||||
model: CDIModel,
|
||||
dataset: Ptycho2DDataset,
|
||||
subset: List[int] = None):
|
||||
|
||||
# Define the optimizer for use in this subclass
|
||||
optimizer = t.optim.Adam(model.parameters())
|
||||
|
||||
super().__init__(model, dataset, optimizer, subset=subset)
|
||||
|
||||
|
||||
|
||||
def adjust_optimizer(self,
|
||||
lr: int = 0.005,
|
||||
betas: Tuple[float] = (0.9, 0.999),
|
||||
amsgrad: bool = False):
|
||||
"""
|
||||
Change hyperparameters for the utilized optimizer.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
lr : float
|
||||
Optional, The learning rate (alpha) to use. Default is 0.005. 0.05
|
||||
is typically the highest possible value with any chance of being
|
||||
stable.
|
||||
betas : tuple
|
||||
Optional, the beta_1 and beta_2 to use. Default is (0.9, 0.999).
|
||||
amsgrad : bool
|
||||
Optional, whether to use the AMSGrad variant of this algorithm.
|
||||
"""
|
||||
for param_group in self.optimizer.param_groups:
|
||||
param_group['lr'] = lr
|
||||
param_group['betas'] = betas
|
||||
param_group['amsgrad'] = amsgrad
|
||||
|
||||
|
||||
def optimize(self,
|
||||
iterations: int,
|
||||
batch_size: int = 15,
|
||||
lr: float = 0.005,
|
||||
betas: Tuple[float] = (0.9, 0.999),
|
||||
custom_data_loader: t.utils.data.DataLoader = None,
|
||||
schedule: bool = False,
|
||||
amsgrad: bool = False,
|
||||
regularization_factor: Union[float, List[float]] = None,
|
||||
thread: bool = True,
|
||||
calculation_width: int = 10,
|
||||
shuffle: bool = True):
|
||||
"""
|
||||
Runs a round of reconstruction using the Adam optimizer
|
||||
|
||||
Formerly `CDIModel.Adam_optimize`
|
||||
|
||||
This calls the Reconstructor.optimize superclass method
|
||||
(formerly `CDIModel.AD_optimize`) to run a round of reconstruction
|
||||
once the dataloader and optimizer hyperparameters have been
|
||||
set up.
|
||||
|
||||
The `batch_size` parameter sets the batch size for the default
|
||||
dataloader. If a custom data loader is desired, it can be passed
|
||||
in to the `custom_data_loader` argument, which will override the
|
||||
`batch_size` and `shuffle` parameters
|
||||
|
||||
|
||||
Parameters
|
||||
----------
|
||||
iterations : int
|
||||
How many epochs of the algorithm to run.
|
||||
batch_size : int
|
||||
Optional, the size of the minibatches to use.
|
||||
lr : float
|
||||
Optional, The learning rate (alpha) to use. Default is 0.005. 0.05
|
||||
is typically the highest possible value with any chance of being
|
||||
stable.
|
||||
betas : tuple
|
||||
Optional, the beta_1 and beta_2 to use. Default is (0.9, 0.999).
|
||||
schedule : bool
|
||||
Optional, create a learning rate scheduler
|
||||
(torch.optim.lr_scheduler._LRScheduler).
|
||||
custom_data_loader : t.utils.data.DataLoader
|
||||
Optional, a custom DataLoader to use. If set, will override
|
||||
batch_size.
|
||||
amsgrad : bool
|
||||
Optional, whether to use the AMSGrad variant of this algorithm.
|
||||
regularization_factor : float or list(float)
|
||||
Optional, if the model has a regularizer defined, the set of
|
||||
parameters to pass the regularizer method.
|
||||
thread : bool
|
||||
Default True, whether to run the computation in a separate thread
|
||||
to allow interaction with plots during computation.
|
||||
calculation_width : int
|
||||
Default 10, how many translations to pass through at once for each
|
||||
round of gradient accumulation. Does not affect the result, only
|
||||
the calculation speed.
|
||||
shuffle : bool
|
||||
Optional, enable/disable shuffling of the dataset. This option
|
||||
is intended for diagnostic purposes and should be left as True.
|
||||
"""
|
||||
# Update the training history
|
||||
self.model.training_history += (
|
||||
f'Planning {iterations} epochs of Adam, with a learning rate = '
|
||||
f'{lr}, batch size = {batch_size}, regularization_factor = '
|
||||
f'{regularization_factor}, and schedule = {schedule}.\n'
|
||||
)
|
||||
|
||||
# The optimizer is created in self.__init__, but the
|
||||
# hyperparameters need to be set up with self.adjust_optimizer
|
||||
self.adjust_optimizer(lr=lr,
|
||||
betas=betas,
|
||||
amsgrad=amsgrad)
|
||||
|
||||
# Set up the scheduler
|
||||
if schedule:
|
||||
self.scheduler = \
|
||||
t.optim.lr_scheduler.ReduceLROnPlateau(self.optimizer,
|
||||
factor=0.2,
|
||||
threshold=1e-9)
|
||||
else:
|
||||
self.scheduler = None
|
||||
|
||||
# Now, we run the optimize routine defined in the base class
|
||||
return super(AdamReconstructor, self).optimize(
|
||||
iterations,
|
||||
batch_size=batch_size,
|
||||
custom_data_loader=custom_data_loader,
|
||||
regularization_factor=regularization_factor,
|
||||
thread=thread,
|
||||
calculation_width=calculation_width,
|
||||
shuffle=shuffle,
|
||||
)
|
||||
@@ -0,0 +1,381 @@
|
||||
"""This module contains the base Reconstructor class for performing
|
||||
optimization ('reconstructions') on ptychographic/CDI models.
|
||||
|
||||
The Reconstructor class is designed to resemble so-called
|
||||
'Trainer' classes that (in the language of the AI/ML folks) handles
|
||||
the 'training' of a model given some dataset and optimizer.
|
||||
|
||||
The subclasses of Reconstructor are required to implement
|
||||
their own data loaders and optimizer adjusters
|
||||
"""
|
||||
from __future__ import annotations
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import torch as t
|
||||
from torch.utils import data as td
|
||||
import threading
|
||||
import queue
|
||||
import time
|
||||
from typing import List, Union
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from cdtools.models import CDIModel
|
||||
from cdtools.datasets import CDataset
|
||||
|
||||
|
||||
__all__ = ['Reconstructor']
|
||||
|
||||
|
||||
class Reconstructor:
|
||||
"""
|
||||
Reconstructor handles the optimization ('reconstruction') of ptychographic
|
||||
models given a CDIModel (or subclass) and corresponding CDataset.
|
||||
|
||||
This is a base model that defines all functions Reconstructor subclasses
|
||||
must implement.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
model: CDIModel
|
||||
Model for CDI/ptychography reconstruction
|
||||
dataset: CDataset
|
||||
The dataset to reconstruct against
|
||||
optimizer: torch.optim.Optimizer
|
||||
The optimizer to use for the reconstruction
|
||||
subset : list(int) or int
|
||||
Optional, a pattern index or list of pattern indices to use
|
||||
|
||||
Attributes
|
||||
----------
|
||||
model : CDIModel
|
||||
Points to the core model used.
|
||||
optimizer : torch.optim.Optimizer
|
||||
Must be defined when initializing the Reconstructor subclass.
|
||||
scheduler : torch.optim.lr_scheduler, optional
|
||||
May be defined during the ``optimize`` method.
|
||||
data_loader : torch.utils.data.DataLoader
|
||||
Defined by calling the ``setup_dataloader`` method.
|
||||
"""
|
||||
def __init__(self,
|
||||
model: CDIModel,
|
||||
dataset: CDataset,
|
||||
optimizer: t.optim.Optimizer,
|
||||
subset: Union[int, List[int]] = None):
|
||||
|
||||
# Store parameters as attributes of Reconstructor
|
||||
self.model = model
|
||||
self.optimizer = optimizer
|
||||
|
||||
# Store the dataset, clipping it to a subset if needed
|
||||
if subset is not None:
|
||||
# if subset is just one pattern, turn into a list for convenience
|
||||
if isinstance(subset, int):
|
||||
subset = [subset]
|
||||
dataset = td.Subset(dataset, subset)
|
||||
|
||||
self.dataset = dataset
|
||||
|
||||
# Initialize attributes that must be defined by the subclasses
|
||||
self.scheduler = None
|
||||
self.data_loader = None
|
||||
|
||||
|
||||
def setup_dataloader(self,
|
||||
batch_size: int = None,
|
||||
shuffle: bool = True):
|
||||
"""
|
||||
Sets up or re-initializes the dataloader.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
batch_size : int
|
||||
Optional, the size of the minibatches to use
|
||||
shuffle : bool
|
||||
Optional, enable/disable shuffling of the dataset. This option
|
||||
is intended for diagnostic purposes and should be left as True.
|
||||
"""
|
||||
if batch_size is not None:
|
||||
self.data_loader = td.DataLoader(self.dataset,
|
||||
batch_size=batch_size,
|
||||
shuffle=shuffle)
|
||||
else:
|
||||
self.data_loader = td.Dataloader(self.dataset)
|
||||
|
||||
|
||||
def adjust_optimizer(self, **kwargs):
|
||||
"""
|
||||
Change hyperparameters for the utilized optimizer.
|
||||
|
||||
For each optimizer, the keyword arguments should be manually defined
|
||||
as parameters.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
|
||||
def run_epoch(self,
|
||||
stop_event: threading.Event = None,
|
||||
regularization_factor: Union[float, List[float]] = None,
|
||||
calculation_width: int = 10):
|
||||
"""
|
||||
Runs one full epoch of the reconstruction. Intended to be called
|
||||
by Reconstructor.optimize.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
stop_event : threading.Event
|
||||
Default None, causes the reconstruction to stop when an exception
|
||||
occurs in Optimizer.optimize.
|
||||
regularization_factor : float or list(float)
|
||||
Optional, if the model has a regularizer defined, the set of
|
||||
parameters to pass the regularizer method
|
||||
calculation_width : int
|
||||
Default 10, how many translations to pass through at once for each
|
||||
round of gradient accumulation. This does not affect the result,
|
||||
but may affect the calculation speed.
|
||||
|
||||
Returns
|
||||
------
|
||||
loss : float
|
||||
The summed loss over the latest epoch, divided by the total
|
||||
diffraction pattern intensity
|
||||
"""
|
||||
|
||||
# Setting this as an explicit catch makes me feel more comfortable
|
||||
# exposing it as a public method. This way a user won't be confused
|
||||
# if they try to use this directly
|
||||
if self.data_loader is None:
|
||||
raise RuntimeError(
|
||||
'No data loader was defined. Please run '
|
||||
'Reconstructor.setup_dataloader() before running '
|
||||
'Reconstructor.run_epoch(), or use Reconstructor.optimize(), '
|
||||
'which does it automatically.'
|
||||
)
|
||||
|
||||
|
||||
# Initialize some tracking variables
|
||||
normalization = 0
|
||||
loss = 0
|
||||
N = 0
|
||||
t0 = time.time()
|
||||
|
||||
# The data loader is responsible for setting the minibatch
|
||||
# size, so each set is a minibatch
|
||||
for inputs, patterns in self.data_loader:
|
||||
normalization += t.sum(patterns).cpu().numpy()
|
||||
N += 1
|
||||
|
||||
def closure():
|
||||
self.optimizer.zero_grad()
|
||||
|
||||
# We further break up the minibatch into a set of chunks.
|
||||
# This lets us use larger minibatches than can fit
|
||||
# on the GPU at once, while still doing batch processing
|
||||
# for efficiency
|
||||
input_chunks = [[inp[i:i + calculation_width]
|
||||
for inp in inputs]
|
||||
for i in range(0, len(inputs[0]),
|
||||
calculation_width)]
|
||||
pattern_chunks = [patterns[i:i + calculation_width]
|
||||
for i in range(0, len(inputs[0]),
|
||||
calculation_width)]
|
||||
|
||||
total_loss = 0
|
||||
|
||||
for inp, pats in zip(input_chunks, pattern_chunks):
|
||||
# This check allows for graceful exit when threading
|
||||
if stop_event is not None and stop_event.is_set():
|
||||
exit()
|
||||
|
||||
# Run the simulation
|
||||
sim_patterns = self.model.forward(*inp)
|
||||
|
||||
# Calculate the loss
|
||||
if hasattr(self.model, 'mask'):
|
||||
loss = self.model.loss(pats,
|
||||
sim_patterns,
|
||||
mask=self.model.mask)
|
||||
else:
|
||||
loss = self.model.loss(pats,
|
||||
sim_patterns)
|
||||
|
||||
# And accumulate the gradients
|
||||
loss.backward()
|
||||
|
||||
# Normalize the accumulating total loss
|
||||
total_loss += loss.detach()
|
||||
|
||||
# If we have a regularizer, we can calculate it separately,
|
||||
# and the gradients will add to the minibatch gradient
|
||||
if regularization_factor is not None \
|
||||
and hasattr(self.model, 'regularizer'):
|
||||
|
||||
loss = self.model.regularizer(regularization_factor)
|
||||
loss.backward()
|
||||
|
||||
return total_loss
|
||||
|
||||
# This takes the step for this minibatch
|
||||
loss += self.optimizer.step(closure).detach().cpu().numpy()
|
||||
|
||||
loss /= normalization
|
||||
|
||||
# We step the scheduler after the full epoch
|
||||
if self.scheduler is not None:
|
||||
self.scheduler.step(loss)
|
||||
|
||||
self.model.loss_history.append(loss)
|
||||
self.model.epoch = len(self.model.loss_history)
|
||||
self.model.latest_iteration_time = time.time() - t0
|
||||
self.model.training_history += self.model.report() + '\n'
|
||||
return loss
|
||||
|
||||
def optimize(self,
|
||||
iterations: int,
|
||||
batch_size: int = 1,
|
||||
custom_data_loader: torch.utils.data.DataLoader = None,
|
||||
regularization_factor: Union[float, List[float]] = None,
|
||||
thread: bool = True,
|
||||
calculation_width: int = 10,
|
||||
shuffle=True):
|
||||
"""
|
||||
Runs a round of reconstruction using the provided optimizer
|
||||
|
||||
Formerly CDIModel.AD_optimize
|
||||
|
||||
This is the basic automatic differentiation reconstruction tool
|
||||
which all the other, algorithm-specific tools, use. It is a
|
||||
generator which yields the average loss each epoch, ending after
|
||||
the specified number of iterations.
|
||||
|
||||
By default, the computation will be run in a separate thread. This
|
||||
is done to enable live plotting with matplotlib during a
|
||||
reconstruction.
|
||||
|
||||
If the computation was done in the main thread, this would freeze
|
||||
the plots. This behavior can be turned off by setting the keyword
|
||||
argument 'thread' to False.
|
||||
|
||||
The `batch_size` parameter sets the batch size for the default
|
||||
dataloader. If a custom data loader is desired, it can be passed
|
||||
in to the `custom_data_loader` argument, which will override the
|
||||
`batch_size` and `shuffle` parameters
|
||||
|
||||
Please see `AdamReconstructor.optimize()` for an example of how to
|
||||
override this function when designing a subclass
|
||||
|
||||
Parameters
|
||||
----------
|
||||
iterations : int
|
||||
How many epochs of the algorithm to run.
|
||||
batch_size : int
|
||||
Optional, the batch size to use. Default is 1. This is typically
|
||||
overridden by subclasses with an appropriate default for the
|
||||
specific optimizer.
|
||||
custom_data_loader : torch.utils.data.DataLoader
|
||||
Optional, a custom DataLoader to use. Will override batch_size
|
||||
if set.
|
||||
regularization_factor : float or list(float)
|
||||
Optional, if the model has a regularizer defined, the set of
|
||||
parameters to pass the regularizer method.
|
||||
thread : bool
|
||||
Default True, whether to run the computation in a separate thread
|
||||
to allow interaction with plots during computation.
|
||||
calculation_width : int
|
||||
Default 10, how many translations to pass through at once for each
|
||||
round of gradient accumulation. This does not affect the result,
|
||||
but may affect the calculation speed.
|
||||
shuffle : bool
|
||||
Optional, enable/disable shuffling of the dataset. This option
|
||||
is intended for diagnostic purposes and should be left as True.
|
||||
|
||||
|
||||
Yields
|
||||
------
|
||||
loss : float
|
||||
The summed loss over the latest epoch, divided by the total
|
||||
diffraction pattern intensity.
|
||||
"""
|
||||
|
||||
if custom_data_loader is None:
|
||||
self.setup_dataloader(batch_size=batch_size, shuffle=shuffle)
|
||||
else:
|
||||
self.data_loader = custom_data_loader
|
||||
|
||||
# We store the current optimizer as a model parameter so that
|
||||
# it can be saved and loaded for checkpointing
|
||||
self.current_optimizer = self.optimizer
|
||||
|
||||
# If we don't want to run in a different thread, this is easy
|
||||
if not thread:
|
||||
for it in range(iterations):
|
||||
if self.model.skip_computation():
|
||||
self.epoch = self.epoch + 1
|
||||
if len(self.model.loss_history) >= 1:
|
||||
yield self.model.loss_history[-1]
|
||||
else:
|
||||
yield float('nan')
|
||||
continue
|
||||
|
||||
yield self.run_epoch(
|
||||
regularization_factor=regularization_factor, # noqa
|
||||
calculation_width=calculation_width,
|
||||
)
|
||||
|
||||
# But if we do want to thread, it's annoying:
|
||||
else:
|
||||
# Here we set up the communication with the computation thread
|
||||
result_queue = queue.Queue()
|
||||
stop_event = threading.Event()
|
||||
|
||||
def target():
|
||||
try:
|
||||
result_queue.put(
|
||||
self.run_epoch(
|
||||
stop_event=stop_event,
|
||||
regularization_factor=regularization_factor, # noqa
|
||||
calculation_width=calculation_width,
|
||||
)
|
||||
)
|
||||
except Exception as e:
|
||||
# If something bad happens, put the exception into the
|
||||
# result queue
|
||||
result_queue.put(e)
|
||||
|
||||
# And this actually starts and monitors the thread
|
||||
for it in range(iterations):
|
||||
if self.model.skip_computation():
|
||||
self.model.epoch = self.model.epoch + 1
|
||||
if len(self.model.loss_history) >= 1:
|
||||
yield self.model.loss_history[-1]
|
||||
else:
|
||||
yield float('nan')
|
||||
continue
|
||||
|
||||
calc = threading.Thread(target=target,
|
||||
name='calculator',
|
||||
daemon=True)
|
||||
try:
|
||||
calc.start()
|
||||
while calc.is_alive():
|
||||
if hasattr(self.model, 'figs'):
|
||||
self.model.figs[0].canvas.start_event_loop(0.01)
|
||||
else:
|
||||
calc.join()
|
||||
|
||||
except KeyboardInterrupt as e:
|
||||
stop_event.set()
|
||||
print('\nAsking execution thread to stop cleanly - ' +
|
||||
'please be patient.')
|
||||
calc.join()
|
||||
raise e
|
||||
|
||||
res = result_queue.get()
|
||||
|
||||
# If something went wrong in the thead, we'll get an exception
|
||||
if isinstance(res, Exception):
|
||||
raise res
|
||||
|
||||
yield res
|
||||
|
||||
# And finally, we unset the current optimizer:
|
||||
self.current_optimizer = None
|
||||
@@ -0,0 +1,143 @@
|
||||
"""This module contains the LBFGSReconstructor subclass for performing
|
||||
optimization ('reconstructions') on ptychographic/CDI models using
|
||||
the LBFGS optimizer.
|
||||
|
||||
The Reconstructor class is designed to resemble so-called
|
||||
'Trainer' classes that (in the language of the AI/ML folks) handles
|
||||
the 'training' of a model given some dataset and optimizer.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import torch as t
|
||||
from typing import List, Union
|
||||
from cdtools.reconstructors import Reconstructor
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from cdtools.models import CDIModel
|
||||
from cdtools.datasets.ptycho_2d_dataset import Ptycho2DDataset
|
||||
|
||||
|
||||
__all__ = ['LBFGSReconstructor']
|
||||
|
||||
|
||||
class LBFGSReconstructor(Reconstructor):
|
||||
"""
|
||||
The LBFGSReconstructor subclass handles the optimization
|
||||
('reconstruction') of ptychographic models and datasets using the LBFGS
|
||||
optimizer.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
model: CDIModel
|
||||
Model for CDI/ptychography reconstruction.
|
||||
dataset: Ptycho2DDataset
|
||||
The dataset to reconstruct against.
|
||||
subset : list(int) or int
|
||||
Optional, a pattern index or list of pattern indices to use.
|
||||
schedule : bool
|
||||
Optional, create a learning rate scheduler
|
||||
(torch.optim.lr_scheduler._LRScheduler).
|
||||
|
||||
Important attributes:
|
||||
- **model** -- Always points to the core model used.
|
||||
- **optimizer** -- This class by default uses `torch.optim.LBFGS` to
|
||||
perform optimizations.
|
||||
- **scheduler** -- A `torch.optim.lr_scheduler` that is defined during
|
||||
the `optimize` method.
|
||||
- **data_loader** -- A torch.utils.data.DataLoader that is defined by
|
||||
calling the `setup_dataloader` method.
|
||||
"""
|
||||
def __init__(self,
|
||||
model: CDIModel,
|
||||
dataset: Ptycho2DDataset,
|
||||
subset: List[int] = None):
|
||||
|
||||
# Define the optimizer for use in this subclass
|
||||
optimizer = t.optim.LBFGS(model.parameters())
|
||||
|
||||
super().__init__(
|
||||
model,
|
||||
dataset,
|
||||
optimizer,
|
||||
subset=subset,
|
||||
)
|
||||
|
||||
|
||||
def adjust_optimizer(self,
|
||||
lr: int = 0.005,
|
||||
history_size: int = 2,
|
||||
line_search_fn: str = None):
|
||||
"""
|
||||
Change hyperparameters for the utilized optimizer.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
lr : float
|
||||
Optional, The learning rate (alpha) to use. Default is 0.005. 0.05
|
||||
is typically the highest possible value with any chance of being
|
||||
stable.
|
||||
history_size : int
|
||||
Optional, the length of the history to use.
|
||||
line_search_fn : str
|
||||
Optional, either `strong_wolfe` or None
|
||||
"""
|
||||
for param_group in self.optimizer.param_groups:
|
||||
param_group['lr'] = lr
|
||||
param_group['history_size'] = history_size
|
||||
param_group['line_search_fn'] = line_search_fn
|
||||
|
||||
def optimize(self,
|
||||
iterations: int,
|
||||
lr: float = 0.1,
|
||||
history_size: int = 2,
|
||||
regularization_factor: Union[float, List[float]] = None,
|
||||
thread: bool = True,
|
||||
calculation_width: int = 10,
|
||||
line_search_fn: str = None):
|
||||
"""
|
||||
Runs a round of reconstruction using the LBFGS optimizer
|
||||
|
||||
Formerly `CDIModel.LBFGS_optimize`
|
||||
|
||||
This algorithm is often less stable that Adam, however in certain
|
||||
situations or geometries it can be shockingly efficient. Like all
|
||||
the other optimization routines, it is defined as a generator
|
||||
function which yields the average loss each epoch.
|
||||
|
||||
NOTE: There is no batch size, because it is a usually a bad idea to use
|
||||
LBFGS on anything but all the data at onece
|
||||
|
||||
Parameters
|
||||
----------
|
||||
iterations : int
|
||||
How many epochs of the algorithm to run.
|
||||
lr : float
|
||||
Optional, The learning rate (alpha) to use. Default is 0.1.
|
||||
history_size : int
|
||||
Optional, the length of the history to use.
|
||||
regularization_factor : float or list(float)
|
||||
Optional, if the model has a regularizer defined, the set of
|
||||
parameters to pass the regularizer method.
|
||||
thread : bool
|
||||
Default True, whether to run the computation in a separate thread
|
||||
to allow interaction with plots during computation.
|
||||
calculation_width : int
|
||||
Default 10, how many translations to pass through at once for each
|
||||
round of gradient accumulation. Does not affect the result, only
|
||||
the calculation speed.
|
||||
"""
|
||||
|
||||
# The optimizer is created in self.__init__, but the
|
||||
# hyperparameters need to be set up with self.adjust_optimizer
|
||||
self.adjust_optimizer(lr=lr,
|
||||
history_size=history_size,
|
||||
line_search_fn=line_search_fn)
|
||||
|
||||
# Now, we run the optimize routine defined in the base class
|
||||
return super(LBFGSReconstructor, self).optimize(
|
||||
iterations,
|
||||
batch_size=len(self.dataset),
|
||||
regularization_factor=regularization_factor,
|
||||
thread=thread,
|
||||
calculation_width=calculation_width)
|
||||
@@ -0,0 +1,164 @@
|
||||
"""This module contains the SGDReconstructor subclass for performing
|
||||
optimization ('reconstructions') on ptychographic/CDI models using
|
||||
stochastic gradient descent.
|
||||
|
||||
The Reconstructor class is designed to resemble so-called
|
||||
'Trainer' classes that (in the language of the AI/ML folks) handles
|
||||
the 'training' of a model given some dataset and optimizer.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import torch as t
|
||||
from typing import List, Union
|
||||
from cdtools.reconstructors import Reconstructor
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from cdtools.models import CDIModel
|
||||
from cdtools.datasets.ptycho_2d_dataset import Ptycho2DDataset
|
||||
|
||||
|
||||
__all__ = ['SGDReconstructor']
|
||||
|
||||
|
||||
class SGDReconstructor(Reconstructor):
|
||||
"""
|
||||
The SGDReconstructor subclass handles the optimization ('reconstruction')
|
||||
of ptychographic models and datasets using the SGD optimizer.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
model: CDIModel
|
||||
Model for CDI/ptychography reconstruction.
|
||||
dataset: Ptycho2DDataset
|
||||
The dataset to reconstruct against.
|
||||
subset : list(int) or int
|
||||
Optional, a pattern index or list of pattern indices to use.
|
||||
|
||||
Important attributes:
|
||||
- **model** -- Always points to the core model used.
|
||||
- **optimizer** -- This class by default uses `torch.optim.Adam` to perform
|
||||
optimizations.
|
||||
- **scheduler** -- A `torch.optim.lr_scheduler` that is defined during the
|
||||
`optimize` method.
|
||||
- **data_loader** -- A torch.utils.data.DataLoader that is defined by
|
||||
calling the `setup_dataloader` method.
|
||||
"""
|
||||
def __init__(self,
|
||||
model: CDIModel,
|
||||
dataset: Ptycho2DDataset,
|
||||
subset: List[int] = None):
|
||||
|
||||
# Define the optimizer for use in this subclass
|
||||
optimizer = t.optim.SGD(model.parameters())
|
||||
|
||||
super().__init__(
|
||||
model,
|
||||
dataset,
|
||||
optimizer,
|
||||
subset=subset,
|
||||
)
|
||||
|
||||
|
||||
def adjust_optimizer(self,
|
||||
lr: int = 0.005,
|
||||
momentum: float = 0,
|
||||
dampening: float = 0,
|
||||
weight_decay: float = 0,
|
||||
nesterov: bool = False):
|
||||
"""
|
||||
Change hyperparameters for the utilized optimizer.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
lr : float
|
||||
Optional, The learning rate (alpha) to use. Default is 0.005. 0.05
|
||||
is typically the highest possible value with any chance of being
|
||||
stable.
|
||||
momentum : float
|
||||
Optional, the length of the history to use.
|
||||
dampening : float
|
||||
Optional, dampening for the momentum.
|
||||
weight_decay : float
|
||||
Optional, weight decay (L2 penalty).
|
||||
nesterov : bool
|
||||
Optional, enables Nesterov momentum. Only applicable when momentum
|
||||
is non-zero.
|
||||
"""
|
||||
for param_group in self.optimizer.param_groups:
|
||||
param_group['lr'] = lr
|
||||
param_group['momentum'] = momentum
|
||||
param_group['dampening'] = dampening
|
||||
param_group['weight_decay'] = weight_decay
|
||||
param_group['nesterov'] = nesterov
|
||||
|
||||
def optimize(self,
|
||||
iterations: int,
|
||||
batch_size: int = 15,
|
||||
lr: float = 2e-7,
|
||||
momentum: float = 0,
|
||||
dampening: float = 0,
|
||||
weight_decay: float = 0,
|
||||
nesterov: bool = False,
|
||||
regularization_factor: Union[float, List[float]] = None,
|
||||
thread: bool = True,
|
||||
calculation_width: int = 10,
|
||||
shuffle: bool = True):
|
||||
"""
|
||||
Runs a round of reconstruction using the Adam optimizer
|
||||
|
||||
Formerly `CDIModel.Adam_optimize`
|
||||
|
||||
This calls the Reconstructor.optimize superclass method
|
||||
(formerly `CDIModel.AD_optimize`) to run a round of reconstruction
|
||||
once the dataloader and optimizer hyperparameters have been
|
||||
set up.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
iterations : int
|
||||
How many epochs of the algorithm to run.
|
||||
batch_size : int
|
||||
Optional, the size of the minibatches to use.
|
||||
lr : float
|
||||
Optional, The learning rate to use. The default is 2e-7.
|
||||
momentum : float
|
||||
Optional, the length of the history to use.
|
||||
dampening : float
|
||||
Optional, dampening for the momentum.
|
||||
weight_decay : float
|
||||
Optional, weight decay (L2 penalty).
|
||||
nesterov : bool
|
||||
Optional, enables Nesterov momentum. Only applicable when momentum
|
||||
is non-zero.
|
||||
regularization_factor : float or list(float)
|
||||
Optional, if the model has a regularizer defined, the set of
|
||||
parameters to pass the regularizer method.
|
||||
thread : bool
|
||||
Default True, whether to run the computation in a separate thread
|
||||
to allow interaction with plots during computation.
|
||||
calculation_width : int
|
||||
Default 10, how many translations to pass through at once for each
|
||||
round of gradient accumulation. Does not affect the result, only
|
||||
the calculation speed.
|
||||
shuffle : bool
|
||||
Optional, enable/disable shuffling of the dataset. This option
|
||||
is intended for diagnostic purposes and should be left as True.
|
||||
"""
|
||||
|
||||
# The optimizer is created in self.__init__, but the
|
||||
# hyperparameters need to be set up with self.adjust_optimizer
|
||||
self.adjust_optimizer(lr=lr,
|
||||
momentum=momentum,
|
||||
dampening=dampening,
|
||||
weight_decay=weight_decay,
|
||||
nesterov=nesterov)
|
||||
|
||||
# Now, we run the optimize routine defined in the base class
|
||||
return super(SGDReconstructor, self).optimize(
|
||||
iterations,
|
||||
batch_size=batch_size,
|
||||
regularization_factor=regularization_factor,
|
||||
thread=thread,
|
||||
calculation_width=calculation_width,
|
||||
)
|
||||
@@ -14,6 +14,7 @@ from scipy import linalg as sla
|
||||
from scipy import special
|
||||
from scipy import optimize as opt
|
||||
from scipy import spatial
|
||||
import warnings
|
||||
|
||||
__all__ = [
|
||||
'product_svd',
|
||||
@@ -1443,6 +1444,13 @@ def calc_spectral_info(dataset, nbins=50):
|
||||
the scan pattern whose area matches one detector conjugate field of
|
||||
view.
|
||||
|
||||
This estimation will start to deviate from the truth if the scan area
|
||||
is not significantly larger than the illumination function, because
|
||||
the nonzero size of the illumination function is not taken into account.
|
||||
Furthermore, in the edge case where all the scan points are colinear,
|
||||
the estimate will fail, and the mean diffraction pattern will be returned
|
||||
instead
|
||||
|
||||
Parameters
|
||||
----------
|
||||
dataset : Ptycho2DDataset
|
||||
@@ -1461,10 +1469,12 @@ def calc_spectral_info(dataset, nbins=50):
|
||||
|
||||
"""
|
||||
|
||||
scan_hull = spatial.ConvexHull(dataset.translations[:,:2].cpu().numpy())
|
||||
|
||||
scan_area = scan_hull.volume
|
||||
|
||||
try:
|
||||
scan_hull = spatial.ConvexHull(dataset.translations[:,:2].cpu().numpy())
|
||||
scan_area = scan_hull.volume
|
||||
except spatial._qhull.QhullError as e:
|
||||
scan_area = None
|
||||
|
||||
ewg = cdtools.tools.initializers.exit_wave_geometry
|
||||
obj_basis = ewg(
|
||||
dataset.detector_geometry['basis'],
|
||||
@@ -1477,8 +1487,12 @@ def calc_spectral_info(dataset, nbins=50):
|
||||
np.cross(obj_basis[:,0]*dataset.patterns.shape[-2],
|
||||
obj_basis[:,1]*dataset.patterns.shape[-1])
|
||||
)
|
||||
scale_factor = det_conj_fov_area / scan_area
|
||||
|
||||
if scan_area is not None:
|
||||
scale_factor = det_conj_fov_area / scan_area
|
||||
else:
|
||||
warnings.warn("The scan points in this dataset are all colinear. The mean pattern will be calculated rather than a scaled mean based on the scanned area.")
|
||||
scale_factor = 1/len(dataset)
|
||||
|
||||
mask = dataset.mask.cpu().numpy().astype(int)
|
||||
sum_pattern = dataset.mask * t.sum(dataset.patterns, dim=0) * scale_factor
|
||||
|
||||
@@ -22,6 +22,7 @@ __all__ = ['get_entry_info',
|
||||
'get_wavelength',
|
||||
'get_detector_geometry',
|
||||
'get_mask',
|
||||
'get_qe_mask',
|
||||
'get_dark',
|
||||
'get_data',
|
||||
'get_shot_to_shot_info',
|
||||
@@ -32,6 +33,7 @@ __all__ = ['get_entry_info',
|
||||
'add_source',
|
||||
'add_detector',
|
||||
'add_mask',
|
||||
'add_qe_mask',
|
||||
'add_dark',
|
||||
'add_data',
|
||||
'add_shot_to_shot_info',
|
||||
@@ -300,6 +302,42 @@ def get_mask(cxi_file):
|
||||
return None
|
||||
|
||||
|
||||
def get_qe_mask(cxi_file):
|
||||
"""Returns the quantum efficiency mask defined in the cxi file object
|
||||
|
||||
There is no way to store a quantum efficiency mask (a.k.a. a flat-field
|
||||
image) in the .cxi file specification, but experience has indicated that
|
||||
this is often a valuable thing to store, because just correcting for a
|
||||
flatfield with e.g. a division will mess up the photon counting statistics.
|
||||
|
||||
Because there is no specification, I have simply chosen to store the
|
||||
quantum efficiency mask as a float32 array in the same location as the
|
||||
mask is, i.e. `entry_1/instrument_1/detector_1/qe_mask`.
|
||||
|
||||
The stored quantum efficiency mask should be defined as the mask that
|
||||
a simulated intensity pattern needs to be multiplied by to realize the
|
||||
measured image. In other words, it should be a flat-field image, not the
|
||||
inverse of a flat-field image.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
cxi_file : h5py.File
|
||||
A file object to be read
|
||||
|
||||
Returns
|
||||
-------
|
||||
qe_mask : np.array
|
||||
A float32 array storing the quantum efficiency mask from the cxi file
|
||||
"""
|
||||
|
||||
i1 = cxi_file['entry_1/instrument_1']
|
||||
if 'detector_1/qe_mask' in i1:
|
||||
qe_mask = i1['detector_1/qe_mask'][()].astype(np.float32)
|
||||
return qe_mask
|
||||
else:
|
||||
return None
|
||||
|
||||
|
||||
def get_dark(cxi_file):
|
||||
"""Returns an array with a dark image to use for initialization of a background model
|
||||
|
||||
@@ -635,6 +673,43 @@ def add_mask(cxi_file, mask):
|
||||
d1.create_dataset('mask',data=mask_to_save)
|
||||
|
||||
|
||||
def add_qe_mask(cxi_file, qe_mask):
|
||||
"""Adds the specified quantum efficiency mask to the cxi file
|
||||
|
||||
There is no way to store a quantum efficiency mask (a.k.a. a flat-field
|
||||
image) in the .cxi file specification, but experience has indicated that
|
||||
this is often a valuable thing to store, because just correcting for a
|
||||
flatfield with e.g. a division will mess up the photon counting statistics.
|
||||
|
||||
Because there is no specification, I have simply chosen to store the
|
||||
quantum efficiency mask as an array in the same location as the
|
||||
mask is, i.e. `entry_1/instrument_1/detector_1/qe_mask`.
|
||||
|
||||
The stored quantum efficiency mask should be defined as the mask that
|
||||
a simulated intensity pattern needs to be multiplied by to realize the
|
||||
measured image. In other words, it should be a flat-field image, not the
|
||||
inverse of a flat-field image.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
cxi_file : h5py.File
|
||||
The file to add the mask to
|
||||
qe_mask : array
|
||||
The quantum efficiency mask to save out to the file
|
||||
"""
|
||||
|
||||
if 'entry_1/instrument_1' not in cxi_file:
|
||||
cxi_file['entry_1'].create_group('instrument_1')
|
||||
i1 = cxi_file['entry_1/instrument_1']
|
||||
if 'detector_1' not in i1:
|
||||
i1.create_group('detector_1')
|
||||
d1 = i1['detector_1']
|
||||
if isinstance(qe_mask, t.Tensor):
|
||||
qe_mask = qe_mask.detach().cpu().numpy()
|
||||
|
||||
d1.create_dataset('qe_mask',data=qe_mask)
|
||||
|
||||
|
||||
def add_dark(cxi_file, dark):
|
||||
"""Adds the specified dark image to a cxi file
|
||||
|
||||
|
||||
@@ -155,7 +155,18 @@ def incoherent_sum(wavefields, detector_slice=None, epsilon=1e-7, saturation=Non
|
||||
return t.clamp(output + epsilon,0,saturation)
|
||||
|
||||
|
||||
def quadratic_background(wavefield, background, *args, detector_slice=None, measurement=intensity, epsilon=1e-7, saturation=None, oversampling=1, simulate_finite_pixels=False):
|
||||
def quadratic_background(
|
||||
wavefield,
|
||||
background,
|
||||
*args,
|
||||
detector_slice=None,
|
||||
measurement=intensity,
|
||||
epsilon=1e-7,
|
||||
qe_mask=None,
|
||||
saturation=None,
|
||||
oversampling=1,
|
||||
simulate_finite_pixels=False
|
||||
):
|
||||
"""Returns the intensity of a wavefield plus a background
|
||||
|
||||
The intensity is calculated via the given measurment function
|
||||
@@ -173,6 +184,8 @@ def quadratic_background(wavefield, background, *args, detector_slice=None, meas
|
||||
Optional, a slice or tuple of slices defining a section of the simulation to return
|
||||
measurement : function
|
||||
Default is measurements.intensity, the measurement function to use.
|
||||
qe_mask : torch.Tensor
|
||||
A tensor storing the per-pixel quantum efficiency (up to an unknown global scaling factor)
|
||||
saturation : float
|
||||
Optional, a maximum saturation value to clamp the resulting intensities to
|
||||
oversampling : int
|
||||
@@ -184,17 +197,20 @@ def quadratic_background(wavefield, background, *args, detector_slice=None, meas
|
||||
A real MxN array storing the wavefield's intensities
|
||||
"""
|
||||
|
||||
if detector_slice is None:
|
||||
output = measurement(wavefield, *args, epsilon=epsilon,
|
||||
oversampling=oversampling,
|
||||
simulate_finite_pixels=simulate_finite_pixels) \
|
||||
+ background**2
|
||||
else:
|
||||
output = measurement(wavefield, *args, detector_slice=detector_slice,
|
||||
epsilon=epsilon, oversampling=oversampling,
|
||||
simulate_finite_pixels=simulate_finite_pixels) \
|
||||
+ background**2
|
||||
raw_intensity = measurement(
|
||||
wavefield,
|
||||
*args,
|
||||
detector_slice=detector_slice,
|
||||
epsilon=epsilon,
|
||||
oversampling=oversampling,
|
||||
simulate_finite_pixels=simulate_finite_pixels
|
||||
)
|
||||
|
||||
if qe_mask is None:
|
||||
output = raw_intensity + background**2
|
||||
else:
|
||||
output = (qe_mask * raw_intensity) + background**2
|
||||
|
||||
# This has to be done after the background is added, hence we replicate
|
||||
# it here
|
||||
if saturation is None:
|
||||
|
||||
@@ -522,7 +522,7 @@ def plot_colorized(im, fig=None, basis=None, units='$\\mu$m', **kwargs):
|
||||
units=units, show_cbar=False, **kwargs)
|
||||
|
||||
|
||||
def plot_translations(translations, fig=None, units='$\\mu$m', lines=True, invert_xaxis=True, **kwargs):
|
||||
def plot_translations(translations, fig=None, units='$\\mu$m', lines=True, invert_xaxis=True, clear_fig=True, label=None, color=None, marker='.', **kwargs):
|
||||
"""Plots a set of probe translations in a nicely formatted way
|
||||
|
||||
Parameters
|
||||
@@ -537,6 +537,14 @@ def plot_translations(translations, fig=None, units='$\\mu$m', lines=True, inver
|
||||
Whether to plot lines indicating the path taken
|
||||
invert_xaxis : bool
|
||||
Default is True. This flips the x axis to match the convention from .cxi files of viewing the image from the beam's perspective
|
||||
clear_fig : bool
|
||||
Default is True. Whether to clear the figure before plotting.
|
||||
label : str
|
||||
Default is None. A label to give the plotted markers for a legend.
|
||||
color : str
|
||||
Default is None. The color to plot the markers in. By default, will follow the matplotlib color cycle.
|
||||
color : str
|
||||
Default is '.'. The marker style to plot with.
|
||||
\\**kwargs
|
||||
All other args are passed to fig.add_subplot(111, \\**kwargs)
|
||||
|
||||
@@ -554,18 +562,28 @@ def plot_translations(translations, fig=None, units='$\\mu$m', lines=True, inver
|
||||
ax = fig.add_subplot(111, **kwargs)
|
||||
else:
|
||||
plt.figure(fig.number)
|
||||
plt.gcf().clear()
|
||||
if clear_fig:
|
||||
plt.gcf().clear()
|
||||
|
||||
if isinstance(translations, t.Tensor):
|
||||
translations = translations.detach().cpu().numpy()
|
||||
|
||||
translations = translations * factor
|
||||
plt.plot(translations[:,0], translations[:,1],'k.')
|
||||
|
||||
linestyle = '-' if lines else 'None'
|
||||
linewidth = 1 if lines else 0
|
||||
plt.plot(translations[:,0], translations[:,1],
|
||||
marker=marker, linestyle=linestyle,
|
||||
label=label, color=color,
|
||||
linewidth=linewidth)
|
||||
|
||||
if invert_xaxis:
|
||||
plt.gca().invert_xaxis()
|
||||
ax = plt.gca()
|
||||
x_min, x_max = ax.get_xlim()
|
||||
# Protect against flipping twice if plotting on top of existing graph
|
||||
if x_min <= x_max:
|
||||
ax.invert_xaxis()
|
||||
|
||||
if lines:
|
||||
plt.plot(translations[:,0], translations[:,1],'b-', linewidth=0.5)
|
||||
plt.xlabel('X (' + units + ')')
|
||||
plt.ylabel('Y (' + units + ')')
|
||||
|
||||
|
||||
Reference in new issue
Block a user