### Setup Imports and Device Source: https://deepinv.github.io/deepinv/_downloads/3ba136e423d0890a98d52cc90a3e1723/demo_custom_niqe.ipynb Import necessary libraries and get the computation device. ```python import deepinv as dinv from deepinv.utils import plot import torch import numpy as np import matplotlib.pyplot as plt from torch.utils.data import Subset from torchvision.transforms import Compose, ToTensor, CenterCrop, Lambda from natsort import natsorted device = dinv.utils.get_device() ``` -------------------------------- ### Import Libraries and Setup Source: https://deepinv.github.io/deepinv/_sources/auto_examples/basics/demo_custom_optim.rst.txt Imports necessary libraries and sets up the computation device. This is a standard setup for DeepInverse examples. ```Python import deepinv as dinv import torch from deepinv.optim import PGD device = dinv.utils.get_device()) ``` -------------------------------- ### General Setup and Imports Source: https://deepinv.github.io/deepinv/_sources/auto_examples/physics/demo_phase_retrieval.rst.txt Imports necessary libraries and sets up the device and random seed for reproducibility. This snippet is essential for running any subsequent code in the example. ```Python import deepinv as dinv from pathlib import Path import torch import matplotlib.pyplot as plt from deepinv.models import DRUNet from deepinv.optim.data_fidelity import L2 from deepinv.optim.prior import PnP, ZeroPrior from deepinv.optim import PGD from deepinv.utils import load_example from deepinv.utils.plotting import plot from deepinv.optim.phase_retrieval import ( correct_global_phase, ) from deepinv.models.complex import to_complex_denoiser BASE_DIR = Path(".") RESULTS_DIR = BASE_DIR / "results" # Set global random seed to ensure reproducibility. torch.manual_seed(0) device = dinv.utils.get_device()) ``` -------------------------------- ### Load Example Image and Setup Source: https://deepinv.github.io/deepinv/_downloads/31f92417d030e0d2382c52178325ad67/demo_dps.ipynb Loads a sample image and sets up necessary libraries including PyTorch and DeepInverse. It also configures matplotlib for animation. ```python import torch import deepinv as dinv from deepinv.utils.plotting import plot from deepinv.utils import load_example import matplotlib as mpl mpl.rcParams["animation.html"] = "jshtml" device = dinv.utils.get_device() x_true = load_example("butterfly.png", img_size=64, device=device) x = x_true.clone() ``` -------------------------------- ### Install DeepInverse Source: https://deepinv.github.io/deepinv/auto_examples/index.html Install DeepInverse from GitHub. This is typically the first step before running any examples. ```bash pip install git+https://github.com/deepinv/deepinv.git#egg=deepinv ``` -------------------------------- ### Load Example Image and Setup Source: https://deepinv.github.io/deepinv/_sources/auto_examples/sampling/demo_dps.rst.txt Imports necessary libraries and loads a sample image for demonstration. It also sets up the computation device and clones the ground truth image for later use. Note that a smaller image size is used to reduce computation time. ```Python import torch import deepinv as dinv from deepinv.utils.plotting import plot from deepinv.utils import load_example import matplotlib as mpl mpl.rcParams["animation.html"] = "jshtml" device = dinv.utils.get_device() x_true = load_example("butterfly.png", img_size=64, device=device) x = x_true.clone() ``` -------------------------------- ### Setup DeepINV and Device Source: https://deepinv.github.io/deepinv/_sources/auto_examples/self-supervised-learning/demo_lowfieldmri.rst.txt Imports the necessary libraries and gets the computation device (GPU or CPU). ```Python import torch import deepinv as dinv device = dinv.utils.get_device()) ``` -------------------------------- ### Setup and Load Data Source: https://deepinv.github.io/deepinv/_sources/auto_examples/basics/demo_pretrained_model.rst.txt Initializes the DeepInverse library, sets the computation device, and loads an example image. It also defines the physics model including blur and noise. ```Python import deepinv as dinv import torch device = dinv.utils.get_device()) # Ground truth x = dinv.utils.load_example("butterfly.png", device=device) # Define physics physics = dinv.physics.BlurFFT( x.shape[1:], filter=dinv.physics.functional.gaussian_blur(sigma=(5, 5)), noise_model=dinv.physics.GaussianNoise( sigma=0.1, rng=torch.Generator(device=x.device).manual_seed(123) ), device=device, ) y = physics(x) ``` -------------------------------- ### Load Example Image Source: https://deepinv.github.io/deepinv/_downloads/5a89e1000770b922d57eed794f82857e/demo_sampling.ipynb Loads an example image ('messi.jpg') from the internet and moves it to the appropriate device (CPU or GPU). ```python device = dinv.utils.get_device() x = load_example("messi.jpg", img_size=32).to(device) ``` -------------------------------- ### setup_train Source: https://deepinv.github.io/deepinv/api/stubs/deepinv.training.AdversarialTrainer.html After usual Trainer setup, setup losses for discriminator too. ```APIDOC ## AdversarialTrainer.setup_train(_** kwargs_)[source] After usual Trainer setup, setup losses for discriminator too. ``` -------------------------------- ### Install DeepInverse Source: https://deepinv.github.io/deepinv/_downloads/27365b4f1c4bfbe1cc5e089da624baf3/demo_PnP_DPIR_deblur.ipynb Installs the DeepInverse library using pip. Run this in a new cell to get started. ```python # To get started, install DeepInverse by creating a new cell and running %pip install deepinv ``` -------------------------------- ### Import Libraries and Setup Source: https://deepinv.github.io/deepinv/_downloads/c7e36bcaa21741ac5318f37ab8658137/demo_unfolded_constant_memory.ipynb Imports necessary libraries and sets up the device, data type, image size, and number of images for the demo. It automatically selects a free GPU if available. ```python import deepinv as dinv import torch from torch.utils.data import DataLoader from deepinv.optim.data_fidelity import L2 from deepinv.optim.prior import PnP from torchvision import transforms from deepinv.utils.demo import load_dataset import time import numpy as np import matplotlib.pyplot as plt from deepinv.optim import HQS device = ( dinv.utils.get_freer_gpu() if torch.cuda.is_available() else torch.device("cpu") ) dtype = torch.float32 img_size = 64 if torch.cuda.is_available() else 32 num_images = 480 if torch.cuda.is_available() else 64 ``` -------------------------------- ### Import Libraries for DeepInverse Denoiser Example Source: https://deepinv.github.io/deepinv/auto_examples/models/demo_denoiser_tour.html Imports necessary libraries including PyTorch, pandas, matplotlib, and DeepInverse utilities for loading examples and plotting. Ensure these are installed before running. ```python import time import torch import pandas as pd import matplotlib.pyplot as plt import deepinv as dinv from deepinv.utils import plot_inset, load_example ``` -------------------------------- ### Setup Paths Source: https://deepinv.github.io/deepinv/auto_examples/external-libraries/demo_astra_tomography.html Sets up the base directory and results directory for data loading and saving. ```python BASE_DIR = Path(".") RESULTS_DIR = BASE_DIR / "results" ``` -------------------------------- ### General Setup and Imports Source: https://deepinv.github.io/deepinv/_downloads/9b34c9b1030da0c6d31466da3ee5468e/demo_phase_retrieval.ipynb Imports necessary libraries and sets up the device and random seed for DeepInverse. ```python import deepinv as dinv from pathlib import Path import torch import matplotlib.pyplot as plt from deepinv.models import DRUNet from deepinv.optim.data_fidelity import L2 from deepinv.optim.prior import PnP, ZeroPrior from deepinv.optim import PGD from deepinv.utils import load_example from deepinv.utils.plotting import plot from deepinv.optim.phase_retrieval import ( correct_global_phase, ) from deepinv.models.complex import to_complex_denoiser BASE_DIR = Path(".") RESULTS_DIR = BASE_DIR / "results" # Set global random seed to ensure reproducibility. torch.manual_seed(0) device = dinv.utils.get_device() ``` -------------------------------- ### Import DeepInverse and Utilities Source: https://deepinv.github.io/deepinv/_downloads/8e399ee05bc5d98e971a8019c1b5d2d2/demo_custom_kernel.ipynb Imports necessary libraries including PyTorch, DeepInverse, plotting utilities, and functions for loading example data. Ensure DeepInverse is installed using `%pip install deepinv`. ```python import torch from typing import Any import deepinv as dinv from deepinv.utils.plotting import plot from deepinv.utils import load_example ``` -------------------------------- ### Load and Use Pretrained RAM Model Source: https://deepinv.github.io/deepinv/_sources/user_guide/reconstruction/pretrained-models.rst.txt Demonstrates how to load an example image, define a physics model, and use a pretrained RAM model for reconstruction. Ensure DeepINV is installed and example data is available. ```python import deepinv as dinv x = dinv.utils.load_example("butterfly.png") physics = dinv.physics.Downsampling(filter="bicubic", noise_model=dinv.physics.GaussianNoise(0.01)) y = physics(x) model = dinv.models.RAM(pretrained=True) x_hat = model(y, physics) # Model inference dinv.metric.PSNR()(x_hat, x) > 29.75 ``` -------------------------------- ### Load and plot example image Source: https://deepinv.github.io/deepinv/_downloads/49627ef65058db4ee7109eae1451b91c/demo_connect_spyrit.ipynb Loads the butterfly image using `deepinv.utils.load_example` and plots it. Ensure DeepInverse is installed. ```python import torch.nn from deepinv.utils import plot import deepinv as dinv device = dinv.utils.get_freer_gpu() if torch.cuda.is_available() else "cpu" im_size = 64 x = dinv.utils.load_example( "butterfly.png", device=device, img_size=(im_size, im_size), grayscale=True ) print(f"Ground-truth image: {x.shape}") ``` ```python plot(x, r"$32\times 32$ image $X$") ``` -------------------------------- ### General Setup and Imports Source: https://deepinv.github.io/deepinv/_downloads/9464f38579ff220e8d6a07bba06944d9/demo_ptychography.ipynb Imports necessary libraries for image processing, PyTorch, and DeepINV modules. Sets the computation device to GPU if available. ```python import matplotlib.pyplot as plt import torch import numpy as np import deepinv as dinv from deepinv.utils import load_example from deepinv.utils.plotting import plot from deepinv.physics import Ptychography from deepinv.optim.data_fidelity import L1 from deepinv.optim.phase_retrieval import correct_global_phase device = dinv.utils.get_device() ``` -------------------------------- ### Get Git Repository Root Source: https://deepinv.github.io/deepinv/_modules/deepinv/utils/demo.html Retrieves the root directory of the Git repository. Requires the 'git' Python package to be installed. ```python from deepinv.utils import demo git_root = demo.get_git_root() print(f"Git root directory: {git_root}") ``` -------------------------------- ### Setup paths and device Source: https://deepinv.github.io/deepinv/_downloads/1f000b13523fc415ca34330757b9bc85/demo_custom_prior.ipynb Configures directories for data, results, and degradations, sets the random seed for reproducibility, and determines the appropriate device (CPU or GPU). ```python # Setup paths for data loading, results and checkpoints. BASE_DIR = Path(".") DATA_DIR = BASE_DIR / "measurements" RESULTS_DIR = BASE_DIR / "results" DEG_DIR = BASE_DIR / "degradations" # Set the global random seed from pytorch to ensure reproducibility of the example. torch.manual_seed(0) device = dinv.utils.get_device() ``` -------------------------------- ### DRUNet Initialization and Usage Example Source: https://deepinv.github.io/deepinv/_modules/deepinv/models/drunet.html Demonstrates how to initialize a DRUNet denoiser and apply it to a noisy image. Ensure deepinv is installed and PyTorch is available. ```python import deepinv as dinv import torch denoiser = dinv.models.DRUNet() y = torch.randn(1, 3, 32, 32) sigma = 0.1 with torch.no_grad(): denoised = denoiser(y, sigma) ``` -------------------------------- ### Set up device and directories Source: https://deepinv.github.io/deepinv/auto_examples/adversarial-learning/demo_gan_imaging.html Configures the computation device (GPU or CPU) and defines base and data directories for the project, including the location for original datasets. ```python device = dinv.utils.get_device() BASE_DIR = Path(".") DATA_DIR = BASE_DIR / "measurments" ORGINAL_DATA_DIR = get_cache_home() / "datasets" / "Urban100" ``` -------------------------------- ### Load Example Image and Initialize Parameters Source: https://deepinv.github.io/deepinv/_downloads/96a631387aec4a1a9994f425f58e4c2f/demo_scattering.ipynb Loads a sample image (SheppLogan.png) to represent the object's contrast and initializes necessary parameters like image width, contrast level, and PSNR metric. Adjusts contrast for CPU execution speed. ```python import deepinv as dinv import torch from matplotlib import pyplot as plt device = dinv.utils.get_freer_gpu() if torch.cuda.is_available() else "cpu" img_width = 32 x = dinv.utils.load_example( "SheppLogan.png", img_size=img_width, resize_mode="resize", device=device, grayscale=True, ) contrast = ( 0.5 if device != "cpu" else 0.1 ) # reduce contrast for CPU for faster convergence x = x * contrast psnr = dinv.metric.PSNR(max_pixel=contrast) ``` -------------------------------- ### Set Up DeepInverse Problem Source: https://deepinv.github.io/deepinv/_downloads/5611eb7a5e4c3863d7158fef25a0fff0/demo_custom_dataset.ipynb Initialize the device, physics model, and DeepInverse model for testing. ```python device = dinv.utils.get_device() physics = dinv.physics.Inpainting(img_size=(3, 256, 256)) model = dinv.models.RAM(pretrained=True, device=device) ``` -------------------------------- ### Wavelet Noise Estimator Example Source: https://deepinv.github.io/deepinv/_modules/deepinv/models/noise_level_estimation.html Demonstrates how to use the WaveletNoiseEstimator to estimate the noise level of a noisy image. Requires Pytorch Wavelets (ptwt) to be installed. ```python import deepinv as dinv from deepinv.models import WaveletNoiseEstimator rng = torch.Generator('cpu').manual_seed(0) noise = dinv.physics.GaussianNoise(0.1, rng=rng)(torch.zeros(1, 1, 256, 256)) noise_estimator = WaveletNoiseEstimator() sigma_est = noise_estimator(noise) print(sigma_est) ``` -------------------------------- ### Load Example Image and Set Up Reconstruction Parameters Source: https://deepinv.github.io/deepinv/_downloads/b33a1eb4de39658ecbc7b0bf022ff0b2/demo_PnP_custom_optim.ipynb Loads a sample image ('barbara.jpeg') and sets up parameters for a PnP reconstruction task, including image size and the degradation operation. ```python # Set the global random seed from pytorch to ensure reproducibility of the example. torch.manual_seed(0) device = dinv.utils.get_device() # Set up the variable to fetch dataset and operators. method = "PnP" dataset_name = "set3c" img_size = 64 x = load_example( "barbara.jpeg", img_size=img_size, grayscale=True, resize_mode="resize", device=device, ) operation = "single_pixel" ``` -------------------------------- ### DataGenerator Initialization and Setup Source: https://deepinv.github.io/deepinv/_modules/deepinv/datasets/datagenerator.html This snippet shows the initial setup for the DataGenerator, including directory creation, physics operator handling, and dataset size calculations. It prepares for dataset generation by ensuring the save directory exists and cloning physics operators. ```python import h5py import os from warnings import warn # Assuming Dataset, Physics, StackedPhysics, PhysicsGenerator are defined elsewhere # from deepinv.datasets import Dataset # from deepinv.physics import Physics, StackedPhysics # from deepinv.physics.generator import PhysicsGenerator def generate_dataset(train_dataset=None, physics=None, save_dir="./", test_dataset=None, val_dataset=None, dataset_filename="dataset", overwrite_existing=False, train_datapoints=None, test_datapoints=None, val_datapoints=None, physics_generator=None, save_physics_generator_params=False, batch_size=1, num_workers=1, supervised=True, verbose=True, show_progress_bar=True, device=None): """ Generates measurement data for training, testing, and validation sets. :param torch.utils.data.Dataset train_dataset: base dataset of ground-truth images. Must return tensors `x` or tuples `(x, ...)`. :param deepinv.physics.Physics physics: Forward operator used to generate the measurement data. It can be either a single operator or a list of forward operators. In the latter case, the dataset will be assigned evenly across operators. :param str save_dir: folder where the dataset and forward operator will be saved. :param torch.utils.data.Dataset test_dataset: if included, the function will also generate measurements associated to the test dataset. :param torch.utils.data.Dataset val_dataset: if included, the function will also generate measurements associated to the validation dataset. :param str dataset_filename: desired filename of the dataset (without extension). :param bool overwrite_existing: if ``True``, create new dataset file, overwriting any existing dataset with the same ``dataset_filename``. If ``False`` and dataset file already exists, does not create new dataset. :param int, None train_datapoints: Desired number of datapoints in the training dataset. If set to ``None``, it will use the number of datapoints in the base dataset. This is useful for generating a larger train dataset via data augmentation (which should be chosen in the train_dataset). :param int, None test_datapoints: Desired number of datapoints in the test dataset. If set to ``None``, it will use the number of datapoints in the base test dataset. :param int, None val_datapoints: Desired number of datapoints in the val dataset. :param None, deepinv.physics.generator.PhysicsGenerator physics_generator: Optional physics generator for generating the physics operators. If not None, the physics operators are randomly sampled at each iteration using the generator. :param bool save_physics_generator_params: save physics generator params too, ignored if ``physics_generator`` not used. :param int batch_size: batch size for generating the measurement data (it affects the speed of the generating process, and the physics generator batch size) :param int num_workers: number of workers for generating the measurement data (it only affects the speed of the generating process) :param bool supervised: Generates supervised pairs ``(x,y)`` of measurements and signals. If set to ``False``, it will generate a training dataset with measurements only ``(y)`` and a test dataset with pairs ``(x,y)`` :param bool verbose: Output progress information in the console. :param bool show_progress_bar: Show progress bar during the generation of the dataset (if verbose is set to ``True``). :param torch.device, str device: device, e.g. cpu or gpu, on which to generate measurements. All data is moved back to cpu before saving. """ if test_dataset is None and train_dataset is None and val_dataset is None: raise ValueError("No train or test datasets provided.") if not os.path.exists(save_dir): os.makedirs(save_dir) if not isinstance(physics, (list, tuple)): physics = [physics] physics = [p.clone() for p in physics] G = len(physics) save_physics_generator_params = ( save_physics_generator_params and physics_generator is not None ) if train_dataset is not None: n_train = train_datapoints or len(train_dataset) n_train_g = int(n_train / G) n_dataset_g = int(min(len(train_dataset), n_train) / G) if test_dataset is not None: n_test = min(len(test_dataset), test_datapoints or len(test_dataset)) n_test_g = int(n_test / G) if val_dataset is not None: n_val = min(len(val_dataset), val_datapoints or len(val_dataset)) n_val_g = int(n_val / G) hf_paths = [] for g in range(G): hf_path = f"{save_dir}/{dataset_filename}{g}.h5" hf_paths.append(hf_path) if os.path.exists(hf_path): if overwrite_existing: warn( f"Dataset {hf_path} already exists, this will close and overwrite the previous dataset." ) # remove existing dataset to avoid open file error os.remove(hf_path) else: warn(f"Dataset {hf_path} already exists, skipping...") continue hf = h5py.File(hf_path, "w") op_g = physics[g] hf.attrs["operator"] = op_g.__class__.__name__ # type: ignore if isinstance(op_g, StackedPhysics): hf.attrs["stacked"] = len(op_g) if physics_generator is not None: physics_generator.reset_rng() ``` -------------------------------- ### Initiating Training Source: https://deepinv.github.io/deepinv/_modules/deepinv/training/trainer.html Starts the model training process. This method typically orchestrates the entire training loop, including setup, forward/backward passes, and evaluation. ```python self.setup_train() ``` -------------------------------- ### Setup Paths and Load Data Source: https://deepinv.github.io/deepinv/auto_examples/plug-and-play/demo_PnP_mirror_descent.html Configures directories for data and results, sets random seed, loads a sample image, and defines image size and device. ```python BASE_DIR = Path(".") ORIGINAL_DATA_DIR = BASE_DIR / "datasets" DATA_DIR = BASE_DIR / "measurements" RESULTS_DIR = BASE_DIR / "results" CKPT_DIR = BASE_DIR / "ckpts" # Set the global random seed from pytorch to ensure reproducibility of the example. torch.manual_seed(0) img_size = 64 device = dinv.utils.get_device() # Selects the appropriate device (CPU or GPU) x_true = load_example("butterfly.png", img_size=img_size).to(device) x = x_true.clone() ``` -------------------------------- ### DiffusersDenoiserWrapper Initialization and Usage Example Source: https://deepinv.github.io/deepinv/_modules/deepinv/models/wrapper.html Demonstrates how to initialize and use the `DiffusersDenoiserWrapper` to denoise an image using a pre-trained model from Hugging Face. Ensure `diffusers` and `transformers` are installed. ```python import deepinv as dinv from deepinv.models import DiffusersDenoiserWrapper import torch device = dinv.utils.get_device(verbose=False) denoiser = DiffusersDenoiserWrapper(mode_id='google/ddpm-cat-256', device=device) x = dinv.utils.load_example( "cat.jpg", img_size=256, resize_mode="resize", ).to(device) sigma = 0.1 x_noisy = x + sigma * torch.randn_like(x) with torch.no_grad(): x_denoised = denoiser(x_noisy, sigma=sigma) ``` -------------------------------- ### Setup Device and Paths Source: https://deepinv.github.io/deepinv/_downloads/7995a858ee9f9a7ca83a0681697c7f54/demo_poisson_mlem.ipynb Sets up the base directory for results and determines the computation device (GPU or CPU). Ensures reproducibility with a fixed random seed. ```python BASE_DIR = Path(".") RESULTS_DIR = BASE_DIR / "results" torch.manual_seed(0) device = dinv.utils.get_freer_gpu() if torch.cuda.is_available() else "cpu" ``` -------------------------------- ### Load SKMTEASliceDataset Example Source: https://deepinv.github.io/deepinv/_modules/deepinv/datasets/skmtea.html Demonstrates how to load the SKMTEASliceDataset and iterate through its DataLoader to get sample data. It shows the expected shapes for the reconstructed image (x) and kspace measurements (y). ```python from deepinv.datasets import SKMTEASliceDataset # doctest: +SKIP from torch.utils.data import DataLoader # doctest: +SKIP dataset = SKMTEASliceDataset(".") # doctest: +SKIP len(dataset) # doctest: +SKIP 512 x, y, params = next(iter(DataLoader(dataset))) # doctest: +SKIP x.shape # (B, 2, H, W) # doctest: +SKIP torch.Size([1, 2, 512, 160]) y.shape # (B, 2, N, H, W) # doctest: +SKIP torch.Size([1, 2, 8, 512, 160]) ``` -------------------------------- ### Poisson-Gaussian Noise Model Example Source: https://deepinv.github.io/deepinv/user_guide/physics/physics.html Demonstrates the setup of a combined Poisson-Gaussian noise model. This model accounts for both Poisson noise (e.g., photon counting) and additive Gaussian noise. ```python import deepinv as di # Initialize a Poisson-Gaussian noise model noise_model = di.physics.PoissonGaussianNoise(gamma=1.0, sigma=0.1) print(noise_model) ``` -------------------------------- ### Load Example Image Source: https://deepinv.github.io/deepinv/auto_examples/sampling/demo_ddrm.html Loads a sample image ('messi.jpg') of size 32x32 from the internet and moves it to the appropriate device (CPU or GPU). ```python device = dinv.utils.get_device() x = load_example("messi.jpg", img_size=32).to(device) ``` -------------------------------- ### Get Item from RandomSampler Source: https://deepinv.github.io/deepinv/_modules/deepinv/datasets/random_sampler.html Retrieves a data sample (image or image pair) at a given index. It loads the image(s) from disk, applying specified start coordinates for patching if patch_size is defined. ```python def __getitem__(self, idx: int) -> tuple[torch.Tensor, torch.Tensor] | torch.Tensor: shape = self.shapes[idx] start_coords = [ torch.randint(0, s - p, (1,)).item() if p is not None else p for p, s in zip(self.patch_size, shape, strict=True) ] fname = self.imgs[idx] x = ( self._fix_ch( self.load( os.path.join(self.x_dir, fname), start_coords=start_coords, ) ) if self.x_dir else torch.nan ) if self.y_dir is not None: y = self._fix_ch( self.load( os.path.join(self.y_dir, fname), start_coords=start_coords, ) ) return (x, y) else: return x ``` -------------------------------- ### Setup Directories and Device Source: https://deepinv.github.io/deepinv/_downloads/efd340f322404f947b6ce19444834905/demo_learned_primal_dual.ipynb Configure base directories for data, results, and checkpoints. Set the PyTorch random seed for reproducibility and determine the appropriate device (CPU or GPU). ```python BASE_DIR = Path(".") DATA_DIR = BASE_DIR / "measurements" RESULTS_DIR = BASE_DIR / "results" CKPT_DIR = BASE_DIR / "ckpts" # Set the global random seed from pytorch to ensure reproducibility of the example. torch.manual_seed(0) device = dinv.utils.get_device() ``` -------------------------------- ### Importing Libraries and Setting Up Environment Source: https://deepinv.github.io/deepinv/auto_examples/sampling/demo_diffusion_sde.html Imports necessary PyTorch and DeepInverse modules, sets the device and data type, and configures matplotlib for inline animations. This setup is essential for running the subsequent code examples. ```python import torch import matplotlib as mpl import deepinv as dinv from deepinv.models import NCSNpp device = dinv.utils.get_device() dtype = torch.float32 figsize = 2.5 gif_frequency = 10 # Increase this value to save the GIF saving time mpl.rcParams["animation.html"] = "jshtml" ``` -------------------------------- ### Setup Project Directories and Device Source: https://deepinv.github.io/deepinv/_downloads/85eca6753deb47b1745550a476354d05/demo_DEQ.ipynb Define base directories for data, results, checkpoints, and degradations. Also, set the global random seed for reproducibility and determine the computation device (CPU or GPU). ```python BASE_DIR = Path(".") DATA_DIR = BASE_DIR / "measurements" RESULTS_DIR = BASE_DIR / "results" CKPT_DIR = BASE_DIR / "ckpts" DEG_DIR = BASE_DIR / "degradations" # Set the global random seed from pytorch to ensure reproducibility of the example. torch.manual_seed(0) device = dinv.utils.get_device() ``` -------------------------------- ### DiffPIR for Image Inpainting Example Source: https://deepinv.github.io/deepinv/_modules/deepinv/sampling/diffusion.html Demonstrates how to use the DiffPIR model for image inpainting with a pretrained DRUNet denoiser. This snippet shows the setup of a physics model, generation of measurements, definition of the DiffPIR model, and running the restoration algorithm. ```python import deepinv as dinv import torch device = dinv.utils.get_device(verbose=False) x = 0.5 * torch.ones(1, 3, 32, 32, device=device) # Define a plain gray 32x32 image physics = dinv.physics.Inpainting(mask=0.5, img_size=(3, 32, 32), noise_model=dinv.physics.GaussianNoise(0.1), device=device) y = physics(x) # Measurements denoiser = dinv.models.DRUNet(device=device) model = dinv.sampling.DiffPIR(model=denoiser, data_fidelity=dinv.optim.data_fidelity.L2(), device=device) # Define the DiffPIR model xhat = model(y, physics) # Run the DiffPIR algorithm print((dinv.metric.PSNR()(xhat, x) > dinv.metric.PSNR()(y, x))) # should be True ``` -------------------------------- ### Setup and Imports Source: https://deepinv.github.io/deepinv/_sources/auto_examples/metrics/demo_custom_niqe.rst.txt Imports necessary libraries for DeepInverse, plotting, tensor operations, and dataset handling. It also sets up the computation device. ```Python import deepinv as dinv from deepinv.utils import plot import torch import numpy as np import matplotlib.pyplot as plt from torch.utils.data import Subset from torchvision.transforms import Compose, ToTensor, CenterCrop, Lambda from natsort import natsorted device = dinv.utils.get_device()) ``` -------------------------------- ### Example Usage of StackedPhysicsDataFidelity Source: https://deepinv.github.io/deepinv/_modules/deepinv/optim/data_fidelity.html Demonstrates how to define and use a stacked data fidelity term with different noise models (Gaussian and Poisson) for a stacked physics operator. It shows the setup of physics, individual data fidelities, and the combined stacked data fidelity. ```python >>> import torch >>> import deepinv as dinv >>> # define two observations, one with Gaussian noise and one with Poisson noise >>> physics1 = dinv.physics.Denoising(dinv.physics.GaussianNoise(.1)) >>> physics2 = dinv.physics.Denoising(dinv.physics.PoissonNoise(.1)) >>> physics = dinv.physics.StackedLinearPhysics([physics1, physics2]) >>> fid1 = dinv.optim.L2() >>> fid2 = dinv.optim.PoissonLikelihood() >>> data_fidelity = dinv.optim.StackedPhysicsDataFidelity([fid1, fid2]) >>> x = torch.ones(1, 1, 3, 3) # image >>> y = physics(x) # noisy measurements >>> d = data_fidelity(x, y, physics) # data fidelity ``` -------------------------------- ### Set up directories and device Source: https://deepinv.github.io/deepinv/_downloads/0dbb9da1987a70e21aae950d9f50f937/demo_r2r_denoising.ipynb Configures base directories for data and checkpoints, sets the random seed for reproducibility, and determines the computation device (CPU or GPU). ```python BASE_DIR = Path(".") DATA_DIR = BASE_DIR / "measurements" CKPT_DIR = BASE_DIR / "ckpts" ORIGINAL_DATA_DIR = get_cache_home() / "datasets" / "MNIST" # Set the global random seed from pytorch to ensure reproducibility of the example. torch.manual_seed(0) device = dinv.utils.get_device() print(device) ``` -------------------------------- ### Loading and Streaming Raster Data with Patches Source: https://deepinv.github.io/deepinv/_sources/auto_examples/external-libraries/demo_io.rst.txt This snippet shows how to load a raster file from a URL and stream it in patches using `deepinv.utils.io.load_raster`. It requires the `rasterio` library to be installed. The `patch` argument specifies the size of each patch, and `patch_start` defines the starting coordinates for patching. ```Python patches = dinv.utils.io.load_raster( dinv.utils.io.load_url( "https://download.osgeo.org/geotiff/samples/spot/chicago/SP27GTIF.TIF" ), patch=500, patch_start=(200, 200), ) x = next(patches) # Stream patch dinv.utils.plot({"raster": x.unsqueeze(0)}) ``` -------------------------------- ### Quick Start: Distributed Computing Workflow Source: https://deepinv.github.io/deepinv/user_guide/reconstruction/distributed.html This example demonstrates the complete workflow for distributed computing in DeepINV. It shows how to set up a distributed context, distribute physics operators, denoisers, and data fidelity terms, and then use them for reconstruction. Ensure the image is loaded onto the correct device managed by the distributed context. ```python from deepinv.physics import Blur, stack from deepinv.physics.blur import gaussian_blur from deepinv.optim.data_fidelity import L2 from deepinv.models import DRUNet from deepinv.distributed import DistributedContext, distribute from deepinv.utils.demo import load_example # Step 1: Create distributed context with DistributedContext() as ctx: # Load an example image x = load_example( "CBSD_0010.png", grayscale=False, device=str(ctx.device) # Make sure the image is on the correct device ) # Step 2: Create and stack your physics operators physics_list = [ Blur( filter=gaussian_blur(sigma=1.0), padding="circular" ), Blur( filter=gaussian_blur(sigma=2.0), padding="circular" ), Blur( filter=gaussian_blur(sigma=3.0), padding="circular" ), ] stacked_physics = stack(*physics_list) # Step 3: Distribute physics distributed_physics = distribute(stacked_physics, ctx) # Distribute physics operators, transfers to correct devices # Use it like regular physics y = distributed_physics(x) # Forward operation x_adj = distributed_physics.A_adjoint(y) # Adjoint # Step 4: Distribute a denoiser for large images denoiser = DRUNet() distributed_denoiser = distribute( denoiser, ctx, patch_size=256, # Split image into patches overlap=64, # Overlap for smooth blending ) # Use it like regular denoiser denoised = distributed_denoiser(x_adj, sigma=0.1) # Step 5: Distribute a data fidelity term data_fidelity = L2() distributed_data_fidelity = distribute(data_fidelity, ctx) # Use it like regular data fidelity loss = distributed_data_fidelity.fn(denoised, y, distributed_physics) # Step 6: debug and print on rank 0 only if ctx.rank == 0: print("Distributed physics output shape:", y.shape) print("Distributed physics adjoint output shape:", x_adj.shape) print("Distributed denoiser output shape:", denoised.shape) print(f"Distributed data fidelity loss: {loss.item():.6f}") ``` ```text Distributed physics output shape: [torch.Size([1, 3, 481, 321]), torch.Size([1, 3, 481, 321]), torch.Size([1, 3, 481, 321])] Distributed physics adjoint output shape: torch.Size([1, 3, 481, 321]) Distributed denoiser output shape: torch.Size([1, 3, 481, 321]) Distributed data fidelity loss: ... ``` -------------------------------- ### Setup paths and device Source: https://deepinv.github.io/deepinv/_downloads/8951ca8fee4e9b4ca466202eee01392f/demo_unfolded_constrained_LISTA.ipynb Configures base directories for data and checkpoints, sets the random seed for reproducibility, and determines the computation device (CPU or GPU). ```python BASE_DIR = Path(".") DATA_DIR = BASE_DIR / "measurements" CKPT_DIR = BASE_DIR / "ckpts" # Set the global random seed from pytorch to ensure reproducibility of the example. torch.manual_seed(0) device = dinv.utils.get_device() ``` -------------------------------- ### Install DeepInverse with uv Source: https://deepinv.github.io/deepinv/_sources/auto_examples/basics/demo_quickstart.rst.txt Install the latest stable release of deepinv using uv. uv is a fast Python package installer and resolver. ```bash uv pip install deepinv ``` -------------------------------- ### Initialize Project and Install DeepInverse with Pixi (Stable Release) Source: https://deepinv.github.io/deepinv/index.html Initialize a new project with pixi and add the deepinv package. This ensures a reproducible environment. ```bash pixi init && pixi add python pixi add --pypi deepinv ``` -------------------------------- ### Import Libraries and Setup Source: https://deepinv.github.io/deepinv/_downloads/9df1cf2e94dc0725a73bf7d3d2a8ee90/demo_splitting_loss.ipynb Imports necessary libraries including PyTorch, torchvision, and deepinv utilities. Sets up manual seed, device, and directory paths for data and cache. ```python from pathlib import Path import torch from torch.utils.data import DataLoader from torchvision import transforms, datasets import deepinv as dinv from deepinv.utils import get_cache_home from deepinv.models.utils import get_weights_url torch.manual_seed(0) device = dinv.utils.get_device() BASE_DIR = Path(".") DATA_DIR = BASE_DIR / "measurements" ORIGINAL_DATA_HOME = get_cache_home() / "datasets" / "MNIST" ``` -------------------------------- ### Initialize DeepInverse and Device Source: https://deepinv.github.io/deepinv/_downloads/3438ffeaadf39bb93e9392a88bccb8fd/demo_lowfieldmri.ipynb Import necessary libraries and get the computation device. ```python import torch import deepinv as dinv device = dinv.utils.get_device() ``` -------------------------------- ### Minimal Working Docstring Example for DeepINV Class Source: https://deepinv.github.io/deepinv/contributing.html This example demonstrates a typical docstring for a DeepINV class, including mathematical equations, notes, usage examples, and parameter descriptions using reStructuredText. ```python class MyDenoiser: r""" Denoiser denoiser from the paper :footcite:t:`my_paper`. .. math:: y = \D_\sigma{x + \sigma \omega} .. note:: This is a note. |sep| :Example: >>> import torch >>> import deepinv as dinv >>> model = dinv.models.DRUNet() >>> x = torch.ones((1, 3, 8, 8)) >>> y = model(x, sigma=0.01) :param int in_channels: number of input channels. :param int out_channels: number of output channels. :param str pretrained: path to pretrained weights or 'download'. """ def __init__(self, in_channels: int, out_channels: int, pretrained: bool = None): pass ```