PyFinitDiff 2.3.3__py3-none-any.whl → 2.4.0__py3-none-any.whl

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.
@@ -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/_version.py CHANGED
@@ -1,5 +1,5 @@
1
1
  """Release version maintained by martinpdes-maintenance."""
2
2
 
3
- __version__ = version = "2.3.3"
3
+ __version__ = version = "2.4.0"
4
4
  __version_tuple__ = version_tuple = tuple(int(part) for part in version.split("."))
5
5
  __commit_id__ = commit_id = None
@@ -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 not self._triplet:
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 = self.boundaries.offset_to_boundary(offset=offset)
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
- x_diagonals = self.get_diagonal_set_full(
232
- offset_multiplier=1,
233
- delta=self._dx
234
- )
235
-
236
- self._triplet = x_diagonals.triplet
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 = module.Boundaries()) -> np.ndarray:
16
+ boundaries: module.Boundaries | None = None) -> np.ndarray:
17
17
  """
18
- Compute the 2D gradient of a given array using finite differences.
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
- The array for which to compute the nth derivative.
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
- The 2D gradient array computed using finite differences.
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
- n_x, n_y = array.shape
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() * array.ravel()
66
+ gradient = triplet.to_scipy_sparse() @ array.ravel()
67
67
 
68
- return gradient.reshape([n_x, n_y])
68
+ return gradient.reshape(array.shape)
@@ -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 not self._triplet:
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 = self.boundaries.offset_to_boundary(offset=offset)
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
- self._triplet = Triplet(array=[[0, 0, 0]], shape=self.mesh_info.shape)
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
- self._triplet += x_diagonals.triplet
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
- self._triplet += y_diagonals.triplet
257
+ triplet += y_diagonals.triplet
258
+ self._triplet = triplet
259
+ self._cached_boundary_values = self._boundary_values()
@@ -0,0 +1,5 @@
1
+ """Sparse finite differences on uniform Cartesian volumes."""
2
+
3
+ from .operator import Boundaries, FiniteDifference, get_array_derivative
4
+
5
+ __all__ = ["Boundaries", "FiniteDifference", "get_array_derivative"]
@@ -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)
PyFinitDiff/triplet.py CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env python
2
2
  # -*- coding: utf-8 -*-
3
3
 
4
- from typing import NoReturn, Tuple, Union
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
- new_array = self.array
262
- index_to_delete = []
263
- duplicate = self.get_duplicate_index()
264
-
265
- if duplicate.size == 0:
266
- return Triplet(array=self.array, shape=self.shape)
267
-
268
- for duplicate in duplicate:
269
- index_to_keep = duplicate[0]
270
- for index_to_merge in duplicate[1:]:
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
- duplicates = self.get_duplicate_index()
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.ones(min(self.max_i, self.max_j)) * value, shape=self.shape)
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) -> NoReturn:
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
- dense_matrix = numpy.flip(self.to_dense(), axis=0)
479
- plt.pcolormesh(dense_matrix, cmap='Blues')
480
- plt.gca().set_aspect('equal')
481
- plt.grid(True)
482
- plt.colorbar()
483
- plt.show()
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.3
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
- Example: triplets 0
104
- ===================
103
+ Inspect the sparse pattern of a five-point stencil
104
+ ==================================================
105
105
 
106
- In this example, we generate a finite difference instance and visualize the resulting triplets.
107
- The boundary conditions, derivative, and accuracy settings are specified for demonstration purposes.
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
- plt.show()
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
 
@@ -1,9 +1,10 @@
1
1
  PyFinitDiff/__init__.py,sha256=2W6LdHIO-28A_9Y5iNndtZ0Dd53aMF4VR1041JgLQXQ,175
2
- PyFinitDiff/_version.py,sha256=qXe5d9DAV_vE_EWjaN0qSi4j7lYhy2X_im3tqJzKnHc,210
2
+ PyFinitDiff/_operator.py,sha256=isvoXwQhYHvhNgFn70120wJyyoaFhEXLjlNZupGikms,1204
3
+ PyFinitDiff/_version.py,sha256=BpaL7VNjQGhGVcPeEDyBoaKl2h1ehrijvWhInxRpr10,210
3
4
  PyFinitDiff/boundary_values.py,sha256=SPqckrx85N7aDoM8G9xfp01-f7zUQ3iRN-3fMXL5YWI,907
4
5
  PyFinitDiff/diagonal.py,sha256=mHPEniSMiRppjGjIgolkmxVCylD4MWphyTgxroB3ISI,10296
5
6
  PyFinitDiff/directories.py,sha256=CjG37eY-Z68Czo5L7MzHJpu8KEJNhZPnh5VB5MTQ2Tg,837
6
- PyFinitDiff/triplet.py,sha256=rlNFtfXea3sQGSACAGenV_J7HiIFV3_utlPEfOxiA1E,13878
7
+ PyFinitDiff/triplet.py,sha256=bsvUK6uV4mXwJcweCxuk3bGmqAApAL2UR9AiHOSDCMg,14559
7
8
  PyFinitDiff/coefficients/__init__.py,sha256=D6leOHW6065G9S6rdcQLmTc99bhWJ9OldfR8lWYQJIU,4179
8
9
  PyFinitDiff/coefficients/backward.py,sha256=4PQ1Yb3TOey7PnEhQs1nBRnpJo_aqhAKGeeSDWRZbCo,2274
9
10
  PyFinitDiff/coefficients/central.py,sha256=xrnZeK2CfgaAcuhAfofBo6WiBNQZKGJ-61vBXLaQ82s,2377
@@ -11,15 +12,17 @@ PyFinitDiff/coefficients/forward.py,sha256=2mhE40Ywerl3wDCm_ygJ3m2Wh8ALZG3p-y2my
11
12
  PyFinitDiff/finite_difference_1D/__init__.py,sha256=VIxWZB2VhtmtnU-Qz-VDGLIz1V1ufqXHyUxlIAYKgW4,237
12
13
  PyFinitDiff/finite_difference_1D/boundaries.py,sha256=yA5RsLDQA0DJQq1a9Ks4ujlKU9f5fpXOH6pxTEfF8E4,6093
13
14
  PyFinitDiff/finite_difference_1D/derivative.py,sha256=DjJD_b9GBJdjaIyeET2WgcPT18CeCJ9rnxq3igVX5LY,1698
14
- PyFinitDiff/finite_difference_1D/finite_difference.py,sha256=4fJImie1arwaFX_7qSWDf1cQOLR28YlDHL0IEbePiL4,7555
15
+ PyFinitDiff/finite_difference_1D/finite_difference.py,sha256=IW1eSpM3cRKESQGSyqjEd_QRSEBRKijLh-RgGPLqydk,7914
15
16
  PyFinitDiff/finite_difference_1D/utils.py,sha256=NKRognj1v5asGubHBV0uMgY-gJlloVFWE-1N3hsNxTg,1963
16
17
  PyFinitDiff/finite_difference_2D/__init__.py,sha256=TIijlPbN-SiZ9UsaO5zVSZrb5ZsKVm0P63TZ_rjEySU,234
17
18
  PyFinitDiff/finite_difference_2D/boundaries.py,sha256=3UKMpxDnmeNP8x7f3dVkSwpleJe1Ad1g5CnTrwz0PYE,7596
18
- PyFinitDiff/finite_difference_2D/derivative.py,sha256=5BvZl7gImgGHMxAkAdNrtofGrv9m9e2BIYR4Uuz08HI,2013
19
- PyFinitDiff/finite_difference_2D/finite_difference.py,sha256=bVzpGZGXDnmBERT6laWa_1wOok7JrBQ71N-1htKJGxU,8381
19
+ PyFinitDiff/finite_difference_2D/derivative.py,sha256=bUQFGg_hS70sQ9EfZELhaIlViODxFEGyfV9pqJGYJLU,2089
20
+ PyFinitDiff/finite_difference_2D/finite_difference.py,sha256=9EqdjhZd2Ry7OCdEGobNsrfOX3xRE06xHCzxIrVV8BA,8628
20
21
  PyFinitDiff/finite_difference_2D/utils.py,sha256=299k0sFfGRw5l0f8nFQef9x5J1zFMoD-IaifdX6LLhs,2454
21
- pyfinitdiff-2.3.3.dist-info/licenses/LICENSE,sha256=U6YG4UEW9XJzHa53oijR0qw6JNN_SZ38WOBmYn3NPd0,1072
22
- pyfinitdiff-2.3.3.dist-info/METADATA,sha256=9hnqrLUUWGFQOVj_VIbzQDYhdK3JfN9Iycfb2sRHRQM,7326
23
- pyfinitdiff-2.3.3.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
24
- pyfinitdiff-2.3.3.dist-info/top_level.txt,sha256=yl_A1Z9VT4HxBK5PTOM4ZyRcXZb-VtbQo1TzRUc1mW4,12
25
- pyfinitdiff-2.3.3.dist-info/RECORD,,
22
+ PyFinitDiff/finite_difference_3D/__init__.py,sha256=3G0I3Z4VBpCC0E6OsmZax9J2NmyBDNwiYU8Il-QPMF0,206
23
+ PyFinitDiff/finite_difference_3D/operator.py,sha256=5GgeK4a_Tq2erXw9piTK9lPBGcWqgjGoM-qn7SAH35o,8495
24
+ pyfinitdiff-2.4.0.dist-info/licenses/LICENSE,sha256=U6YG4UEW9XJzHa53oijR0qw6JNN_SZ38WOBmYn3NPd0,1072
25
+ pyfinitdiff-2.4.0.dist-info/METADATA,sha256=Iepe50GUTzi8TnSKjXL1N8e8yUuyUICNOVmyW1pQzTM,6478
26
+ pyfinitdiff-2.4.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
27
+ pyfinitdiff-2.4.0.dist-info/top_level.txt,sha256=yl_A1Z9VT4HxBK5PTOM4ZyRcXZb-VtbQo1TzRUc1mW4,12
28
+ pyfinitdiff-2.4.0.dist-info/RECORD,,