PyFinitDiff 2.3.2__tar.gz → 2.4.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {pyfinitdiff-2.3.2 → pyfinitdiff-2.4.0}/PKG-INFO +12 -47
- pyfinitdiff-2.4.0/PyFinitDiff/_operator.py +32 -0
- {pyfinitdiff-2.3.2 → pyfinitdiff-2.4.0}/PyFinitDiff/_version.py +1 -1
- {pyfinitdiff-2.3.2 → pyfinitdiff-2.4.0}/PyFinitDiff/finite_difference_1D/finite_difference.py +12 -9
- {pyfinitdiff-2.3.2 → pyfinitdiff-2.4.0}/PyFinitDiff/finite_difference_2D/derivative.py +8 -8
- {pyfinitdiff-2.3.2 → pyfinitdiff-2.4.0}/PyFinitDiff/finite_difference_2D/finite_difference.py +10 -6
- pyfinitdiff-2.4.0/PyFinitDiff/finite_difference_3D/__init__.py +5 -0
- pyfinitdiff-2.4.0/PyFinitDiff/finite_difference_3D/operator.py +236 -0
- {pyfinitdiff-2.3.2 → pyfinitdiff-2.4.0}/PyFinitDiff/triplet.py +52 -39
- {pyfinitdiff-2.3.2 → pyfinitdiff-2.4.0}/PyFinitDiff.egg-info/PKG-INFO +12 -47
- {pyfinitdiff-2.3.2 → pyfinitdiff-2.4.0}/PyFinitDiff.egg-info/SOURCES.txt +5 -0
- {pyfinitdiff-2.3.2 → pyfinitdiff-2.4.0}/README.rst +11 -46
- {pyfinitdiff-2.3.2 → pyfinitdiff-2.4.0}/pyproject.toml +1 -1
- pyfinitdiff-2.4.0/tests/test_3D_operator.py +92 -0
- pyfinitdiff-2.4.0/tests/test_operator_regressions.py +99 -0
- {pyfinitdiff-2.3.2 → pyfinitdiff-2.4.0}/LICENSE +0 -0
- {pyfinitdiff-2.3.2 → pyfinitdiff-2.4.0}/PyFinitDiff/__init__.py +0 -0
- {pyfinitdiff-2.3.2 → pyfinitdiff-2.4.0}/PyFinitDiff/boundary_values.py +0 -0
- {pyfinitdiff-2.3.2 → pyfinitdiff-2.4.0}/PyFinitDiff/coefficients/__init__.py +0 -0
- {pyfinitdiff-2.3.2 → pyfinitdiff-2.4.0}/PyFinitDiff/coefficients/backward.py +0 -0
- {pyfinitdiff-2.3.2 → pyfinitdiff-2.4.0}/PyFinitDiff/coefficients/central.py +0 -0
- {pyfinitdiff-2.3.2 → pyfinitdiff-2.4.0}/PyFinitDiff/coefficients/forward.py +0 -0
- {pyfinitdiff-2.3.2 → pyfinitdiff-2.4.0}/PyFinitDiff/diagonal.py +0 -0
- {pyfinitdiff-2.3.2 → pyfinitdiff-2.4.0}/PyFinitDiff/directories.py +0 -0
- {pyfinitdiff-2.3.2 → pyfinitdiff-2.4.0}/PyFinitDiff/finite_difference_1D/__init__.py +0 -0
- {pyfinitdiff-2.3.2 → pyfinitdiff-2.4.0}/PyFinitDiff/finite_difference_1D/boundaries.py +0 -0
- {pyfinitdiff-2.3.2 → pyfinitdiff-2.4.0}/PyFinitDiff/finite_difference_1D/derivative.py +0 -0
- {pyfinitdiff-2.3.2 → pyfinitdiff-2.4.0}/PyFinitDiff/finite_difference_1D/utils.py +0 -0
- {pyfinitdiff-2.3.2 → pyfinitdiff-2.4.0}/PyFinitDiff/finite_difference_2D/__init__.py +0 -0
- {pyfinitdiff-2.3.2 → pyfinitdiff-2.4.0}/PyFinitDiff/finite_difference_2D/boundaries.py +0 -0
- {pyfinitdiff-2.3.2 → pyfinitdiff-2.4.0}/PyFinitDiff/finite_difference_2D/utils.py +0 -0
- {pyfinitdiff-2.3.2 → pyfinitdiff-2.4.0}/PyFinitDiff.egg-info/dependency_links.txt +0 -0
- {pyfinitdiff-2.3.2 → pyfinitdiff-2.4.0}/PyFinitDiff.egg-info/requires.txt +0 -0
- {pyfinitdiff-2.3.2 → pyfinitdiff-2.4.0}/PyFinitDiff.egg-info/top_level.txt +0 -0
- {pyfinitdiff-2.3.2 → pyfinitdiff-2.4.0}/setup.cfg +0 -0
- {pyfinitdiff-2.3.2 → pyfinitdiff-2.4.0}/tests/test_1D_api.py +0 -0
- {pyfinitdiff-2.3.2 → pyfinitdiff-2.4.0}/tests/test_1D_derivative.py +0 -0
- {pyfinitdiff-2.3.2 → pyfinitdiff-2.4.0}/tests/test_2D_api.py +0 -0
- {pyfinitdiff-2.3.2 → pyfinitdiff-2.4.0}/tests/test_2D_derivative.py +0 -0
- {pyfinitdiff-2.3.2 → pyfinitdiff-2.4.0}/tests/test_2D_eigen.py +0 -0
- {pyfinitdiff-2.3.2 → pyfinitdiff-2.4.0}/tests/test_eighth_order_first_derivative.py +0 -0
- {pyfinitdiff-2.3.2 → pyfinitdiff-2.4.0}/tests/test_triplet.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: PyFinitDiff
|
|
3
|
-
Version: 2.
|
|
3
|
+
Version: 2.4.0
|
|
4
4
|
Summary: A package for generating finite-difference matrices, particularly suited for physics and engineering applications.
|
|
5
5
|
Author-email: Martin Poinsinet de Sivry-Houle <martin.poinsinet.de.sivry@gmail.com>
|
|
6
6
|
License-Expression: MIT
|
|
@@ -67,7 +67,7 @@ PyFinitDiff
|
|
|
67
67
|
|
|
68
68
|
A package for generating finite-difference matrices, particularly suited for physics and engineering applications.
|
|
69
69
|
|
|
70
|
-
Construct sparse derivative operators from the mesh spacing, derivative order,
|
|
70
|
+
Construct 1D, 2D and 3D sparse derivative operators from the mesh spacing, derivative order,
|
|
71
71
|
accuracy, and boundary conditions. Inspect the matrix entries before combining the
|
|
72
72
|
operator with a potential or solving an eigenvalue problem.
|
|
73
73
|
|
|
@@ -100,55 +100,20 @@ Inspect a two-dimensional finite-difference stencil
|
|
|
100
100
|
.. code-block:: python
|
|
101
101
|
|
|
102
102
|
"""
|
|
103
|
-
|
|
104
|
-
|
|
103
|
+
Inspect the sparse pattern of a five-point stencil
|
|
104
|
+
==================================================
|
|
105
105
|
|
|
106
|
-
|
|
107
|
-
|
|
106
|
+
On a square grid the second-order Laplacian couples each interior sample
|
|
107
|
+
to its four nearest neighbors. Plot its matrix entries to see how those
|
|
108
|
+
neighbors become five bands when the grid is flattened into a vector.
|
|
108
109
|
"""
|
|
109
110
|
|
|
110
|
-
|
|
111
|
-
# .. list-table:: Finite-difference parameters
|
|
112
|
-
# :widths: 25
|
|
113
|
-
# :header-rows: 1
|
|
114
|
-
#
|
|
115
|
-
# * - boundaries: {left: 0, right: 0, top: 0, bottom: 0}
|
|
116
|
-
# * - derivative: 2
|
|
117
|
-
# * - accuracy: 4
|
|
118
|
-
|
|
119
|
-
# %%
|
|
120
|
-
# Importing required packages
|
|
121
|
-
# ---------------------------
|
|
122
|
-
# Here we import the necessary libraries for numerical computations and finite difference operations.
|
|
123
|
-
|
|
124
|
-
from PyFinitDiff.finite_difference_2D import FiniteDifference, Boundaries
|
|
125
|
-
import matplotlib.pyplot as plt
|
|
126
|
-
|
|
127
|
-
# %%
|
|
128
|
-
# Setting up the finite difference instance and boundaries
|
|
129
|
-
# ---------------------------------------------------------
|
|
130
|
-
# We define the grid size and set up the finite difference instance with specified boundary conditions.
|
|
131
|
-
|
|
132
|
-
sparse_instance = FiniteDifference(
|
|
133
|
-
n_x=20,
|
|
134
|
-
n_y=20,
|
|
135
|
-
dx=1,
|
|
136
|
-
dy=1,
|
|
137
|
-
derivative=2,
|
|
138
|
-
accuracy=2,
|
|
139
|
-
boundaries=Boundaries()
|
|
140
|
-
)
|
|
141
|
-
|
|
142
|
-
# %%
|
|
143
|
-
# Visualizing the triplets with matplotlib
|
|
144
|
-
# -----------------------------------------
|
|
145
|
-
# We plot the triplets using matplotlib to visualize the finite difference operator.
|
|
146
|
-
|
|
147
|
-
sparse_instance.triplet.plot()
|
|
111
|
+
from PyFinitDiff.finite_difference_2D import Boundaries, FiniteDifference
|
|
148
112
|
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
113
|
+
laplacian = FiniteDifference(
|
|
114
|
+
n_x=20, n_y=20, dx=1, dy=1, derivative=2, accuracy=2, boundaries=Boundaries()
|
|
115
|
+
)
|
|
116
|
+
laplacian.triplet.plot()
|
|
152
117
|
|
|
153
118
|
.. figure:: https://raw.githubusercontent.com/MartinPdeS/PyFinitDiff/HEAD/docs/images/triplet_example_0.png
|
|
154
119
|
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"""Cache management shared by the mutable finite-difference operators."""
|
|
2
|
+
|
|
3
|
+
from copy import copy
|
|
4
|
+
from dataclasses import fields
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class MutableOperator:
|
|
8
|
+
"""Refresh derived state after assignment and track edits to boundary values."""
|
|
9
|
+
|
|
10
|
+
def __setattr__(self, name, value):
|
|
11
|
+
"""Reinitialize derived state when a public configuration field changes."""
|
|
12
|
+
if "_triplet" not in self.__dict__ or name not in self.__dataclass_fields__:
|
|
13
|
+
super().__setattr__(name, value)
|
|
14
|
+
return
|
|
15
|
+
previous = getattr(self, name)
|
|
16
|
+
super().__setattr__(name, value)
|
|
17
|
+
try:
|
|
18
|
+
self.__post_init__()
|
|
19
|
+
except Exception:
|
|
20
|
+
super().__setattr__(name, previous)
|
|
21
|
+
self.__post_init__()
|
|
22
|
+
raise
|
|
23
|
+
|
|
24
|
+
def _boundary_values(self):
|
|
25
|
+
"""Return the boundary conditions that determine the cached matrix."""
|
|
26
|
+
return tuple(getattr(self.boundaries, field.name) for field in fields(self.boundaries))
|
|
27
|
+
|
|
28
|
+
def _mesh_boundaries(self):
|
|
29
|
+
"""Bind boundary lookups to this grid even when operators share settings."""
|
|
30
|
+
boundaries = copy(self.boundaries)
|
|
31
|
+
boundaries.mesh_info = self.mesh_info
|
|
32
|
+
return boundaries
|
{pyfinitdiff-2.3.2 → pyfinitdiff-2.4.0}/PyFinitDiff/finite_difference_1D/finite_difference.py
RENAMED
|
@@ -4,6 +4,8 @@
|
|
|
4
4
|
from pydantic.dataclasses import dataclass
|
|
5
5
|
from pydantic import ConfigDict
|
|
6
6
|
from dataclasses import field
|
|
7
|
+
from PyFinitDiff._operator import MutableOperator
|
|
8
|
+
from PyFinitDiff.triplet import Triplet
|
|
7
9
|
from PyFinitDiff.coefficients import FiniteCoefficients
|
|
8
10
|
from PyFinitDiff.finite_difference_1D.boundaries import Boundaries
|
|
9
11
|
from PyFinitDiff.finite_difference_1D.utils import MeshInfo
|
|
@@ -19,7 +21,7 @@ config_dict = ConfigDict(
|
|
|
19
21
|
|
|
20
22
|
|
|
21
23
|
@dataclass(config=config_dict)
|
|
22
|
-
class FiniteDifference:
|
|
24
|
+
class FiniteDifference(MutableOperator):
|
|
23
25
|
"""
|
|
24
26
|
Represents a specific finite difference configuration, including the discretization
|
|
25
27
|
of the mesh, derivative order, accuracy, and boundary conditions.
|
|
@@ -93,7 +95,7 @@ class FiniteDifference:
|
|
|
93
95
|
tuple
|
|
94
96
|
The triplet representation of the finite-difference matrix.
|
|
95
97
|
"""
|
|
96
|
-
if
|
|
98
|
+
if self._triplet is None or self._cached_boundary_values != self._boundary_values():
|
|
97
99
|
self.construct_triplet()
|
|
98
100
|
return self._triplet
|
|
99
101
|
|
|
@@ -137,10 +139,11 @@ class FiniteDifference:
|
|
|
137
139
|
tuple
|
|
138
140
|
A tuple containing the offset, value, and corresponding boundary type.
|
|
139
141
|
"""
|
|
142
|
+
boundaries = self._mesh_boundaries()
|
|
140
143
|
for offset, value in coefficients:
|
|
141
144
|
offset *= offset_multiplier
|
|
142
145
|
|
|
143
|
-
boundary =
|
|
146
|
+
boundary = boundaries.offset_to_boundary(offset=offset)
|
|
144
147
|
|
|
145
148
|
yield offset, value, boundary
|
|
146
149
|
|
|
@@ -228,9 +231,9 @@ class FiniteDifference:
|
|
|
228
231
|
"""
|
|
229
232
|
Constructs the triplet representation of the finite-difference matrix for the x direction.
|
|
230
233
|
"""
|
|
231
|
-
|
|
232
|
-
offset_multiplier=1,
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
self.
|
|
234
|
+
if self.x_derivative:
|
|
235
|
+
diagonals = self.get_diagonal_set_full(offset_multiplier=1, delta=self._dx)
|
|
236
|
+
self._triplet = diagonals.triplet
|
|
237
|
+
else:
|
|
238
|
+
self._triplet = Triplet(array=[[0, 0, 0]], shape=self.shape)
|
|
239
|
+
self._cached_boundary_values = self._boundary_values()
|
|
@@ -13,14 +13,14 @@ def get_array_derivative(
|
|
|
13
13
|
dy: float = 1,
|
|
14
14
|
x_derivative: bool = True,
|
|
15
15
|
y_derivative: bool = True,
|
|
16
|
-
boundaries: module.Boundaries =
|
|
16
|
+
boundaries: module.Boundaries | None = None) -> np.ndarray:
|
|
17
17
|
"""
|
|
18
|
-
Compute the
|
|
18
|
+
Compute and sum the selected directional derivatives of a 2D array.
|
|
19
19
|
|
|
20
20
|
Parameters
|
|
21
21
|
----------
|
|
22
22
|
array : np.ndarray
|
|
23
|
-
|
|
23
|
+
Samples of shape (n_y, n_x), with x along columns and y along rows.
|
|
24
24
|
derivative : int
|
|
25
25
|
The order of the derivative.
|
|
26
26
|
accuracy : int, optional
|
|
@@ -39,7 +39,7 @@ def get_array_derivative(
|
|
|
39
39
|
Returns
|
|
40
40
|
-------
|
|
41
41
|
np.ndarray
|
|
42
|
-
|
|
42
|
+
Sum of the selected partial derivatives, with the same shape as the input.
|
|
43
43
|
|
|
44
44
|
Examples
|
|
45
45
|
--------
|
|
@@ -47,7 +47,7 @@ def get_array_derivative(
|
|
|
47
47
|
>>> get_array_derivative(array, derivative=1, dx=0.1, dy=0.1)
|
|
48
48
|
array([[ ... ], [ ... ]])
|
|
49
49
|
"""
|
|
50
|
-
|
|
50
|
+
n_y, n_x = array.shape
|
|
51
51
|
|
|
52
52
|
finite_difference = module.FiniteDifference(
|
|
53
53
|
n_x=n_x,
|
|
@@ -56,13 +56,13 @@ def get_array_derivative(
|
|
|
56
56
|
dy=dy,
|
|
57
57
|
derivative=derivative,
|
|
58
58
|
accuracy=accuracy,
|
|
59
|
-
boundaries=boundaries,
|
|
59
|
+
boundaries=module.Boundaries() if boundaries is None else boundaries,
|
|
60
60
|
x_derivative=x_derivative,
|
|
61
61
|
y_derivative=y_derivative
|
|
62
62
|
)
|
|
63
63
|
|
|
64
64
|
triplet = finite_difference.triplet
|
|
65
65
|
|
|
66
|
-
gradient = triplet.to_scipy_sparse()
|
|
66
|
+
gradient = triplet.to_scipy_sparse() @ array.ravel()
|
|
67
67
|
|
|
68
|
-
return gradient.reshape(
|
|
68
|
+
return gradient.reshape(array.shape)
|
{pyfinitdiff-2.3.2 → pyfinitdiff-2.4.0}/PyFinitDiff/finite_difference_2D/finite_difference.py
RENAMED
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
from pydantic.dataclasses import dataclass
|
|
5
5
|
from pydantic import ConfigDict
|
|
6
6
|
from dataclasses import field
|
|
7
|
+
from PyFinitDiff._operator import MutableOperator
|
|
7
8
|
from PyFinitDiff.coefficients import FiniteCoefficients
|
|
8
9
|
from PyFinitDiff.triplet import Triplet
|
|
9
10
|
from PyFinitDiff.finite_difference_2D.boundaries import Boundaries
|
|
@@ -20,7 +21,7 @@ config_dict = ConfigDict(
|
|
|
20
21
|
|
|
21
22
|
|
|
22
23
|
@dataclass(config=config_dict)
|
|
23
|
-
class FiniteDifference:
|
|
24
|
+
class FiniteDifference(MutableOperator):
|
|
24
25
|
"""
|
|
25
26
|
Represents a specific finite difference configuration, defined by the discretization
|
|
26
27
|
of the mesh, derivative order, accuracy, and boundary conditions.
|
|
@@ -108,7 +109,7 @@ class FiniteDifference:
|
|
|
108
109
|
Triplet
|
|
109
110
|
The Triplet instance containing the array and shape.
|
|
110
111
|
"""
|
|
111
|
-
if
|
|
112
|
+
if self._triplet is None or self._cached_boundary_values != self._boundary_values():
|
|
112
113
|
self.construct_triplet()
|
|
113
114
|
return self._triplet
|
|
114
115
|
|
|
@@ -152,9 +153,10 @@ class FiniteDifference:
|
|
|
152
153
|
tuple
|
|
153
154
|
A tuple containing the offset, value, and corresponding boundary type.
|
|
154
155
|
"""
|
|
156
|
+
boundaries = self._mesh_boundaries()
|
|
155
157
|
for offset, value in coefficients:
|
|
156
158
|
offset *= offset_multiplier
|
|
157
|
-
boundary =
|
|
159
|
+
boundary = boundaries.offset_to_boundary(offset=offset)
|
|
158
160
|
yield offset, value, boundary
|
|
159
161
|
|
|
160
162
|
def _add_diagonal_coefficient(self, coefficient_type: str, offset_multiplier: int, delta: float) -> 'DiagonalSet':
|
|
@@ -238,18 +240,20 @@ class FiniteDifference:
|
|
|
238
240
|
"""
|
|
239
241
|
Constructs the Triplet instance for the finite-difference configuration.
|
|
240
242
|
"""
|
|
241
|
-
|
|
243
|
+
triplet = Triplet(array=[[0, 0, 0]], shape=self.mesh_info.shape)
|
|
242
244
|
|
|
243
245
|
if self.x_derivative:
|
|
244
246
|
x_diagonals = self.get_diagonal_set_full(
|
|
245
247
|
offset_multiplier=1,
|
|
246
248
|
delta=self._dx
|
|
247
249
|
)
|
|
248
|
-
|
|
250
|
+
triplet += x_diagonals.triplet
|
|
249
251
|
|
|
250
252
|
if self.y_derivative:
|
|
251
253
|
y_diagonals = self.get_diagonal_set_full(
|
|
252
254
|
offset_multiplier=self.n_x,
|
|
253
255
|
delta=self._dy
|
|
254
256
|
)
|
|
255
|
-
|
|
257
|
+
triplet += y_diagonals.triplet
|
|
258
|
+
self._triplet = triplet
|
|
259
|
+
self._cached_boundary_values = self._boundary_values()
|
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
"""Cartesian volume operators indexed with x varying fastest."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import field
|
|
4
|
+
from typing import Annotated, Literal
|
|
5
|
+
import numpy as np
|
|
6
|
+
from pydantic import ConfigDict, Field
|
|
7
|
+
from pydantic.dataclasses import dataclass
|
|
8
|
+
from scipy import sparse
|
|
9
|
+
from PyFinitDiff.boundary_values import BoundaryValue
|
|
10
|
+
from PyFinitDiff.coefficients.backward import coefficients as backward_stencils
|
|
11
|
+
from PyFinitDiff.coefficients.central import coefficients as centered_stencils
|
|
12
|
+
from PyFinitDiff.coefficients.forward import coefficients as forward_stencils
|
|
13
|
+
from PyFinitDiff.triplet import Triplet
|
|
14
|
+
|
|
15
|
+
_config = ConfigDict(validate_assignment=True, extra="forbid")
|
|
16
|
+
Count = Annotated[int, Field(gt=0, strict=True)]
|
|
17
|
+
Spacing = Annotated[float, Field(gt=0, allow_inf_nan=False)]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass(kw_only=True, config=_config)
|
|
21
|
+
class Boundaries:
|
|
22
|
+
"""Boundary conditions at the six faces of a Cartesian grid.
|
|
23
|
+
|
|
24
|
+
Parameters
|
|
25
|
+
----------
|
|
26
|
+
left, right : BoundaryValue
|
|
27
|
+
Low and high x faces.
|
|
28
|
+
bottom, top : BoundaryValue
|
|
29
|
+
Low and high y faces.
|
|
30
|
+
front, back : BoundaryValue
|
|
31
|
+
Low and high z faces.
|
|
32
|
+
|
|
33
|
+
Notes
|
|
34
|
+
-----
|
|
35
|
+
ZERO uses zero exterior samples. SYMMETRIC and ANTI_SYMMETRIC reflect
|
|
36
|
+
samples about the endpoint with even and odd parity, respectively.
|
|
37
|
+
NONE uses a one-sided stencil wherever a centered row crosses that face.
|
|
38
|
+
The active axis must contain each one-sided or reflected stencil it uses.
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
left: BoundaryValue = BoundaryValue.ZERO
|
|
42
|
+
right: BoundaryValue = BoundaryValue.ZERO
|
|
43
|
+
bottom: BoundaryValue = BoundaryValue.ZERO
|
|
44
|
+
top: BoundaryValue = BoundaryValue.ZERO
|
|
45
|
+
front: BoundaryValue = BoundaryValue.ZERO
|
|
46
|
+
back: BoundaryValue = BoundaryValue.ZERO
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _axis_matrix(*, size, spacing, derivative, accuracy, low, high):
|
|
50
|
+
"""Assemble one line from the package coefficient tables, handling each face locally."""
|
|
51
|
+
order, precision = f"d{derivative}", f"a{accuracy}"
|
|
52
|
+
center = centered_stencils[order][precision]
|
|
53
|
+
rows, columns, weights = [], [], []
|
|
54
|
+
for row in range(size):
|
|
55
|
+
stencil = center
|
|
56
|
+
if row + center[0][0] < 0 and low == BoundaryValue.NONE:
|
|
57
|
+
stencil = forward_stencils[order].get(precision)
|
|
58
|
+
elif row + center[-1][0] >= size and high == BoundaryValue.NONE:
|
|
59
|
+
stencil = backward_stencils[order].get(precision)
|
|
60
|
+
if stencil is None:
|
|
61
|
+
raise ValueError(
|
|
62
|
+
f"No one-sided stencil for derivative {derivative} at accuracy {accuracy}"
|
|
63
|
+
)
|
|
64
|
+
for offset, weight in stencil:
|
|
65
|
+
column = row + offset
|
|
66
|
+
if column < 0 or column >= size:
|
|
67
|
+
face = low if column < 0 else high
|
|
68
|
+
if stencil is not center:
|
|
69
|
+
raise ValueError(
|
|
70
|
+
f"Axis of length {size} is too short for the one-sided stencil"
|
|
71
|
+
)
|
|
72
|
+
if face == BoundaryValue.ZERO:
|
|
73
|
+
continue
|
|
74
|
+
column = -column if column < 0 else 2 * (size - 1) - column
|
|
75
|
+
if not 0 <= column < size:
|
|
76
|
+
raise ValueError(
|
|
77
|
+
f"Axis of length {size} is too short for the reflected stencil"
|
|
78
|
+
)
|
|
79
|
+
if face == BoundaryValue.ANTI_SYMMETRIC:
|
|
80
|
+
weight = -weight
|
|
81
|
+
rows.append(row)
|
|
82
|
+
columns.append(column)
|
|
83
|
+
weights.append(weight)
|
|
84
|
+
values = np.asarray(weights) / spacing**derivative
|
|
85
|
+
return sparse.csr_matrix((values, (rows, columns)), shape=(size, size))
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
@dataclass(kw_only=True, config=_config)
|
|
89
|
+
class FiniteDifference:
|
|
90
|
+
"""Construct the sum of selected Cartesian partial derivatives on a uniform grid.
|
|
91
|
+
|
|
92
|
+
Parameters
|
|
93
|
+
----------
|
|
94
|
+
n_x, n_y, n_z : int
|
|
95
|
+
Positive sample counts along x, y and z.
|
|
96
|
+
dx, dy, dz : float
|
|
97
|
+
Positive finite sample spacings in the same length units.
|
|
98
|
+
derivative : {1, 2, 3}
|
|
99
|
+
Derivative order along each enabled axis. Order two on all axes
|
|
100
|
+
gives the Laplacian.
|
|
101
|
+
accuracy : {2, 4, 6, 8}
|
|
102
|
+
Stencil accuracy. Eighth order is available for first derivatives
|
|
103
|
+
and centered second derivatives.
|
|
104
|
+
boundaries : Boundaries
|
|
105
|
+
Face conditions. The default uses zero exterior values.
|
|
106
|
+
x_derivative, y_derivative, z_derivative : bool
|
|
107
|
+
Directions to include in the sum.
|
|
108
|
+
|
|
109
|
+
Notes
|
|
110
|
+
-----
|
|
111
|
+
Multiply the sparse matrix by a C-flattened volume of shape
|
|
112
|
+
(n_z, n_y, n_x). The result has units of field / length**derivative.
|
|
113
|
+
"""
|
|
114
|
+
|
|
115
|
+
n_x: Count
|
|
116
|
+
n_y: Count
|
|
117
|
+
n_z: Count
|
|
118
|
+
dx: Spacing = 1.0
|
|
119
|
+
dy: Spacing = 1.0
|
|
120
|
+
dz: Spacing = 1.0
|
|
121
|
+
derivative: Literal[1, 2, 3] = 1
|
|
122
|
+
accuracy: Literal[2, 4, 6, 8] = 2
|
|
123
|
+
boundaries: Boundaries = field(default_factory=Boundaries)
|
|
124
|
+
x_derivative: bool = True
|
|
125
|
+
y_derivative: bool = True
|
|
126
|
+
z_derivative: bool = True
|
|
127
|
+
|
|
128
|
+
@property
|
|
129
|
+
def shape(self):
|
|
130
|
+
"""Grid dimensions (n_x, n_y, n_z), in operator parameter order."""
|
|
131
|
+
return (self.n_x, self.n_y, self.n_z)
|
|
132
|
+
|
|
133
|
+
def _configuration(self):
|
|
134
|
+
"""Return operator inputs in assembly order, including mutable face conditions."""
|
|
135
|
+
faces = self.boundaries
|
|
136
|
+
return (
|
|
137
|
+
(
|
|
138
|
+
(self.n_x, self.dx, self.x_derivative, faces.left, faces.right),
|
|
139
|
+
(self.n_y, self.dy, self.y_derivative, faces.bottom, faces.top),
|
|
140
|
+
(self.n_z, self.dz, self.z_derivative, faces.front, faces.back),
|
|
141
|
+
),
|
|
142
|
+
self.derivative,
|
|
143
|
+
self.accuracy,
|
|
144
|
+
)
|
|
145
|
+
|
|
146
|
+
def construct_triplet(self):
|
|
147
|
+
"""Rebuild the sparse volume operator from its one-dimensional factors."""
|
|
148
|
+
configuration = self._configuration()
|
|
149
|
+
axes, derivative, accuracy = configuration
|
|
150
|
+
if f"a{accuracy}" not in centered_stencils[f"d{derivative}"]:
|
|
151
|
+
raise ValueError(
|
|
152
|
+
f"No centered stencil for derivative {derivative} at accuracy {accuracy}"
|
|
153
|
+
)
|
|
154
|
+
factors = []
|
|
155
|
+
for size, spacing, enabled, low, high in axes:
|
|
156
|
+
if enabled:
|
|
157
|
+
matrix = _axis_matrix(
|
|
158
|
+
size=size,
|
|
159
|
+
spacing=spacing,
|
|
160
|
+
derivative=derivative,
|
|
161
|
+
accuracy=accuracy,
|
|
162
|
+
low=low,
|
|
163
|
+
high=high,
|
|
164
|
+
)
|
|
165
|
+
else:
|
|
166
|
+
matrix = sparse.csr_matrix((size, size))
|
|
167
|
+
factors.append(matrix)
|
|
168
|
+
x, y, z = factors
|
|
169
|
+
matrix = sparse.kronsum(sparse.kronsum(x, y, format="csr"), z, format="coo")
|
|
170
|
+
matrix.eliminate_zeros()
|
|
171
|
+
entries = np.column_stack((matrix.row, matrix.col, matrix.data))
|
|
172
|
+
object.__setattr__(
|
|
173
|
+
self, "_cache", (configuration, Triplet(shape=self.shape, array=entries))
|
|
174
|
+
)
|
|
175
|
+
|
|
176
|
+
@property
|
|
177
|
+
def triplet(self):
|
|
178
|
+
"""Return the cached Triplet, rebuilding after configuration changes."""
|
|
179
|
+
cache = getattr(self, "_cache", None)
|
|
180
|
+
if cache is None or cache[0] != self._configuration():
|
|
181
|
+
self.construct_triplet()
|
|
182
|
+
return self._cache[1]
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def get_array_derivative(
|
|
186
|
+
*,
|
|
187
|
+
array,
|
|
188
|
+
derivative,
|
|
189
|
+
accuracy=4,
|
|
190
|
+
dx=1.0,
|
|
191
|
+
dy=1.0,
|
|
192
|
+
dz=1.0,
|
|
193
|
+
x_derivative=True,
|
|
194
|
+
y_derivative=True,
|
|
195
|
+
z_derivative=True,
|
|
196
|
+
boundaries=None,
|
|
197
|
+
):
|
|
198
|
+
"""Apply the sum of selected derivatives to a Cartesian volume.
|
|
199
|
+
|
|
200
|
+
Parameters
|
|
201
|
+
----------
|
|
202
|
+
array : array_like
|
|
203
|
+
Real or complex field with shape (n_z, n_y, n_x).
|
|
204
|
+
derivative, accuracy : int
|
|
205
|
+
Derivative order and stencil accuracy.
|
|
206
|
+
dx, dy, dz : float
|
|
207
|
+
Sample spacings along the three physical axes.
|
|
208
|
+
x_derivative, y_derivative, z_derivative : bool
|
|
209
|
+
Select the partial derivatives to sum.
|
|
210
|
+
boundaries : Boundaries, optional
|
|
211
|
+
Face conditions for the volume.
|
|
212
|
+
|
|
213
|
+
Returns
|
|
214
|
+
-------
|
|
215
|
+
numpy.ndarray
|
|
216
|
+
Derivative sum with the input shape, in field / length**derivative.
|
|
217
|
+
"""
|
|
218
|
+
volume = np.asarray(array)
|
|
219
|
+
if volume.ndim != 3:
|
|
220
|
+
raise ValueError("Expected a volume with shape (n_z, n_y, n_x)")
|
|
221
|
+
n_z, n_y, n_x = volume.shape
|
|
222
|
+
operator = FiniteDifference(
|
|
223
|
+
n_x=n_x,
|
|
224
|
+
n_y=n_y,
|
|
225
|
+
n_z=n_z,
|
|
226
|
+
dx=dx,
|
|
227
|
+
dy=dy,
|
|
228
|
+
dz=dz,
|
|
229
|
+
derivative=derivative,
|
|
230
|
+
accuracy=accuracy,
|
|
231
|
+
x_derivative=x_derivative,
|
|
232
|
+
y_derivative=y_derivative,
|
|
233
|
+
z_derivative=z_derivative,
|
|
234
|
+
boundaries=Boundaries() if boundaries is None else boundaries,
|
|
235
|
+
)
|
|
236
|
+
return (operator.triplet.to_scipy_sparse() @ volume.ravel()).reshape(volume.shape)
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env python
|
|
2
2
|
# -*- coding: utf-8 -*-
|
|
3
3
|
|
|
4
|
-
from typing import
|
|
4
|
+
from typing import Tuple, Union
|
|
5
5
|
import numpy
|
|
6
6
|
from scipy.sparse import coo_matrix
|
|
7
7
|
from dataclasses import dataclass
|
|
@@ -258,22 +258,16 @@ class Triplet:
|
|
|
258
258
|
Triplet
|
|
259
259
|
A new Triplet instance with duplicate entries removed.
|
|
260
260
|
"""
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
index_to_delete.append(index_to_merge)
|
|
272
|
-
new_array[index_to_keep, 2] += new_array[index_to_merge, 2]
|
|
273
|
-
|
|
274
|
-
triplet_array = numpy.delete(new_array, index_to_delete, axis=0)
|
|
275
|
-
|
|
276
|
-
return Triplet(array=triplet_array, shape=self.shape)
|
|
261
|
+
_, first, groups = numpy.unique(
|
|
262
|
+
self.index, axis=0, return_index=True, return_inverse=True
|
|
263
|
+
)
|
|
264
|
+
totals = numpy.zeros(len(first), dtype=self.values.dtype)
|
|
265
|
+
numpy.add.at(totals, groups.ravel(), self.values)
|
|
266
|
+
# Keep the first occurrence of each coordinate in input order.
|
|
267
|
+
order = numpy.argsort(first)
|
|
268
|
+
merged = self.array[first[order]]
|
|
269
|
+
merged[:, 2] = totals[order]
|
|
270
|
+
return Triplet(array=merged, shape=self.shape.copy())
|
|
277
271
|
|
|
278
272
|
def coincide_i(self, mask: 'Triplet') -> None:
|
|
279
273
|
"""
|
|
@@ -338,13 +332,7 @@ class Triplet:
|
|
|
338
332
|
"""
|
|
339
333
|
Merge duplicate entries by summing their values.
|
|
340
334
|
"""
|
|
341
|
-
|
|
342
|
-
if duplicates.size == 0:
|
|
343
|
-
return
|
|
344
|
-
for duplicate in duplicates:
|
|
345
|
-
first_idx = duplicate[0]
|
|
346
|
-
self.array[first_idx, 2] = self.array[duplicate, 2].sum()
|
|
347
|
-
self.delete(duplicate[1:])
|
|
335
|
+
self.array = self.remove_duplicate().array
|
|
348
336
|
|
|
349
337
|
def get_duplicate_index(self) -> numpy.ndarray:
|
|
350
338
|
"""
|
|
@@ -433,7 +421,7 @@ class Triplet:
|
|
|
433
421
|
Triplet
|
|
434
422
|
A new Triplet instance with the shifted diagonal.
|
|
435
423
|
"""
|
|
436
|
-
diagonal_triplet = DiagonalTriplet(numpy.
|
|
424
|
+
diagonal_triplet = DiagonalTriplet(numpy.full(numpy.prod(self.shape), value), shape=self.shape)
|
|
437
425
|
return self + diagonal_triplet
|
|
438
426
|
|
|
439
427
|
def update_elements(self, other_triplet: 'Triplet', i_range: slice) -> 'Triplet':
|
|
@@ -466,21 +454,46 @@ class Triplet:
|
|
|
466
454
|
"""
|
|
467
455
|
return self.to_scipy_sparse().toarray()
|
|
468
456
|
|
|
469
|
-
def plot(self
|
|
470
|
-
"""
|
|
471
|
-
Plot the dense matrix representation of the triplet.
|
|
472
|
-
"""
|
|
473
|
-
plt.figure()
|
|
474
|
-
plt.title('Finite-difference coefficients structure')
|
|
475
|
-
plt.xlabel('Columns')
|
|
476
|
-
plt.ylabel('Rows')
|
|
457
|
+
def plot(self, *, ax=None, show: bool = True):
|
|
458
|
+
"""Plot nonzero matrix entries, colored by their coefficient.
|
|
477
459
|
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
460
|
+
Parameters
|
|
461
|
+
----------
|
|
462
|
+
ax : matplotlib.axes.Axes, optional
|
|
463
|
+
Axes on which to draw the sparse matrix.
|
|
464
|
+
show : bool, optional
|
|
465
|
+
Display the figure when true.
|
|
466
|
+
|
|
467
|
+
Returns
|
|
468
|
+
-------
|
|
469
|
+
matplotlib.figure.Figure
|
|
470
|
+
Figure containing the matrix and its color scale.
|
|
471
|
+
"""
|
|
472
|
+
matrix = self.to_scipy_sparse()
|
|
473
|
+
matrix.sum_duplicates()
|
|
474
|
+
matrix.eliminate_zeros()
|
|
475
|
+
owns_figure = ax is None
|
|
476
|
+
if owns_figure:
|
|
477
|
+
figure, ax = plt.subplots()
|
|
478
|
+
else:
|
|
479
|
+
figure = ax.figure
|
|
480
|
+
try:
|
|
481
|
+
limit = max(abs(float(matrix.data.min(initial=0))), float(matrix.data.max(initial=0))) or 1
|
|
482
|
+
points = ax.scatter(
|
|
483
|
+
matrix.col, matrix.row, c=matrix.data, cmap="RdBu_r", vmin=-limit,
|
|
484
|
+
vmax=limit, marker="s", s=5, linewidths=0, rasterized=True,
|
|
485
|
+
)
|
|
486
|
+
extent = max(matrix.shape[0], 1) - 0.5
|
|
487
|
+
ax.set(xlim=(-0.5, extent), ylim=(extent, -0.5), aspect="equal",
|
|
488
|
+
xlabel="Columns", ylabel="Rows", title="Finite-difference coefficients")
|
|
489
|
+
figure.colorbar(points, ax=ax, label="Coefficient")
|
|
490
|
+
if show:
|
|
491
|
+
plt.show()
|
|
492
|
+
return figure
|
|
493
|
+
except Exception:
|
|
494
|
+
if owns_figure:
|
|
495
|
+
plt.close(figure)
|
|
496
|
+
raise
|
|
484
497
|
|
|
485
498
|
def to_scipy_sparse(self) -> coo_matrix:
|
|
486
499
|
"""
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: PyFinitDiff
|
|
3
|
-
Version: 2.
|
|
3
|
+
Version: 2.4.0
|
|
4
4
|
Summary: A package for generating finite-difference matrices, particularly suited for physics and engineering applications.
|
|
5
5
|
Author-email: Martin Poinsinet de Sivry-Houle <martin.poinsinet.de.sivry@gmail.com>
|
|
6
6
|
License-Expression: MIT
|
|
@@ -67,7 +67,7 @@ PyFinitDiff
|
|
|
67
67
|
|
|
68
68
|
A package for generating finite-difference matrices, particularly suited for physics and engineering applications.
|
|
69
69
|
|
|
70
|
-
Construct sparse derivative operators from the mesh spacing, derivative order,
|
|
70
|
+
Construct 1D, 2D and 3D sparse derivative operators from the mesh spacing, derivative order,
|
|
71
71
|
accuracy, and boundary conditions. Inspect the matrix entries before combining the
|
|
72
72
|
operator with a potential or solving an eigenvalue problem.
|
|
73
73
|
|
|
@@ -100,55 +100,20 @@ Inspect a two-dimensional finite-difference stencil
|
|
|
100
100
|
.. code-block:: python
|
|
101
101
|
|
|
102
102
|
"""
|
|
103
|
-
|
|
104
|
-
|
|
103
|
+
Inspect the sparse pattern of a five-point stencil
|
|
104
|
+
==================================================
|
|
105
105
|
|
|
106
|
-
|
|
107
|
-
|
|
106
|
+
On a square grid the second-order Laplacian couples each interior sample
|
|
107
|
+
to its four nearest neighbors. Plot its matrix entries to see how those
|
|
108
|
+
neighbors become five bands when the grid is flattened into a vector.
|
|
108
109
|
"""
|
|
109
110
|
|
|
110
|
-
|
|
111
|
-
# .. list-table:: Finite-difference parameters
|
|
112
|
-
# :widths: 25
|
|
113
|
-
# :header-rows: 1
|
|
114
|
-
#
|
|
115
|
-
# * - boundaries: {left: 0, right: 0, top: 0, bottom: 0}
|
|
116
|
-
# * - derivative: 2
|
|
117
|
-
# * - accuracy: 4
|
|
118
|
-
|
|
119
|
-
# %%
|
|
120
|
-
# Importing required packages
|
|
121
|
-
# ---------------------------
|
|
122
|
-
# Here we import the necessary libraries for numerical computations and finite difference operations.
|
|
123
|
-
|
|
124
|
-
from PyFinitDiff.finite_difference_2D import FiniteDifference, Boundaries
|
|
125
|
-
import matplotlib.pyplot as plt
|
|
126
|
-
|
|
127
|
-
# %%
|
|
128
|
-
# Setting up the finite difference instance and boundaries
|
|
129
|
-
# ---------------------------------------------------------
|
|
130
|
-
# We define the grid size and set up the finite difference instance with specified boundary conditions.
|
|
131
|
-
|
|
132
|
-
sparse_instance = FiniteDifference(
|
|
133
|
-
n_x=20,
|
|
134
|
-
n_y=20,
|
|
135
|
-
dx=1,
|
|
136
|
-
dy=1,
|
|
137
|
-
derivative=2,
|
|
138
|
-
accuracy=2,
|
|
139
|
-
boundaries=Boundaries()
|
|
140
|
-
)
|
|
141
|
-
|
|
142
|
-
# %%
|
|
143
|
-
# Visualizing the triplets with matplotlib
|
|
144
|
-
# -----------------------------------------
|
|
145
|
-
# We plot the triplets using matplotlib to visualize the finite difference operator.
|
|
146
|
-
|
|
147
|
-
sparse_instance.triplet.plot()
|
|
111
|
+
from PyFinitDiff.finite_difference_2D import Boundaries, FiniteDifference
|
|
148
112
|
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
113
|
+
laplacian = FiniteDifference(
|
|
114
|
+
n_x=20, n_y=20, dx=1, dy=1, derivative=2, accuracy=2, boundaries=Boundaries()
|
|
115
|
+
)
|
|
116
|
+
laplacian.triplet.plot()
|
|
152
117
|
|
|
153
118
|
.. figure:: https://raw.githubusercontent.com/MartinPdeS/PyFinitDiff/HEAD/docs/images/triplet_example_0.png
|
|
154
119
|
|
|
@@ -2,6 +2,7 @@ LICENSE
|
|
|
2
2
|
README.rst
|
|
3
3
|
pyproject.toml
|
|
4
4
|
PyFinitDiff/__init__.py
|
|
5
|
+
PyFinitDiff/_operator.py
|
|
5
6
|
PyFinitDiff/_version.py
|
|
6
7
|
PyFinitDiff/boundary_values.py
|
|
7
8
|
PyFinitDiff/diagonal.py
|
|
@@ -26,10 +27,14 @@ PyFinitDiff/finite_difference_2D/boundaries.py
|
|
|
26
27
|
PyFinitDiff/finite_difference_2D/derivative.py
|
|
27
28
|
PyFinitDiff/finite_difference_2D/finite_difference.py
|
|
28
29
|
PyFinitDiff/finite_difference_2D/utils.py
|
|
30
|
+
PyFinitDiff/finite_difference_3D/__init__.py
|
|
31
|
+
PyFinitDiff/finite_difference_3D/operator.py
|
|
29
32
|
tests/test_1D_api.py
|
|
30
33
|
tests/test_1D_derivative.py
|
|
31
34
|
tests/test_2D_api.py
|
|
32
35
|
tests/test_2D_derivative.py
|
|
33
36
|
tests/test_2D_eigen.py
|
|
37
|
+
tests/test_3D_operator.py
|
|
34
38
|
tests/test_eighth_order_first_derivative.py
|
|
39
|
+
tests/test_operator_regressions.py
|
|
35
40
|
tests/test_triplet.py
|
|
@@ -25,7 +25,7 @@ PyFinitDiff
|
|
|
25
25
|
|
|
26
26
|
A package for generating finite-difference matrices, particularly suited for physics and engineering applications.
|
|
27
27
|
|
|
28
|
-
Construct sparse derivative operators from the mesh spacing, derivative order,
|
|
28
|
+
Construct 1D, 2D and 3D sparse derivative operators from the mesh spacing, derivative order,
|
|
29
29
|
accuracy, and boundary conditions. Inspect the matrix entries before combining the
|
|
30
30
|
operator with a potential or solving an eigenvalue problem.
|
|
31
31
|
|
|
@@ -58,55 +58,20 @@ Inspect a two-dimensional finite-difference stencil
|
|
|
58
58
|
.. code-block:: python
|
|
59
59
|
|
|
60
60
|
"""
|
|
61
|
-
|
|
62
|
-
|
|
61
|
+
Inspect the sparse pattern of a five-point stencil
|
|
62
|
+
==================================================
|
|
63
63
|
|
|
64
|
-
|
|
65
|
-
|
|
64
|
+
On a square grid the second-order Laplacian couples each interior sample
|
|
65
|
+
to its four nearest neighbors. Plot its matrix entries to see how those
|
|
66
|
+
neighbors become five bands when the grid is flattened into a vector.
|
|
66
67
|
"""
|
|
67
68
|
|
|
68
|
-
|
|
69
|
-
# .. list-table:: Finite-difference parameters
|
|
70
|
-
# :widths: 25
|
|
71
|
-
# :header-rows: 1
|
|
72
|
-
#
|
|
73
|
-
# * - boundaries: {left: 0, right: 0, top: 0, bottom: 0}
|
|
74
|
-
# * - derivative: 2
|
|
75
|
-
# * - accuracy: 4
|
|
76
|
-
|
|
77
|
-
# %%
|
|
78
|
-
# Importing required packages
|
|
79
|
-
# ---------------------------
|
|
80
|
-
# Here we import the necessary libraries for numerical computations and finite difference operations.
|
|
81
|
-
|
|
82
|
-
from PyFinitDiff.finite_difference_2D import FiniteDifference, Boundaries
|
|
83
|
-
import matplotlib.pyplot as plt
|
|
84
|
-
|
|
85
|
-
# %%
|
|
86
|
-
# Setting up the finite difference instance and boundaries
|
|
87
|
-
# ---------------------------------------------------------
|
|
88
|
-
# We define the grid size and set up the finite difference instance with specified boundary conditions.
|
|
89
|
-
|
|
90
|
-
sparse_instance = FiniteDifference(
|
|
91
|
-
n_x=20,
|
|
92
|
-
n_y=20,
|
|
93
|
-
dx=1,
|
|
94
|
-
dy=1,
|
|
95
|
-
derivative=2,
|
|
96
|
-
accuracy=2,
|
|
97
|
-
boundaries=Boundaries()
|
|
98
|
-
)
|
|
99
|
-
|
|
100
|
-
# %%
|
|
101
|
-
# Visualizing the triplets with matplotlib
|
|
102
|
-
# -----------------------------------------
|
|
103
|
-
# We plot the triplets using matplotlib to visualize the finite difference operator.
|
|
104
|
-
|
|
105
|
-
sparse_instance.triplet.plot()
|
|
69
|
+
from PyFinitDiff.finite_difference_2D import Boundaries, FiniteDifference
|
|
106
70
|
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
71
|
+
laplacian = FiniteDifference(
|
|
72
|
+
n_x=20, n_y=20, dx=1, dy=1, derivative=2, accuracy=2, boundaries=Boundaries()
|
|
73
|
+
)
|
|
74
|
+
laplacian.triplet.plot()
|
|
110
75
|
|
|
111
76
|
.. figure:: https://raw.githubusercontent.com/MartinPdeS/PyFinitDiff/HEAD/docs/images/triplet_example_0.png
|
|
112
77
|
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "PyFinitDiff"
|
|
7
|
-
version = "2.
|
|
7
|
+
version = "2.4.0"
|
|
8
8
|
description = "A package for generating finite-difference matrices, particularly suited for physics and engineering applications."
|
|
9
9
|
license = "MIT"
|
|
10
10
|
license-files = ["LICENSE"]
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
"""Accuracy, boundary, indexing and caching checks for Cartesian volumes."""
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
import pytest
|
|
5
|
+
from PyFinitDiff import BoundaryValue
|
|
6
|
+
from PyFinitDiff.finite_difference_3D import Boundaries, FiniteDifference, get_array_derivative
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@pytest.mark.parametrize("axis", ("x", "y", "z"))
|
|
10
|
+
@pytest.mark.parametrize("order,accuracy", [(1, 2), (1, 8), (2, 4), (3, 6)])
|
|
11
|
+
def test_polynomial_on_all_faces(axis, order, accuracy):
|
|
12
|
+
"""Recover the derivative of an axis-dependent cubic on an anisotropic grid."""
|
|
13
|
+
z, y, x = np.indices((15, 16, 34))
|
|
14
|
+
x, y, z = 0.125 * x, 0.5 * y, 0.75 * z
|
|
15
|
+
volume = ((2 * x**order + 3 * y**order + 5 * z**order) * (1 + 1j))[:, :, ::2]
|
|
16
|
+
faces = Boundaries(**{name: BoundaryValue.NONE for name in Boundaries.__dataclass_fields__})
|
|
17
|
+
result = get_array_derivative(
|
|
18
|
+
array=volume,
|
|
19
|
+
derivative=order,
|
|
20
|
+
accuracy=accuracy,
|
|
21
|
+
dx=0.25,
|
|
22
|
+
dy=0.5,
|
|
23
|
+
dz=0.75,
|
|
24
|
+
x_derivative=axis == "x",
|
|
25
|
+
y_derivative=axis == "y",
|
|
26
|
+
z_derivative=axis == "z",
|
|
27
|
+
boundaries=faces,
|
|
28
|
+
)
|
|
29
|
+
expected = {"x": 2, "y": 3, "z": 5}[axis] * (1, 2, 6)[order - 1] * (1 + 1j)
|
|
30
|
+
np.testing.assert_allclose(result, expected, atol=1e-8)
|
|
31
|
+
assert result.shape == volume.shape
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@pytest.mark.parametrize(
|
|
35
|
+
"axis,low,high", [(2, "left", "right"), (1, "bottom", "top"), (0, "front", "back")]
|
|
36
|
+
)
|
|
37
|
+
def test_distinct_reflections_at_opposing_faces(axis, low, high):
|
|
38
|
+
"""Even reflection doubles the neighbor weight and odd reflection cancels it."""
|
|
39
|
+
volume = np.arange(60).reshape(3, 4, 5)
|
|
40
|
+
result = get_array_derivative(
|
|
41
|
+
array=volume,
|
|
42
|
+
derivative=2,
|
|
43
|
+
accuracy=2,
|
|
44
|
+
x_derivative=axis == 2,
|
|
45
|
+
y_derivative=axis == 1,
|
|
46
|
+
z_derivative=axis == 0,
|
|
47
|
+
boundaries=Boundaries(**{low: "symmetric", high: "anti-symmetric"}),
|
|
48
|
+
)
|
|
49
|
+
rows = np.moveaxis(volume, axis, 0)
|
|
50
|
+
expected = -2 * rows.copy()
|
|
51
|
+
expected[1:-1] += rows[:-2] + rows[2:]
|
|
52
|
+
expected[0] += 2 * rows[1]
|
|
53
|
+
np.testing.assert_allclose(np.moveaxis(result, axis, 0), expected)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def test_laplacian_convergence():
|
|
57
|
+
"""The relative eigenvalue error for a Dirichlet box mode falls quadratically."""
|
|
58
|
+
errors = []
|
|
59
|
+
for divisions in (8, 16, 32):
|
|
60
|
+
counts = np.array([divisions, divisions + 2, divisions + 4])
|
|
61
|
+
lengths = np.array([1.0, 1.5, 2.0])
|
|
62
|
+
spacings = lengths / counts
|
|
63
|
+
x, y, z = [np.sin(np.pi * np.arange(1, count) / count) for count in counts]
|
|
64
|
+
mode = z[:, None, None] * y[None, :, None] * x
|
|
65
|
+
result = get_array_derivative(
|
|
66
|
+
array=mode, derivative=2, accuracy=2, dx=spacings[0], dy=spacings[1], dz=spacings[2]
|
|
67
|
+
)
|
|
68
|
+
exact = -np.sum((np.pi / lengths) ** 2) * mode
|
|
69
|
+
errors.append(np.linalg.norm(result - exact) / np.linalg.norm(exact))
|
|
70
|
+
assert np.all(np.array(errors[:-1]) / errors[1:] > 3.5)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def test_cache_disabled_axes_and_validation():
|
|
74
|
+
"""Grid edits and face edits replace the cached operator."""
|
|
75
|
+
operator = FiniteDifference(n_x=5, n_y=4, n_z=3, derivative=2)
|
|
76
|
+
original = operator.triplet
|
|
77
|
+
assert operator.triplet is original
|
|
78
|
+
operator.boundaries.front = BoundaryValue.SYMMETRIC
|
|
79
|
+
assert operator.triplet is not original
|
|
80
|
+
operator.dz = 2
|
|
81
|
+
matrix = operator.triplet.to_scipy_sparse().tocsr()
|
|
82
|
+
assert matrix[0, 20] == 0.5
|
|
83
|
+
operator.x_derivative = operator.y_derivative = operator.z_derivative = False
|
|
84
|
+
assert operator.triplet.to_scipy_sparse().nnz == 0
|
|
85
|
+
with pytest.raises(ValueError):
|
|
86
|
+
operator.dz = 0
|
|
87
|
+
with pytest.raises(ValueError, match="one-sided"):
|
|
88
|
+
FiniteDifference(
|
|
89
|
+
n_x=2, n_y=2, n_z=2, boundaries=Boundaries(left="none")
|
|
90
|
+
).construct_triplet()
|
|
91
|
+
with pytest.raises(ValueError, match="shape"):
|
|
92
|
+
get_array_derivative(array=np.ones((4, 5)), derivative=2)
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
"""Regression checks for grid layout, mutable operators, and sparse arithmetic."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import replace
|
|
4
|
+
from unittest.mock import patch
|
|
5
|
+
import matplotlib.pyplot as plt
|
|
6
|
+
import numpy as np
|
|
7
|
+
import pytest
|
|
8
|
+
from PyFinitDiff import BoundaryValue
|
|
9
|
+
from PyFinitDiff.finite_difference_1D import FiniteDifference as Operator1D
|
|
10
|
+
from PyFinitDiff.finite_difference_2D import FiniteDifference as Operator2D, get_array_derivative
|
|
11
|
+
from PyFinitDiff.triplet import Triplet
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@pytest.mark.parametrize(("use_x", "use_y", "expected"), [(True, False, 3), (False, True, 5), (True, True, 8)])
|
|
15
|
+
def test_rectangular_linear_field(use_x, use_y, expected):
|
|
16
|
+
"""Recover the analytical partials on an anisotropic, noncontiguous grid."""
|
|
17
|
+
y, x = np.indices((7, 22))
|
|
18
|
+
samples = ((3 * x * 0.25 + 5 * y * 1.5) * (1 + 2j))[:, ::2]
|
|
19
|
+
result = get_array_derivative(samples, derivative=1, accuracy=2, x_derivative=use_x,
|
|
20
|
+
y_derivative=use_y, dx=0.5, dy=1.5)
|
|
21
|
+
assert result.shape == samples.shape
|
|
22
|
+
np.testing.assert_allclose(result[1:-1, 1:-1], expected * (1 + 2j))
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@pytest.mark.parametrize("entries", [[], [[0, 0, 1]], [[0, 0, 1], [1, 1, 1], [2, 2, 1]]])
|
|
26
|
+
def test_shift_covers_full_diagonal(entries):
|
|
27
|
+
"""Shift all declared degrees of freedom, including those without entries."""
|
|
28
|
+
triplet = Triplet(shape=(1, 3), array=np.array(entries).reshape(-1, 3))
|
|
29
|
+
expected = triplet.to_dense() + 2 * np.eye(3)
|
|
30
|
+
np.testing.assert_array_equal(triplet.shift_diagonal(2).to_dense(), expected)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def test_merge_keeps_first_coordinate_order_and_independent_storage():
|
|
34
|
+
"""Two duplicate groups sum independently and repeated calls agree."""
|
|
35
|
+
entries = np.array([[1, 0, 2], [0, 0, 3], [1, 0, 5], [0, 0, -3], [1, 0, -1]])
|
|
36
|
+
triplet = Triplet(shape=(2,), array=entries.copy())
|
|
37
|
+
expected = [[1, 0, 6], [0, 0, 0]]
|
|
38
|
+
for _ in range(2):
|
|
39
|
+
result = triplet.remove_duplicate()
|
|
40
|
+
np.testing.assert_array_equal(result.array, expected)
|
|
41
|
+
np.testing.assert_array_equal(triplet.array, entries)
|
|
42
|
+
unique = result.remove_duplicate()
|
|
43
|
+
unique.values = 42
|
|
44
|
+
np.testing.assert_array_equal(result.array, expected)
|
|
45
|
+
triplet.merge_duplicate()
|
|
46
|
+
np.testing.assert_array_equal(triplet.array, expected)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@pytest.mark.parametrize("operator_type, dimensions", [(Operator1D, {}), (Operator2D, {"n_y": 9})])
|
|
50
|
+
def test_operator_refreshes_after_configuration_changes(operator_type, dimensions):
|
|
51
|
+
"""Each edit matches a fresh operator and subsequent reads reuse its matrix."""
|
|
52
|
+
operator = operator_type(n_x=12, **dimensions)
|
|
53
|
+
original = operator.triplet
|
|
54
|
+
operator.dx = 2.0
|
|
55
|
+
assert operator.mesh_info.dx == 2.0
|
|
56
|
+
assert operator.triplet is not original
|
|
57
|
+
changes = [("n_x", 15), ("derivative", 2), ("accuracy", 4), ("x_derivative", False)]
|
|
58
|
+
if dimensions:
|
|
59
|
+
changes.extend([("dy", 3.0), ("n_y", 11), ("y_derivative", False)])
|
|
60
|
+
for name, value in changes:
|
|
61
|
+
setattr(operator, name, value)
|
|
62
|
+
fresh = replace(operator, boundaries=replace(operator.boundaries))
|
|
63
|
+
np.testing.assert_allclose(operator.triplet.to_dense(), fresh.triplet.to_dense())
|
|
64
|
+
assert operator.triplet is operator.triplet
|
|
65
|
+
operator.x_derivative = True
|
|
66
|
+
previous = operator.triplet.to_dense()
|
|
67
|
+
operator.boundaries.left = BoundaryValue.SYMMETRIC
|
|
68
|
+
expected = replace(operator, boundaries=replace(operator.boundaries)).triplet.to_dense()
|
|
69
|
+
assert not np.array_equal(previous, expected)
|
|
70
|
+
np.testing.assert_allclose(operator.triplet.to_dense(), expected)
|
|
71
|
+
operator.boundaries = replace(operator.boundaries, left=BoundaryValue.ZERO)
|
|
72
|
+
np.testing.assert_allclose(operator.triplet.to_dense(), previous)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
@pytest.mark.parametrize("operator_type, dimensions", [(Operator1D, {}), (Operator2D, {"n_y": 9})])
|
|
76
|
+
def test_shared_boundaries_use_each_operators_grid(operator_type, dimensions):
|
|
77
|
+
"""Building a second operator cannot change the stencil dimensions of the first."""
|
|
78
|
+
first = operator_type(n_x=10, **dimensions)
|
|
79
|
+
expected = first.triplet.to_dense()
|
|
80
|
+
second = operator_type(n_x=14, boundaries=first.boundaries, **dimensions)
|
|
81
|
+
second.construct_triplet()
|
|
82
|
+
first.construct_triplet()
|
|
83
|
+
np.testing.assert_array_equal(first.triplet.to_dense(), expected)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def test_sparse_plot_sums_duplicate_coordinates_without_dense_allocation():
|
|
87
|
+
"""The plot represents the full matrix extent and colors only nonzero sums."""
|
|
88
|
+
triplet = Triplet(shape=(100, 100), array=[[7, 3, 1], [7, 3, 2], [9999, 2, 0]])
|
|
89
|
+
figure, axis = plt.subplots()
|
|
90
|
+
try:
|
|
91
|
+
with patch.object(Triplet, "to_dense", side_effect=AssertionError), patch.object(plt, "show") as show:
|
|
92
|
+
assert triplet.plot(ax=axis, show=False) is figure
|
|
93
|
+
show.assert_not_called()
|
|
94
|
+
points = axis.collections[0]
|
|
95
|
+
np.testing.assert_array_equal(points.get_offsets(), [[3, 7]])
|
|
96
|
+
np.testing.assert_array_equal(points.get_array(), [3])
|
|
97
|
+
assert axis.get_ylim() == (9999.5, -0.5)
|
|
98
|
+
finally:
|
|
99
|
+
plt.close(figure)
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|