Skip to content

API Reference

Models (SwinIR-2.5D, RRDB-ESRGAN, SRGAN & Native 3D CNN)

Bases: LightningModule

Learnable Super-Resolution Module (SRGAN / RRDB-RaGAN / SwinIR-2.5D) for XCT data.

Supports: - Classical Generator (backbone='srgan'), normalization-free RRDBGenerator (backbone='rrdb'), or shifted-window attention SwinIRGenerator (backbone='swinir') - Single-slice 2D (context_slices=1) or multi-slice 2.5D (context_slices=3, 5) - Standard BCE adversarial loss or Relativistic Average GAN (gan_loss_type='ragan') - Quantitative domain losses: AttenuationConservationLoss, SoftCLDiceLoss (pore-throat connectivity), SobelGradientLoss, and FocalFrequencyLoss - Built-in PSNR, SSIM, MAE, and RMSE logging on validation and test splits

Bases: Module

SwinIR Generator for 2D and 2.5D synchrotron XCT super-resolution.

Bases: Module

Residual Swin Transformer Block (RSTB) combining alternating W-MSA/SW-MSA with a 3x3 Conv.

forward(x)

Forward on (B, C, H, W) with automatic padding to window_size.

Bases: Module

ESRGAN-style RRDB Generator adapted for quantitative single-channel XCT slices.

Bases: Module

Hybrid sub-pixel + resize-convolution upsampler supporting any scale >= 1.0.

Bases: Module

Residual-in-Residual Dense Block chaining three DenseResidualBlock units.

Bases: LightningModule

PyTorch Lightning 3D CNN super-resolution baseline for XCT volumes.

Bases: Module

3D residual super-resolution network using trilinear resize-Conv3d upsampling.

Sliding-window 3D inference with raised-cosine feathering to eliminate tile seams.

Bases: Module

SRResNet / SRGAN Generator adapted for single-channel XCT data with reflect padding.

Bases: Module

SRGAN Discriminator outputting raw logits for BCEWithLogitsLoss.

Bases: Module

2D convolution followed by optional normalization and PReLU/LeakyReLU activation.

Bases: Module

Sub-pixel convolution upsampling block using nn.PixelShuffle and reflect padding.

Bases: Module

Residual block with reflect-padded convolutions and configurable normalization.


Physics, Topology & Perceptual Losses

Bases: Module

Enforces linear-attenuation (mu) downsampling consistency between HR predictions and LR inputs.

In reconstructed absorption micro-CT, coarse voxel linear attenuation approximates the spatial average of sub-voxel linear attenuation convolved with the system point-spread function (assuming joint intensity calibration between LR and HR). When low_res provides 2.5D multi-slice context (C >= 3 sampled at unit native-LR spacing +-Delta z_LR) and psf_sigma > 0, incorporates the leading-order through-plane z-PSF curvature term 0.5 * sigma_{z,LR}^2 * d^2 mu / dz_{LR}^2 so horizontal phase boundaries are not biased toward out-of-plane partial-volume blur.

Bases: Module

Differentiable centerline-Dice (soft-clDice) pore-throat connectivity loss for XCT.

Uses a bimodal quantile midpoint 0.5 * (Q_20 + Q_80) when threshold=None and gates out single-phase homogeneous patches (dynamic range < min_phase_contrast) so pure solid grains or pure macro-pores never have acquisition noise amplified into fake skeletons.

Bases: Module

Differentiable 2D/3D spatial gradient L1 loss preserving sharp phase boundaries.

Bases: Module

Adaptive 2D/3D Fourier-domain loss focusing optimization on hard high-frequency modes.

Bases: Module

Perceptual feature-space loss computed with frozen VGG-19 features.

Inputs in [0, 1] with shape (B, 1, H, W) or (B, 3, H, W) are normalized with ImageNet channel statistics before feature extraction. Frozen VGG weights are intentionally excluded from state_dict so model checkpoints remain compact and strictly loadable across configurations.

Bases: Module

Channel-wise pixel feature vector normalization (Karras et al., 2018).

Upcasts internally to float32 before computing x^2 and rsqrt so mixed-precision (16-mixed / FP16) training never overflows 65504 or underflows epsilon to 0.0 (0 / 0 = NaN).

Numerically stable parameterized sigmoid 1 / (1 + exp(-k * x)).

Uses torch.sigmoid(k * x) so mixed-precision (FP16/BF16) training never overflows torch.exp on large negative inputs.


3D Orthogonal Inference & Epistemic Uncertainty

Super-resolve an isotropic 3D LR volume along multiple orthogonal planes and fuse them.

Super-resolve a 3D XCT volume (D, H, W) using a 2D/2.5D generator along axis.

Uses zoom_cell_centered (grid_mode=True) along the stacking axis so half-voxel cell centers remain strictly aligned with PixelShuffle across all 3 orthogonal sweeps, and samples 2.5D context neighbors at native-LR spacing (context_stride = round(zoom_n)).

Fuse aligned single-axis 3D super-resolved volumes into an isotropic 3D reconstruction.

Compute zero-overhead voxel-wise orthogonal view-disagreement uncertainty (n=3 sweeps).


Data Modules, Synchrotron Registration & Transforms

Bases: LightningDataModule

Leakage-free 3D synthetic PoreSpy LightningDataModule for XCT super-resolution.

Enforces strict spatial isolation across train / val / test: - Splits the 3D HR volume spatially before fitting minmax bounds (on train only) and before applying 3D PSF Gaussian blur + downsampling independently per split, so no val/test voxel or intensity bound ever leaks into train.

test_volumes property

Return (lr_test_subvolume, hr_test_subvolume) for 3D volumetric benchmarks.

Generate a deterministic 3D porous-media benchmark tuple (lr_vol, hr_vol, pore_mask).

Bases: LightningDataModule

Config-driven LightningDataModule for LabXCT, Synchrotron HDF5 (Diamond I13), and PoreSpy stacks.

Enforces strict spatial split isolation: 1. Splits raw 3D volumes into disjoint train / val / test slabs before computing intensity normalization bounds (fitted exclusively on train) or applying synthetic 3D PSF degradation (applied independently per split so val/test never leak). 2. Uses cell-centered grid_mode=True spline resampling across integer and fractional scale_factor values (e.g., 2, 2.5, 4, 8).

test_volumes property

Return (lr_test_subvolume, hr_test_subvolume) for 3D volumetric evaluation.

Load a 2D/3D XCT volume from multi-page TIFF, a slice directory, .npy, or HDF5/NeXus.

When loading large synchrotron HDF5 reconstructions (e.g., 53 GB Savu/TomoPy files), roi_slices (specified in post-transpose (Z, Y, X) coordinates) are mapped back to the on-disk HDF5 axis order and sliced before materializing the array in host RAM.

Prepare aligned LR & HR 3D TIFF volumes + provenance manifest for Diamond I13-2 Zn-13X.

Resolution priority: 1. Cached zn13x_<pair>_lr.tif + zn13x_<pair>_hr.tif + manifest if size and source provenance match. 2. Local synchrotron HDF5 reconstructions in raw_h5_dir (supports <scan_id>_recon.h5, Zenodo <scan_id>/tomo_p4_tomopy_recon.h5, and 16906*_8bit_cropped.h5 layouts). 3. Public Zenodo 8-bit preview HDF5 sub-volumes (10.5281/zenodo.14245751, 16906*_8bit_cropped.h5) when online and prefer_offline=False. 4. Calibrated tri-phase Zn-13X synchrotron phantom when offline or prefer_offline=True (raises RuntimeError when allow_offline_fallback=False).

HR-voxel sub-pixel 3D registration of paired multi-magnification XCT volumes.

Uses sub-voxel FFT phase cross-correlation (upsample_factor=scale_factor) followed by integer HR-grid translation search scored by tri-planar 3D SSIM, eliminating residual half-LR-voxel (up to scale_factor // 2 HR voxels) misregistration.

Extract and normalize an aligned 3D slab from raw >50 GB I13-2 HDF5 files without loading full cubes.

When consistent_attenuation_window=True (default), both magnifications are normalized using the joint physical linear-attenuation range [min(vmin), max(vmax)] so identical physical mu values map to identical [0, 1] intensities across LR and HR (essential for linear-attenuation downsampling consistency in AttenuationConservationLoss).

Partition a 3D HR (and optional 3D LR) volume into disjoint spatial sub-volumes.

Simulate realistic isotropic 3D low-resolution XCT acquisition from an HR volume.

Supports both integer and fractional optical magnification ratios (e.g., 2x, 2.5x, 4x) via exact cell-centered box-area integration.


Spectral Metrology, Petrophysics, Transport & OpenImpala I/O

Compute 3D Fourier Shell Correlation (FSC) against a reference volume.

Compute 2D Fourier Ring Correlation (FRC) against a reference slice.

Return JSON-serializable scalar summary of 3D FSC/MTF (or 2D FRC/MTF) agreement with ground truth.

Reports both fsc_cutoff_050_cyc_vox / fsc_half_pitch_050_um (phase/SNR=1 shell correlation FSC = 0.5; Rosenthal & Henderson, J. Mol. Biol. 2003) and mtf_cutoff_050_cyc_vox / mtf_half_pitch_050_um (reference-normalized amplitude modulation transfer MTF_eff = 0.5, sensitive even to noiseless zero-phase Gaussian blur) alongside legacy 1/2-bit / 0.143 shell thresholds.

Compute a complete dictionary of image-fidelity metrics (safe on both 2D slices and 3D cubes).

Compute a comprehensive dictionary of porous-media XCT metrics.

Headline morphological metrics (porosity_abs_error, pore_dice, pore_iou, specific_surface_rel_error, euler_density_abs_error, pore_radius_wasserstein, two_point_corr_rmse) apply the physical ground-truth HR threshold threshold_true consistently to both target and pred (matching evaluate_transport_metrics), so greyscale drift or attenuation bias is rigorously penalized. Secondary contrast-invariant diagnostics under independent Otsu thresholding are reported with *_auto_otsu keys.

Quantify three-phase reactive microstructure in Zn-doped Zeolite 13X XCT volumes.

Locks (t_low, t_high) on target (ground-truth HR) and applies those exact physical attenuation thresholds to pred so greyscale shift across Pore / Na-13X / Zn-13X phases is faithfully measured.

Evaluate 3D diffusive transport and capillary drainage fidelity between SR and HR XCT volumes.

Propagate voxel-wise orthogonal epistemic uncertainty sigma_ortho into 3D tortuosity bounds.

Compute directional effective diffusivity D_eff/D_0, tortuosity tau, and anisotropy across z, y, x.

Reports tortuosity_mean = porosity / d_eff_mean (the macroscopic 3D tensor-trace bulk tortuosity phi / ((D_z + D_y + D_x) / 3)), which equals directional tau for isotropic media and varies monotonically across single-axis percolation transitions without dropping disconnected inf axes.

RMSE between simulated capillary drainage saturation curves S_nwp(P_c).

Export a 3D XCT volume or binary mask for direct simulation in BASE-Laboratory/OpenImpala.

Writes: 1. <output_dir>/<name>.tif: Uncompressed 8-bit multi-page TIFF (uint8, shape (D, H, W)) with pore_label marking the active diffusive phase and solid_label marking solid. 2. <output_dir>/<name>_openimpala.inputs: Ready-to-run AMReX ParmParse input deck for OpenImpala's Tortuosity / Diffusion executable.

Upsample a 2D image (H, W) or stack of 2D slices (N, H, W) by scale_factor.

Upsample a 3D volume (D, H, W) isotropically or anisotropically with cell-centered alignment.