### Install findiff Source: https://github.com/maroba/findiff/blob/master/docs/source/getstarted.rst Installs or upgrades the findiff library using pip. ```ipython pip install --upgrade findiff ``` -------------------------------- ### Laplacian Stencil Coefficients (Shell Output) Source: https://github.com/maroba/findiff/blob/master/docs/source/getstarted.rst Example output showing the stencil coefficients for a 2D Laplacian operator. The keys represent grid point offsets and boundary conditions, and the values are the finite difference coefficients. ```shell { ('L', 'L'): {(0, 0): 4.0, (0, 1): -5.0, (0, 2): 4.0, (0, 3): -1.0, (1, 0): -5.0, (2, 0): 4.0, (3, 0): -1.0}, ('L', 'C'): {(0, -1): 1.0, (0, 1): 1.0, (1, 0): -5.0, (2, 0): 4.0, (3, 0): -1.0}, ('L', 'H'): {(0, -3): -1.0, (0, -2): 4.0, (0, -1): -5.0, (0, 0): 4.0, (1, 0): -5.0, (2, 0): 4.0, (3, 0): -1.0}, ('C', 'L'): {(-1, 0): 1.0, (0, 1): -5.0, (0, 2): 4.0, (0, 3): -1.0, (1, 0): 1.0}, ('C', 'C'): {(-1, 0): 1.0, (0, -1): 1.0, (0, 0): -4.0, (0, 1): 1.0, (1, 0): 1.0}, ('C', 'H'): {(-1, 0): 1.0, (0, -3): -1.0, (0, -2): 4.0, (0, -1): -5.0, (0, 0): 0.0, (1, 0): 1.0}, ('H', 'L'): {(-3, 0): -1.0, (-2, 0): 4.0, (-1, 0): -5.0, (0, 0): 4.0, (0, 1): -5.0, (0, 2): 4.0, (0, 3): -1.0}, ('H', 'C'): {(-3, 0): -1.0, (-2, 0): 4.0, (-1, 0): -5.0, (0, -1): 1.0, (0, 0): 0.0, (0, 1): 1.0}, ('H', 'H'): {(-3, 0): -1.0, (-2, 0): 4.0, (-1, 0): -5.0, (0, -3): -1.0, (0, -2): 4.0, (0, -1): -5.0, (0, 0): 4.0}} ``` -------------------------------- ### Get Finite Difference Coefficients Source: https://github.com/maroba/findiff/blob/master/docs/source/getstarted.rst Retrieves the coefficients and offsets for finite difference schemes for a given derivative order and accuracy. ```ipython from findiff import coefficients coefficients(deriv=2, acc=2) ``` -------------------------------- ### 1D Differentiation Setup Source: https://github.com/maroba/findiff/blob/master/docs/source/examples-basic.rst Sets up a 1D grid and arrays for sine and cosine functions to demonstrate numerical differentiation. ```ipython3 x = np.linspace(0, 10, 100) dx = x[1] - x[0] f = np.sin(x) g = np.cos(x) ``` -------------------------------- ### 3D Differentiation Setup Source: https://github.com/maroba/findiff/blob/master/docs/source/examples-basic.rst Sets up a 3D grid and a function f(x, y, z) = sin(x)cos(y)sin(z) for partial derivative calculations. ```ipython3 x, y, z = [np.linspace(0, 10, 100)]*3 dx, dy, dz = x[1] - x[0], y[1] - y[0], z[1] - z[0] X, Y, Z = np.meshgrid(x, y, z, indexing='ij') f = np.sin(X) * np.cos(Y) * np.sin(Z) ``` -------------------------------- ### Setup 3D grid and function values Source: https://github.com/maroba/findiff/blob/master/examples/examples-basic.ipynb Sets up a 3D grid and calculates function values for f(x, y, z) = sin(x)cos(y)sin(z) using numpy's meshgrid. ```python x, y, z = [np.linspace(0, 10, 100)]*3 dx, dy, dz = x[1] - x[0], y[1] - y[0], z[1] - z[0] X, Y, Z = np.meshgrid(x, y, z, indexing='ij') f = np.sin(X) * np.cos(Y) * np.sin(Z) ``` -------------------------------- ### Import Libraries Source: https://github.com/maroba/findiff/blob/master/docs/source/examples-basic.rst Imports necessary libraries, including numpy for numerical operations and Diff and coefficients from the findiff library. ```ipython3 import numpy as np from findiff import Diff, coefficients ``` -------------------------------- ### Get finite difference coefficients Source: https://github.com/maroba/findiff/blob/master/examples/examples-basic.ipynb Shows how to retrieve finite difference coefficients for a given derivative order and accuracy using the coefficients function. ```python from findiff import coefficients coefficients(deriv=2, acc=2) coefficients(deriv=2, acc=10) ``` -------------------------------- ### Create Custom X-Shaped Laplacian Stencil Source: https://github.com/maroba/findiff/blob/master/docs/source/getstarted.rst Demonstrates creating a custom finite difference stencil for the 2D Laplacian using an X-shaped pattern of grid points. This involves defining the offsets and the derivative operator. ```ipython offsets = [(0, 0), (1, 1), (-1, -1), (1, -1), (-1, 1)] # x-shaped offsets stencil = Stencil(offsets, {(2, 0): 1, (0, 2): 1}) ``` -------------------------------- ### Control Accuracy of Derivatives Source: https://github.com/maroba/findiff/blob/master/docs/source/getstarted.rst Sets the accuracy order for finite difference schemes using the 'acc' keyword argument. ```ipython Diff(0, dx, acc=4) ``` -------------------------------- ### Import findiff and numpy Source: https://github.com/maroba/findiff/blob/master/examples/examples-basic.ipynb Imports the necessary libraries, numpy for numerical operations and Diff from findiff for differentiation. ```python import numpy as np from findiff import Diff ``` -------------------------------- ### Calculate partial derivatives in 3D Source: https://github.com/maroba/findiff/blob/master/examples/examples-basic.ipynb Demonstrates calculating the partial derivative with respect to x (d_dx) and z (d_dz) for a 3D array. ```python from findiff import FinDiff d_dx = FinDiff(0, dx) d_dz = FinDiff(2, dz) ``` -------------------------------- ### Set up Findiff Development Environment Source: https://github.com/maroba/findiff/blob/master/README.md Instructions for setting up a local development environment for the findiff project. This includes forking the repository, cloning it, and installing the package in editable mode using pip. ```Shell pip install -e . ``` -------------------------------- ### Get Second Order Finite Difference Coefficients Source: https://github.com/maroba/findiff/blob/master/docs/source/examples-basic.rst Retrieves the finite difference coefficients for a second derivative with second-order accuracy. ```python coefficients(deriv=2, acc=2) ``` -------------------------------- ### Apply differential operator with variable coefficients Source: https://github.com/maroba/findiff/blob/master/examples/examples-basic.ipynb Demonstrates how to use the Coefficient wrapper to apply differential operators with variable coefficients, such as x * d/dx + y^2 * d/dy. ```python from findiff import Coefficient, FinDiff linear_op = Coefficient(X) * FinDiff(0, dx) + Coefficient(Y**2) * FinDiff(1, dy) result = linear_op(f) ``` -------------------------------- ### Custom Stencil Coefficients (IPython Output) Source: https://github.com/maroba/findiff/blob/master/docs/source/getstarted.rst The resulting coefficients for the custom X-shaped Laplacian stencil. The dictionary maps grid point offsets to their corresponding finite difference coefficients. ```ipython {(0, 0): -2.0, (1, 1): 0.5, (-1, -1): 0.5, (1, -1): 0.5, (-1, 1): 0.5} ``` -------------------------------- ### Get Matrix Representation of Operator Source: https://github.com/maroba/findiff/blob/master/docs/source/getstarted.rst Generates the sparse matrix representation of a finite difference operator for a given shape. ```ipython import numpy as np x = [np.linspace(0, 6, 7)] d2_dx2 = Diff(0, x[1]-x[0]) ** 2 u = x**2 mat = d2_dx2.matrix(u.shape) # this method returns a scipy sparse matrix print(mat.toarray()) ``` -------------------------------- ### Run Findiff Tests Source: https://github.com/maroba/findiff/blob/master/README.md Instructions for running the test suite for the findiff library. It requires installing the pytest framework and then executing pytest from the console. ```Shell pip install pytest pytest tests ``` -------------------------------- ### Combine differential operators Source: https://github.com/maroba/findiff/blob/master/examples/examples-basic.ipynb Illustrates how to combine multiple differential operators using addition and scalar multiplication to represent general linear differential operators. ```python from findiff import FinDiff linear_op = FinDiff(0, dx, 2) + 2 * FinDiff((0, dx), (1, dy)) + FinDiff(1, dy, 2) ``` -------------------------------- ### Get Tenth Order Accurate Coefficients Source: https://github.com/maroba/findiff/blob/master/docs/source/examples-basic.rst Retrieves the finite difference coefficients for a second derivative with tenth-order accuracy. ```python coefficients(deriv=2, acc=10) ``` -------------------------------- ### Define Higher-Order Derivative Source: https://github.com/maroba/findiff/blob/master/docs/source/getstarted.rst Defines higher-order partial derivatives by exponentiating a Diff object. ```ipython Diff(k, dx_k) ** n ``` -------------------------------- ### Inspect Laplacian Stencils Source: https://github.com/maroba/findiff/blob/master/docs/source/getstarted.rst Inspects the finite difference stencils used by a Laplacian operator for a given grid shape. This helps understand how derivatives are approximated at different grid locations. ```ipython laplacian.stencil(f.shape) ``` -------------------------------- ### Symbolic Mesh and Operator Setup Source: https://github.com/maroba/findiff/blob/master/examples/symbolic.ipynb Initializes a symbolic mesh and defines symbolic differential operators for finite difference approximations. It sets up the basic components for deriving schemes. ```Python from findiff import SymbolicMesh, SymbolicDiff from sympy import symbols, Eq, solve mesh = SymbolicMesh("x, y") dx, dy = mesh.spacing u = mesh.create_symbol("u") rho = mesh.create_symbol(r"\ ho") m, n = symbols("m, n") ``` -------------------------------- ### Apply General Differential Operator to a Function Source: https://github.com/maroba/findiff/blob/master/docs/source/examples-basic.rst This snippet shows how to apply a previously defined general differential operator to a function 'f'. ```ipython3 result = linear_op(f) ``` -------------------------------- ### Calculate First Derivative Source: https://github.com/maroba/findiff/blob/master/docs/source/getstarted.rst Applies a defined first derivative operator to a numpy array to compute the derivative. ```ipython import numpy as np x = np.linspace(-np.pi, np.pi, 100) dx = x[1] - x[0] f = np.sin(x) d_dx = Diff(0, dx) df_dx = d_dx(f) ``` -------------------------------- ### Create 3D Partial Derivative Operators Source: https://github.com/maroba/findiff/blob/master/docs/source/examples-basic.rst Creates Diff objects for partial derivatives with respect to x (0th axis) and z (2nd axis). ```ipython3 d_dx = Diff(0, dx) d_dz = Diff(2, dz) ``` -------------------------------- ### Define First Derivative Source: https://github.com/maroba/findiff/blob/master/docs/source/getstarted.rst Defines a first derivative operator along a specified axis with a given grid spacing. ```ipython from findiff import Diff d_dx = Diff(0, dx) ``` ```ipython Diff(k, dx_k) ``` -------------------------------- ### Create Mixed Partial Derivative Operator Source: https://github.com/maroba/findiff/blob/master/docs/source/examples-basic.rst Creates a Diff object for the mixed partial derivative (d^2 f / dx dy) by multiplying first-order partial derivative operators. ```ipython3 d2_dxdy = Diff(0, dx) * Diff(1, dy) result = d2_dxdy(f) ``` -------------------------------- ### Define and Apply Second-Order Differential Operator Source: https://github.com/maroba/findiff/blob/master/docs/source/examples-basic.rst This snippet shows how to define a second-order differential operator using the Diff class and apply it to a function. ```ipython3 linear_op = Diff(0, dx)**2 + 2 * Diff(0, dx) * Diff(1, dy) + Diff(1, dy)**2 ``` -------------------------------- ### Apply 1D Second Derivative Source: https://github.com/maroba/findiff/blob/master/docs/source/examples-basic.rst Applies the second derivative operator to the sine and cosine arrays to compute their second derivatives numerically. ```ipython3 result_f = d2_dx2(f) result_g = d2_dx2(g) ``` -------------------------------- ### Define Mixed Partial Derivative Source: https://github.com/maroba/findiff/blob/master/docs/source/getstarted.rst Defines mixed partial derivatives by multiplying Diff objects representing derivatives along different axes. ```ipython Diff(0, dx)**2 * Diff(1, dy) ``` -------------------------------- ### Calculate mixed partial derivative in 3D Source: https://github.com/maroba/findiff/blob/master/examples/examples-basic.ipynb Shows how to calculate a mixed partial derivative (d^3 f / dx^2 dy) in 3D by specifying multiple derivative tuples. ```python from findiff import FinDiff d3_dx2dy = FinDiff((0, dx, 2), (1, dy)) result = d3_dx2dy(f) ``` -------------------------------- ### Create 1D Second Derivative Operator Source: https://github.com/maroba/findiff/blob/master/docs/source/examples-basic.rst Creates a Diff object representing the second derivative operator (d^2/dx^2) for a 1D array with a given grid spacing. ```ipython3 d_dx = Diff(0, dx) d2_dx2 = Diff(0, dx) ** 2 ``` -------------------------------- ### Create 1D Tenth Order Derivative Operator Source: https://github.com/maroba/findiff/blob/master/docs/source/examples-basic.rst Creates a Diff object for the second derivative with tenth-order accuracy and applies it to a function. ```ipython3 d2_dx2 = Diff(0, dx, acc=10) ** 2 result = d2_dx2(f) ``` -------------------------------- ### Define and Apply Differential Operator with Symbolic Multiplication Source: https://github.com/maroba/findiff/blob/master/docs/source/examples-basic.rst This snippet demonstrates defining a differential operator that includes multiplication by symbolic variables like 'x' and 'y^2'. ```ipython3 linear_op = X * Diff(0, dx) + Y**2 * Diff(1, dy) ``` -------------------------------- ### Import findiff and numpy Source: https://github.com/maroba/findiff/blob/master/docs/source/examples-polar.rst Imports necessary libraries, numpy for numerical operations and findiff for differential calculations. ```ipython3 import numpy as np from findiff import Diff, Laplacian ``` -------------------------------- ### Apply Stencil to Individual Grid Point Source: https://github.com/maroba/findiff/blob/master/docs/source/getstarted.rst Applies a pre-computed stencil to a specific grid point within an array. The library automatically selects the appropriate stencil based on the point's location (e.g., corner, edge, interior). ```ipython x = y = np.linspace(0, 1, 101) X, Y = np.meshgrid(x, y, indexing='ij') f = X**3 + Y**3 stencils = laplacian.stencil(f.shape) stencils.apply(f, (100, 100)) # evaluate at f[100, 100] ``` -------------------------------- ### Calculate 2nd derivative of sin(x) and cos(x) Source: https://github.com/maroba/findiff/blob/master/examples/examples-basic.ipynb Demonstrates calculating the second derivative of 1D arrays representing sin(x) and cos(x) using the Diff object with a specified accuracy. ```python x = np.linspace(0, 10, 100) dx = x[1] - x[0] f = np.sin(x) g = np.cos(x) d2_dx2 = Diff(0, dx, acc=2) result_f = d2_dx2(f) result_g = d2_dx2(g) ``` -------------------------------- ### Calculate 2nd derivative with 10th order accuracy Source: https://github.com/maroba/findiff/blob/master/examples/examples-basic.ipynb Illustrates how to specify a higher accuracy order (10th order) when creating a FinDiff object for calculating derivatives. ```python from findiff import FinDiff d2_dx2 = FinDiff(0, dx, 2, acc=10) result = d2_dx2(f) ``` -------------------------------- ### Findiff Module Overview Source: https://github.com/maroba/findiff/blob/master/docs/source/modules.rst This section provides an overview of the main modules within the Findiff project. It includes references to documentation for finite differences, coefficients, partial differential equations, and stencils. ```Markdown .. toctree:: :maxdepth: 2 diff coefs pde stencils ``` -------------------------------- ### Define General Differential Operator Source: https://github.com/maroba/findiff/blob/master/docs/source/getstarted.rst Combines Diff objects to represent complex differential operators, such as the wave operator. ```ipython 1 / c**2 * Diff(0, dt)**2 - Diff(1, dx)**2 ``` ```ipython d_dx = Diff(0, dx) d_dy = Diff(1, dy) (d_dx - d_dy) * (d_dx + d_dy) ``` -------------------------------- ### Define Laplacian Operator Source: https://github.com/maroba/findiff/blob/master/docs/source/getstarted.rst Defines a second-order accurate Laplacian operator using the Diff class from the findiff library. This operator can then be applied to arrays. ```ipython laplacian = Diff(0, dx) ** 2 + Diff(1, dy) ** 2 ``` -------------------------------- ### Custom Stencil Derivative Operator Definition Source: https://github.com/maroba/findiff/blob/master/docs/source/getstarted.rst Defines the derivative operator for a custom stencil. This dictionary specifies the order of the partial derivatives with respect to each dimension. ```code { (2, 0): 1, # 1 * d^2/dx^2 (0, 2): 1 # 1 * d^2/dy^2 } ``` -------------------------------- ### Handle Periodic Boundary Conditions Source: https://github.com/maroba/findiff/blob/master/README.md Demonstrates how to specify periodic boundary conditions for derivative operators, either during initialization or by updating the grid settings. ```Python d_dx = Diff(0, dx, periodic=True) # or later d_dx = Diff(0) d_dx.set_grid({0: {"h": dx, "periodic": True}}) ``` -------------------------------- ### Import Libraries for FinDiff Source: https://github.com/maroba/findiff/blob/master/examples/examples-non-uniform-grids.ipynb Imports necessary libraries including numpy for numerical operations, FinDiff for finite difference calculations, and matplotlib for plotting. Sets up the plotting environment for inline display. ```Python %matplotlib inline import numpy as np from findiff import FinDiff import matplotlib.pyplot as plt ``` -------------------------------- ### Import Libraries and Define Function Source: https://github.com/maroba/findiff/blob/master/docs/source/examples-non-uniform-grids.rst Imports necessary libraries (numpy, findiff, matplotlib) and defines a sample function f(x) and its derivative df_dx(x) for demonstration purposes. ```ipython3 %matplotlib inline import numpy as np from findiff import Diff import matplotlib.pyplot as plt def f(x): return x * np.exp(-x**2) def df_dx(x): return np.exp(-x**2) - 2*x**2*np.exp(-x**2) ``` -------------------------------- ### Creating and Applying Symbolic Derivatives Source: https://github.com/maroba/findiff/blob/master/examples/symbolic.ipynb Shows how to create symbolic second-order derivatives (d2_dx2, d2_dy2) and apply them to mesh functions using specified offsets for finite difference approximations. ```Python d2_dx2, d2_dy2 = [SymbolicDiff(mesh, axis=k, degree=2) for k in range(2)] (d2_dx2(u, at=(m, n), offsets=(-1, 0, 1)) + d2_dy2(u, at=(m, n), offsets=(-1, 0, 1))) ``` -------------------------------- ### Create Stencil for Mixed Partial Derivative Source: https://github.com/maroba/findiff/blob/master/examples/examples-stencils.ipynb Creates a stencil for a mixed partial derivative (∂²/∂x∂y) using a 3x3 grid and calculates its values and accuracy. ```Python offsets = list(product([-1, 0, 1], repeat=2)) stencil = Stencil(offsets, partials={(1, 1): 1}, spacings=(1, 1)) stencil.values, stencil.accuracy ``` -------------------------------- ### Create and Plot Uniform Grids Source: https://github.com/maroba/findiff/blob/master/docs/source/examples-non-uniform-grids.rst Creates two uniform grids (coarse and fine) and plots the function evaluated on these grids alongside the original function to illustrate grid density. ```ipython3 x1 = np.linspace(0, 10, 20) x2 = np.linspace(0, 10, 100) f1 = f(x1) f2 = f(x2) fig = plt.figure(figsize=(16,4)) ax1 = fig.add_subplot(121) ax2 = fig.add_subplot(122) ax1.plot(x_fine, f_fine) ax2.plot(x_fine, f_fine) ax1.plot(x1, f1, 'o') ax2.plot(x2, f2, 'o') ``` -------------------------------- ### Converting to LaTeX Source: https://github.com/maroba/findiff/blob/master/examples/symbolic.ipynb Converts the symbolic finite difference approximation to its LaTeX representation for display. ```Python from sympy import latex print(latex(_)) ``` -------------------------------- ### Import findiff Vector Calculus Classes Source: https://github.com/maroba/findiff/blob/master/examples/examples-vector-calculus.ipynb Imports necessary classes from the findiff library for performing vector calculus operations, including Gradient, Divergence, Laplacian, and Curl. ```python import numpy as np from findiff import Gradient, Divergence, Laplacian, Curl ``` -------------------------------- ### findiff.coefs Module Documentation Source: https://github.com/maroba/findiff/blob/master/docs/source/coefs.rst This section provides the API documentation for the findiff.coefs module. It lists all the members and their functionalities related to finite difference coefficients. ```APIDOC .. automodule:: findiff.coefs :members: ``` -------------------------------- ### Cartesian Laplacian Calculation Source: https://github.com/maroba/findiff/blob/master/docs/source/examples-polar.rst Defines a 2D grid and a function f(x, y) = x^2 + y^2. It then applies the Laplacian operator in Cartesian coordinates to this function and displays the result. ```ipython3 x, y = [np.linspace(-5, 5, 100)] * 2 dx, dy = x[1] - x[0], y[1] - y[0] X, Y = np.meshgrid(x, y, indexing='ij') f = X**2 + Y**2 laplace = Laplacian(h=[dx, dy]) laplace_f = laplace(f) ``` -------------------------------- ### Generate 3x3 Grid Offsets for Stencils Source: https://github.com/maroba/findiff/blob/master/examples/examples-stencils.ipynb Generates a list of all possible 2D offsets within a 3x3 grid centered at (0,0), useful for creating stencils. ```Python from findiff.stencils import Stencil from itertools import product offsets = list(product([-1, 0, 1], repeat=2)) offsets ``` -------------------------------- ### Define 2D Laplacian Stencil with 5 Points Source: https://github.com/maroba/findiff/blob/master/examples/examples-stencils.ipynb Creates a stencil for the 2D Laplacian operator using a 5-point stencil. The 'partials' dictionary specifies the second derivative along the first and second axes, and 'spacings' defines the grid spacing. ```Python from findiff.stencils import Stencil # Which points (given as offsets) to use: offsets = [(0, 0), (1, 0), (-1, 0), (0, 1), (0, -1)] # For the partials argument, see the section above stencil = Stencil(offsets, partials={(2, 0): 1, (0, 2): 1}, spacings=(1, 1)) stencil.values ``` -------------------------------- ### Define Higher-Order Derivatives Source: https://github.com/maroba/findiff/blob/master/README.md Shows how to define higher-order derivatives by exponentiating a base derivative operator. For example, the second derivative with respect to x is represented as Diff(0, dx)**2. ```Python d2_dx2 = Diff(0, dx)**2 ``` -------------------------------- ### findiff.pde Module Members Source: https://github.com/maroba/findiff/blob/master/docs/source/pde.rst Lists all members (classes, functions, variables) available within the findiff.pde module. This is automatically generated documentation. ```APIDOC .. automodule:: findiff.pde :members: ``` -------------------------------- ### Create 1D Second Derivative Stencil Source: https://github.com/maroba/findiff/blob/master/examples/examples-stencils.ipynb Creates a stencil for the second derivative in a 1D grid using a range of offsets and calculates its values and accuracy. ```Python offsets = list(range(-4, 5)) stencil = Stencil(offsets, partials={(2,): 1}, spacings=(1,)) stencil.values, stencil.accuracy ``` -------------------------------- ### Polar Coordinates Laplacian Calculation Source: https://github.com/maroba/findiff/blob/master/docs/source/examples-polar.rst Defines a grid in polar coordinates (r, phi) and the function f(r, phi) = r^2. It constructs the Laplacian operator for polar coordinates and applies it to the function, comparing the output to the Cartesian result. ```ipython3 r = np.linspace(0.1, 10, 100) phi = np.linspace(0, 2*np.pi, 100, endpoint=False) dr, dphi = r[1] - r[0], phi[1] - phi[0] R, Phi = np.meshgrid(r, phi, indexing='ij') f_polar = R**2 laplace_polar = Diff(0, dr)**2 + (1/R) * Diff(0, dr) + (1/R**2) * Diff(1, dphi)**2 result = laplace_polar(f_polar) ``` -------------------------------- ### Create 2D Laplacian Stencil with 3x3 Grid Source: https://github.com/maroba/findiff/blob/master/examples/examples-stencils.ipynb Creates a stencil for the 2D Laplacian operator using all points in a 3x3 grid. The 'partials' dictionary specifies the second derivative along the first and second axes. ```Python # For the partials argument, see the section above stencil = Stencil(offsets, partials={(2, 0): 1, (0, 2): 1}, spacings=(1, 1)) stencil.values ``` -------------------------------- ### Import findiff Vector Calculus Classes Source: https://github.com/maroba/findiff/blob/master/docs/source/examples-vector-calculus.rst Imports necessary classes (Gradient, Divergence, Laplacian, Curl) from the findiff library and numpy for numerical operations. ```ipython3 import numpy as np from findiff import Gradient, Divergence, Laplacian, Curl ``` -------------------------------- ### Simplifying with Uniform Grid Spacing Source: https://github.com/maroba/findiff/blob/master/examples/symbolic.ipynb Substitutes a uniform grid spacing 'h' for dx and dy, and then simplifies the expression. ```Python h = symbols("h") _.subs({dx: h, dy: h}) ``` ```Python _.simplify() ``` -------------------------------- ### Solve Schrödinger Equation with Scipy Source: https://github.com/maroba/findiff/blob/master/docs/source/examples-matrix.rst Constructs the Hamiltonian matrix for the Schrödinger equation by combining the discretized Laplacian and potential energy, then solves the eigenvalue problem using scipy.sparse.linalg.eigs. ```python import scipy.sparse.linalg import numpy as np shape = (10, 10, 10) # Example grid shape # Assuming 'laplace' is a FinDiff object and 'V' is a numpy array representing potential # V = np.random.rand(*shape) # Example potential hamiltonian = -laplace.matrix(shape) + V.reshape(-1) # Solve for the 6 lowest real eigenvalues and eigenfunctions eigenvalues, eigenvectors = scipy.sparse.linalg.eigs(hamiltonian, k=6, which='SR') ``` -------------------------------- ### Create and Plot Uniform Grids Source: https://github.com/maroba/findiff/blob/master/examples/examples-non-uniform-grids.ipynb Creates two uniform grids (coarse and finer) and plots the function values on these grids against the fine grid visualization. This sets up a comparison for derivative calculations. ```Python x1 = np.linspace(0, 10, 20) x2 = np.linspace(0, 10, 100) f1 = f(x1) f2 = f(x2) fig = plt.figure(figsize=(16,4)) ax1 = fig.add_subplot(121) ax2 = fig.add_subplot(122) ax1.plot(x_fine, f_fine) ax2.plot(x_fine, f_fine) ax1.plot(x1, f1, 'o') ax2.plot(x2, f2, 'o') ``` -------------------------------- ### Accessing Meshed Symbols Source: https://github.com/maroba/findiff/blob/master/examples/symbolic.ipynb Demonstrates how to access meshed symbols, which can hold multiple symbolic indices, representing points on the mesh. ```Python u[m, n] ``` ```Python rho[m, n] ``` -------------------------------- ### Calculate and Plot Derivatives on Uniform Grids Source: https://github.com/maroba/findiff/blob/master/docs/source/examples-non-uniform-grids.rst Calculates the numerical first derivative using the findiff library on both uniform grids with different accuracies and plots the results against the exact derivative. ```ipython3 dx1 = x1[1] - x1[0] dx2 = x2[1] - x2[0] d_dx1 = Diff(0, dx1, acc=2) d_dx2 = Diff(0, dx2) df_dx1 = d_dx1(f1) df_dx2 = d_dx2(f2) df_dx_exact = df_dx(x_fine) fig = plt.figure(figsize=(16,4)) ax1 = fig.add_subplot(121) ax2 = fig.add_subplot(122) ax1.plot(x_fine, df_dx_exact) ax2.plot(x_fine, df_dx_exact) ax1.plot(x1, df_dx1, 'o') ax2.plot(x2, df_dx2, 'o') ``` -------------------------------- ### Plot Original Function Source: https://github.com/maroba/findiff/blob/master/docs/source/examples-non-uniform-grids.rst Generates and plots the sample function f(x) over a fine range of x values to visualize its behavior. ```ipython3 x_fine = np.linspace(0, 10, 200) f_fine = f(x_fine) plt.plot(x_fine, f_fine) plt.xlabel("x") plt.ylabel("f") ``` -------------------------------- ### Formulating the Equation Source: https://github.com/maroba/findiff/blob/master/examples/symbolic.ipynb Constructs a sympy Equation object by equating the symbolic finite difference approximation to the source term. ```Python Eq(_, rho[m,n]) ``` -------------------------------- ### Define Function and its Derivative Source: https://github.com/maroba/findiff/blob/master/examples/examples-non-uniform-grids.ipynb Defines a sample function f(x) = x * exp(-x^2) and its analytical first derivative df/dx. These functions are used to test the numerical differentiation methods. ```Python def f(x): return x * np.exp(-x**2) def df_dx(x): return np.exp(-x**2) - 2*x**2*np.exp(-x**2) ``` -------------------------------- ### Solve 1D Forced Harmonic Oscillator with Friction using Findiff Source: https://github.com/maroba/findiff/blob/master/README.md Demonstrates solving a second-order ordinary differential equation with friction and specific boundary conditions using the findiff library. It sets up the differential operator, forcing function, and boundary conditions to find the solution u(t). ```Python from findiff import Diff, Id, PDE shape = (300, ) t = numpy.linspace(0, 10, shape[0]) dt = t[1]-t[0] L = Diff(0, dt)**2 - Diff(0, dt) + 5 * Id() f = numpy.cos(2*t) bc = BoundaryConditions(shape) bc[0] = 0 bc[-1] = 1 pde = PDE(L, f, bc) u = pde.solve() ``` -------------------------------- ### Solve Second-Order ODE with Periodic Boundary Conditions Source: https://github.com/maroba/findiff/blob/master/examples/examples-periodic.ipynb Demonstrates solving a second-order ordinary differential equation with periodic boundary conditions using findiff. The ODE is (d^2/dx^2 + 1)f(x) = 0 with f(0) = f(2*pi) and f(0) = 1. ```python import numpy as np from findiff import Diff, BoundaryConditions, PDE D = Diff(0) ** 2 + 1 shape = 100, x = np.linspace(0, 2*np.pi, shape[0], endpoint=False) dx = x[1] - x[0] D.set_grid({0: {"h": dx, "periodic": True}}) D.set_accuracy(4) bc = BoundaryConditions(shape) bc[0] = 1 ode = PDE(D, np.zeros_like(x), bc) actual = ode.solve() expected = np.cos(x) np.max(abs(actual - expected)) ``` -------------------------------- ### Findiff Citation Information Source: https://github.com/maroba/findiff/blob/master/README.md Provides the citation details for the findiff software package, including a URL and a BibTeX entry for academic referencing. ```BibTeX @misc{findiff, title = {{findiff} Software Package}, author = {M. Baer}, url = {https://github.com/maroba/findiff}, key = {findiff}, note = {\url{https://github.com/maroba/findiff}}, year = {2018} } ``` -------------------------------- ### Solve 2D Heat Conduction with Mixed Boundary Conditions using Findiff Source: https://github.com/maroba/findiff/blob/master/README.md Illustrates solving a 2D heat conduction problem with Dirichlet and Neumann boundary conditions on a plate. The code defines the spatial discretization, the differential operator, the source term (f), and applies mixed boundary conditions to solve for the temperature distribution u(x,y). ```Python shape = (100, 100) x, y = np.linspace(0, 1, shape[0]), np.linspace(0, 1, shape[1]) dx, dy = x[1]-x[0], y[1]-y[0] X, Y = np.meshgrid(x, y, indexing='ij') L = FinDiff(0, dx, 2) + FinDiff(1, dy, 2) f = np.zeros(shape) bc = BoundaryConditions(shape) bc[1,:] = FinDiff(0, dx, 1), 0 # Neumann BC bc[-1,:] = 300. - 200*Y # Dirichlet BC bc[:, 0] = 300. # Dirichlet BC bc[1:-1, -1] = FinDiff(1, dy, 1), 0 # Neumann BC pde = PDE(L, f, bc) u = pde.solve() ```