### Install MRpro
Source: https://github.com/ptb-mr/mrpro/blob/main/docs/source/user_guide.rst
Provides instructions for installing the MRpro package using pip, including options for installing additional dependencies for notebooks and installing directly from GitHub.
```bash
pip install mrpro
```
```bash
pip install mrpro[notebooks]
```
```bash
pip install "git+https://github.com/PTB-MR/mrpro"
```
--------------------------------
### Install mrpro
Source: https://github.com/ptb-mr/mrpro/blob/main/examples/notebooks/comparison_trajectory_calculators.ipynb
Installs the mrpro library with notebook support if it's not already found.
```python
import importlib
if not importlib.util.find_spec('mrpro'):
%pip install mrpro[notebooks]
```
--------------------------------
### Install MRPRO
Source: https://github.com/ptb-mr/mrpro/blob/main/examples/notebooks/pgd_wavelet_reconstruction.ipynb
Installs the MRPRO library with support for notebooks. This is a prerequisite for running the reconstruction examples.
```python
import importlib
if not importlib.util.find_spec('mrpro'):
%pip install mrpro[notebooks]
```
--------------------------------
### Install Development Dependencies
Source: https://github.com/ptb-mr/mrpro/blob/main/docs/source/contributor_guide.rst
Installs MRpro along with development dependencies required for testing and linting.
```shell
pip install -e .[dev]
```
--------------------------------
### Install MRpro
Source: https://github.com/ptb-mr/mrpro/blob/main/examples/notebooks/cartesian_reconstruction.ipynb
Installs the MRpro library with support for notebooks if it's not already found.
```python
import importlib
if not importlib.util.find_spec('mrpro'):
%pip install mrpro[notebooks]
```
--------------------------------
### Install Testing Dependencies
Source: https://github.com/ptb-mr/mrpro/blob/main/docs/source/contributor_guide.rst
Installs MRpro along with dependencies specifically required for running tests.
```shell
pip install -e .[tests]
```
--------------------------------
### Install mrpro
Source: https://github.com/ptb-mr/mrpro/blob/main/examples/notebooks/qmri_t1_mapping_with_grad_acq.ipynb
Installs the mrpro library with notebook support if it's not already found. This is a prerequisite for running the example.
```python
import importlib
if not importlib.util.find_spec('mrpro'):
%pip install mrpro[notebooks]
```
--------------------------------
### Install mrpro
Source: https://github.com/ptb-mr/mrpro/blob/main/examples/notebooks/tv_minimization_reconstruction_pdhg.ipynb
Installs the 'mrpro' library with notebook support if it's not already found. This is a prerequisite for running the reconstruction examples.
```python
import importlib
if not importlib.util.find_spec('mrpro'):
%pip install mrpro[notebooks]
```
--------------------------------
### Pre-commit Hooks Installation
Source: https://github.com/ptb-mr/mrpro/blob/main/docs/source/contributor_guide.rst
Installs git pre-commit hooks to ensure code quality checks are performed before each commit.
```shell
pre-commit install
```
--------------------------------
### Install mrpro
Source: https://github.com/ptb-mr/mrpro/blob/main/examples/notebooks/qmri_cardiac_fingerprinting.ipynb
Installs the mrpro library with notebook support if it's not already found. This is a prerequisite for running the rest of the notebook.
```python
import importlib
if not importlib.util.find_spec('mrpro'):
%pip install mrpro[notebooks]
```
--------------------------------
### Setup Pre-commit Hook
Source: https://github.com/ptb-mr/mrpro/blob/main/README.md
Installs the pre-commit framework, which helps automate the process of checking code style and quality before commits. This ensures code consistency across the project.
```shell
pre-commit install
```
--------------------------------
### Build Documentation Locally
Source: https://github.com/ptb-mr/mrpro/blob/main/docs/source/contributor_guide.rst
Builds the project documentation locally using make in the docs directory.
```shell
make html
```
--------------------------------
### Download Data and Initialize mrpro
Source: https://github.com/ptb-mr/mrpro/blob/main/examples/notebooks/comparison_trajectory_calculators.ipynb
Downloads necessary raw data from Zenodo and initializes the mrpro library for use. It utilizes a temporary directory for data storage.
```python
# Download raw data from Zenodo
import tempfile
from pathlib import Path
import mrpro
import torch
import zenodo_get
tmp = tempfile.TemporaryDirectory() # RAII, automatically cleaned up
data_folder = Path(tmp.name)
zenodo_get.download(record='14617082', retry_attempts=5, output_dir=data_folder)
```
--------------------------------
### Install mrpro
Source: https://github.com/ptb-mr/mrpro/blob/main/examples/notebooks/iterative_sense_reconstruction_radial2D.ipynb
Installs the mrpro library with support for notebooks if it's not already installed.
```python
import importlib
if not importlib.util.find_spec('mrpro'):
%pip install mrpro[notebooks]
```
--------------------------------
### Install mrpro
Source: https://github.com/ptb-mr/mrpro/blob/main/examples/notebooks/iterative_sense_reconstruction_with_regularization.ipynb
Installs the mrpro library with support for notebooks if it's not already found.
```python
import importlib
if not importlib.util.find_spec('mrpro'):
%pip install mrpro[notebooks]
```
--------------------------------
### Download Example Data
Source: https://github.com/ptb-mr/mrpro/blob/main/examples/notebooks/cartesian_reconstruction.ipynb
Downloads ISMRMRD raw data files (.mrd) from Zenodo for Cartesian acquisition examples.
```python
# Get the raw data from zenodo
import tempfile
from pathlib import Path
import zenodo_get
tmp = tempfile.TemporaryDirectory() # RAII, automatically cleaned up
data_folder = Path(tmp.name)
zenodo_get.download(record='15223816', retry_attempts=5, output_dir=data_folder, file_glob=('*.mrd',))
```
--------------------------------
### PEP 8 Naming Convention
Source: https://github.com/ptb-mr/mrpro/blob/main/docs/source/contributor_guide.rst
Highlights adherence to PEP 8 for naming conventions.
```markdown
We try to follow the `PEP 8 `_ naming convention (e.g., all lowercase variable names, CapWords class names).
```
--------------------------------
### VS Code Ruff Extension
Source: https://github.com/ptb-mr/mrpro/blob/main/docs/source/contributor_guide.rst
Recommends the Ruff extension for VS Code for linting.
```markdown
See `extension `_.
```
--------------------------------
### Install mrpro
Source: https://github.com/ptb-mr/mrpro/blob/main/examples/notebooks/qmri_sg_challenge_2024_t1.ipynb
Installs the mrpro library with notebook support if it's not already found. This is a prerequisite for running the subsequent code.
```python
import importlib
if not importlib.util.find_spec('mrpro'):
%pip install mrpro[notebooks]
```
--------------------------------
### MRpro KData Indexing Example
Source: https://github.com/ptb-mr/mrpro/blob/main/docs/source/data.rst
Demonstrates how to load KData from a file and print its shape, illustrating the indexing and dimension conventions used in MRpro.
```python
import mrpro
# Example: Indexing a broadcasted tensor
kdata = mrpro.data.KData.from_file('example.mrd')
print(kdata.shape) # Example shape: (4, 8, 64, 64, 128)
```
--------------------------------
### Install mrpro for Notebooks
Source: https://github.com/ptb-mr/mrpro/blob/main/examples/notebooks/direct_reconstruction.ipynb
Installs the mrpro library with the 'notebooks' extra, which is necessary for using mrpro in a Jupyter Notebook environment. This command checks if mrpro is already installed and installs it if not.
```python
import importlib
if not importlib.util.find_spec('mrpro'):
%pip install mrpro[notebooks]
```
--------------------------------
### Manual Pre-commit Execution
Source: https://github.com/ptb-mr/mrpro/blob/main/docs/source/contributor_guide.rst
Manually runs all pre-commit checks on all files in the repository.
```shell
pre-commit run --all-files
```
--------------------------------
### Jupytext Usage for Notebook Conversion
Source: https://github.com/ptb-mr/mrpro/blob/main/docs/source/contributor_guide.rst
Demonstrates the use of jupytext for converting Python scripts to Jupyter notebooks and vice versa.
```markdown
See `jupytext `_ documentation for more details.
```
--------------------------------
### Setup Python Environment
Source: https://github.com/ptb-mr/mrpro/blob/main/README.md
Creates a new Conda environment named 'mrpro' with Python 3.12 installed. This is a prerequisite for setting up the development environment.
```shell
conda create -n mrpro python=3.12
```
--------------------------------
### Install MRpro with Developer Dependencies
Source: https://github.com/ptb-mr/mrpro/blob/main/README.md
Installs the MRpro package in editable mode, including all necessary developer dependencies. This command is essential for making and testing changes to the project.
```shell
pip install -e ".[dev]"
```
--------------------------------
### Download Example Data
Source: https://github.com/ptb-mr/mrpro/blob/main/examples/notebooks/pgd_wavelet_reconstruction.ipynb
Downloads the necessary raw data files (k-space data with trajectory information) from Zenodo using the zenodo_get library. This data is required for the image reconstruction.
```python
# ### Download raw data from Zenodo
import tempfile
from pathlib import Path
import zenodo_get
tmp = tempfile.TemporaryDirectory() # RAII, automatically cleaned up
data_folder = Path(tmp.name)
zenodo_get.download(record='14617082', retry_attempts=5, output_dir=data_folder)
```
--------------------------------
### Display Comparison of Reconstructions
Source: https://github.com/ptb-mr/mrpro/blob/main/examples/notebooks/comparison_trajectory_calculators.ipynb
Calls the show_images function to display the images reconstructed using the three different trajectory methods, with corresponding titles for identification.
```python
show_images(
img_using_ismrmrd_traj.rss()[0, 0],
img_using_rad2d_traj.rss()[0, 0],
img_using_pulseq_traj.rss()[0, 0],
titles=['KTrajectoryIsmrmrd', 'KTrajectoryRadial2D', 'KTrajectoryPulseq'],
)
```
--------------------------------
### Load and Explore KData
Source: https://github.com/ptb-mr/mrpro/blob/main/examples/notebooks/cartesian_reconstruction.ipynb
Loads ISMRMRD data using mrpro.data.KData and a Cartesian trajectory calculator, then prints basic information.
```python
import mrpro
kdata = mrpro.data.KData.from_file(
data_folder / 'cart_t1.mrd',
mrpro.data.traj_calculators.KTrajectoryCartesian(),
)
print(kdata)
```
--------------------------------
### Initial Parameter Setup for LBFGS Optimization
Source: https://github.com/ptb-mr/mrpro/blob/main/examples/notebooks/qmri_t1_mapping_with_grad_acq.ipynb
Sets up initial parameters for the LBFGS optimizer, including equilibrium magnetization (M0), T1 relaxation time, and flip angle, using provided dynamic images and header information.
```python
m0_start = img_rss_dynamic[0]
t1_start = torch.ones_like(m0_start)
flip_angle_start = torch.ones_like(m0_start) * torch.as_tensor(kdata_dynamic.header.fa)
```
--------------------------------
### Python Script with Code Cells
Source: https://github.com/ptb-mr/mrpro/blob/main/docs/source/contributor_guide.rst
Illustrates the format for Python scripts intended for conversion to notebooks, using specific comment markers for code and markdown cells.
```python
# %% Individual cells should be indicated with ``# %%``.
# %% [markdown] For markdown cells use ``# %% [markdown]``.
```
--------------------------------
### MRpro Acquisition Model Operators
Source: https://github.com/ptb-mr/mrpro/blob/main/docs/source/user_guide.rst
Illustrates how to build an acquisition model in MRpro by chaining operators like `SensitivityOp` and `FourierOp`. These operators describe the physical processes involved in MR imaging and can be combined to form a complete model.
```python
import mrpro.operators
# Example: Create a sensitivity operator and a Fourier operator
# Assuming 'sensitivity_maps' and 'trajectory' are defined
sensitivity_op = mrpro.operators.SensitivityOp(sensitivity_maps)
# Assuming 'encoding_matrix' is defined
fourier_op = mrpro.operators.FourierOp(encoding_matrix, trajectory)
# Chain operators to form an acquisition model
acquisition_model = sensitivity_op @ fourier_op
# Operators also support addition, multiplication, etc.
```
--------------------------------
### Fourier Operator Setup
Source: https://github.com/ptb-mr/mrpro/blob/main/examples/notebooks/direct_reconstruction.ipynb
Sets up the Fourier operator by specifying the reconstruction matrix, encoding matrix, and trajectory.
```python
fourier_operator = mrpro.operators.FourierOp(
recon_matrix=kdata.header.recon_matrix,
encoding_matrix=kdata.header.encoding_matrix,
traj=kdata.traj,
)
```
--------------------------------
### SpatialDimension and Rotation in MRPRO
Source: https://github.com/ptb-mr/mrpro/blob/main/docs/source/data.rst
This example demonstrates the creation and usage of `SpatialDimension` and `Rotation` objects from the `mrpro.data` module. It shows how to define a position and a rotation, and then apply the rotation to the position.
```python
# Example: Creating and using SpatialDimension and Rotation
position = mrpro.data.SpatialDimension(z=3, y=2, x=1)
rotation = mrpro.data.Rotation.from_euler("xyz", (0,0,torch.pi))
rotated = rotation(position)
```
--------------------------------
### Create and Use FastFourierOp
Source: https://github.com/ptb-mr/mrpro/blob/main/examples/notebooks/cartesian_reconstruction.ipynb
Demonstrates the creation of a FastFourierOp for image reconstruction and its adjoint application to k-space data. It also shows how to combine coil data using root-sum-of-squares and display the resulting image.
```python
import mrpro.operators
import mrpro.data
# Assuming kdata is loaded and available
# kdata = mrpro.data.KData.from_file(...)
fft_op = mrpro.operators.FastFourierOp(
dim=(-2, -1),
recon_matrix=kdata.header.recon_matrix,
encoding_matrix=kdata.header.encoding_matrix,
)
(img,) = fft_op.adjoint(kdata.data)
print('Shape:', img.shape)
```
```python
import matplotlib.pyplot as plt
import torch
def show_images(*images: torch.Tensor, titles: list[str] | None = None) -> None:
"""Plot images."""
n_images = len(images)
_, axes = plt.subplots(1, n_images, squeeze=False, figsize=(n_images * 3, 3))
for i in range(n_images):
axes[0][i].imshow(images[i], cmap='gray', vmin=0, vmax=images[i].max() * 0.6)
axes[0][i].axis('off')
if titles:
axes[0][i].set_title(titles[i])
plt.show()
# Combine data from different coils using root-sum-of-squares
# Assuming 'img' is the reconstructed image from the previous step
# magnitude_fully_sampled = img.abs().square().sum(dim=-4).sqrt().squeeze()
# show_images(magnitude_fully_sampled)
```
--------------------------------
### Download and Display Scanner DICOM Image
Source: https://github.com/ptb-mr/mrpro/blob/main/examples/notebooks/cartesian_reconstruction.ipynb
Downloads a sample DICOM image from a Zenodo record and loads it using IData. This is used for comparison with MRpro reconstructions.
```python
# Download dicom image
zenodo_get.download(record='15223816', retry_attempts=5, output_dir=data_folder, file_glob=('*.dcm',))
idat_dcm = mrpro.data.IData.from_dicom_files(data_folder / 'cart_t1_msense_integrated.dcm')
```
--------------------------------
### DirectReconstruction Algorithm
Source: https://github.com/ptb-mr/mrpro/blob/main/examples/notebooks/cartesian_reconstruction.ipynb
Demonstrates the use of the DirectReconstruction algorithm, a high-level function that simplifies the reconstruction process by operating directly on KData objects. It handles all underlying operator steps automatically.
```python
# Create DirectReconstruction object from KData object
direct_recon_pe_pf = mrpro.algorithms.reconstruction.DirectReconstruction(kdata_pe_pf)
# Reconstruct image by calling the DirectReconstruction object
idat_pe_pf = direct_recon_pe_pf(kdata_pe_pf)
```
--------------------------------
### Reconstruction using KTrajectoryPulseq
Source: https://github.com/ptb-mr/mrpro/blob/main/examples/notebooks/comparison_trajectory_calculators.ipynb
Loads k-space data and calculates the trajectory by parsing a PyPulseq sequence file. This method is suitable when the acquisition sequence details are available in a .seq file.
```python
# Read raw data and calculate trajectory using KTrajectoryPulseq
seq_path = data_folder / 'radial2D_402spokes_golden_angle.seq'
kdata = mrpro.data.KData.from_file(
data_folder / 'radial2D_402spokes_golden_angle_with_traj.h5',
mrpro.data.traj_calculators.KTrajectoryPulseq(seq_path),
)
# Reconstruct image
reconstruction = mrpro.algorithms.reconstruction.DirectReconstruction(kdata)
img_using_pulseq_traj = reconstruction(kdata)
```
--------------------------------
### MRpro Reconstruction Algorithms
Source: https://github.com/ptb-mr/mrpro/blob/main/docs/source/user_guide.rst
Highlights the use of reconstruction algorithms provided by MRpro, such as `RegularizedIterativeSENSEReconstruction`. It also mentions the flexibility to create custom reconstruction algorithms using the provided building blocks and optimizers.
```python
import mrpro.algorithms.reconstruction
import mrpro.algorithms.optimizers
# Example: Using a high-level reconstruction function
# Assuming 'acquisition_model', 'kdata', 'image_data' are defined
# recon_result = mrpro.algorithms.reconstruction.RegularizedIterativeSENSEReconstruction(acquisition_model, kdata, image_data, optimizer=...)
# Or building a custom reconstruction using optimizers and operators
```
--------------------------------
### Reconstruction of Undersampled Data
Source: https://github.com/ptb-mr/mrpro/blob/main/examples/notebooks/cartesian_reconstruction.ipynb
Applies the DirectReconstruction algorithm to undersampled k-space data loaded from a file. This showcases the algorithm's ability to handle data with reduced sampling.
```python
kdata_us = mrpro.data.KData.from_file(
data_folder / 'cart_t1_msense_integrated.mrd',
mrpro.data.traj_calculators.KTrajectoryCartesian(),
)
direct_recon_us = mrpro.algorithms.reconstruction.DirectReconstruction(kdata_us)
idat_us = direct_recon_us(kdata_us)
show_images(idat_pe_pf.rss().squeeze(), idat_us.rss().squeeze(), titles=['PE & PF', 'Undersampled'])
```
--------------------------------
### Wavelet Operator Setup
Source: https://github.com/ptb-mr/mrpro/blob/main/examples/notebooks/pgd_wavelet_reconstruction.ipynb
Defines the acquisition operator $\tilde{A}$ which combines Fourier transform, coil sensitivity maps, and the adjoint of a wavelet operator. This is a crucial step for wavelet-based reconstruction.
```python
fourier_operator = direct_reconstruction_24.fourier_op
assert direct_reconstruction_24.csm is not None
csm_operator = direct_reconstruction_24.csm.as_operator()
# Define the wavelet operator
wavelet_operator = mrpro.operators.WaveletOp(
domain_shape=img_direct_24.data.shape[-2:], dim=(-2, -1), wavelet_name='db4', level=None
)
# Create the full acquisition operator $\tilde{A}$ including the adjoint of the wavelet operator
acquisition_operator = fourier_operator @ csm_operator @ wavelet_operator.H
```
--------------------------------
### Operator Composition for Simplified Reconstruction
Source: https://github.com/ptb-mr/mrpro/blob/main/examples/notebooks/cartesian_reconstruction.ipynb
Shows how to compose multiple operators (FourierOp and SensitivityOp) into a single composite operator for a more streamlined reconstruction process. The adjoint of the composite operator is then applied.
```python
### Operator Composition
# Create composite operator
adjoint_operator = (fourier_op @ csm_op).H
(magnitude_pe_pf,) = adjoint_operator(kdata_pe_pf.data)
magnitude_pe_pf = magnitude_pe_pf.abs().squeeze()
show_images(magnitude_pe_pf, titles=['PF & PE'])
```
--------------------------------
### Reconstruction using KTrajectoryRadial2D
Source: https://github.com/ptb-mr/mrpro/blob/main/examples/notebooks/comparison_trajectory_calculators.ipynb
Loads k-space data and calculates the trajectory using the KTrajectoryRadial2D calculator, which requires parameters like the angle between spokes. This is useful for standard radial trajectories.
```python
# Read raw data and calculate trajectory using KTrajectoryRadial2D
golden_angle = torch.pi * 0.618034
kdata = mrpro.data.KData.from_file(
data_folder / 'radial2D_402spokes_golden_angle_with_traj.h5',
mrpro.data.traj_calculators.KTrajectoryRadial2D(golden_angle),
)
# Reconstruct image
reconstruction = mrpro.algorithms.reconstruction.DirectReconstruction(kdata)
img_using_rad2d_traj = reconstruction(kdata)
```
--------------------------------
### Compare MRpro and Scanner Reconstructions
Source: https://github.com/ptb-mr/mrpro/blob/main/examples/notebooks/cartesian_reconstruction.ipynb
Compares the reconstructed image from MRpro (Iterative SENSE) with the scanner's reconstruction by displaying both side-by-side. This highlights differences and potential areas for improvement.
```python
show_images(idat_us_sense.rss().squeeze(), torch.fliplr(idat_dcm.rss().squeeze()), titles=['MRpro', 'Scanner'])
```
--------------------------------
### Project Dependencies
Source: https://github.com/ptb-mr/mrpro/blob/main/docker/minimal_requirements.txt
This snippet lists the core Python dependencies required for the MRPRO project. It includes specific version numbers for each package, ensuring compatibility and reproducibility. The extra index URL is crucial for installing the CPU version of PyTorch.
```python
torch==2.3.1+cpu
torchvision==0.18.1+cpu
numpy==1.23
ismrmrd==1.14.1
einops==0.7.0
pydicom==3.0.1
pypulseq==1.4.2
pytorch-finufft==0.1.0
cufinufft==2.3.1
scipy==1.12
ptwt==0.1.8
tqdm==4.60.0
typing-extensions==4.12
platformdirs==4.0
requests==2.25
--extra-index-url https://download.pytorch.org/whl/cpu
```
--------------------------------
### MRpro Data Reading
Source: https://github.com/ptb-mr/mrpro/blob/main/docs/source/user_guide.rst
Demonstrates how to read raw MR data from an MRD file using `mrpro.data.KData.from_file`. This involves creating a `KData` object and providing a `KTrajectoryCalculator` for accurate trajectory calculation.
```python
import mrpro.data
# Assuming 'mrd_file_path' is the path to your MRD file
kdata = mrpro.data.KData.from_file(mrd_file_path, traj_calculator=...) # Provide an appropriate trajectory calculator
```
--------------------------------
### MRpro Operators
Source: https://github.com/ptb-mr/mrpro/blob/main/docs/source/user_guide.rst
Lists the types of operators available in `mrpro.operators` for preparing data for reconstruction. This includes noise prewhiting, oversampling removal, density compensation, coil sensitivity estimation, and Fourier transformation.
```APIDOC
MRpro Operators (`mrpro.operators`):
Functionality:
- Noise prewhiting
- Removal of oversampling along readout direction
- Calculation of the density compensation function
- Estimation of coil sensitivity maps
- Fourier transformation
Usage:
- Operators are implemented as `torch.nn.Module`.
- Take one or more tensors as input and return a tuple of one or more tensors.
- Can be chained using '@' to form acquisition models.
- Support addition, multiplication, etc. between operators.
```
--------------------------------
### Visualize Starting Values
Source: https://github.com/ptb-mr/mrpro/blob/main/examples/notebooks/qmri_sg_challenge_2024_t1.ipynb
Generates plots for the initial values of M0 and T1 using matplotlib. It displays M0 and T1 images with colorbars and sets appropriate titles.
```python
import matplotlib.pyplot as plt
from matplotlib.colors import Colormap
# Assuming m0_start, t1_start, and plt are defined elsewhere
# fig, axes = plt.subplots(1, 2, figsize=(6, 2), squeeze=False)
# im = axes[0, 0].imshow(m0_start[0, 0])
# axes[0, 0].set_title('$M_0$ start values')
# axes[0, 0].set_axis_off()
# fig.colorbar(im, ax=axes[0, 0], label='a.u.')
# im = axes[0, 1].imshow(t1_start[0, 0], vmin=0, vmax=2.5, cmap=Colormap('lipari').to_mpl())
# axes[0, 1].set_title('$T_1$ start values')
# axes[0, 1].set_axis_off()
# fig.colorbar(im, ax=axes[0, 1], label='s')
# plt.show()
```
--------------------------------
### Problem Setup for FISTA
Source: https://github.com/ptb-mr/mrpro/blob/main/examples/notebooks/pgd_wavelet_reconstruction.ipynb
Defines the objective functional $f(\tilde{x})$ and the regularization term $g(\tilde{x})$ for the FISTA algorithm. $f$ is based on the L2 norm of the difference between the acquired data and the forward model, while $g$ is an L1 norm for sparsity in the wavelet domain.
```python
# Regularization parameter for the $\ell_1$-norm
regularization_parameter = 1e-5
# Set up the problem by using the previously described identification
l2 = 0.5 * mrpro.operators.functionals.L2NormSquared(target=kdata_24spokes.data, divide_by_n=False)
l1 = mrpro.operators.functionals.L1NormViewAsReal(divide_by_n=False)
f = l2 @ acquisition_operator
g = regularization_parameter * l1
```
--------------------------------
### Apply CartesianSamplingOp for Undersampled Data
Source: https://github.com/ptb-mr/mrpro/blob/main/examples/notebooks/cartesian_reconstruction.ipynb
Demonstrates the use of the CartesianSamplingOp to correctly sort k-space data acquired with asymmetric sampling (partial echo and partial Fourier). This operator ensures data is arranged correctly before applying the FFT, leading to accurate reconstructions.
```python
import mrpro.operators
# Assuming kdata_pe_pf is loaded and available
cart_sampling_op = mrpro.operators.CartesianSamplingOp(
encoding_matrix=kdata_pe_pf.header.encoding_matrix,
traj=kdata_pe_pf.traj
)
# Assuming fft_op and kdata_pe_pf.data are available
# (img_pe_pf,) = fft_op.adjoint(cart_sampling_op.adjoint(kdata_pe_pf.data)[0])
# magnitude_pe_pf = img_pe_pf.abs().square().sum(dim=-4).sqrt().squeeze()
# Assuming show_images and magnitude_fully_sampled are available
# show_images(magnitude_fully_sampled, magnitude_pe_pf, titles=['fully sampled', 'PF & PE'])
```
--------------------------------
### Run CUDA Tests with Pytest
Source: https://github.com/ptb-mr/mrpro/blob/main/docs/source/contributor_guide.rst
Executes tests that require CUDA capabilities, typically on machines with a GPU.
```shell
pytest -m cuda
```
--------------------------------
### Check Reconstructed Image Shape
Source: https://github.com/ptb-mr/mrpro/blob/main/examples/notebooks/cartesian_reconstruction.ipynb
Prints the shape of the reconstructed image tensor, showing dimensions for spatial resolution and coils.
```python
print('Shape:', img.shape)
```
--------------------------------
### Download Raw Data
Source: https://github.com/ptb-mr/mrpro/blob/main/examples/notebooks/tv_minimization_reconstruction_pdhg.ipynb
Downloads the necessary raw k-space data files from Zenodo using the 'zenodo_get' library. These files contain k-space data and trajectory information required for reconstruction.
```python
# Download raw data from Zenodo
import tempfile
from pathlib import Path
import zenodo_get
tmp = tempfile.TemporaryDirectory() # RAII, automatically cleaned up
data_folder = Path(tmp.name)
zenodo_get.download(record='14617082', retry_attempts=5, output_dir=data_folder)
```
--------------------------------
### Access Header Information
Source: https://github.com/ptb-mr/mrpro/blob/main/examples/notebooks/cartesian_reconstruction.ipynb
Retrieves and prints specific header information, such as the proton Lamor frequency, from the loaded KData object.
```python
print('Lamor Frequency:', kdata.header.lamor_frequency_proton)
```
--------------------------------
### Display Calibration Image
Source: https://github.com/ptb-mr/mrpro/blob/main/examples/notebooks/cartesian_reconstruction.ipynb
Displays the reconstructed image from the calibration lines. This image is typically low-resolution but sufficient for deriving coil sensitivity maps.
```python
show_images(idat_calib_lines.rss().squeeze(), titles=['Calibration Image'])
```
--------------------------------
### Reconstruction Comparison Visualization
Source: https://github.com/ptb-mr/mrpro/blob/main/examples/notebooks/pgd_wavelet_reconstruction.ipynb
This code snippet visualizes the results of different image reconstruction methods: direct reconstruction with 402 spokes, direct reconstruction with 24 spokes, SENSE reconstruction with 24 spokes, and PGD reconstruction with 24 spokes using wavelets. It relies on the `show_images` function defined elsewhere.
```python
# see the collapsed cell above for the implementation of show_images
show_images(
img_direct_402.rss().squeeze(),
img_direct_24.rss().squeeze(),
img_sense_24.rss().squeeze(),
img_pgd_24.abs().squeeze(),
titles=['402 spokes', '24 spokes (Direct)', '24 spokes (SENSE)', '24 spokes (PGD)'],
)
```
--------------------------------
### MRpro Trajectory Calculators
Source: https://github.com/ptb-mr/mrpro/blob/main/docs/source/user_guide.rst
Describes the role of `mrpro.data.traj_calculators.KTrajectoryCalculator` in MRpro for calculating k-space trajectories. Trajectories can be calculated internally, read from MRD, or derived from pulseq files.
```APIDOC
MRpro Trajectory Calculators (`mrpro.data.traj_calculators`):
Purpose:
- Calculate k-space trajectories for accurate data processing.
Integration:
- Required when creating `mrpro.data.KData` objects using `from_file`.
Sources:
- MRpro internal calculations (e.g., 2D radial sampling).
- Reading from MRD files.
- Calculation from `pulseq` files.
Reference:
- See `mrpro.data.traj_calculators` for available calculators.
- See `:doc:_notebooks/comparison_trajectory_calculators` for examples.
```
--------------------------------
### Initialize Signal Model
Source: https://github.com/ptb-mr/mrpro/blob/main/examples/notebooks/qmri_t1_mapping_with_grad_acq.ipynb
Initializes the TransientSteadyStateWithPreparation signal model with calculated sampling time, repetition time, and a fixed delay after preparation. M0 scaling is set to -1.
```python
model_op = mrpro.operators.models.TransientSteadyStateWithPreparation(
sampling_time, repetition_time, m0_scaling_preparation=-1, delay_after_preparation=0.02
)
```
--------------------------------
### MRpro API Modules
Source: https://github.com/ptb-mr/mrpro/blob/main/docs/source/api.rst
This section outlines the main modules available in the MRpro API. It provides a high-level overview of the project's structure and the areas covered by the documentation, including algorithms, data structures, operators, phantoms, and utility functions.
```APIDOC
mrpro.algorithms
- Documentation for various algorithms used within MRpro.
mrpro.data
- Documentation related to data structures and handling.
mrpro.operators
- Documentation for operators and their functionalities.
mrpro.phantoms
- Documentation for phantom data and generation.
mrpro.utils
- Documentation for utility functions and helpers.
```
--------------------------------
### Reconstruct Image with FFT
Source: https://github.com/ptb-mr/mrpro/blob/main/examples/notebooks/cartesian_reconstruction.ipynb
Applies a Fast Fourier Transform (FFT) operator to the k-space data to reconstruct an image. Note that MRpro operators work on PyTorch tensors.
```python
fft_op = mrpro.operators.FastFourierOp(dim=(-2, -1))
(img,) = fft_op.adjoint(kdata.data)
```
--------------------------------
### Download Raw Data
Source: https://github.com/ptb-mr/mrpro/blob/main/examples/notebooks/qmri_t1_mapping_with_grad_acq.ipynb
Downloads the necessary raw data in ISMRMRD format from Zenodo to a temporary directory. This data is required for the subsequent reconstruction steps.
```python
# Download raw data in ISMRMRD format from zenodo into a temporary directory
import tempfile
from pathlib import Path
import zenodo_get
tmp = tempfile.TemporaryDirectory() # RAII, automatically cleaned up
data_folder = Path(tmp.name)
zenodo_get.download(record='13207352', retry_attempts=5, output_dir=data_folder)
```
--------------------------------
### Plot Reconstructed Images
Source: https://github.com/ptb-mr/mrpro/blob/main/examples/notebooks/comparison_trajectory_calculators.ipynb
A utility function to display multiple images using matplotlib, allowing for visual comparison of reconstructions obtained from different trajectory calculation methods.
```python
import matplotlib.pyplot as plt
import torch
def show_images(*images: torch.Tensor, titles: list[str] | None = None) -> None:
"""Plot images."""
n_images = len(images)
_, axes = plt.subplots(1, n_images, squeeze=False, figsize=(n_images * 3, 3))
for i in range(n_images):
axes[0][i].imshow(images[i], cmap='gray')
axes[0][i].axis('off')
if titles:
axes[0][i].set_title(titles[i])
plt.show()
```
--------------------------------
### Initialize DirectReconstruction
Source: https://github.com/ptb-mr/mrpro/blob/main/examples/notebooks/direct_reconstruction.ipynb
Creates an instance of the DirectReconstruction class from the mrpro library. The instance is initialized with the loaded k-space data (kdata), which it uses to set up internal components like the Fourier transform, density compensation factors, and coil sensitivity maps.
```python
import mrpro
reconstruction = mrpro.algorithms.reconstruction.DirectReconstruction(kdata)
```
--------------------------------
### Import Libraries
Source: https://github.com/ptb-mr/mrpro/blob/main/examples/notebooks/qmri_t1_mapping_with_grad_acq.ipynb
Imports the required libraries for the $T_1$ mapping process, including matplotlib for plotting, mrpro for reconstruction, and torch for tensor operations.
```python
import matplotlib.pyplot as plt
import mrpro
import torch
```
--------------------------------
### MRpro API Documentation
Source: https://github.com/ptb-mr/mrpro/blob/main/docs/source/index.rst
This section provides comprehensive API documentation for the MRpro library, detailing its modules, classes, methods, and parameters. It covers data handling, reconstruction algorithms, signal models, and utility functions.
```APIDOC
MRpro Library Overview:
MRpro is a PyTorch-based library for MR image reconstruction and processing.
Key Features:
- Support for ISMRMRD and DICOM file formats.
- PyTorch tensor integration for all data containers.
- Handling of Cartesian and non-Cartesian trajectories (FFT and nuFFT).
- Pulseq sequence support for trajectory calculation.
- Implementation of various MR signal models (e.g., T1 recovery, WASABI).
- Regularized image reconstruction algorithms (wavelet compressed sensing, total variation).
Modules:
- `mrpro.data`: Handles data loading, processing, and storage.
- `mrpro.reconstruct`: Implements image reconstruction algorithms.
- `mrpro.models`: Contains various MR signal models.
- `mrpro.utils`: Utility functions for MR processing.
Example Usage (Conceptual):
# Load ISMRMRD data
data = mrpro.data.load_ismrmrd('path/to/data.h5')
# Reconstruct image using a specific algorithm
reconstructed_image = mrpro.reconstruct.reconstruct_image(data, algorithm='wavelet_cs')
# Apply a signal model
processed_image = mrpro.models.apply_signal_model(reconstructed_image, model='T1_recovery')
# Save the processed image
mrpro.data.save_dicom('path/to/output.dcm', processed_image)
Refer to specific module documentation for detailed function signatures and parameters.
```
--------------------------------
### Fourier Operator for Cartesian Data
Source: https://github.com/ptb-mr/mrpro/blob/main/examples/notebooks/cartesian_reconstruction.ipynb
Demonstrates the use of FourierOp to reconstruct images from Cartesian k-space data. It handles resorting and can process non-Cartesian data, simplifying manual steps.
```python
fourier_op = mrpro.operators.FourierOp.from_kdata(kdata_pe_pf)
# no need for an explicit CartesianSamplingOp anymore!
(img_pe_pf,) = fourier_op.adjoint(kdata_pe_pf.data)
magnitude_pe_pf = img_pe_pf.abs().square().sum(dim=-4).sqrt().squeeze()
show_images(magnitude_fully_sampled, magnitude_pe_pf, titles=['fully sampled', 'PF & PE'])
```
--------------------------------
### Run FISTA Algorithm
Source: https://github.com/ptb-mr/mrpro/blob/main/examples/notebooks/pgd_wavelet_reconstruction.ipynb
Executes the FISTA algorithm to solve the defined minimization problem. It calculates an appropriate step size based on the operator norm and uses the wavelet coefficients of the iterative SENSE image as an initial guess for faster convergence.
```python
# compute the stepsize based on the operator norm of the acquisition operator and run FISTA
import torch
# initialize FISTA with adjoint solution
initial_values = wavelet_operator(img_direct_24.data)
op_norm = acquisition_operator.operator_norm(
initial_value=torch.randn_like(initial_values[0]), dim=(-2, -1), max_iterations=36
).item()
# define step size with a security factor to ensure to
# have stepsize $t \in (0, L(f))$, where $L(f)=1/\|\tilde{A}\|\|_2^2)$ is
# the Lipschitz constant of the functional $f$
stepsize = 0.9 * (1 / op_norm**2)
(img_wave_pgd_24,) = mrpro.algorithms.optimizers.pgd(
f=f,
g=g,
initial_value=initial_values,
stepsize=stepsize,
max_iterations=48,
backtrack_factor=1.0,
callback=callback,
)
```
--------------------------------
### Quantitative Parameter Estimation using Optimization
Source: https://github.com/ptb-mr/mrpro/blob/main/README.md
Illustrates the estimation of quantitative MR parameters by defining a signal model and a loss function, then using an optimization algorithm like ADAM to minimize the functional. This is useful for generating parameter maps like T1.
```Python
from mrpro.operators import MagnitudeOp
from mrpro.models import InversionRecovery
from mrpro.operators.loss import MSE
from mrpro.algorithms.optimization import adam
# Define signal model
model = MagnitudeOp() @ InversionRecovery(ti=idata_multi_ti.header.ti)
# Define loss function and combine with signal model
mse = MSE(idata_multi_ti.data.abs())
functional = mse @ model
# [...]
# Run optimization
params_result = adam(functional, [m0_start, t1_start], n_iterations=n_iterations, learning_rate=learning_rate)
```
--------------------------------
### Coil Sensitivity Map Calculation and Operator Setup
Source: https://github.com/ptb-mr/mrpro/blob/main/examples/notebooks/direct_reconstruction.ipynb
Calculates coil sensitivity maps using the Walsh algorithm and sets up a SensitivityOp operator.
```python
csm_data = mrpro.algorithms.csm.walsh(img_tensor_coilwise[0], smoothing_width=5)
csm_operator = mrpro.operators.SensitivityOp(csm_data)
```
--------------------------------
### Reconstruction using Calibration CSM
Source: https://github.com/ptb-mr/mrpro/blob/main/examples/notebooks/cartesian_reconstruction.ipynb
Performs image reconstruction using the previously calculated coil sensitivity maps with the DirectReconstruction method. This demonstrates how CSMs are applied to reconstruct undersampled data.
```python
direct_recon_us_csm = mrpro.algorithms.reconstruction.DirectReconstruction(kdata_us, csm=direct_recon_calib_lines.csm)
idat_us_csm = direct_recon_us_csm(kdata_us)
show_images(idat_us.rss().squeeze(), idat_us_csm.rss().squeeze(), titles=['Autocalibration', 'Calibration Lines'])
```
--------------------------------
### Set up Acquisition Operator
Source: https://github.com/ptb-mr/mrpro/blob/main/examples/notebooks/tv_minimization_reconstruction_pdhg.ipynb
Defines the acquisition operator by composing a Fourier transform operator with a sensitivity map operator. This operator models the process of acquiring k-space data from an image, considering coil sensitivities.
```python
fourier_operator = mrpro.operators.FourierOp.from_kdata(kdata_24spokes)
assert direct_reconstruction_24.csm is not None
csm_operator = direct_reconstruction_24.csm.as_operator()
# The acquisition operator is the composition of the Fourier operator and the CSM operator
acquisition_operator = fourier_operator @ csm_operator
```
--------------------------------
### Reconstruction using ISMRMRD Trajectory
Source: https://github.com/ptb-mr/mrpro/blob/main/examples/notebooks/comparison_trajectory_calculators.ipynb
Loads k-space data from an ISMRMRD file and uses the trajectory information embedded within it for image reconstruction. This method is convenient if the trajectory is available in the file.
```python
# Read the raw data and the trajectory from ISMRMRD file
kdata = mrpro.data.KData.from_file(
data_folder / 'radial2D_402spokes_golden_angle_with_traj.h5',
mrpro.data.traj_calculators.KTrajectoryIsmrmrd(),
)
# Reconstruct image
reconstruction = mrpro.algorithms.reconstruction.DirectReconstruction(kdata)
img_using_ismrmrd_traj = reconstruction(kdata)
```
--------------------------------
### Download Raw Data
Source: https://github.com/ptb-mr/mrpro/blob/main/examples/notebooks/iterative_sense_reconstruction_radial2D.ipynb
Downloads the necessary raw k-space data and trajectory information from Zenodo using the zenodo_get library.
```python
# ### Download raw data from Zenodo
import tempfile
from pathlib import Path
import zenodo_get
tmp = tempfile.TemporaryDirectory() # RAII, automatically cleaned up
data_folder = Path(tmp.name)
zenodo_get.download(record='14617082', retry_attempts=5, output_dir=data_folder)
```