.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "auto_examples/001_usage_of_the_class_tensorspline.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. note:: :class: sphx-glr-download-link-note :ref:`Go to the end ` to download the full example code. or to run this example in your browser via JupyterLite or Binder .. rst-class:: sphx-glr-example-title .. _sphx_glr_auto_examples_001_usage_of_the_class_tensorspline.py: Usage of the Class TensorSpline =============================== Showcase TensorSpline class basic functionality. You can download this example at the tab at right (Python script or Jupyter notebook. .. GENERATED FROM PYTHON SOURCE LINES 11-15 Imports ------- Import the necessary libraries and modules. .. GENERATED FROM PYTHON SOURCE LINES 15-21 .. code-block:: Python import numpy as np import matplotlib.pyplot as plt from splineops.interpolate.tensorspline import TensorSpline from splineops.bases.utils import create_basis .. GENERATED FROM PYTHON SOURCE LINES 22-26 Data Preparation ---------------- General configuration and sample data. .. GENERATED FROM PYTHON SOURCE LINES 26-39 .. code-block:: Python dtype = "float32" nx, ny = 2, 5 xmin, xmax = 0, 2.0 ymin, ymax = 0, 5.0 xx = np.linspace(xmin, xmax, nx, dtype=dtype) yy = np.linspace(ymin, ymax, ny, dtype=dtype) coordinates = xx, yy prng = np.random.default_rng(seed=5250) data = prng.standard_normal(size=tuple(c.size for c in coordinates)) data = np.ascontiguousarray(data, dtype=dtype) .. GENERATED FROM PYTHON SOURCE LINES 40-44 TensorSpline Setup ------------------ Configure bases and modes for the TensorSpline. .. GENERATED FROM PYTHON SOURCE LINES 44-49 .. code-block:: Python bases = "bspline3" modes = "mirror" tensor_spline = TensorSpline(data=data, coordinates=coordinates, bases=bases, modes=modes) .. GENERATED FROM PYTHON SOURCE LINES 50-54 Evaluation Coordinates ---------------------- Define evaluation coordinates to extend and oversample the original grid. .. GENERATED FROM PYTHON SOURCE LINES 54-64 .. code-block:: Python dx = (xx[-1] - xx[0]) / (nx - 1) dy = (yy[-1] - yy[0]) / (ny - 1) pad_fct = 1.0 px = pad_fct * nx * dx py = pad_fct * ny * dy eval_xx = np.linspace(xx[0] - px, xx[-1] + px, 100 * nx) eval_yy = np.linspace(yy[0] - py, yy[-1] + py, 100 * ny) eval_coords = eval_xx, eval_yy .. GENERATED FROM PYTHON SOURCE LINES 65-69 Interpolation and Visualization ------------------------------- Perform interpolation and visualize the original and interpolated data. .. GENERATED FROM PYTHON SOURCE LINES 69-88 .. code-block:: Python data_eval = tensor_spline(coordinates=eval_coords) extent = [xx[0] - dx / 2, xx[-1] + dx / 2, yy[0] - dy / 2, yy[-1] + dy / 2] eval_extent = [ eval_xx[0] - dx / 2, eval_xx[-1] + dx / 2, eval_yy[0] - dy / 2, eval_yy[-1] + dy / 2, ] fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(12, 6), sharex="all", sharey="all") axes[0].imshow(data.T, extent=extent, cmap="gray", aspect="equal") axes[0].set_title("Original Data Samples") axes[1].imshow(data_eval.T, extent=eval_extent, cmap="gray", aspect="equal") axes[1].set_title("Interpolated Data") plt.tight_layout() plt.show() .. image-sg:: /auto_examples/images/sphx_glr_001_usage_of_the_class_tensorspline_001.png :alt: Original Data Samples, Interpolated Data :srcset: /auto_examples/images/sphx_glr_001_usage_of_the_class_tensorspline_001.png :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 89-93 Plotting of Spline Bases ------------------------ Define a helper function to visualize the spline bases. .. GENERATED FROM PYTHON SOURCE LINES 93-114 .. code-block:: Python x_values = np.linspace(-3, 3, 1000) # Define x range def plot_bases(names, x_values, title): plt.figure(figsize=(12, 6)) for name in names: if name == "keys": readable_name = "Keys Spline" else: name_parts = name.split("-") readable_name = f"{name_parts[0][:-1]} degree {name_parts[0][-1]}" y_values = create_basis(name).eval(x_values) plt.plot(x_values, y_values, label=readable_name) plt.title(title) plt.xlabel("x") plt.ylabel("y") plt.grid(True) plt.legend() plt.show() .. GENERATED FROM PYTHON SOURCE LINES 115-119 Plot B-Spline Bases ~~~~~~~~~~~~~~~~~~~ Plot B-spline basis functions for degree 0 to 9. .. GENERATED FROM PYTHON SOURCE LINES 119-126 .. code-block:: Python plot_bases( names=[f"bspline{i}" for i in range(10)], x_values=x_values, title="B-Spline Basis Functions: Degrees 0 to 9", ) .. image-sg:: /auto_examples/images/sphx_glr_001_usage_of_the_class_tensorspline_002.png :alt: B-Spline Basis Functions: Degrees 0 to 9 :srcset: /auto_examples/images/sphx_glr_001_usage_of_the_class_tensorspline_002.png :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 127-131 Plot OMOMS Bases ~~~~~~~~~~~~~~~~ Plot OMOMS basis functions for degree 0 to 5. .. GENERATED FROM PYTHON SOURCE LINES 131-138 .. code-block:: Python plot_bases( names=[f"omoms{i}" for i in range(6)], x_values=x_values, title="OMOMS Basis Functions: Degrees 0 to 5", ) .. image-sg:: /auto_examples/images/sphx_glr_001_usage_of_the_class_tensorspline_003.png :alt: OMOMS Basis Functions: Degrees 0 to 5 :srcset: /auto_examples/images/sphx_glr_001_usage_of_the_class_tensorspline_003.png :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 139-143 Plot Keys Basis ~~~~~~~~~~~~~~~ Plot the Keys basis function. .. GENERATED FROM PYTHON SOURCE LINES 143-150 .. code-block:: Python plot_bases( names=["keys"], x_values=x_values, title="Keys Basis Function", ) .. image-sg:: /auto_examples/images/sphx_glr_001_usage_of_the_class_tensorspline_004.png :alt: Keys Basis Function :srcset: /auto_examples/images/sphx_glr_001_usage_of_the_class_tensorspline_004.png :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 151-155 Plot Extension Modes -------------------- Visualize how the extension modes allow one to control the values that a signal is assumed to take outside of its original domain. .. GENERATED FROM PYTHON SOURCE LINES 155-188 .. code-block:: Python # Generate a signal that is mostly linear but includes a "bump." x_values = np.linspace(0, 6, 101) # Define x range def create_signal_with_bump(x_values, bump_location=3, bump_width=0.5, bump_height=5): linear_part = x_values bump = np.where( (x_values > (bump_location - bump_width / 2)) & (x_values < (bump_location + bump_width / 2)), bump_height, 0, ) return linear_part + bump def plot_extension_modes_for_bump_function(mode_name, x_values, title): plt.figure(figsize=(12, 6)) data = create_signal_with_bump(x_values) tensor_spline = TensorSpline( data=data, coordinates=(x_values,), bases="linear", modes=mode_name ) eval_x_values = np.linspace(-10, 10, 2000) extended_data = tensor_spline.eval(coordinates=(eval_x_values,)) plt.plot(eval_x_values, extended_data, label="Extended Signal") plt.axvline(x=x_values[0], color="red", linestyle="--", label="Original Start") plt.axvline(x=x_values[-1], color="blue", linestyle="--", label="Original End") plt.title(title) plt.xlabel("x") plt.ylabel("Interpolated Value") plt.grid(True) plt.legend() plt.show() .. GENERATED FROM PYTHON SOURCE LINES 189-191 Finite-Support Coefficients ~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. GENERATED FROM PYTHON SOURCE LINES 191-198 .. code-block:: Python plot_extension_modes_for_bump_function( mode_name="zero", x_values=x_values, title="Extension Mode: Finite Support Coefficients", ) .. image-sg:: /auto_examples/images/sphx_glr_001_usage_of_the_class_tensorspline_005.png :alt: Extension Mode: Finite Support Coefficients :srcset: /auto_examples/images/sphx_glr_001_usage_of_the_class_tensorspline_005.png :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 199-201 Narrow Mirroring ~~~~~~~~~~~~~~~~ .. GENERATED FROM PYTHON SOURCE LINES 201-208 .. code-block:: Python plot_extension_modes_for_bump_function( mode_name="mirror", x_values=x_values, title="Extension Mode: Narrow Mirroring", ) .. image-sg:: /auto_examples/images/sphx_glr_001_usage_of_the_class_tensorspline_006.png :alt: Extension Mode: Narrow Mirroring :srcset: /auto_examples/images/sphx_glr_001_usage_of_the_class_tensorspline_006.png :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 209-211 Periodic Padding ~~~~~~~~~~~~~~~~ .. GENERATED FROM PYTHON SOURCE LINES 211-218 .. code-block:: Python plot_extension_modes_for_bump_function( mode_name="periodic", x_values=x_values, title="Extension Mode: Periodic Padding", ) .. image-sg:: /auto_examples/images/sphx_glr_001_usage_of_the_class_tensorspline_007.png :alt: Extension Mode: Periodic Padding :srcset: /auto_examples/images/sphx_glr_001_usage_of_the_class_tensorspline_007.png :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 219-224 GPU Support ----------- We leverage the GPU for TensorSpline if cupy is installed. If cupy is not available, we skip this section. .. GENERATED FROM PYTHON SOURCE LINES 224-254 .. code-block:: Python try: import cupy as cp HAS_CUPY = True except ImportError: HAS_CUPY = False if not HAS_CUPY: print("CuPy is not installed, skipping GPU demonstration.") else: # Convert existing data/coordinates to CuPy data_cp = cp.asarray(data) coords_cp = tuple(cp.asarray(c) for c in coordinates) # Create CuPy-based spline ts_cp = TensorSpline(data=data_cp, coordinates=coords_cp, bases=bases, modes=modes) # Convert evaluation coordinates to CuPy eval_coords_cp = tuple(cp.asarray(c) for c in eval_coords) # Evaluate on the GPU data_eval_cp = ts_cp(coordinates=eval_coords_cp) # Compare with NumPy evaluation # (Ensure you already have data_eval from the CPU version above.) data_eval_cp_np = data_eval_cp.get() # Move from GPU to CPU diff = data_eval_cp_np - data_eval # 'data_eval' is from the CPU TensorSpline mse = np.mean(diff**2) print(f"Max abs diff (CPU vs GPU): {np.max(np.abs(diff)):.3e}") print(f"MSE (CPU vs GPU): {mse:.3e}") .. rst-class:: sphx-glr-script-out .. code-block:: none CuPy is not installed, skipping GPU demonstration. .. rst-class:: sphx-glr-timing **Total running time of the script:** (0 minutes 0.884 seconds) .. _sphx_glr_download_auto_examples_001_usage_of_the_class_tensorspline.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: binder-badge .. image:: images/binder_badge_logo.svg :target: https://mybinder.org/v2/gh/splineops/splineops.github.io/main?urlpath=lab/tree/notebooks_binder/auto_examples/001_usage_of_the_class_tensorspline.ipynb :alt: Launch binder :width: 150 px .. container:: lite-badge .. image:: images/jupyterlite_badge_logo.svg :target: ../lite/lab/index.html?path=auto_examples/001_usage_of_the_class_tensorspline.ipynb :alt: Launch JupyterLite :width: 150 px .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: 001_usage_of_the_class_tensorspline.ipynb <001_usage_of_the_class_tensorspline.ipynb>` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: 001_usage_of_the_class_tensorspline.py <001_usage_of_the_class_tensorspline.py>` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: 001_usage_of_the_class_tensorspline.zip <001_usage_of_the_class_tensorspline.zip>` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_