Changelog#
All notable changes to this project will be documented in this file.
The format is based on Keep a Changelog, and this project adheres to Semantic Versioning.
[0.1.0b12] - 2025-09-30#
Added#
Add
pos_recenterconstraint to remove potential global offset from cropping positions. This will help keeping probe, position, and object relatively in place.Add
get_error_distribution.ipynb,read_ptyrad_output_hdf5.ipynb, andget_local_obj_tilts.ipynb(issue #15) todemo/scripts/analysis/
Changed#
Refactor
plot_probe_modesso it can take either 1 or 2 input probes for easier visualizationFix incorrect probe shifting direction in
obj_z_recenterso it can shift the object and probe correctlyExplictly assign device for
near_field_evolution_torchinobj_z_recneterconstraint so it can correctly work on multi-GPU machines when assigned device != ‘cuda’Improve
obj_z_recenterconstraint by approximatingtorch.quantileso it can operate on large tensors with more than 16.7M elements; Addapprox_torch_quantiletoptyrad.utils.math_ops.Fix missing cache initialization in
init_cacheforinit_obj_tiltsas mentioned in issue #24 by @yifengh3Rename
probe_add_dfintoprobe_z_shiftfor clarity as mentioned in issue #18. Positive value means propagate the probe forward (increasing z depth).Fix a torch.compile edge case in
get_probes when position learning rate = 0. len(indices) would be treated incorrectly as a FakeTensor despite it should just be an int from len(np.ndarray).Remove a pair of fftshifts in
imshift_batchand adjust the k-space grid accordingly increate_grids. This improves the forward pass efficiency without affecting the reconstruction.Allow
pruner_paramsto be null during pydantic validation as mentioned in issue #20 by @GeriTopore
[0.1.0b11] - 2025-08-21#
Added#
Add
obj_z_resamplepreprocessing toinit_paramsso we can reslice the object along depth dimension to adjust the slice thickness without changing total thickness. This is useful for refining an existing multislice restruction with finer slices as mentioned in issue #5, or to convert between single <-> multislice objectAdd
obj_z_padpreprocessing toinit_paramsso we can pad more depth slices with ‘vacuum’, ‘mean’, or ‘edge’ options. This is useful for re-centering or expanding the loaded/initialized object along depth as mentioned in issue #5, or to quickly experiment the total thickness.Add
obj_z_croppreprocessing toinit_paramsso we can remove unwanted depth slices. This is useful for re-centering the loaded/initialized object along depth as mentioned in issue #5Add
obj_z_recenterconstraint to keep the multislice object centered within depth by measuring object CoM and adjusting probe defocus accordingly. This is useful when there’re vacuum region around the object. This is in response to issue #5 suggested by @HanHsuanWu.Add
probe_add_dftoinit_paramsso we can adjust defocus of loaded probe, which could help the multislice object z-recentering; Addadd_dfas new hypertunable params to sweep additional defocus of loaded probe; Addprobe_add_dfto the illumination preset ofrecon_dir_affixesfor folder nameEnable
probe_pmode_maxandobj_omode_maxto automatically pad the mixed states if the loaded probe/object has fewer modes than the specified number of modes as suggested by @Xinyan-Li; Add numpy version oforthogonalize_modes_vec_npandsort_by_mode_int_npto utils; improvecheck_modes_orthowith automatic np.ndarray-to-torch.tensor castingEnable
start_iter,step, andend_iterfor more flexible control of iter-wise constraints. This change is backward compatible. Original key offreqis still supported but is deprecated and will be removed in futureImprove reproducibility by adding
--seedto CLI argument andinit_params.random_seedto params file. Randomness includes object and position initialization, measurements Poisson noise, batches, and shuffling, etc. The seed is automatically set to 42 if not specified in multiGPU optimization, where we need exact same initialzation across devices.Enable
start_iterfor torch.compile and multiGPU in response to issue #13 via manual recompilation; Addend_itertoupdate_paramsto further control grads for optimizable tensors
Changed#
Change the appended digit of scan affines for clearer display. scale and asymmetry has been changed from
.2gto.2f, while rotation and shear are changed from.2gto.1fso 3-digits angle like 179.5 degree can be displayed properly.Improve
init_calibrationlogging clarity by displaying the final RBF, Npix, and suggested probe_mask_k radius after meas_resample despite resampling won’t change the ratio
[0.1.0b10] - 2025-07-23#
Added#
Add
compiler_configstorecon_paramsto allow optional PyTorch JIT compilation for significant speedup (1.9x faster on PSO tested on A100 20gb MIG). Special thanks to @dy327 and @guanxing.li for helping me testing on macOS and Windows machines! Currently thetorch.compileworks for Windows, macOS, and Linux, although it has a bit more hardware/firmware requirements including:Windows users would need to install
triton-windowsNVIDIA GPU needs to have Compute Capability >7.0 (Volta architecture or newer).
NVIDIA GPU needs to get a more modern driver version, 520.61.05 is known to be not working.
Changed#
Add CUDA Compute Capability and
torch.compileTriton info toprint_gpu_infoImprove
print_system_infoby addingplatform.platform()to show user-facing macOS version stringFix incorrect MPS device count for macOS in
set_acceleratorso the CLI command ofptyrad runcan pass the accelerator initializationAdd CPU fallback to
orthogonalize_modes_vecsince MPS doesn’t seem to have implementedtorch.linalg.eigyet as pointed out by @dy327Fix incorrect type check for
init_tiltsto allow float values of initial tilts as pointed out by @dy327
[0.1.0b9] - 2025-07-10#
Changed#
Update README with new installation guide and references to docs, youtube, and other links
Change the output shape of propagated probe amplitude from a binned 2D tableau into a 3D stack
Fix incorrect caching of H for an edge case of fixed but non-zero pos-dependent tilts; Fix incorrect indexing for
model.get_propagated_probeof pos-dependent tilts; Refactor and improvemodel.get_propagatorsby unifying grid usage; Remove unused propagator-related functions fromutils.physics.pyAllow
plot_obj_tiltsandplot_slice_thicknessto savie figures even for fixed tilts and thickness by appending results to model regardless; Add a safety guard to skip quiver plot of effective 0 tilt; Update demo params files comments regarding available selected_figs; Update recon_params to add the missing figure optionsUpdate
FilePathWithKeyininit_params.pyso we can load ‘.raw’ file with arbitrary shape, offset, and gapFix incorrect modes orthogonalization (missing .conj()) in
orthogonalize_modes_vecin response to issue #11 as pointed out by @dong-zehao. This error doesn’t negatively impact results but just produce probe modes that aren’t really orthognal with each other; Update check_modes_ortho in utils.dev_tools.py so it can check complex modes as well
[0.1.0b8] - 2025-07-02#
Added#
Add
params/module to enable params default filling, type check, and validation via pydantic. This adds a new dependency (pydantic) but greatly enhances the robustness of PtyRAD and promotes “fail early” philosophy reggarding params configuration. Default filling makes it possible to create a minimal params file with ~ 15 fields. The validation would check for variable types, option availability, and file existence, etc.Add demo
tBL_WSe2_reconstruct_minimal.ymlparams file for demonstrationAllow
tilt_sourceto takefileoption so we can load object tilts from file. This is suggested by @zb87Add
meas_normalizationoption to demo params filesAdd ‘force’ boolean option to
meas_remove_neg_valuesso that we can subtract values from measurements without negative valuesAdd versioning strings to demo params/notebooks for calrity
Allow fine-grained control of output folder name by adding high-level presets including ‘minimal’, ‘default’, and ‘all’ to
recon_dir_affixesinrecon_paramswhile supporting 16 individual control options as well. High-level presets would introduce a breaking change for previous params files.
Changed#
Update
load_paramsto include the validation logic and optionUpdate CLI
runto include optional validation (–skip_validate)Update CLI
validate-params command so we can simplify validate the params files in command lineSimplify
_process_measby removing unnecessary neg correction and normalizationImprove
_meas_add_poisson_noiseby adding built-in negative values check and switching to global normalization to maintain relative intensity between each patternMove Slurm scripts to demo/scripts for simplicity
Change
prefix_dateoption inrecon_paramsintoprefix_timeto enable more control of the time format prepended to the output folder name. Default time format is ‘date’ for output folder, and ‘datetime’ for the output log file. This introduces a breaking change for previous params files.Fix
_tiltrecon folder name appending when ‘tilt_type’ : ‘each’ otherwise it was appending all (N,2) values
[0.1.0b7] - 2025-05-30#
Added#
Add CLI command
ptyrad export-meas-initto allow quick exporting initialized measurement arrays to disk with specified file types (.mat, .hdf5, .tif, .npy)Add utils functions
get_nestedandlist_nested_keysto better handle nested dicts / HDF5 filesAdd
meas_exporttoinit_paramsso we can export the PtyRAD initialized diffraction patterns for further processing, analysis, or visulaization if needed. Currently supporting hdf5, tif, and npy that can be directly ported intopy4D-browser.Add
is_mig_enabledutil function and improve the overall error message related to multiGPUAdd
Nlayerto hypertune optimizable params as suggested by @zb87
Changed#
Switch the PtyRAD model output from .pt to .hdf5 for better interoperability. Previous .pt files are still supported via the wrapper function
load_ptyrad. The full (de)serialization process is handled bysave_dict_to_hdf5,tensors_to_ndarrays,handle_hdf5_types, andndarrays_to_tensorspecifically for optimizer state dictsSignificantly refactor and enhance
load_hdf5andload_matto handle different file version, list of keys and specified delimiter for nested keysAllow key-less data loading for .mat and .hdf5, so users don’t necessarily need to specify a key when loading diffraction patterns. Add a general purpose
load_measurementsfunction inload.pyto automatically detect file extension and dispatch. This change is inspired by py4D-browser.Internal clean up of the
model.forwardmethod to only return diffraction patterns. The object patches are cached inmodel._current_object_patches. An intermediate wrapper functionmodel.get_forward_measis addedFix incorrect
dzintermediate output folder name in hypertune mode from issue 4 pointed out by @HanHsuanWu
[0.1.0b6] - 2025-05-24#
Added#
Add
__main__.pyto allowpython -m ptyrad. Now we can executeptyradpackage as a module/script foraccelerate launch.Add
.github/workflows/publish_pypi.ymlfor automation. Future release will automatically be published to PyPI.
Changed#
Fix
set_gpu_deviceso we can properly returndevice=Noneto allowacceleratesetting devices for multiGPU. The--gpuidargument can now take'acc','cpu', and integers for GPU ID, which is still backward compatible. This hotfix is motivated by the question of multiGPU raised by @ccs1019.Update
slurm_run_ptyrad.subwith clearer comments about the normal and accelerate (multiGPU) modes.Update
pyproject.tomlfor the PyPI (pip) publishing. The dependencies are moved to the core list sopip install -e . --no-depsis now preferred to preventpipfrom pulling packages.
Removed#
Remove
scripts/run_ptyrad.pyscript because it’s completely covered by theptyrad runCLI command for reconstruction, hypertune, and accelerate (multiGPU) modes.
[0.1.0b5] - 2025-05-20#
Added#
Add
meas_calibrationoption into the params yml file to enable calibration using 7 different units, or to directly fit the experimental data. This change is strongly advised by @noahschnitzer, @ecchung, and @shaqekar!Add
dxas a hypertunable parameter, although technically one should do the kMax calibration and fix the dx value for each collection angle, and use hypertune for scan affine transformationAdd
append_paramsboolean flag tohypertune_paramsso we can optionally append the hypertune params to the collate results. This is advised by @shaqekar and @YinChen!Add the Command Line Interface (CLI) tools as
cli.pymodule. We can callptyrad run --params_path <PARAMS_PATH> --gpuid 0from anywhere, or callptyrad check-gputo quickly check whether GPU-supported PyTorch is installed or not. This is suggested by @sezelt!Add
envs/to keep CUDA-specific environment.yml files. Set suggested versions to CUDA 11.8, Python>=3.10, <3.13. and pytorch>=2.0, <2.7 for maximal compatibility. This is motivated by @dasol-yoon!
Changed#
Fix the potential mismatch from rounding Npix during
meas_resample. This was first pointed out by @ecchung!Improve
init_initializationprocess significatly, especially theinit_calibrationlogic withinit_measurements.Add
safe_filenametoutils/common/so we can correct illegal filenames (total length and component length) across different platforms, extra str except file extension would be clipped, this should completely prevent the file name too long error especially on Windows.Enable proper pip install via
pip install .by modifying thepyproject.tomlThanks @ercius for pointing this out!Split
print_gpu_infoandprint_packages_infoout ofprint_system_infofor clarity and allow easier check via CLI. Also improve the printed message and format a bit.Enhance error messages about missing fields and shape mismatch of
load_measand_process_measofinit_measurements. This is motivated by @PhysX.
Removed#
Remove
probe_dxoption from params yml and incorporate it intomeas_calibration. Note thatdxis still used internally by PtyRAD as the only calibration metric.
[0.1.0b4] - 2025-05-12 (soft public release)#
Added#
Add
demo/folder to organize demo-specific data, params, and notebooksAdd
LICENSE,CONTRIBUTING, andWISHLIST.mdAdd
load_tomlfor supporting .toml params fileAdd
environment_ptyrad.ymlfor ease of creating Python environment
Changed#
Slight restructure of the params file format of
init_params, this will cause BREAKING CHANGES so all users need to update their current params filesMajor refactoring of the
initialization.pymodule internally for clarity and future extensibilityChange the repo to
src/layout for more install and import robustnessChange the
utils.pyinto autils/module for better organization, split off thesave.pymoduleChange the
data_io.pyintoload.pySplit
optimizaiton.pymodule intolosses.pyandconstraints.pyRefine
README.mdfor more comprehensive step-by-step guide
Removed#
Remove
notes/andscripts/analysis/for clarity in the soft public releaseRemove paper related figure notebooks as they’ll be included in final Zenodo record and another repo
[0.1.0b3.dev3] - 2025-04-26#
Added#
Add
Git_workflow.md,CONTRIBUTING.md, andWISHLIST.mddrafts
Changed#
Modify
set_gpu_deviceto add automatic support for Apple Silicon (MPS) GPUs.Fix
UnicodeDecodeErrorby specifying UTF-8 encoding when loading YAML / JSON params files on non-UTF8 terminalsAdd paper figure saving as pdf and png with 600 DPI
Fix hypertune when no pruner. The final optuna_error should only be calculated when pruner = None. Thanks to @noahschnitzer
Update
pyproject.tomlwith the PEP 440 valid versioning and installation setup forpip install -e .Change the versioning
v0.1.0-beta3.3->0.1.0b3.dev3to getpyproject.tomlinstall working.
[v0.1.0-beta3.2] - 2025-04-11#
Added#
Add
simulate_tBL_WSe2_4dstemandpreprocess_simulated_4dstemnotebooks and script toscripts/paperto generate simulated data with abTEMAdd
meas_padtoexp_parmaswith both ‘precompute’ and ‘on_the_fly’ mode. The ‘padding_type’ can be ‘constant’, ‘edge’, ‘linear_ramp’, ‘exp’, and ‘power’. This allows flexible diffraction padding to conveniently change the real-space object pixel sampling.Add options to
objp_postivconstraint, including ‘mode’: ‘subtract_min’ and ‘clip_neg’. The default is ‘clip_neg’ because it performs much better than ‘subtract_min’. The ‘subtract_min’ option is added mostly for completeness.Add
padding_with_fitted_backgroundnotebook toscripts/analysis/to show the fitting processAdd
figure_kz_seriesnotebook toscripts/paper/Add
mfft2(the P+S decomposition) andcenter_croptoutilsfor cleaner figure notebooks
Changed#
Fix the incorrect unit conversion of
meas_add_source_sizefor partial spatial coherence. It was applying source size effect incorrectly as ang / scan_step_size. This would make an intended 0.34 Ang std with 0.4 Ang scan step size becomes effectively 0.34 scan step size, so 0.136 Ang std.Fix
model.probe_int_sumso it takes the padded background into account during ‘on-the-fly’ padding mode.Modify the
get_loss_pacbedso it’s normalized by data_mean as well just like other losses.
[v0.1.0-beta3.1] - 2025-02-13#
Added#
Add
create_optuna_samplerandcreate_optuna_prunerto allow flexible hyperameter tuning algorithm cofigurations in Optuna. The chosen sampler/pruner names will be affixed to the hypertune result folder.Add new hypertunable parameters including PyTorch optimizers, learning rates, batch sizes, and number of probe modes.
Add
params/paperto keep the params files used in the paperAdd
docs/20241202_packages_iter_times/for the package iteration time benchmarkingAdd
docs/20241215_multiGPU/for multiGPU benchmarkingAdd
docs/20241219_GPU_comparison/for GPU performance comparisonAdd
scripts/paper/to keep the scripts used in the paperAdd
meas_remove_neg_valuesoption so that we can choose whether to clip the negative values or subtract the minimum. Original default behavior is subtracting the minimum value, while clipping negative values behaves better for low dose data. NOTE that the default behavior of PtyRAD has changed fromsubtract_mintoclip_negto support better convergence.Add
timeouttohypertune_paramsso that we can limit the overall time for a hypertune studyAdd
optim_stateas a new saving option tosave_result. This changes the default saving behavior ofmodelso ifoptim_stateis not specified, the savedmodel.ptis roughly 40% of the file size comparing to the model with an Adam state dict using the default history setting.Add
tilt_avgtoselected_figsinrecon_paramsso we can visualize how averaged tilt_y, tilt_x evolve with iterations when optimized with AD.Add a new unit in
meas_add_poisson_noiseso we can apply Poisson noise with eithertotal_e_per_patternore_per_Ang2Add
complex_ratioandmirrored_ampintoconstraint_paramsas initial attempts to constrain object amplitude based on object phase, which should help the doughnut issues in thick samples or samples with heavy atoms
Changed#
Reformat the
'tune_params'for hypertune mode so users can freely set the Optuna suggesting int, float, or categorical values and pass whatever keyword arguments (kwargs) for maximal flexibility and future compatibility. This allows users to use smart samplers to navigate a discrete search space defined arbitrarily if the users specify the ‘choices’ when using'suggest': 'cat'for categorical values. The alternative approach for discrete search space would be to useGridSamplerbut it’s as inefficient asBruteForceSamplerRefine
optuna_objectiveto take the updated'tune_params'formatUpdate the
hypertune_paramsfor demo params filesSimplify
load_fields_from_matby calling the updatedload_hdf5so matlab file version 7.3 can be loaded in a unified way with normal hdf5Update
initialization.pysoPtyShvcan be loaded correctly with either matlab file version 7.3 or older versions. Special handling is necessary because matlab file version 7.3 will be loaded byload_hdf5usingh5pyand the array would be loaded using C-order, which is reversed from the normal matlab F-order. Complex array would also be loaded as nested array hence special casting is needed.Refine
load_rawby adding a file size check. If the specified shape gives a file size different from the actual file size, it will raise an error immediatelyImprove information logging in hypertune mode by printing relevant configurations
Improve information logging of
init_measurementsin the Poisson noise simulation and normalization partsImprove information logging of
loss_paramsandconstraint_paramsby printing relevant configurations
[v0.1.0-beta3.0] - 2024-11-26#
Added#
Add
LBFGSas available optimizer option. LBFGS is a Quasi-Newton 2nd order optimizer that was designed for full-batch update scheme and converges very fast on certain convex problems. While generally it requires full-batch update and ideally noiseless gradients, it’s included for completeness and certain special cases.Add
.jsonas supported params file type in hope of better support for LLM-related interfacesAdd
slice_thicknessas an AD-optimizable parameter and rename mostz_distanceintoslice_thicknessfor clarity.Add
plot_slice_thicknessfor visualizationAdd
npyas the new measurements data type intodata_io.pyandinitialization.py
Changed#
Refine
near_field_evolution(Fresnel propagator) for performance and simplify the function signature.Refactor
recon_stepandrecon_loopa bit by movingiter_times,loss_iters, anddz_itersall insiderecon_stepsince they’ll be stored inmodelfor every iterationSimplify the function signature of
save_results,make_save_dict, andplot_summaryby moving the iter-result-lists insidemodelFix the
model_instanceusage inrecon_stepfor multiGPU mode (model.moduleis required due to DDP wrapping). Note thatstart_itercurrently doesn’t work properly in DDP mode (multiGPU).
[v0.1.0-beta2.10] - 2024-11-06#
Added#
Add
CustomLoggerto notebooks/scripts to log the Python terminal stdout specifically to a log file under the reconstructed folder. IfSAVE_ITERS = Noneand no output directory is generated, the log would be saved tologs.
Changed#
Fix the printing error when using
GROUP_MODE = 'sparse'by makingsparse_batchesa list of arrays so we can dobatch.tolist()for cleaner printing of the batch_tChange the default update step size for
py4dstemscripts to 0.1 for numerical stability, otherwise the default 0.5 would easily give NaNs on my tBL-WSe2 dataset. Thanks the input from @sezeltSimplify
run_py4dstem.pyandrun_py4dstem_detailed_walkthrough.ipynbby calling the v0.0.2 version of locally modified py4DSTEM repoMove
scikit-learnas optional dependency because it’s only used for compact/sparse groupingAdd
self.optimizerto PtychoAD object so we can retrieve optimizer after the reconstruction
[v0.1.0-beta2.9] - 2024-10-17#
Added#
Add
py4DTEMas a new source for object, probe, and positions in params file with inputs from @dsmagiyaRefine
run_py4dstem.py,slurm_run_py4dstem.sub, andrun_py4dstem_detailed_walkthrough.ipynbAdd
probe_propas a new option forsave_resultlist. It’ll save a 2D montage of (Nz x Ny, pmode x Nx) to show how the probe modes propagate through the object
Changed#
Modify
load_hdf5so that it can return the entire dict ifdataset_key = NoneAdd a
with torch.no_grad()block for the saving/plotting block to locally disable autogradMove the
init_acceleratorfromPtyRADSolverclass toutilsto reduce duplicated printing because DDP is only initialized after initializingaccelerateChange the interpolation mode for on-the-fly resampling (torch.nn.functional.interpolate) from ‘area’ to ‘bilinear’ to avoid the edge artifact in reconstructed probe
[v0.1.0-beta2.8] - 2024-10-14#
Added#
Add x-ray ptychography capability to PtyRAD with the help from @ameyluktuke, @xyin-anl, and @yijiang1
Add
simu_xray_ptycho.ymland demo data for x-ray ptychographyAdd
make_fzp_probetoutils.pyto simulate x-ray probe generated by Fresnel zone platesAdd
foldslice_hdf5as a new position source for most APS instruments that generate hdf5 position files. The hdf5 files are commonly handled infold_sliceusingp.src_positions = 'hdf5_pos';
Changed#
illumination_typeis now a required field in theexp_paramsdict inside the yml param filesModify
initialization.pyto be compatible with x-ray ptycho includinginit_exp_params,init_measurments,init_probe,init_pos,init_obj, andinit_H
[v0.1.0-beta2.7] - 2024-10-05#
Added#
Add on-the-fly measurements resampling into
meas_resampleto reduce GPU VRAM usage with negligible performace impairmentAdd
20241005_effect_of_cpu_cores/underdocs/
Changed#
Update
time_syncby replacingtime.time()withtime.perf_counter()so that it can better measure events that are shorter than 1 ms.Let
PtyRADSolver.reconstruct()create an attribute of reconstructedPtychoADmodel calledPtyRADSolver.reconstruct_resultsso that we can do some further work if neededModify
acceleratebranch so that the HuggingFaceacceleratepackage becomes optional and can work on environments withoutaccelerateinstalled. This makes it possible to mergeacceleratebranch intomainand allow Windows users to at least runPtyRADon a single GPU using the exact same codebase.Modify
imshift_batchso that PtyRAD is compatible with older Python version < 3.11 as wellSimplify the output message of
set_gpu_device()Merge
acceleratebranch intomainso that it’s easier to maintain. Windows users without NCCL do not need to installacceleratepackage, and they can still use a conda environment withoutaccelerateto execute PtyRAD frommainbranch
[v0.1.0-beta2.6] - 2024-09-30#
Added#
Add
--gpuidas a command line argument forrun_ptyrad.py@sezeltAdd
set_gpu_devicetoutilsfor cleanerrun_ptyrad.pyscriptAdd
c5explicitly underexp_paramsso we have more control on simulated initial probeAdd
c3andc5into hypertunable params @sezeltEnable
'step': nullinside'tune_params'for continuous parameter space in hypertune mode @sezeltAdd multi-GPU and mixed-precision capabilities via HuggingFace
acceleratepackage. This is implemented in a separate branchaccelerateand would require a different environment.
Changed#
Update
get_default_probe_simu_paramsto take in ‘c5’ fromexp_paramsas wellUpdate
make_output_folderto include c3, c5 values under theinitcondition insiderecon_dir_affixesUpdate
make_stem_probewith more robust param parsing @sezeltUpdate
run_ptyradscript and notebooks, andslurm_run_ptyrad.subaccordingly
[v0.1.0-beta2.5] - 2024-09-19#
Added#
Add
optimizer_paramsdict undermodel_paramsin the .yml params file to support more PyTorch available optimizers with configurations and allow loading the optimizer stateAdd
create_optimizerfunction underoptimization.pyfor arbitrary PyTorch optimizer creation with configurationsAdd
grad_accumulationintoBATCH_SIZEso we can approximate large batch size that doesn’t fit into memory by accumulating gradients from many sub-batches. This is essentially a “memory-save” mode for PtyRAD
Changed#
Refine the
plot_forward_passdefault indices generation method so it works better for different INDICES_MODEUpdate
make_output_folderso the optimizer name can be optionally affixedChange
make_save_dictandsave_resultsso that it saves the optimizer state intomodel.ptas wellRename
model.set_optimizer_paramsintomodel.create_optimizable_params_dictfor clarityMove some jupyter notebooks into
scripts/analysis/for clarityMove
spec-file_ptyrad.txtto new folderenvs/for clarity
[v0.1.0-beta2.4] - 2024-09-17#
Added#
Add an
'obja'option to thesave_resultsto allow saving the object amplitude.
Changed#
Change the
plot_forward_passdefault behavior inplot_summaryfrom random indices to fixed indices so the reconstruction progress can be better observed by visualizing the same region throughout the run.Fix normalization error of
'bit: ['raw']in'result_modes'since beta2.2 (2024-09-03). It was incorrectly normalizing the tif outputs from 0 to 1 when it should be outputting the original range. The output figure likeforwardand saved optimized tensors inmodel.ptwere not affected by this error.
[v0.1.0-beta2.3] - 2024-09-13#
Added#
Add a simple notebook
check_sqlite.ipynbto check duplicated params in sqlite database for hypertune mode, though the duplicatation is an expected behavior for BO algorithmAdd
rawas new measurement data source to handle EMPAD and pre-processed EMPAD2 4D-STEM datasetsAdd
power_threshtoprobe_mask_kconstraint so we can select how much probe modes should be masked in k-space
Changed#
Specify the file_path in all loading functions in
data_iowhen there’s aFileNotFoundErrorAdd
indicesinto the argument ofmake_save_dictso that the selected probe position indices are saved intomodel.ptas well. This enables more convenient custom object cropping.lr_paramsis merged withstart_iterand renamed toupdate_paramsundermodel_paramsto add extra control over when to start optimizing the optimizable tensorsmodify
make_output_dirto affix non-zerostart_iter, also change thelraffix to non-zero learning rates only
[v0.1.0-beta2.2] - 2024-09-03#
Added#
Add a default
/datafolder with txt instructionAdd
demounderparamswith a couple tBL_WSe2 examplesAdd
run_PtyShv.mandslurm_run_PtyShv.subfor direct comparison with PtychoShelvesAdd
copy_paramsboolean torecon_paramsto copy the params files to the output directories for better record keepingAdd
save_resultslist torecon_paramsto specify which result (obj, probe) to saveAdd
result_modesdict torecon_paramsto specify the dimension of output object and whether to postprocess (crop, bit depth) the result before savingAdd
collate_resultsboolean tohypertune_paramsto specify whether to collect hypertune results underoutput_dirAdd
parse_sec_to_time_strtoutilsto display the solver time and iteration time in flexible time string from days, hours, mins, to secsAdd full description to every entry in the params file
Changed#
Move
subscan_slowandsubscan_fastunderINDICES_MODEfor (hopefully) clarityLet
load_paramsadd additional entry ofparams_pathto the params dict before return for easier usage ofcopy_paramsAbsorb
--hypertuneand--quietinto the params file, simplifying the scripts and letting the entire recontstruction behavior controlled by params fileDrop the
_optunasuffix inREADME.mdandspec-file.txtfor simplicitySimplify the installation guide in
README.mdRename
fig_listtoselected_figsfor clarityRename
dir_affixestorecon_dir_affixesfor clarity
Removed#
Remove
probe_simu_paramsfromexp_paramsbecause it’s duplicated withprobe_paramsinsource_params
[v0.1.0-beta2.1] - 2024-08-28#
Added#
Add
get_scan_affine.ipynbto quickly estimate the scan affine transformation for known crystal structureAdd
decompose_affine_matrixtoutilsto decompose an affine matrix into the 4 componentsAdd
subscan_slowandsubscan_fastintorecon_paramsfor finer control ofINDICES_MODElikecenterandsubAdd
dir_affixestorecon_paramsto enable flexible control of the output folder name withmake_output_folderAdd
defocusandconv_angleto Optuna optimizable params inhypertune_params
Changed#
Fix
optuna_objectiveso that the 4 components ofscan_affinecan be optimized independentlyMove
inputsout ofptyradcore package and rename it asparamsfor simplicityRename the
full_params_xxx.ymlintoxxx.ymlfor simplicityModify
LoopSubmit.shso the 1st loop would wait 10 sec before the 2nd one to finish the database creation, which prevents the sqlite3 “table already exists error”Fix
make_mixed_probearguments with optional verbose
[v0.1.0-beta2.0] - 2024-08-18#
Added#
Add hyperparameter tuning (Bayesian optimization and others) capability for
z_distance,scan_affine, andobj_tiltswith OptunaAdd
reconstructionmodule andPtyRADSolverwrapper class for a more compact workflow and streamlined interfaceAdd
load_paramsintodata_ioAdd
.ymlas a new params file type. The original.pyis still working but deprecated, might be removed before public releaseAdd
vprintas verbose print toutilsto better control the verbosity of printed information (especially for hyperparamter tuning)Add a rough version of doc string for major classes and functions
Changed#
Simplify the arguments for
save_resultsandmake_save_dictRearrange the argument order of
plot_summaryand add default value tofig_listRefactor the
run_ptyradscripts and notebooks and move them intoscriptsMove previous params.py files to
ptyrad/inputs/archiveand stop updating themFix
make_output_folderso that dz will only print 3 significant figures after rounded to 2 decimal points. So dz = 12.8 would be printed as 12.8 instead of 12.800000190734863.Add the
eps=1e-10back tomultislice_forward_model_vec_allinforwardso that thedp.pow()is more numerically stable, especially for large collection angles with intensities near 0
Removed#
Remove
rbffromexp_paramsandmake_stem_probe. This is to encourage/enforce users to calibrated their dk for each camera length to getdx_spec.Remove
make_recon_params_dictfromutilsRemove
load_empad_as_4dandsave_4D_as_hdf5and other archived fromdata_iobecause we’re not using it at the moment
[v0.1.0-beta1.3] - 2024-07-10#
Added#
Add 4D-STEM preprocessing methods including
meas_crop,meas_resample,meas_add_source_size,meas_add_detector_blur,meas_add_poisson_noisetoinitializationfor better handling of input simulated 4D-STEM data. With these new methods, users can easily reconstruct with different 4D-STEM data conditions without manually generating and saving each 4D-STEM variants. We may create 4D-STEM datasets with different collection angles, k-space sampling, partial spatial coherence, detector blur, and noise level from a single dataset right before the reconstruction.Add
obj_preblur_stdtomodelfor an effective real space deconvolution with a 2D Gaussian kernel. By pre-convolving the obj with a 2D Gaussian before simulating the diffraction pattern, the reconstructed obj is essentially the deconvolution version of the transmission function.
Changed#
Rename
cbedsvariables/keys intomeasorDPfor generalizability. Changes are primarily made insideinitialization,optimization, andvisualizationbut you will need to modify the params files.Modify
make_output_folderto includeobj_preblur_stdvaluesModify the gaussian_blur implementation in
loss_simlarfrom a stack/list comp version to a reshape version and gets a 25% speed up (45 sec vs. 1min /iter)!
Removed#
Remove
recenter_cbedsinmodel_paramsbecause sub-px shifting noisy CBEDs is really not a good idea and leaves quite some artifact as well. We should directly handle the obj linear phase ramp from the off-centered CBEDs.Remove
run_ptyrad_local.pyfor simplicity as I don’t expect a lot of users would need it anymore. One can modify the atlas script by changing the path ofptyradpackage.
[v0.1.0-beta1.2] - 2024-06-05#
Added#
Add
obj_zblurtooptimizationfor a real-space substitution ofkz_filter. By convolving a 1D Gaussian filter along z-direciton, we could remove the wrap-around while maintaining the z-regularization behavior. Note that there’s no free lunch so instead of the wrap-around fromkz_filter, theobj_zblurwould still introduce edge effect due to the convolution. The default is “same” padding with “replicate” padding mode, so the object is padded with edge elements like abc|ccc, where | stands for the object edgeAdd
get_decomposed_affine_matrixtoutilsto quickly estimate the needed scan affine transformation components if we already have a reconstructed object and we know the ideal lattice constant and the angle between lattice vectors
Changed#
Move
obj_tiltstosource_paramsso that we can decouple it with theinit_cacheand use it freely from scratch (e.g. start from random object, probe, pos but with known local tilts from previous reconstructions)Change the
measurements_paramsfor'mat'and'hdf5'from alistto adictfor better clarity, i.e. [path, ‘cbed’] -> {‘path’:, ‘key’:‘cbed’} Modify
make_output_folderto includeobja_threshvalues in accordance with the addedobj_zblurfeature. Because thekz_filterautomatically contains a soft thresholding for obja so in order to fully replace it withobj_zblur, we’ll need to additionally specifyobja_threshas wellDecouple the obj tilts from
plot_scan_posby addingplot_obj_tiltstovisualization
[v0.1.0-beta1.1] - 2024-05-31#
Added#
Add
scan_rand_stdoption toinitializationfor Guassian displacements of scan positions to reduce the raster grid pathologyAdd
loss_poissntooptimizationfor loss calculation with Poisson noise statistics. This should be helpful for low dose data.
Changed#
Add the
show_figflag andplt.iofftoplot_pos_groupingso that it’s consistent with other plotting functionsRemove the
os.environ["OMP_NUM_THREADS"] = "4"inutilssince I somehow don’t get the warning fromMiniBatchKMeansanymoreAdd the description about reading py4dstem-processed .hdf5 with data key
'/datacube_root/datacube/data'found by Desheng toparams_description.mdRearrange output strings in
make_output_folderand add keywords (show_lr,show_constraint,show_model,show_loss)to disable optional info like learning rates, constraints, detector blur, and losses
[v0.1.0-beta1.0] - 2024-05-23#
Added#
Add
blur_stdoption forloss_simlarso we could compare the std between Gaussian blurred object modesAdd
kr_filteras additional obj constraint tooptimizationso we could set our desirable maximum kr that contributes to the object image. Note that the positivity clipping could be doubling the apparent spatial frequenciesAdd
run_ptyrad_altas.py,run_ptyrad_local.py, andslurm_run_ptyrad.subas demo scriptsAdd
docs/andparams_description.mdfor some more explanation
Changed#
Rename the
kz_filteroutput folder string inmake_output_folderfromkzregintokzffor simplicity, and to be consistent withkrfforkr_filterChange the
shift_cbedsinmodelsfrom.abs()to.real.clamp(min=0)because it seems that taking the real part of the complex Fourier filtered output from a real-valued input is a more correct approachUse the
plt.show(block=False)flag forplot_pos_groupingso that the non-interactive python execution wouldn’t be block by theplt.show()when executed from scriptUpdate
README.mdwith the new conda install commands for local and altas usage
[v0.1.0-alpha3.10] - 2024-05-20#
Added#
Add
load_PtyRADoption forobj_tiltsinitialization inexp_paramsso we can reconstuct from previous PtyRAD runs withopt_obj_tiltsAdd
get_local_obj_tiltsestimation function intoutilsAdd
get_local_obj_tilts.ipynbnotebooks toscripts/for interactive demonstrationUpdate
CHANGELOG.mdand fill in previous record information for record keeping
Changed#
Rename
source_paramskeyword ininitializationfrompttoPtyRADfor clarityChange the comments in params files to hint the expected keywords for
obj_tilts
Removed#
Remove
z_padargument fromkz_filterbecause it’s not as helpful. The obj still shows artificial intensity decay for top and bottom layers for z_pad = 2 and 8 and can not fix the multislice obj wrap-around artifactRemove
pphase_smoothconstraint because it’s not as helpful. Naively modifying (smoothing or scaling) the Fourier probe phase has a rough effect of focusing the real space probe and doesn’t really stabilize the Fourer probe phase nor fixing the corner intensity problem
[v0.1.0-alpha3.9] - 2024-05-16#
Added#
Add selective figure saving with
fig_listtoplot_summaryAdd
pphase_smoothsmooth with Fourier probe phase unwrapping and Gaussian smooth in hope of stabilizing the Fourier probe phase during optimization (doesn’t help, will be removed by the next commit)Add an image overlay argument and dashed lines to
plot_sigmoid_maskfor better visualization
Changed#
Rename
scan_flipfield inexp_paramstoscan_flipTto be consistent withcbed_flipTand the PtychoShelves convention of [flipup, fliplr, transpose]Update all params files to be consistent with the new
scan_flipTfield
Removed#
Remove
fix_probe_phiconstraint for simplicity because it’s only for visualization purpose (setting phase at k(0,0) as 0) without actual funcitonality
[v0.1.0-alpha3.8] - 2024-05-10#
Added#
= Add loss_simlar for omode similarity regularization
Changed#
Update params files with the new
obj_tiltsfieldMove
omode_occufromsource_paramstoexp_paramsfor params files becauseomode_occuis no longer planned to be an optimizable/loadable variable
[v0.1.0-alpha3.7] - 2024-05-09#
Added#
Add
get_dateandprefixtomake_output_folder
Changed#
Add new fields like
tilt_obj,dk, anddxtomake_save_dictFix the condition statements for
self.tilt_objinmodelsso it behaves correctly when the initializedobj_tiltsis [0,0] so no need for tilt propagatorFix
kz_filterto usetorch.real()for the Fourier filtered obj to respect possible negative valuesDelete the just-added fftshift/ifftshift in
forwardas they don’t seem to matter and the forward pass is 50% slower with additional fftshifts
Removed#
Remove
fix_probe_comconstraints because constantly shifting global probe would cause instability of the obj. Once the obj is fairly reconstructed, shifting the global probe would require shifting the already reconstructed object (or equivalently the entire (N,2)probe_pos_shifts)Remove
probe_mask_rconstraints because it’s just not physical and I can’t justify myself clipping so much real-space probe tailsRemove
obj_chgflipconstraints because the performance is rather poorRemove
obj_sameconstraints because the usecase is rather limited and could probably be replaced withkz_filter. Optimizing the broadcasted averaged slice wouldn’t be computationally faster. Besides, the “rough” result cann’t be used to estimate obj tilts so is less usefull than the obj regularized bykz_filter
[v0.1.0-alpha3.6] - 2024-05-07#
Added#
Add
opt_obj_tiltsfor global (1,2) or local/adaptive (N,2) crystal tilt correction during ptycho reconstructionAdd
obj_tiltsfields intoexp_paramsfor params filesAdd
test_constraint_fnto roughly demonstrate theconstraint_fnExtend
plot_scan_poswith antiltsargument so we can temporarily borrow theplot_scan_posto plot out obj tilt vectors (We should decouple this in the future)Add
get_rbfto roughly estimate the radius of bright-field disk of the CBEDs forprobe_k_mask
Changed#
Move
omode_occuto fromsource_paramstoexp_paramsininitializationfor consistency with the obj tilts as they’re specific for PtyRAD and behaves differently than obj, probe, or pos
[v0.1.0-alpha3.5] - 2024-05-06#
Added#
Add
fix_probe_phifor Fourier probe phase constraint. This is mostly for visualizaiton purpose, not sure if it stabilize the probe update for corner intensity artifact or notAdd
fftshift2andifftshift2toutilsas alias functions to remove the annoyingdim=(-2,-1)argument for most fft, ifft calls
Changed#
Global check for the fft/ifft/fftshift/ifftshift consistency. fft is for real->k, while fftshift is for corner->center. Do ifftshift to preshift before fft. All functions except the
imshift_batchandimshift_singlefollow this patternSimplify
near_field_evolutionby removing the unused far-field propagation and unused variables
[v0.1.0-alpha3.4] - 2024-05-04#
Added#
Add
recenter_cbedsfield into themodelsso we may shift the CBEDs based on their CoM
Changed#
Extend
get_center_of_massfor 3D input (N,Ny,Nx)Rename
imshiftintoimshift_singleand modify it in accordance withget_center_of_mass
[v0.1.0-alpha3.3] - 2024-05-04#
Added#
Add probe constraints
fix_probe_com,probe_mask_r,probe_mask_kin hope of fixing the probe artifactAdd corresponding visualization function
plot_sigmoid_mask
Changed#
Modify the
make_output_folderaccordingly for the probe mask constraints
[v0.1.0-alpha3.2] - 2024-05-03#
Added#
Add a simple charge-flipping constraint
obj_chgflpfor fun and hoping it might fix the “black hole atom” artifact but it does not
[v0.1.0-alpha3.1] - 2024-05-02#
Changed#
Delete the redundant intermediate wrapper function
batch_updateas it’s probably unnecessarily complicated
Removed#
Refactor
optimizationby removing redundant losses likeloss_tv,loss_postiv, andloss_obja1.loss_tvis introducing very strong mosaic-style artifact.loss_postivis overlapping with theobjp_positvconstraint and we can make the constraint soft by the mixing param so there’s no need forloss_postiv. Same reason applies toloss_obja1as we already have the constraint version asobja_threshRemove the placeholder
ortho_omodefunction because I don’t think orthogonalizing omode is the right thing to do. The omode are not necessarily orthogonal with each other and we should probably do the decomposition in the post-processing stage, not during the reconstructionRemove the for-loop implementation of
orthogonalize_modes_loopbecause it’s no longer needed, the vectorized version is much faster
[v0.1.0-alpha3.0] - 2024-05-01#
Added#
Add amplitude options for obj specific constraints
kz_filterandobj_blurso that we have finer controlAdd obja-related loss and constraints for completeness including
loss_obja1,obja_thresh, andobj_same
Changed#
Major refactor of the
optimizationby encapsulating each section of losses and constraints into individual functions for clarityCombine
loss_l1,loss_l2intoloss_sparsefor simplicity, while I think the LN-norm with N > 1 isn’t really sparse so could be uselessExtend
plot_forward_passto plot the obja(zprod) as wellUpdate
make_output_folderwith oalr, obj_blur, and the kz_strRefine visualization functions including the “last N iters” to
plot_loss_itersfor the convergence, adding “iter” to figure title, fixing the displayed scan_pos range, and the probe power toplot_probe_modes
[v0.1.0-alpha2.7] - 2024-04-28#
Added#
Extend
kz_filtertoobja, which turns out to be critical for thick samples like Si and now thekz_filteris fully recovering themultilayer_regulationoperation in PtychoShelvesAdd Fourier probe modes saving to
plot_summaryAdd version printing in
__init__for clarity
Changed#
Fix the incorrect scan position plotting when it’s called in
plot_summaryFix the checkerboard phase artifact in k-space for
plot_probe_modesby adding the necessary fftshiftAdd an amplitude scaling to the displayed phase for better visualization
Refactor
imshift_batchso that it can handle tensors with arbitrary leading dimensions (…, Ny, Nx), which is in preparation for possible need of shifting the object (omode, Nz, Ny, Nx) for global scan affine transformationRename and clarify the variables associated with
create_gridsinmodels
[v0.1.0-alpha2.6] - 2024-04-23#
Added#
Add plot_pos_groupingto visualize the spatial distribution for different grouping
Changed#
Fix the incorrect sparse batch generation due to duplicated indices in the
make_batchfunctionFix the incorrect
imshift_batchdue to a missing “)” so the shifts were not applied correctly. It has very little effect when the sub-px shifts are <<1, but it could’ve been limiting the capability of pos correction
[v0.1.0-alpha2.5] - 2024-04-21#
Added#
Add
plot_scan_positionstoplot_summaryAdd
init_posargument intoplot_scan_positions
Changed#
Extend
plot_probe_modeswith real/reciprocal/amp/phase optionsRefine
plot_forward_modeswith weighted sum of omode for more correct objp visualizationRename all occurence of
iterintoniterto avoid name clashing with native python build-in iteratorFix
make_mixed_probeerror when pmode=1 by expanding the initial probe dim into (1,Ny,Nx) and passing only the probe[0] intomake_mixed_probeto avoid changes inside the function
[v0.1.0-alpha2.4] - 2024-04-21#
Added#
Add
plot_summaryto show and save reconstruction summary figures
Changed#
Refine
plot_forward_passto add probe and remove redundant obj panels
[v0.1.0-alpha2.3] - 2024-04-20#
Changed#
Rename
cbeds_flipintocbeds_flipsTand make it comply with PtychoShelves format (flipup,fluplr,transpose)
[v0.1.0-alpha2.2] - 2024-04-20#
Added#
Add
objp_bluras a new obj constraintAdd lr format into
make_output_folderto save learning rate into the folder name
Changed#
Add an if block for
make_mixed_probeso only pmode>1 would initiate the functionFix the incorrect pos centering inside the affine transformation block in
init_posininitializaiton
[v0.1.0-alpha2.1] - 2024-04-19#
Added#
Add
/scriptsfor .py usageAdd a quick CoM routine
center_of_massinutilsfor future CBED centering purpose
Changed#
Move
init_variablesout ofmodel_paramsfor cleaner params file setup
[v0.1.0-alpha2.0] - 2024-04-17#
Added#
Refactor the path generation and saving by adding
make_output_folderandsave_results
Changed#
Unify grouping indices selection with
select_scan_indices, 3 modes are available (“sparse”, “compact”, and “random”)Refactor the indicies and batch making functions by removing
shuffle_batchesandselect_center_rectangle
[v0.1.0-alpha1.0] - 2024-04-16#
Added#
Add
init_checkintoinitializationAdd
/inputsto store the experimental data paramsAdd position initialization with global affine transformation and flip into
initializationAdd
READMEandCHANGELOG
Removed#
Remove
/archive
[Initial development]#
2024-04-14#
Add
detector_blur_stdformodelsAdd
plot_scan_positionsandplot_affine_transformationtovisualization
2024-04-13#
Add
fix_probe_intconstraint foroptimizationFix incorrect model saving and loading from .pt
Modify
orthogonalize_modes_vecfor probe_int sorting and printingModify
obj_ROI_gridto on-the-fly generation to reduce memory consumption for large 4D datasetAdd
init_cacheto reduce file loading time, especially for large .mat from PtychoShelves
2024-04-10#
Add
CombinedConstraintclass for iter-wise constraints including orthogonalization of pmode/omode, hard positivity clamp, and kz_filter for MS-ptychoModify
orthogonalize_modes_vecto take both 3/4D input and float/complex dtypeModify
make_save_dictto accomodate constraint_paramsAdd
shuffle_batchesto enhance randomness of mini-batch updates
2024-04-06#
Add
select_center_rectangle_indicesfor partial reconstructionsUnify batch generation funciton with “random”, “compact”, and “sparse”
Modify iter/batch printing indices to start at 1
2024-04-04#
Reorganization of package directories
Reformat params dicts
Refine
initializationclassMove probe-related functions from
initializaitontoutils
2024-04-02#
Major refactoring of the
initializationclassAdd epsilon to forward model for numerical stability
Add
make_stem_probe,make_mixed_probe, andorthogonalize_modefunctions for full reconstruction capability from simulated mixed-state probe
2024-03-30#
Implement the
initializaitonclass
2024-03-29#
Add ‘ortho’ kw for FFT intensity normalization
Add
Fresnel_propagatorto move probe defocusModify loss function to regularize on each object mode separately
2024-03-23#
Clean up archived versions class/functions, rename for clarity
Add
set_optimizermethod intomodelsso we may change the list of optimizable tensors or change their learning ratesSplit
opt_objintoobjaandobjp, return opt_patches, calculate loss on obj_patchesImplement
omode_occufor mixed object reconstruction
2024-03-21#
Vectorzied object cropping and Fourier shift porbes. Got probably a 10x speed up
2024-03-20#
Implement the
imshiftwith Fourier shift
2024-03-18#
Initialize the GitHub repo for PtyRAD
2024-03-16#
Implement a probe shift with
torchviosn.transformation.affinebut it seems to introduce artifacts to the probe
2024-03-14#
Implement the probe position with STN (spatial transformation network) on object
Implement object losses including obj phase L1, obj phase positivity, obj phase TV
2024-03-11#
Implement the mixed object reconstruciton with unified dimension (omode,Nz,Ny,Nx)
2024-03-10#
Implement mixed probe reconstruction with 2D/3D object
2024-03-08#
Start working on the PtyRAD package