Shenfun

repository·master·Indexed 42 days ago

https://github.com/spectraldns/shenfun

A high-performance Python-based computing platform for solving partial differential equations (PDEs) using spectral Galerkin methods on multidimensional tensor product grids. It supports various basis types including Chebyshev, Legendre, and Fourier, and provides tools for handling boundary conditions, curvilinear coordinates, and time-dependent problems via integrators like RK4 and ETDRK4.

Tokens
33.3K
Snippets
109
Records
130
Agent score
52%

What's inside Shenfun

  1. Overview of the shenfun.chebyshev package

    master

    The shenfun.chebyshev package provides tools for working with Chebyshev polynomials and related mathematical operations. It is organized into several submodules that handle different aspects of Chebyshev-based computations:

    • shenfun.chebyshev.bases: Contains functionality related to Chebyshev basis functions.
    • shenfun.chebyshev.la: Provides linear algebra (la) utilities specifically for Chebyshev operations, including callable objects.
    • shenfun.chebyshev.matrices: Handles the construction and manipulation of matrices related to Chebyshev methods.
    • shenfun.chebyshev: The main entry point for the package's Chebyshev functionality.
  2. Overview of Shenfun

    master

    Shenfun is a high-performance computing platform designed for solving partial differential equations (PDEs) using the spectral Galerkin method. It is optimized for multidimensional tensor product grids, supporting both Cartesian and curvilinear grids (such as polar, cylindrical, spherical, or parabolic coordinates).

    Key features include:

    • Spectral Accuracy: Uses high-order global orthogonal basis functions (Fourier, Legendre, Chebyshev, Ultraspherical, Jacobi, Laguerre, and Hermite).
    • High Performance: Leverages vectorization via Numpy, parallelization via mpi4py and mpi4py-fft, and critical routines implemented in Cython or Numba.
    • Curvilinear Support: Automatically handles operators like div, grad, and curl on custom curvilinear coordinates, provided the system has separable coefficients.
    • Flexible PDE Solving: Supports coupled and implicit equations, as well as non-periodic directions.
  3. Overview of the shenfun package structure

    master

    The shenfun package is a library for spectral methods. It is organized into several specialized subpackages for different basis functions and mathematical operations:

    • Basis Function Subpackages: shenfun.chebyshev, shenfun.chebyshevu, shenfun.fourier, shenfun.legendre, shenfun.laguerre, shenfun.hermite, shenfun.jacobi, and shenfun.ultraspherical.
    • Mathematical Utilities: shenfun.forms (for differential forms), shenfun.optimization, and shenfun.utilities.

    Core functionality is exposed through several key modules:

    • shenfun.la: Linear algebra operations, including solvers and LU decomposition.
    • shenfun.matrixbase: Base classes for matrix-based spectral methods.
    • shenfun.spectralbase: Base classes for spectral methods.
    • shenfun.tensorproductspace: Handling of tensor product spaces.
    • shenfun.coordinates: Coordinate systems and transformations.
  4. Explore the shenfun.fourier package submodules

    master

    The shenfun.fourier package provides tools for Fourier-related spectral methods and operations. It is organized into the following submodules:

    • shenfun.fourier.bases: Contains Fourier basis functions and related spectral basis definitions.
    • shenfun.fourier.matrices: Provides Fourier-related matrices (e.g., differentiation or integration matrices) used in spectral methods.
    • shenfun.fourier: The main package entry point containing core Fourier functionality.
  5. Use the shenfun.ultraspherical package

    master

    The shenfun.ultraspherical package provides tools for working with ultraspherical (Gegenbauer) polynomials. It is organized into several submodules:

    • shenfun.ultraspherical.bases: Contains basis functions related to ultraspherical polynomials.
    • shenfun.ultraspherical.matrices: Contains modules for generating matrices associated with ultraspherical expansions.
    • shenfun.ultraspherical: The main package entry point for ultraspherical functionality.
  6. Explore the shenfun.utilities package submodules

    master

    The shenfun.utilities package provides specialized helper modules for spectral analysis and geophysical fluid dynamics tasks. It is organized into the following submodules:

    • shenfun.utilities.findbasis: Tools for finding or constructing basis functions.
    • shenfun.utilities.integrators: Numerical integration routines.
    • shenfun.utilities.lagrangian_particles: Utilities for managing and calculating Lagrangian particle trajectories.

    Use these submodules to extend standard spectral operations with specific numerical or physical modeling capabilities.

  7. How the Spectral Galerkin method works in Shenfun

    master

    Shenfun implements the Spectral Galerkin method to solve partial differential equations (PDEs). Unlike the Finite Element Method (FEM) which uses local shape functions, Shenfun uses global shape functions. This results in high accuracy with fewer functions, though it offers less flexibility regarding the computational domain.

    To solve a problem, the method:

    1. Approximates the solution $u$ using a set of basis functions $\phi_k$ and unknown coefficients $\hat{u}_k$.
    2. Calculates a residual $R_N$ by inserting the approximation into the PDE.
    3. Forces the residual to zero in an average sense using a weighted inner product (the Galerkin method).
    4. Solves the resulting linear system $A \boldsymbol{\hat{u}} = \boldsymbol{\tilde{f}}$, where $A$ is the matrix of inner products of the basis functions and $\tilde{f}$ is the projection of the right-hand side function onto the basis.

    Shenfun provides classes for various bases (Chebyshev, Legendre, Laguerre, Hermite, Jacobi, or trigonometric) and handles the associated weighted inner products automatically.

  8. How tensor product spaces are constructed

    master

    For multi-dimensional problems (e.g., 2D), Shenfun uses tensor products to combine one-dimensional function spaces into a multi-dimensional space.

    If you have a 1D space $X_N$ for the $x$-dimension and $Y_M$ for the $y$-dimension, the 2D tensor product space $W_P$ is defined as $W_P = X_N \otimes Y_M$, where the total dimension $P = N \cdot M$.

    Key concepts:

    • Global Basis Functions: Created by taking the outer product of 1D basis functions (e.g., $v_{jk}(x, y) = \mathcal{X}_j(x) \mathcal{Y}_k(y)$).
    • Cartesian Product Domains: Multi-dimensional domains are formed by the Cartesian product of 1D domains.
    • Discretization: 1D domains are discretized using the quadrature points of the chosen basis functions.
  9. Understand the difference between Function and Array

    master

    Shenfun uses two primary types of arrays, both of which are subclasses of NumPy's ndarray:

    1. Function: Represents a complete spectral Galerkin function. Its array values correspond to the sequence of expansion coefficients $\hat{\mathbf{u}} = {\hat{u}k}{k=0}^{N-1}$. It is a subclass of BasisFunction, meaning it can be used in variational forms and with operators like grad or div.
    2. Array: Represents the function evaluated on the quadrature mesh of the function space. It contains the physical values at the mesh points rather than expansion coefficients. It cannot be used in operations involving differentiation (like Dx) because it lacks the necessary basis information.
  10. Use curvilinear coordinates in Shenfun

    master

    Shenfun supports solving equations in curvilinear coordinates (e.g., polar, cylindrical, spherical) by providing a map (position vector) between the new coordinates and Cartesian coordinates.

    Important: Basis Vectors By default, Shenfun uses non-normalized natural (covariant) basis vectors. This means the equations you write may differ from standard textbook formulations that use normalized (physical) basis vectors.

    To switch between basis types, configure the basisvectors parameter in your shenfun.yaml file. Supported values are:

    • covariant: Non-normalized natural basis vectors (default).
    • normal: Normalized physical basis vectors.

    Automatic Operators Once a curvilinear map is defined, Shenfun's core operators—.div, .grad, and .curl—automatically handle the coordinate transformations. You do not need to manually implement the complex coordinate-specific differential equations.

    from shenfun import *
    import sympy as sp
    
    # Define symbols and the position vector (map) for cylindrical coordinates
    r, theta, z = psi = sp.symbols('x,y,z', real=True, positive=True)
    rv = (r*sp.cos(theta), r*sp.sin(theta), z)
    
    N = 10
    F0 = FunctionSpace(N, 'F', dtype='d')
    F1 = FunctionSpace(N, 'F', dtype='D')
    L = FunctionSpace(N, 'L', domain=(0, 1))
    
    # Create the TensorProductSpace using the map 'rv'
    T = TensorProductSpace(comm, (L, F1, F0), coordinates=(psi, rv))
    V = VectorSpace(T)
    u = TrialFunction(V)
    
    # The vector Laplacian is implemented simply via div(grad(u))
    du = div(grad(u))
  11. Create multidimensional problems with TensorProductSpace

    master

    Multidimensional problems are handled using TensorProductSpace, which generates basis functions via the outer products of one-dimensional basis functions.

    To create a 2D space, pass a tuple of 1D FunctionSpace objects to TensorProductSpace. For example, combining a Legendre space and a Fourier space creates a Cartesian domain (e.g., $[-1, 1] imes [0, 2 ext{π})$).

    When using TrialFunction(T) and TestFunction(T) on a tensor product space, operators like inner(grad(u), grad(v)) result in TPMatrix objects (tensor product matrices).

    N, M = (12, 16)
    C0 = FunctionSpace(N+2, 'L', bc=(0, 0), scaled=True)
    K0 = FunctionSpace(M, 'F', dtype='d')
    T = TensorProductSpace(comm, (C0, K0))
    
    u = TrialFunction(T)
    v = TestFunction(T)
    A = inner(grad(u), grad(v))
  12. Understand Shenfun's spectral basis implementations

    master

    Shenfun provides specialized classes for working with modified Chebyshev and Legendre bases, based on the methods described by Jie Shen (1994, 1995). These classes are designed for the spectral Galerkin method and include built-in methods for:

    • Fast transforms: Efficiently moving between physical and spectral space.
    • Inner products: Computing products of basis functions.
    • Matrix computation: Generating matrices that arise from bilinear forms used in spectral Galerkin methods.