Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Clean CPU examples #196

Merged
merged 5 commits into from
Sep 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@
"reference_url": {"mrinufft": None},
"examples_dirs": ["../examples/"],
"gallery_dirs": ["generated/autoexamples"],
"within_subsection_order": "ExampleTitleSortKey",
"filename_pattern": "/example_",
"ignore_pattern": r"(__init__|conftest|utils).py",
"nested_sections": True,
Expand Down
38 changes: 22 additions & 16 deletions examples/example_cg.py → examples/GPU/example_cg.py
Original file line number Diff line number Diff line change
@@ -1,24 +1,27 @@
# %%
"""
Example of using the Conjugate Gradient method.
======================================
Reconstruction with conjugate gradient
======================================

An example to show how to reconstruct volumes using conjugate gradient method.

This script demonstrates the use of the Conjugate Gradient (CG) method
for solving systems of linear equations of the form Ax = b, where A is a symmetric
positive-definite matrix. The CG method is an iterative algorithm that is particularly
This script demonstrates the use of the Conjugate Gradient (CG) method
for solving systems of linear equations of the form Ax = b, where A is a symmetric
positive-definite matrix. The CG method is an iterative algorithm that is particularly
useful for large, sparse systems where direct methods are computationally expensive.

The Conjugate Gradient method is widely used in various scientific and engineering
applications, including solving partial differential equations, optimization problems,
The Conjugate Gradient method is widely used in various scientific and engineering
applications, including solving partial differential equations, optimization problems,
and machine learning tasks.

References
----------
- Inpirations:
- Inpirations:
- https://sigpy.readthedocs.io/en/latest/_modules/sigpy/alg.html#ConjugateGradient
- https://aquaulb.github.io/book_solving_pde_mooc/solving_pde_mooc/notebooks/05_IterativeMethods/05_02_Conjugate_Gradient.html
- Wikipedia:
- https://en.wikipedia.org/wiki/Conjugate_gradient_method
- https://en.wikipedia.org/wiki/Momentum
- Wikipedia:
- https://en.wikipedia.org/wiki/Conjugate_gradient_method
- https://en.wikipedia.org/wiki/Momentum
"""

# %%
Expand All @@ -42,7 +45,10 @@
density = voronoi(samples_loc) # get the density

nufft = NufftOperator(
samples_loc, shape=image.shape, density=density, n_coils=1
samples_loc,
shape=image.shape,
density=density,
n_coils=1,
) # create the NUFFT operator

# %%
Expand All @@ -52,17 +58,17 @@

# %%
# Display the results
plt.figure(figsize=(10, 5))
plt.figure(figsize=(9, 3))
plt.subplot(1, 3, 1)
plt.title("Original Image")
plt.title("Original image")
plt.imshow(abs(image), cmap="gray")

plt.subplot(1, 3, 2)
plt.title("Reconstructed Image with CG")
plt.title("Conjugate gradient")
plt.imshow(abs(reconstructed_image), cmap="gray")

plt.subplot(1, 3, 3)
plt.title("Reconstructed Image with adjoint")
plt.title("Adjoint NUFFT")
plt.imshow(abs(nufft.adj_op(kspace_data)), cmap="gray")

plt.show()
2 changes: 1 addition & 1 deletion examples/README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,4 @@
Examples
========

This is a collection of examples showing how to use mri-nufft to perform MR image reconstruction.
This is a collection of examples showing how to use MRI-nufft to perform MR image reconstruction.
2 changes: 1 addition & 1 deletion examples/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@

"""

import sys
import runpy
import sys
from pathlib import Path

import matplotlib as mpl
Expand Down
6 changes: 1 addition & 5 deletions examples/example_2D_trajectories.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,20 +13,16 @@
# are redundant across the different patterns, some of the documentation
# will refer to previous patterns for explanation.
#
# Note that most sources have not been added yet, but will be in the near
# future.
#

# External
import matplotlib.pyplot as plt
import numpy as np
from utils import show_argument, show_trajectory

# Internal
import mrinufft as mn
import mrinufft.trajectories.maths as mntm
from mrinufft import display_2D_trajectory
from utils import show_argument, show_trajectory


# %%
# Script options
Expand Down
9 changes: 4 additions & 5 deletions examples/example_3D_trajectories.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,10 @@
# are redundant across the different patterns, some of the documentation
# will refer to previous patterns for explanation.
#
# Note that most sources have not been added yet, but will be in the near
# future. Also the examples hereafter only cover natively 3D trajectories
# Note that the examples hereafter only cover natively 3D trajectories
# or famous 3D trajectories obtained from 2D. Examples on how to use
# 2D-to-3D expansion methods will be presented over another page.
# tools to make 3D trajectories out of 2D ones are presented in
# :ref:`sphx_glr_generated_autoexamples_example_trajectory_tools.py`
#
# In this page in particular, we invite the user to manually run the script
# to be able to manipulate the plot orientations with the matplotlib interface
Expand All @@ -26,12 +26,11 @@
# External
import matplotlib.pyplot as plt
import numpy as np
from utils import show_argument, show_trajectory

# Internal
import mrinufft as mn
from mrinufft import display_2D_trajectory, display_3D_trajectory
from utils import show_argument, show_trajectory


# %%
# Script options
Expand Down
59 changes: 27 additions & 32 deletions examples/example_display_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,24 @@
Trajectory display configuration
================================

The look of the display trajectories can be tweaked by using :py:class:`displayConfig`
An example to show how to customize trajectory displays.

You can tune these parameters to your own taste and needs.
The parameters presented here can be tuned to your own taste and needs
by using :py:class:`displayConfig`.
"""

import matplotlib as mpl
import matplotlib.pyplot as plt

# %%
import numpy as np

from mrinufft import display_2D_trajectory, display_3D_trajectory, displayConfig
from mrinufft.trajectories import conify, initialize_2D_spiral

# %%
# Script options
# ==============
# These options are used in the examples below to define trajectories and display options.

# Trajectory parameters
Nc = 120 # Number of shots
Ns = 500 # Number of samples per shot
Expand All @@ -26,7 +30,6 @@
subfigure_size = 6 # Figure size for subplots
one_shot = -5 # Highlight one shot in particular


# %%


Expand All @@ -47,28 +50,32 @@ def show_traj(traj, name, values, **kwargs):
# %%
#
# Trajectory displays
# ====================
# To show case the display parameters of trajectories, we will use the following trajectory
# The effect of trajectory parameter are explained in the :ref:`sphx_glr_generated_autoexamples_example_3D_trajectories.py` Example.
# ===================
#
# The following trajectory will be used to showcase the display parameters.
# The trajectory parameters are explained in the
# :ref:`sphx_glr_generated_autoexamples_example_3D_trajectories.py` example.

traj = conify(initialize_2D_spiral(Nc // 6, Ns), nb_cones=6)[::-1]

# %%
# ``linewidth``
# -------------
# The linewidth of the shot can be updated to have more or less empty space in the plot.
# The ``linewidth`` corresponds to the curve thickness, and can be changed
# to improve the shots visibility.
show_traj(traj, "linewidth", [0.5, 2, 4])

# %%
# ``palette``
# -----------
# The ``palette`` parameter allows to change the color of the shots.
# The ``palette`` parameter allows you to change the color of the shots.
show_traj(traj, "palette", ["tab10", "magma", "jet"])

# %%
# ``one_shot_color``
# ------------------
# The ``one_shot_color`` parameter allows to highlight one shot in particular.
# The ``one_shot_color`` parameter is used to highlight one shot in particular
# with a specified color.
with displayConfig(palette="viridis"):
show_traj(
traj, "one_shot_color", ["tab:blue", "tab:orange", "tab:green"], one_shot=-5
Expand All @@ -77,49 +84,37 @@ def show_traj(traj, name, values, **kwargs):
# %%
# ``nb_colors``
# -------------
# The ``nb_colors`` parameter allows to change the number of colors used to display the shots.

# The ``nb_colors`` parameter allows you to change the number of colors used from the
# specified color palette to display the shots.
show_traj(traj, "nb_colors", [1, 4, 10])


# %%
# Labels, titles and legends
# ==========================

# %%
# ``fontsize``
# ------------
# The ``fontsize`` parameter allows to change the fontsize of the labels /title

# The ``fontsize`` parameter changes the fontsize of the labels/titles.
show_traj(traj, "fontsize", [12, 18, 24])

# %%
# ``pointsize``
# -------------
# To show the gradient constraint violation we can use the ``pointsize`` parameter
# The ``pointsize`` parameter is used when showing the gradient constraint violations
# to change the violation point sizes.
show_traj(traj, "pointsize", [0.5, 2, 4], show_constraints=True)

# %%
# ``gradient_point_color`` and ``slewrate_point_color``
# -----------------------------------------------------
# The ``gradient_point_color`` and ``slewrate_point_color`` parameters allows to change the color of the points
# that are violating the gradient or slewrate constraints.

# The ``gradient_point_color`` and ``slewrate_point_color`` parameters allows you
# to change the color of the points where gradient or slew rate constraint violations
# are observed.
show_traj(
traj,
"slewrate_point_color",
["tab:blue", "tab:orange", "tab:red"],
show_constraints=True,
)


# %%
# Gradients profiles
# ==================

# %%

# %%

# %%

# %%
30 changes: 20 additions & 10 deletions examples/example_gif_2D.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,27 @@
"""
=======================
2D Trajectories display
=======================
========================
Animated 2D trajectories
========================

A collection of 2D trajectories are generated and saved as a gif.
An animation to show 2D trajectory customization.

"""

import time

import joblib
import matplotlib.pyplot as plt
import numpy as np
import tempfile as tmp
from PIL import Image, ImageSequence
import time

import mrinufft.trajectories.display as mtd
import mrinufft.trajectories.trajectory2D as mtt
from mrinufft.trajectories.display import displayConfig

# Options
# %%
# Script options
# ==============

Nc = 16
Ns = 200
Expand All @@ -29,7 +34,9 @@
duration = 150 # seconds


# Generation
# %%
# Trajectory generation
# =====================

# Initialize trajectory function
functions = [
Expand Down Expand Up @@ -125,14 +132,18 @@
]


# %%
# Animation rendering
# ===================

frame_setup = [
(f, i, name, arg)
for (name, f), args in list(zip(functions, arguments))
for i, arg in enumerate(args)
]


def draw_frame(func, index, name, arg, save_dir="/tmp/"):
def draw_frame(func, index, name, arg):
"""Draw a single frame of the gif and save it to a tmp file."""
trajectory = func(arg)
# General configuration
Expand All @@ -158,8 +169,7 @@ def draw_frame(func, index, name, arg, save_dir="/tmp/"):
)

# Save figure
hashed = joblib.hash((index, name, arg, time.time()))
filename = save_dir + f"{hashed}.png"
filename = f"{tmp.NamedTemporaryFile().name}.png"
plt.savefig(filename, bbox_inches="tight")
plt.close()
return filename
Expand Down
Loading
Loading