diff --git a/examples/fancy_ptycho.py b/examples/fancy_ptycho.py new file mode 100644 index 0000000..1e0f3f6 --- /dev/null +++ b/examples/fancy_ptycho.py @@ -0,0 +1,42 @@ +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 +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 +) + +device = 'cuda' +model.to(device=device) +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): + print(model.report()) + model.inspect(dataset) + +# It's totally okay to chain several different reconstructions. 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) + +model.inspect(dataset) +model.compare(dataset) +plt.show() diff --git a/examples/simple_ptycho.py b/examples/simple_ptycho.py index 3dbe246..9376954 100644 --- a/examples/simple_ptycho.py +++ b/examples/simple_ptycho.py @@ -1,72 +1,26 @@ import cdtools from matplotlib import pyplot as plt import torch as t -from cdtools.models.complex_adam import MyAdam 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) -dataset.translations = t.cat([dataset.translations]*5) -dataset.patterns = t.cat([dataset.patterns]*5) # Next, we create a ptychography model from the dataset model = cdtools.models.SimplePtycho.from_dataset(dataset) -print(model.mask) -exit() -#class MyDataParallel(t.nn.DataParallel): -# def __getattr__(self, name): -# return getattr(self.module, name) - -#model = t.nn.DataParallel(model, device_ids=[0,1,2,3]) - - -# Make a dataloader -data_loader = torchdata.DataLoader(dataset, batch_size=20, - shuffle=True) - device = 'cuda' model.to(device=device) -#dataset.get_as(device='cuda') +dataset.get_as(device=device) -# Define the optimizer -optimizer = MyAdam(model.parameters(), lr=0.01) +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 + model.inspect(dataset) -normalization=0 -for inputs, patterns in data_loader: - normalization += t.sum(patterns).cpu().numpy() - -for it in range(20): - loss = 0 - N = 0 - t0 = time.time() - for inputs, patterns in data_loader: - inp = (x.to(device) for x in inputs)#inputs.to(device) - pats = patterns.to(device) - N += 1 - def closure(): - optimizer.zero_grad() - - sim_patterns = model.forward(*inp) - - if hasattr(model, 'mask'): - loss = model.loss(pats,sim_patterns, mask=model.mask) - else: - loss = model.loss(pats,sim_patterns) - - loss.backward() - return loss.detach() - - loss += optimizer.step(closure).detach().cpu().numpy() - print('time', time.time()-t0) - print(loss / normalization) - - -print(model.save_results().keys()) -exit() -# Finally, we plot the results -model.module.inspect(dataset) -model.module.compare(dataset) +model.inspect(dataset) +model.compare(dataset) plt.show() diff --git a/src/cdtools/models/base.py b/src/cdtools/models/base.py index fb3d461..11ec79b 100644 --- a/src/cdtools/models/base.py +++ b/src/cdtools/models/base.py @@ -401,10 +401,20 @@ class CDIModel(t.nn.Module): yield res - def Adam_optimize(self, iterations, dataset, batch_size=15, lr=0.005, - schedule=False, amsgrad=False, subset=None, - regularization_factor=None, thread=True, - calculation_width=10): + 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, + thread=True, + calculation_width=10 + ): """Runs a round of reconstruction using the Adam optimizer This is generally accepted to be the most robust algorithm for use @@ -421,7 +431,9 @@ class CDIModel(t.nn.Module): batch_size : int Optional, the size of the minibatches to use lr : float - Optional, The learning rate (alpha) to use. 0.05 is typically the highest value with any chance of being stable + 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 beta_1 and beta_2 to use. Default is (0.9, 0.999). schedule : float Optional, whether to use the ReduceLROnPlateau scheduler subset : list(int) or int @@ -454,7 +466,11 @@ class CDIModel(t.nn.Module): shuffle=True) # Define the optimizer - optimizer = t.optim.Adam(self.parameters(), lr = lr, amsgrad=amsgrad) + optimizer = t.optim.Adam( + self.parameters(), + lr = lr, + betas=betas, + amsgrad=amsgrad) # Define the scheduler if schedule: diff --git a/src/cdtools/models/fancy_ptycho.py b/src/cdtools/models/fancy_ptycho.py index 7c6d0b8..bae0027 100644 --- a/src/cdtools/models/fancy_ptycho.py +++ b/src/cdtools/models/fancy_ptycho.py @@ -242,7 +242,7 @@ class FancyPtycho(CDIModel): ) obj_size, min_translation = tools.initializers.calc_object_setup( - det_shape, + [s * oversampling for s in det_shape], pix_translations, padding=obj_padding, ) @@ -266,9 +266,8 @@ class FancyPtycho(CDIModel): if hasattr(dataset, 'background') and dataset.background is not None: background = t.sqrt(dataset.background) else: - shape = [s//oversampling - for s in probe.shape[-2:]] - background = 1e-6 * t.ones(shape, dtype=t.float32) + background = 1e-6 * t.ones( + dataset.patterns.shape[-2:], dtype=t.float32) if probe_fourier_crop is not None: probe = tools.propagators.far_field(probe) @@ -458,8 +457,9 @@ class FancyPtycho(CDIModel): self.background, measurement=tools.measurements.incoherent_sum, saturation=self.saturation, - oversampling=self.oversampling, - simulate_finite_pixels=self.simulate_finite_pixels) + oversampling=int(self.oversampling), + simulate_finite_pixels=self.simulate_finite_pixels, + ) # Note: No "loss" function is defined here, because it is added diff --git a/src/cdtools/models/simple_ptycho.py b/src/cdtools/models/simple_ptycho.py index 4c6fea4..f189c5c 100644 --- a/src/cdtools/models/simple_ptycho.py +++ b/src/cdtools/models/simple_ptycho.py @@ -74,24 +74,20 @@ class SimplePtycho(CDIModel): pix_translations = tools.interactions.translations_to_pixel( probe_basis, translations, - surface_normal=surface_normal) + ) obj_size, min_translation = tools.initializers.calc_object_setup( - probe_shape, - pix_translations) + det_shape, + pix_translations, + ) # Finally, initialize the probe and object using this information - probe = tools.initializers.SHARP_style_probe( - dataset, - probe_shape, - det_slice - ) + probe = tools.initializers.SHARP_style_probe(dataset) obj = t.ones(obj_size).to(dtype=t.complex64) return cls( wavelength, dataset.detector_geometry, probe_basis, - det_slice, probe, obj, min_translation=min_translation @@ -103,7 +99,7 @@ class SimplePtycho(CDIModel): # We map from real-space to pixel-space units pix_trans = tools.interactions.translations_to_pixel( self.probe_basis, - translation) + translations) pix_trans -= self.min_translation # This function gets the proper, pixel-accurate crops of the @@ -124,8 +120,7 @@ class SimplePtycho(CDIModel): def measurement(self, wavefields): - return tools.measurements.intensity(wavefields, - detector_slice=self.detector_slice) + return tools.measurements.intensity(wavefields) def loss(self, real_data, sim_data): diff --git a/src/cdtools/tools/initializers/initializers.py b/src/cdtools/tools/initializers/initializers.py index 5e3398d..c0385ee 100644 --- a/src/cdtools/tools/initializers/initializers.py +++ b/src/cdtools/tools/initializers/initializers.py @@ -292,7 +292,7 @@ def SHARP_style_probe(dataset, propagation_distance=None, oversampling=1): shape = dataset.patterns.shape[-2:] # to use the mask or not? - intensities = np.zeros([dim // oversampling for dim in shape]) + intensities = np.zeros([dim for dim in shape]) # Eventually, do something with the recorded intensities, if they exist factors = [1 for idx in range(len(dataset))] @@ -341,13 +341,14 @@ def SHARP_style_probe(dataset, propagation_distance=None, oversampling=1): propagation_distance) probe_guess = near_field(probe_guess,AS_prop) - + # Finally, place this probe in a full-sized array if there is oversampling - final_probe = t.zeros(shape,dtype=t.complex64) - left = shape[0]//2 - probe_guess.shape[0] // 2 - top = shape[1]//2 - probe_guess.shape[1] // 2 - final_probe[left:left+probe_guess.shape[0], - top:top+probe_guess.shape[1]] = probe_guess + full_shape = [oversampling * s for s in shape] + final_probe = t.zeros(full_shape, dtype=t.complex64) + left = full_shape[0]//2 - shape[0] // 2 + top = full_shape[1]//2 - shape[1] // 2 + final_probe[left : left + shape[0], + top : top + shape[1]] = probe_guess return final_probe diff --git a/src/cdtools/tools/losses/losses.py b/src/cdtools/tools/losses/losses.py index 7f50a6c..44e5c5d 100644 --- a/src/cdtools/tools/losses/losses.py +++ b/src/cdtools/tools/losses/losses.py @@ -248,4 +248,4 @@ def poisson_plus_fixed_nll( t.xlogy(masked_intensities, masked_intensities)) \ / masked_intensities.shape[0] - return nll \ No newline at end of file + return nll