Skip to content

API Reference

This page is generated from the Python docstrings. For task-oriented usage, start with the component pages and examples.

gbmsc_pde

Grid-Based Multinode Shepard Collocation solvers for PDEs.

BoundaryConditions

Boundary-condition container for rectangular source-node rows.

Conditions are registered by flattened source-node id. Dirichlet rows replace the corresponding PDE row by u_i = value. Neumann and Robin rows use the derivative matrices assembled by the PDE solver. Scalars are broadcast to all supplied nodes; arrays must have the same length as nodes.

Source code in src/gbmsc_pde/boundary/conditions.py
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
class BoundaryConditions:
    """
    Boundary-condition container for rectangular source-node rows.

    Conditions are registered by flattened source-node id.  Dirichlet rows
    replace the corresponding PDE row by ``u_i = value``.  Neumann and Robin
    rows use the derivative matrices assembled by the PDE solver.  Scalars are
    broadcast to all supplied nodes; arrays must have the same length as
    ``nodes``.
    """

    def __init__(self, grid: SourceGrid) -> None:
        self.grid = grid
        self.dirichlet: Dict[int, float] = {}
        self.neumann: Dict[int, Dict[str, Union[Tuple[float, float], float]]] = {}
        self.robin: Dict[int, Dict[str, Union[Tuple[float, float], float]]] = {}
        self.second_neumann: Dict[int, Dict[str, Union[Tuple[float, float], float, int]]] = {}

    def add_dirichlet(
        self,
        nodes: Union[int, np.ndarray],
        values: Union[float, np.ndarray],
    ) -> None:
        """
        Add Dirichlet conditions ``u_i = value`` on rectangular grid nodes.

        Parameters
        ----------
        nodes : int or ndarray
            Flattened source-node ids.
        values : float or ndarray
            Scalar value or one value per node.
        """
        nodes_arr = np.atleast_1d(nodes).astype(int)
        vals_arr = np.atleast_1d(values).astype(float)
        if vals_arr.size == 1:
            vals_arr = np.full(nodes_arr.shape, vals_arr.item(), dtype=float)
        if nodes_arr.size != vals_arr.size:
            raise ValueError(f"Mismatched nodes ({nodes_arr.size}) and values ({vals_arr.size}).")

        n_nodes = getattr(self.grid, "N", None)
        if n_nodes is None:
            raise AttributeError("SourceGrid must define total node count 'N'.")
        if np.any(nodes_arr < 0) or np.any(nodes_arr >= n_nodes):
            raise ValueError(f"Dirichlet indices out of [0, {n_nodes}): {nodes_arr}")

        for node, val in zip(nodes_arr, vals_arr):
            self.dirichlet[int(node)] = float(val)

    def add_neumann(
        self,
        nodes: Union[int, np.ndarray],
        outwardnormal: Union[Tuple[float, float], Tuple[np.ndarray, np.ndarray]],
        fluxes: Union[float, np.ndarray],
    ) -> None:
        """
        Add Neumann conditions ``du/dn = flux`` on grid nodes.

        Parameters
        ----------
        nodes : int or ndarray
            Flattened source-node ids.
        outwardnormal : tuple
            Normal components ``(n_x, n_y)`` as scalars or arrays.
        fluxes : float or ndarray
            Scalar flux or one flux per node.
        """
        nodes_arr = np.atleast_1d(nodes).astype(int)
        k = nodes_arr.size

        if not (isinstance(outwardnormal, tuple) and len(outwardnormal) == 2):
            raise TypeError("`outwardnormal` must be a tuple of length 2.")
        nx, ny = outwardnormal

        if np.isscalar(nx) and np.isscalar(ny):
            nx_arr = np.full(k, float(nx))
            ny_arr = np.full(k, float(ny))
        else:
            nx_arr = np.atleast_1d(nx).astype(float)
            ny_arr = np.atleast_1d(ny).astype(float)
        if nx_arr.shape != (k,) or ny_arr.shape != (k,):
            raise ValueError("`outwardnormal` components must match length of `nodes`.")

        flux_arr = np.atleast_1d(fluxes).astype(float)
        if flux_arr.size == 1:
            flux_arr = np.full(k, flux_arr.item())
        if flux_arr.shape != (k,):
            raise ValueError("`fluxes` must be scalar or match length of `nodes`.")

        n_nodes = getattr(self.grid, "N", None)
        if n_nodes is None:
            raise AttributeError("BoundaryConditions requires `self.grid.N`.")
        if np.any(nodes_arr < 0) or np.any(nodes_arr >= n_nodes):
            raise ValueError(f"Node indices must be in [0, {n_nodes}); got {nodes_arr}.")

        for node, nx_val, ny_val, flux_val in zip(nodes_arr, nx_arr, ny_arr, flux_arr):
            self.neumann[int(node)] = {
                "normal": (float(nx_val), float(ny_val)),
                "flux": float(flux_val),
            }

    def add_robin(
        self,
        nodes: Union[int, np.ndarray],
        outwardnormal: Union[Tuple[float, float], Tuple[np.ndarray, np.ndarray]],
        alphas: Union[float, np.ndarray],
        betas: Union[float, np.ndarray],
        values: Union[float, np.ndarray],
    ) -> None:
        """
        Add Robin conditions ``alpha*u + beta*du/dn = value`` on grid nodes.

        ``alphas``, ``betas``, and ``values`` may be scalars or arrays with
        one entry per node.
        """
        nodes_arr = np.atleast_1d(nodes).astype(int)
        k = nodes_arr.size

        if not (isinstance(outwardnormal, tuple) and len(outwardnormal) == 2):
            raise TypeError("`outwardnormal` must be a tuple (nx, ny).")
        nx, ny = outwardnormal
        nx_arr = np.full(k, nx, dtype=float) if np.isscalar(nx) else np.atleast_1d(nx).astype(float)
        ny_arr = np.full(k, ny, dtype=float) if np.isscalar(ny) else np.atleast_1d(ny).astype(float)
        if nx_arr.shape != (k,) or ny_arr.shape != (k,):
            raise ValueError("`outwardnormal` components must match length of `nodes`.")

        alpha_arr = np.atleast_1d(alphas).astype(float)
        beta_arr = np.atleast_1d(betas).astype(float)
        value_arr = np.atleast_1d(values).astype(float)

        if alpha_arr.size == 1:
            alpha_arr = np.full(k, alpha_arr.item(), dtype=float)
        if beta_arr.size == 1:
            beta_arr = np.full(k, beta_arr.item(), dtype=float)
        if value_arr.size == 1:
            value_arr = np.full(k, value_arr.item(), dtype=float)

        if not (alpha_arr.size == beta_arr.size == value_arr.size == k):
            raise ValueError(
                f"Sizes must match: nodes({k}), alphas({alpha_arr.size}), "
                f"betas({beta_arr.size}), values({value_arr.size})."
            )

        n_nodes = getattr(self.grid, "N", None)
        if n_nodes is None:
            raise AttributeError("SourceGrid must define total node count 'N'.")
        if np.any(nodes_arr < 0) or np.any(nodes_arr >= n_nodes):
            raise ValueError(f"Node indices out of [0, {n_nodes}): {nodes_arr}")

        for node, nx_val, ny_val, alpha, beta, value in zip(
            nodes_arr, nx_arr, ny_arr, alpha_arr, beta_arr, value_arr
        ):
            self.robin[int(node)] = {
                "normal": (float(nx_val), float(ny_val)),
                "alpha": float(alpha),
                "beta": float(beta),
                "value": float(value),
            }

    def add_neumann_as_second_condition(
        self,
        nodes: Union[int, np.ndarray],
        outwardnormal: Union[Tuple[float, float], Tuple[np.ndarray, np.ndarray]],
        fluxes: Union[float, np.ndarray],
        rows: Union[int, np.ndarray],
    ) -> None:
        """
        Add Neumann equations on user-selected matrix rows.

        This compatibility method is for augmented systems where a Neumann
        boundary equation should be imposed as an additional/second condition
        rather than replacing the row associated with ``node``.
        """
        if not hasattr(self.grid, "N"):
            raise AttributeError("BoundaryConditions.grid must define integer `.N`")

        nodes_arr = np.atleast_1d(nodes).astype(int)
        rows_arr = np.atleast_1d(rows).astype(int)

        if nodes_arr.ndim != 1 or rows_arr.ndim != 1:
            raise TypeError("`nodes` and `rows` must be scalars or 1D sequences")

        n = nodes_arr.size
        if rows_arr.size != n:
            raise ValueError(f"`rows` length ({rows_arr.size}) != `nodes` length ({n})")

        if not (isinstance(outwardnormal, tuple) and len(outwardnormal) == 2):
            raise TypeError("`outwardnormal` must be a tuple of two elements")
        nx_in, ny_in = outwardnormal

        try:
            nx_arr = np.broadcast_to(nx_in, (n,)).astype(float)
            ny_arr = np.broadcast_to(ny_in, (n,)).astype(float)
        except Exception as exc:
            raise ValueError(
                "Cannot broadcast `outwardnormal` components to match `nodes` length"
            ) from exc

        try:
            flux_arr = np.broadcast_to(fluxes, (n,)).astype(float)
        except Exception as exc:
            raise ValueError("Cannot broadcast `fluxes` to match `nodes` length") from exc

        if np.any(nodes_arr < 0) or np.any(nodes_arr >= self.grid.N):
            raise ValueError(f"All `nodes` must be in [0, {self.grid.N})")

        for node, row, nx_val, ny_val, flux in zip(nodes_arr, rows_arr, nx_arr, ny_arr, flux_arr):
            self.second_neumann[int(node)] = {
                "normal": (float(nx_val), float(ny_val)),
                "flux": float(flux),
                "row": int(row),
            }

    def apply(
        self,
        A: spmatrix,
        b: np.ndarray,
        Mx: spmatrix,
        My: spmatrix,
    ) -> tuple[spmatrix, np.ndarray]:
        """Apply all registered conditions to an assembled rectangular system."""
        return apply_boundary_conditions(self, A, b, Mx, My)

add_dirichlet(nodes, values)

Add Dirichlet conditions u_i = value on rectangular grid nodes.

Parameters:

Name Type Description Default
nodes int or ndarray

Flattened source-node ids.

required
values float or ndarray

Scalar value or one value per node.

required
Source code in src/gbmsc_pde/boundary/conditions.py
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
def add_dirichlet(
    self,
    nodes: Union[int, np.ndarray],
    values: Union[float, np.ndarray],
) -> None:
    """
    Add Dirichlet conditions ``u_i = value`` on rectangular grid nodes.

    Parameters
    ----------
    nodes : int or ndarray
        Flattened source-node ids.
    values : float or ndarray
        Scalar value or one value per node.
    """
    nodes_arr = np.atleast_1d(nodes).astype(int)
    vals_arr = np.atleast_1d(values).astype(float)
    if vals_arr.size == 1:
        vals_arr = np.full(nodes_arr.shape, vals_arr.item(), dtype=float)
    if nodes_arr.size != vals_arr.size:
        raise ValueError(f"Mismatched nodes ({nodes_arr.size}) and values ({vals_arr.size}).")

    n_nodes = getattr(self.grid, "N", None)
    if n_nodes is None:
        raise AttributeError("SourceGrid must define total node count 'N'.")
    if np.any(nodes_arr < 0) or np.any(nodes_arr >= n_nodes):
        raise ValueError(f"Dirichlet indices out of [0, {n_nodes}): {nodes_arr}")

    for node, val in zip(nodes_arr, vals_arr):
        self.dirichlet[int(node)] = float(val)

add_neumann(nodes, outwardnormal, fluxes)

Add Neumann conditions du/dn = flux on grid nodes.

Parameters:

Name Type Description Default
nodes int or ndarray

Flattened source-node ids.

required
outwardnormal tuple

Normal components (n_x, n_y) as scalars or arrays.

required
fluxes float or ndarray

Scalar flux or one flux per node.

required
Source code in src/gbmsc_pde/boundary/conditions.py
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
def add_neumann(
    self,
    nodes: Union[int, np.ndarray],
    outwardnormal: Union[Tuple[float, float], Tuple[np.ndarray, np.ndarray]],
    fluxes: Union[float, np.ndarray],
) -> None:
    """
    Add Neumann conditions ``du/dn = flux`` on grid nodes.

    Parameters
    ----------
    nodes : int or ndarray
        Flattened source-node ids.
    outwardnormal : tuple
        Normal components ``(n_x, n_y)`` as scalars or arrays.
    fluxes : float or ndarray
        Scalar flux or one flux per node.
    """
    nodes_arr = np.atleast_1d(nodes).astype(int)
    k = nodes_arr.size

    if not (isinstance(outwardnormal, tuple) and len(outwardnormal) == 2):
        raise TypeError("`outwardnormal` must be a tuple of length 2.")
    nx, ny = outwardnormal

    if np.isscalar(nx) and np.isscalar(ny):
        nx_arr = np.full(k, float(nx))
        ny_arr = np.full(k, float(ny))
    else:
        nx_arr = np.atleast_1d(nx).astype(float)
        ny_arr = np.atleast_1d(ny).astype(float)
    if nx_arr.shape != (k,) or ny_arr.shape != (k,):
        raise ValueError("`outwardnormal` components must match length of `nodes`.")

    flux_arr = np.atleast_1d(fluxes).astype(float)
    if flux_arr.size == 1:
        flux_arr = np.full(k, flux_arr.item())
    if flux_arr.shape != (k,):
        raise ValueError("`fluxes` must be scalar or match length of `nodes`.")

    n_nodes = getattr(self.grid, "N", None)
    if n_nodes is None:
        raise AttributeError("BoundaryConditions requires `self.grid.N`.")
    if np.any(nodes_arr < 0) or np.any(nodes_arr >= n_nodes):
        raise ValueError(f"Node indices must be in [0, {n_nodes}); got {nodes_arr}.")

    for node, nx_val, ny_val, flux_val in zip(nodes_arr, nx_arr, ny_arr, flux_arr):
        self.neumann[int(node)] = {
            "normal": (float(nx_val), float(ny_val)),
            "flux": float(flux_val),
        }

add_neumann_as_second_condition(nodes, outwardnormal, fluxes, rows)

Add Neumann equations on user-selected matrix rows.

This compatibility method is for augmented systems where a Neumann boundary equation should be imposed as an additional/second condition rather than replacing the row associated with node.

Source code in src/gbmsc_pde/boundary/conditions.py
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
def add_neumann_as_second_condition(
    self,
    nodes: Union[int, np.ndarray],
    outwardnormal: Union[Tuple[float, float], Tuple[np.ndarray, np.ndarray]],
    fluxes: Union[float, np.ndarray],
    rows: Union[int, np.ndarray],
) -> None:
    """
    Add Neumann equations on user-selected matrix rows.

    This compatibility method is for augmented systems where a Neumann
    boundary equation should be imposed as an additional/second condition
    rather than replacing the row associated with ``node``.
    """
    if not hasattr(self.grid, "N"):
        raise AttributeError("BoundaryConditions.grid must define integer `.N`")

    nodes_arr = np.atleast_1d(nodes).astype(int)
    rows_arr = np.atleast_1d(rows).astype(int)

    if nodes_arr.ndim != 1 or rows_arr.ndim != 1:
        raise TypeError("`nodes` and `rows` must be scalars or 1D sequences")

    n = nodes_arr.size
    if rows_arr.size != n:
        raise ValueError(f"`rows` length ({rows_arr.size}) != `nodes` length ({n})")

    if not (isinstance(outwardnormal, tuple) and len(outwardnormal) == 2):
        raise TypeError("`outwardnormal` must be a tuple of two elements")
    nx_in, ny_in = outwardnormal

    try:
        nx_arr = np.broadcast_to(nx_in, (n,)).astype(float)
        ny_arr = np.broadcast_to(ny_in, (n,)).astype(float)
    except Exception as exc:
        raise ValueError(
            "Cannot broadcast `outwardnormal` components to match `nodes` length"
        ) from exc

    try:
        flux_arr = np.broadcast_to(fluxes, (n,)).astype(float)
    except Exception as exc:
        raise ValueError("Cannot broadcast `fluxes` to match `nodes` length") from exc

    if np.any(nodes_arr < 0) or np.any(nodes_arr >= self.grid.N):
        raise ValueError(f"All `nodes` must be in [0, {self.grid.N})")

    for node, row, nx_val, ny_val, flux in zip(nodes_arr, rows_arr, nx_arr, ny_arr, flux_arr):
        self.second_neumann[int(node)] = {
            "normal": (float(nx_val), float(ny_val)),
            "flux": float(flux),
            "row": int(row),
        }

add_robin(nodes, outwardnormal, alphas, betas, values)

Add Robin conditions alpha*u + beta*du/dn = value on grid nodes.

alphas, betas, and values may be scalars or arrays with one entry per node.

Source code in src/gbmsc_pde/boundary/conditions.py
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
def add_robin(
    self,
    nodes: Union[int, np.ndarray],
    outwardnormal: Union[Tuple[float, float], Tuple[np.ndarray, np.ndarray]],
    alphas: Union[float, np.ndarray],
    betas: Union[float, np.ndarray],
    values: Union[float, np.ndarray],
) -> None:
    """
    Add Robin conditions ``alpha*u + beta*du/dn = value`` on grid nodes.

    ``alphas``, ``betas``, and ``values`` may be scalars or arrays with
    one entry per node.
    """
    nodes_arr = np.atleast_1d(nodes).astype(int)
    k = nodes_arr.size

    if not (isinstance(outwardnormal, tuple) and len(outwardnormal) == 2):
        raise TypeError("`outwardnormal` must be a tuple (nx, ny).")
    nx, ny = outwardnormal
    nx_arr = np.full(k, nx, dtype=float) if np.isscalar(nx) else np.atleast_1d(nx).astype(float)
    ny_arr = np.full(k, ny, dtype=float) if np.isscalar(ny) else np.atleast_1d(ny).astype(float)
    if nx_arr.shape != (k,) or ny_arr.shape != (k,):
        raise ValueError("`outwardnormal` components must match length of `nodes`.")

    alpha_arr = np.atleast_1d(alphas).astype(float)
    beta_arr = np.atleast_1d(betas).astype(float)
    value_arr = np.atleast_1d(values).astype(float)

    if alpha_arr.size == 1:
        alpha_arr = np.full(k, alpha_arr.item(), dtype=float)
    if beta_arr.size == 1:
        beta_arr = np.full(k, beta_arr.item(), dtype=float)
    if value_arr.size == 1:
        value_arr = np.full(k, value_arr.item(), dtype=float)

    if not (alpha_arr.size == beta_arr.size == value_arr.size == k):
        raise ValueError(
            f"Sizes must match: nodes({k}), alphas({alpha_arr.size}), "
            f"betas({beta_arr.size}), values({value_arr.size})."
        )

    n_nodes = getattr(self.grid, "N", None)
    if n_nodes is None:
        raise AttributeError("SourceGrid must define total node count 'N'.")
    if np.any(nodes_arr < 0) or np.any(nodes_arr >= n_nodes):
        raise ValueError(f"Node indices out of [0, {n_nodes}): {nodes_arr}")

    for node, nx_val, ny_val, alpha, beta, value in zip(
        nodes_arr, nx_arr, ny_arr, alpha_arr, beta_arr, value_arr
    ):
        self.robin[int(node)] = {
            "normal": (float(nx_val), float(ny_val)),
            "alpha": float(alpha),
            "beta": float(beta),
            "value": float(value),
        }

apply(A, b, Mx, My)

Apply all registered conditions to an assembled rectangular system.

Source code in src/gbmsc_pde/boundary/conditions.py
223
224
225
226
227
228
229
230
231
def apply(
    self,
    A: spmatrix,
    b: np.ndarray,
    Mx: spmatrix,
    My: spmatrix,
) -> tuple[spmatrix, np.ndarray]:
    """Apply all registered conditions to an assembled rectangular system."""
    return apply_boundary_conditions(self, A, b, Mx, My)

GBMSCApproximation

Grid-Based Shepard approximation on a structured grid.

The approximation blends local tensor-product Lagrange polynomials defined on sampled subgrids of a :class:~gbmsc_pde.source_grid.grid.SourceGrid. It is used both for interpolation at arbitrary coordinates and for sparse nodal differential operators in the rectangular-domain PDE solver.

For nodal PDE operators, support_mode controls the normalization:

"active" Use only sampled subgrids that contain the evaluated source node. This is the original sparse rectangular-domain PDE mode. "all" Keep the sparse active contributors at source nodes, but normalize the Shepard denominator over all sampled subgrids. "nodal_limit" Use the source-node limiting formula. The common singular factor is cancelled from all active subgrids containing the source node before evaluating the weight values and derivatives.

Interpolation at arbitrary query coordinates uses all sampled subgrids.

Attributes:

Name Type Description
grid SourceGrid

Structured source grid.

step tuple[int, int]

Sampling stride for local subgrids.

subgrids_step_row (ndarray, shape(S, m))

Flattened sampled local subgrid node ids, where m = n_x * n_y.

support_mode {active, all, nodal_limit}

Nodal operator normalization mode.

Source code in src/gbmsc_pde/approximation/shepard.py
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
class GBMSCApproximation:
    """
    Grid-Based Shepard approximation on a structured grid.

    The approximation blends local tensor-product Lagrange polynomials defined
    on sampled subgrids of a :class:`~gbmsc_pde.source_grid.grid.SourceGrid`.  It is used
    both for interpolation at arbitrary coordinates and for sparse nodal
    differential operators in the rectangular-domain PDE solver.

    For nodal PDE operators, ``support_mode`` controls the normalization:

    ``"active"``
        Use only sampled subgrids that contain the evaluated source node.  This
        is the original sparse rectangular-domain PDE mode.
    ``"all"``
        Keep the sparse active contributors at source nodes, but normalize the
        Shepard denominator over all sampled subgrids.
    ``"nodal_limit"``
        Use the source-node limiting formula.  The common singular factor is
        cancelled from all active subgrids containing the source node before
        evaluating the weight values and derivatives.

    Interpolation at arbitrary query coordinates uses all sampled subgrids.

    Attributes
    ----------
    grid : SourceGrid
        Structured source grid.
    step : tuple[int, int]
        Sampling stride for local subgrids.
    subgrids_step_row : ndarray, shape (S, m)
        Flattened sampled local subgrid node ids, where
        ``m = n_x * n_y``.
    support_mode : {"active", "all", "nodal_limit"}
        Nodal operator normalization mode.
    """

    def __init__(
        self,
        grid: SourceGrid,
        step: Tuple[int, int] = (1, 1),
        mu: float = 2.005,
        eps: float = 1e-12,
        support_mode: str = "active",
    ) -> None:
        """
        Initialize the Grid-Based Shepard approximation.

        Parameters
        ----------
        grid : SourceGrid
            Structured source grid providing source-node coordinates, local subgrids,
            and pairwise distances.
        step : tuple[int, int], default=(1, 1)
            Sampling stride for local subgrid starts.
        mu : float, default=2.005
            Shepard exponent parameter.  The implementation stores ``2*mu`` so
            formulas based on squared distances recover the requested power.
        eps : float, default=1e-12
            Distance floor used to avoid division by zero and logarithms of
            zero.
        support_mode : {"active", "all", "nodal_limit"}, default="active"
            Nodal PDE-operator support mode.

        Raises
        ------
        TypeError
            If ``grid`` does not provide local subgrids.
        ValueError
            If ``step`` is invalid, ``mu <= 2``, or ``support_mode`` is
            unknown.
        """
        # Input validation
        if not hasattr(grid, 'subgrids'):
            raise TypeError("grid must have attribute 'subgrids'.")
        if any(s < 1 or not isinstance(s, int) for s in step):
            raise ValueError("step must be a tuple of positive integers.")

        if mu <= 2:
            raise ValueError("mu parameter must be greater than 2.")
        if support_mode not in ("active", "all", "nodal_limit"):
            raise ValueError("support_mode must be 'active', 'all', or 'nodal_limit'.")

        self.grid = grid
        self.step = step
        self.mu = float(2 * mu)
        self.eps = float(eps)
        self.support_mode = support_mode

        # Unpack shapes
        n_x, n_y = grid.subgrid_shape

        # Sample subgrids at the given stride, then flatten for vectorized ops
        subgrids_step, self.subgrids_x_step, self.subgrids_y_step = grid.subgrids_with_step(self.step)
        self.subgrids_step_grid = subgrids_step.reshape(-1, n_x, n_y)    # (S, n_x, n_y)
        self.subgrids_step_row = self.subgrids_step_grid.reshape(-1, n_x * n_y)  # (S, m)
        self._subgrid_x_coords = self.grid.x_coords_flat[self.subgrids_step_row]
        self._subgrid_y_coords = self.grid.y_coords_flat[self.subgrids_step_row]
        self._x_lines = self.grid.X[self.subgrids_x_step, 0]
        self._y_lines = self.grid.Y[0, self.subgrids_y_step]
        self._x_lagrange_weights = _barycentric_weights_batch(self._x_lines)
        self._y_lagrange_weights = _barycentric_weights_batch(self._y_lines)
        self._lagrange_derivative_cache = {}
        self._node_subgrid_ids, self._node_subgrid_counts = self._build_node_subgrid_lookup()
        self._safe_dist = None
        self._safe_logd = None
        self._nodal_limit_data = None
        self._all_node_subgrid_metric_cache = {}

    def _build_node_subgrid_lookup(self) -> Tuple[np.ndarray, np.ndarray]:
        """
        Build a padded lookup from global node id to sampled subgrids containing it.

        Returns
        -------
        node_subgrid_ids : (N, C) ndarray(int)
            Padded subgrid ids for each global node. Unused slots are ``-1``.
        node_subgrid_counts : (N,) ndarray(int)
            Number of valid sampled subgrids per global node.
        """
        flat_nodes = self.subgrids_step_row.ravel()
        node_subgrid_counts = np.bincount(flat_nodes, minlength=self.grid.N)
        max_count = int(node_subgrid_counts.max()) if node_subgrid_counts.size else 0
        node_subgrid_ids = np.full((self.grid.N, max_count), -1, dtype=int)
        offsets = np.zeros(self.grid.N, dtype=int)

        subgrid_ids = np.repeat(np.arange(self.subgrids_step_row.shape[0]), self.subgrids_step_row.shape[1])
        for node_id, subgrid_id in zip(flat_nodes, subgrid_ids):
            slot = offsets[node_id]
            node_subgrid_ids[node_id, slot] = subgrid_id
            offsets[node_id] = slot + 1

        return node_subgrid_ids, node_subgrid_counts

    def _safe_pairwise_data(self) -> Tuple[np.ndarray, np.ndarray]:
        """
        Return cached pairwise squared distances and their logarithm with epsilon floor.
        """
        if self._safe_dist is None or self._safe_logd is None:
            safe_dist = np.maximum(self.grid.dist, self.eps)
            self._safe_dist = safe_dist
            self._safe_logd = np.log(safe_dist)
        return self._safe_dist, self._safe_logd

    def _nodal_limit_pairwise_data(self) -> Tuple[np.ndarray, ...]:
        """
        Return pairwise data for source-node limiting weights.

        At a source node, every active subgrid contains the common singular
        factor associated with the collocation node.  The limiting formula
        cancels that factor before differentiating the normalized weight.  In
        vectorized pairwise arrays this is represented by a neutral diagonal:
        ``dist_ii = 1`` and zero diagonal derivative contributions.
        """
        if self._nodal_limit_data is not None:
            return self._nodal_limit_data

        dist = self.grid.dist.copy()
        np.fill_diagonal(dist, 1.0)
        logd = np.log(dist)

        diff_x = self.grid.diff_x
        diff_y = self.grid.diff_y
        A_x_data = 2.0 * diff_x / dist
        A_y_data = 2.0 * diff_y / dist
        A_xx_data = 2.0 / dist - 4.0 * (diff_x / dist) ** 2
        A_yy_data = 2.0 / dist - 4.0 * (diff_y / dist) ** 2
        np.fill_diagonal(A_xx_data, 0.0)
        np.fill_diagonal(A_yy_data, 0.0)

        self._nodal_limit_data = (
            dist,
            logd,
            A_x_data,
            A_y_data,
            A_xx_data,
            A_yy_data,
        )
        return self._nodal_limit_data

    def _all_node_subgrid_metric_sums(self, second_derivatives: bool = True):
        """
        Precompute node-to-subgrid metric sums for all-denominator nodal rows.

        The active-denominator path only needs the subgrids containing each
        row node.  The all-denominator path needs every sampled subgrid in the
        normalizing sum; using these ``(N, S)`` tables avoids repeatedly
        building much larger ``(block, S, m)`` distance tensors.
        """
        cache_key = bool(second_derivatives)
        cached = self._all_node_subgrid_metric_cache.get(cache_key)
        if cached is not None:
            return cached

        dist, logd = self._safe_pairwise_data()
        idx_rows = self.subgrids_step_row
        S, m = idx_rows.shape

        indicator = np.zeros((self.grid.N, S), dtype=float)
        indicator[
            idx_rows.ravel(),
            np.repeat(np.arange(S, dtype=int), m),
        ] = 1.0

        diff_x = self.grid.diff_x
        diff_y = self.grid.diff_y
        A = logd @ indicator
        A_x = (2.0 * diff_x / dist) @ indicator
        A_y = (2.0 * diff_y / dist) @ indicator

        if not second_derivatives:
            result = (A, A_x, A_y)
            self._all_node_subgrid_metric_cache[cache_key] = result
            return result

        A_xx = (2.0 / dist - 4.0 * (diff_x / dist) ** 2) @ indicator
        A_yy = (2.0 / dist - 4.0 * (diff_y / dist) ** 2) @ indicator
        result = (A, A_x, A_y, A_xx, A_yy)
        self._all_node_subgrid_metric_cache[cache_key] = result
        return result

    def eval_weight_functions_at_nodes_all_denominator_minmax_shift(
        self,
        second_derivatives=True,
        block_s: int = 64,
    ) -> Union[Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray],
               Tuple[np.ndarray, np.ndarray, np.ndarray]
               ]:
        """
        Compute nodal Shepard weights with active contributors and all denominator.

        The returned arrays have the same ``(S, m)`` shape as
        :meth:`eval_weight_functions_at_nodes_data_minmax_shift`: one row for
        each retained/sampled subgrid and one column for each local node.  Only
        the normalization denominator is enlarged to all sampled subgrids.

        Parameters
        ----------
        second_derivatives : bool, default=True
            Whether to also return second derivatives of the weights.
        block_s : int, default=64
            Number of sampled subgrids processed per vectorized block.

        Returns
        -------
        tuple[ndarray, ...]
            ``(f, f_x, f_y, f_xx, f_yy)`` when ``second_derivatives`` is true,
            otherwise ``(f, f_x, f_y)``.  Each array has shape ``(S, m)``.
        """
        mu = self.mu * 0.5
        idx_rows = self.subgrids_step_row
        S, m = idx_rows.shape

        metrics = self._all_node_subgrid_metric_sums(second_derivatives=second_derivatives)
        if second_derivatives:
            A, A_x, A_y, A_xx, A_yy = metrics
        else:
            A, A_x, A_y = metrics

        f_val = np.empty((S, m))
        f_x = np.empty_like(f_val)
        f_y = np.empty_like(f_val)
        if second_derivatives:
            f_xx = np.empty_like(f_val)
            f_yy = np.empty_like(f_val)

        for s0 in range(0, S, block_s):
            s1 = min(s0 + block_s, S)
            blk = slice(s0, s1)
            B = s1 - s0

            flat_eval_nodes = idx_rows[blk].reshape(-1)
            current_subgrid_ids = np.repeat(np.arange(s0, s1, dtype=int), m)

            A_current = A[flat_eval_nodes, current_subgrid_ids]
            A_candidates = A[flat_eval_nodes]
            DeltaA = A_current[:, None] - A_candidates

            z = mu * DeltaA
            z_max = np.max(z, axis=1, keepdims=True)
            with np.errstate(under="ignore"):
                R_shift = np.exp(z - z_max)
            R_shift_sum = R_shift.sum(axis=1)
            normalized_R = R_shift / R_shift_sum[:, None]

            f_val_block = np.exp(-z_max.ravel()) / R_shift_sum

            A_x_current = A_x[flat_eval_nodes, current_subgrid_ids]
            A_y_current = A_y[flat_eval_nodes, current_subgrid_ids]
            beta_x = mu * (A_x_current[:, None] - A_x[flat_eval_nodes])
            beta_y = mu * (A_y_current[:, None] - A_y[flat_eval_nodes])
            log_derivative_x = (normalized_R * beta_x).sum(axis=1)
            log_derivative_y = (normalized_R * beta_y).sum(axis=1)

            f_val[blk] = f_val_block.reshape(B, m)
            f_x[blk] = (-f_val_block * log_derivative_x).reshape(B, m)
            f_y[blk] = (-f_val_block * log_derivative_y).reshape(B, m)

            if second_derivatives:
                A_xx_current = A_xx[flat_eval_nodes, current_subgrid_ids]
                A_yy_current = A_yy[flat_eval_nodes, current_subgrid_ids]
                beta_xx = mu * (A_xx_current[:, None] - A_xx[flat_eval_nodes])
                beta_yy = mu * (A_yy_current[:, None] - A_yy[flat_eval_nodes])
                curvature_x = (normalized_R * (beta_xx + beta_x ** 2)).sum(axis=1)
                curvature_y = (normalized_R * (beta_yy + beta_y ** 2)).sum(axis=1)

                f_xx[blk] = (
                    f_val_block * (2.0 * log_derivative_x ** 2 - curvature_x)
                ).reshape(B, m)
                f_yy[blk] = (
                    f_val_block * (2.0 * log_derivative_y ** 2 - curvature_y)
                ).reshape(B, m)

        if second_derivatives:
            return f_val, f_x, f_y, f_xx, f_yy

        return f_val, f_x, f_y

    def _normalized_weights_at_queries_stable(
        self,
        xq: np.ndarray,
        yq: np.ndarray,
        *,
        return_derivatives: bool = False,
        regularized: bool = True,
    ) -> np.ndarray:
        """
        Stable normalized Shepard weights computed in log-space.

        This variant never forms the raw weights ``W = exp(log_w)`` directly.
        Instead it applies a max-shift per query so the largest exponent is 0,
        then normalizes the shifted weights.

        Parameters
        ----------
        xq, yq : (l,) 1-D arrays
            Query coordinates.
        return_derivatives : bool, default False
            If True, also return derivatives of the normalized weights.

        Returns
        -------
        P : (l, S) ndarray
            Normalized Shepard weights for each query and sampled sub-grid.
        Px, Py : (l, S) ndarray
            First derivatives of the normalized weights (only if requested).
        """
        xq = np.asarray(xq, dtype=float).ravel()
        yq = np.asarray(yq, dtype=float).ravel()
        if xq.size != yq.size:
            raise ValueError("x and y arrays must have same length.")

        Xn = self._subgrid_x_coords
        Yn = self._subgrid_y_coords

        # Broadcasted differences (l, S, m)
        dx = xq[:, None, None] - Xn[None, :, :]
        dy = yq[:, None, None] - Yn[None, :, :]

        # Squared distance.  The legacy path uses an epsilon floor; the
        # exact-nodal interpolation path passes only non-source queries and
        # therefore uses true distances.
        dist2 = dx * dx + dy * dy
        if regularized:
            dist2[dist2 < self.eps] = self.eps
        elif np.any(dist2 <= 0.0):
            raise ZeroDivisionError(
                "Exact non-regularized interpolation received a source-node query. "
                "Use interpolation_mode='exact_nodal' so node hits are handled separately."
            )

        log_w = (-self.mu * 0.5) * np.log(dist2).sum(axis=2)  # (l, S)

        # Stable normalization: exp(log_w - max(log_w))
        log_w_shift = log_w - np.max(log_w, axis=1, keepdims=True)
        W_shift = np.exp(log_w_shift)
        W_sum = W_shift.sum(axis=1, keepdims=True)
        P = W_shift / W_sum

        if not return_derivatives:
            return (P,)

        # alpha_x / alpha_y are derivatives of log_w
        alpha_x = -self.mu * (dx / dist2).sum(axis=2)  # (l, S)
        alpha_y = -self.mu * (dy / dist2).sum(axis=2)  # (l, S)
        mean_alpha_x = (P * alpha_x).sum(axis=1, keepdims=True)
        mean_alpha_y = (P * alpha_y).sum(axis=1, keepdims=True)

        # Derivatives of normalized weights:
        # p_i,x = p_i * (alpha_i,x - sum_j p_j alpha_j,x)
        Px = P * (alpha_x - mean_alpha_x)
        Py = P * (alpha_y - mean_alpha_y)

        return P, Px, Py

    def _source_node_hits(
        self,
        xq: np.ndarray,
        yq: np.ndarray,
        *,
        tolerance: float,
        chunk: int,
    ) -> np.ndarray:
        """Return source-node ids for query points within tolerance, else -1."""
        hits = np.full(xq.shape, -1, dtype=int)
        coords = self.grid.coords
        tol2 = float(tolerance) ** 2
        chunk = max(int(chunk), 1)

        for q0 in range(0, xq.size, chunk):
            q1 = min(q0 + chunk, xq.size)
            dx = xq[q0:q1, None] - coords[None, :, 0]
            dy = yq[q0:q1, None] - coords[None, :, 1]
            dist2 = dx * dx + dy * dy
            nearest = np.argmin(dist2, axis=1)
            nearest_dist2 = dist2[np.arange(q1 - q0), nearest]
            mask = nearest_dist2 <= tol2
            hits[q0:q1][mask] = nearest[mask]

        return hits

    def interpolator(
        self,
        x: np.ndarray,
        y: np.ndarray,
        u: np.ndarray,
        *,
        return_derivatives: bool = False,
        chunk: int = 1000,
        interpolation_mode: str = "exact_nodal",
        tolerance: float = 1e-12,
        Mx=None,
        My=None,
    ) -> Union[
        Tuple[np.ndarray],
        Tuple[np.ndarray, np.ndarray, np.ndarray]
    ]:
        """
        Interpolate a source-node field at arbitrary coordinates.

        Query interpolation uses all sampled subgrids as contributors and
        normalizes the Shepard weights over all sampled subgrids.  Computation
        is chunked and performed in log space to avoid overflow in the raw
        weights.

        ``interpolation_mode="exact_nodal"`` returns exact nodal values when a
        query point coincides with a source node within ``tolerance``.  Other
        query points use true distances without an epsilon floor.

        ``interpolation_mode="regularized"`` preserves the legacy epsilon-floor
        behavior for all query points.

        Parameters
        ----------
        x, y : array_like, shape (n_eval,)
            Query coordinates.
        u : array_like, shape (grid.N,)
            Source-node values ordered like ``grid.coords``.
        return_derivatives : bool, default=False
            If true, also return first derivatives ``du/dx`` and ``du/dy``.
        chunk : int, default=1000
            Number of query points processed per block.
        interpolation_mode : {"exact_nodal", "regularized"}, default="exact_nodal"
            Query distance policy.
        tolerance : float, default=1e-12
            Source-node hit tolerance for ``"exact_nodal"`` mode.
        Mx, My : sparse matrices, optional
            Existing first-derivative operators.  When
            ``return_derivatives=True`` and source-node hits are present, these
            matrices are reused instead of rebuilding operators.

        Returns
        -------
        tuple
            ``(u_eval,)`` or ``(u_eval, u_x, u_y)``.
        """
        xq = np.asarray(x, dtype=float).ravel()
        yq = np.asarray(y, dtype=float).ravel()
        u = np.asarray(u, dtype=float).ravel()
        if xq.size != yq.size:
            raise ValueError("x and y arrays must have same length.")
        if u.size != self.grid.N:
            raise ValueError("`u` must have length grid.N")
        if interpolation_mode not in ("exact_nodal", "regularized"):
            raise ValueError("interpolation_mode must be 'exact_nodal' or 'regularized'.")
        if tolerance < 0:
            raise ValueError("tolerance must be non-negative.")

        l = xq.size
        chunk = max(chunk, 10)

        val = np.empty(l)
        if return_derivatives:
            ux = np.empty_like(val)
            uy = np.empty_like(val)

        hit_nodes = np.full(l, -1, dtype=int)
        if interpolation_mode == "exact_nodal":
            hit_nodes = self._source_node_hits(
                xq,
                yq,
                tolerance=tolerance,
                chunk=chunk,
            )
            hit_mask = hit_nodes != -1
            if np.any(hit_mask):
                val[hit_mask] = u[hit_nodes[hit_mask]]
                if return_derivatives:
                    if Mx is None or My is None:
                        from ..operators.differential import build_differential_operators

                        Mx_built, My_built, _, _ = build_differential_operators(self)
                        if Mx is None:
                            Mx = Mx_built
                        if My is None:
                            My = My_built
                    ux[hit_mask] = Mx.tocsr()[hit_nodes[hit_mask]].dot(u)
                    uy[hit_mask] = My.tocsr()[hit_nodes[hit_mask]].dot(u)

        # Nodal values per sub-grid
        U = u[self.subgrids_step_row]  # (S, m)

        x_lines = self._x_lines
        y_lines = self._y_lines
        x_weights = self._x_lagrange_weights
        y_weights = self._y_lagrange_weights

        Sx, nx = x_lines.shape
        Sy, ny = y_lines.shape
        m = nx * ny
        S = Sx * Sy

        for q0 in range(0, l, chunk):
            q1 = min(q0 + chunk, l)
            block_indices = np.arange(q0, q1)
            if interpolation_mode == "exact_nodal":
                block_indices = block_indices[hit_nodes[q0:q1] == -1]
                if block_indices.size == 0:
                    continue

            xs = xq[block_indices]
            ys = yq[block_indices]
            l_b = block_indices.size

            P_parts = self._normalized_weights_at_queries_stable(
                xs,
                ys,
                return_derivatives=return_derivatives,
                regularized=interpolation_mode == "regularized",
            )
            P = P_parts[0]
            if return_derivatives:
                Px, Py = P_parts[1], P_parts[2]

            Lx = np.empty((l_b, Sx, nx))
            Ly = np.empty((l_b, Sy, ny))
            if return_derivatives:
                dLx = np.empty_like(Lx)
                dLy = np.empty_like(Ly)

            for s in range(Sx):
                if return_derivatives:
                    Lx[:, s], dLx[:, s] = lagrange_1d(
                        x_lines[s],
                        xs,
                        with_first_derivatives=True,
                        barycentric_weights=x_weights[s],
                    )
                else:
                    Lx[:, s] = lagrange_1d(
                        x_lines[s],
                        xs,
                        with_first_derivatives=False,
                        barycentric_weights=x_weights[s],
                    )[0]

            for s in range(Sy):
                if return_derivatives:
                    Ly[:, s], dLy[:, s] = lagrange_1d(
                        y_lines[s],
                        ys,
                        with_first_derivatives=True,
                        barycentric_weights=y_weights[s],
                    )
                else:
                    Ly[:, s] = lagrange_1d(
                        y_lines[s],
                        ys,
                        with_first_derivatives=False,
                        barycentric_weights=y_weights[s],
                    )[0]

            Phi = (Lx[:, :, None, :, None] * Ly[:, None, :, None, :]).reshape(l_b, S, m)

            Li = np.einsum('qsm,sm->qs', Phi, U, optimize=True)
            val[block_indices] = (P * Li).sum(axis=1)

            if return_derivatives:
                Phi_x = (dLx[:, :, None, :, None] * Ly[:, None, :, None, :]).reshape(l_b, S, m)
                Phi_y = (Lx[:, :, None, :, None] * dLy[:, None, :, None, :]).reshape(l_b, S, m)
                Li_x = np.einsum('qsm,sm->qs', Phi_x, U, optimize=True)
                Li_y = np.einsum('qsm,sm->qs', Phi_y, U, optimize=True)
                ux[block_indices] = (P * Li_x + Px * Li).sum(axis=1)
                uy[block_indices] = (P * Li_y + Py * Li).sum(axis=1)

        if return_derivatives:
            return val, ux, uy
        return (val,)

    def lagrange_derivatives_x_direction(self):
        """Return repeated 1D Lagrange derivative matrices in the x direction."""
        l = len(self.subgrids_x_step) 
        (I, L1, L2) = self._lagrange_derivatives_one_subgrids_1dim(self.grid.subgrids_x_coords[0])
        return (I[None, :, :].repeat(l, axis=0), L1[None, :, :].repeat(l, axis=0), L2[None, :, :].repeat(l, axis=0))

    def lagrange_derivatives_y_direction(self):
        """Return repeated 1D Lagrange derivative matrices in the y direction."""
        (I, L1, L2) = self._lagrange_derivatives_one_subgrids_1dim(self.grid.subgrids_y_coords[0])
        l = len(self.subgrids_y_step)
        return (I[None, :, :].repeat(l, axis=0), L1[None, :, :].repeat(l, axis=0), L2[None, :, :].repeat(l, axis=0))

    def _lagrange_derivatives_one_subgrids_1dim(self, X: np.ndarray) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
        """
        Compute nodal 1D Lagrange derivative matrices.

        Parameters
        ----------
        X : ndarray, shape (m,)
            Distinct interpolation nodes.

        Returns
        -------
        I, L1, L2 : tuple[ndarray, ndarray, ndarray]
            Basis, first-derivative, and second-derivative matrices evaluated
            at the nodes ``X``.
        """
        X = np.asarray(X, dtype=float)
        cache_key = tuple(X.tolist())
        cached = self._lagrange_derivative_cache.get(cache_key)
        if cached is not None:
            return cached

        m = X.size
        diff = X[:, None] - X[None, :]
        diag = np.eye(m, dtype=bool)

        # Barycentric weights
        diff[diag] = 1.0
        w = 1.0 / np.prod(diff, axis=1)

        # First derivative
        with np.errstate(divide='ignore', invalid='ignore'):
            L1 = np.where(
                diag, 
                0.0, 
                (w[None, :] / (w[:, None] * diff))
            )
        L1[diag] = -np.sum(L1, axis=1)

        # Compute S_vector for second derivative
        offdiag = ~diag
        with np.errstate(divide='ignore', invalid='ignore'):
            inv_diff = np.where(offdiag, 1.0 / diff, 0.0)
        S_vec = np.sum(inv_diff, axis=1)

        # Second derivative
        with np.errstate(divide='ignore', invalid='ignore'):
            L2 = np.where(
                offdiag,
                2 * L1 * (S_vec[:, None] - 1.0 / diff),
                0.0
            )
        L2[diag] = -np.sum(L2, axis=1)

        result = (np.eye(m), L1, L2)
        self._lagrange_derivative_cache[cache_key] = result
        return result

    def eval_weight_functions_at_nodes_data_minmax_shift(
        self,
        second_derivatives=True,
        block_s: int = 128
    ) -> Union[Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray],
               Tuple[np.ndarray, np.ndarray, np.ndarray]
               ]:
        """
        Compute active-mode nodal Shepard weights and derivatives.

        For each source-node row, only subgrids containing that source node
        participate in both the contributors and the denominator.  The
        implementation uses shifted log-ratios,

            f_i = 1 / sum_j exp(z_j),  z_j = mu * (A_i - A_j)

        and evaluates ``exp(z_j - max(z))`` instead of directly forming
        ``exp(z_j)``.

        Parameters
        ----------
        second_derivatives : bool, default=True
            Whether to also return second derivatives of the weights.
        block_s : int, default=128
            Number of sampled subgrids processed per vectorized block.

        Returns
        -------
        tuple[ndarray, ...]
            ``(f, f_x, f_y, f_xx, f_yy)`` when ``second_derivatives`` is true,
            otherwise ``(f, f_x, f_y)``.  Each array has shape ``(S, m)``.
        """
        mu = self.mu * 0.5
        diff_x, diff_y = self.grid.diff_x, self.grid.diff_y
        dist, logd = self._safe_pairwise_data()

        idx_rows = self.subgrids_step_row
        S, m = idx_rows.shape

        f_val = np.empty((S, m))
        f_x = np.empty_like(f_val)
        f_y = np.empty_like(f_val)
        if second_derivatives:
            f_xx = np.empty_like(f_val)
            f_yy = np.empty_like(f_val)

        for s0 in range(0, S, block_s):
            s1 = min(s0 + block_s, S)
            blk = slice(s0, s1)
            B = s1 - s0

            rows = idx_rows[blk]
            flat_eval_nodes = rows.reshape(-1)
            current_subgrid_ids = np.repeat(np.arange(s0, s1), m)
            current_subgrid_nodes = idx_rows[current_subgrid_ids]

            current_row_index = flat_eval_nodes[:, None]
            current_logd = logd[current_row_index, current_subgrid_nodes]
            current_dx = diff_x[current_row_index, current_subgrid_nodes]
            current_dy = diff_y[current_row_index, current_subgrid_nodes]
            current_dist = dist[current_row_index, current_subgrid_nodes]

            A_current = current_logd.sum(axis=1)
            A_x_current = (2.0 * current_dx / current_dist).sum(axis=1)
            A_y_current = (2.0 * current_dy / current_dist).sum(axis=1)

            candidate_subgrid_ids = self._node_subgrid_ids[flat_eval_nodes]
            candidate_mask = candidate_subgrid_ids != -1
            safe_candidate_ids = np.where(candidate_mask, candidate_subgrid_ids, 0)
            candidate_nodes = idx_rows[safe_candidate_ids]

            row_index = flat_eval_nodes[:, None, None]
            candidate_logd = logd[row_index, candidate_nodes]
            candidate_dx = diff_x[row_index, candidate_nodes]
            candidate_dy = diff_y[row_index, candidate_nodes]
            candidate_dist = dist[row_index, candidate_nodes]

            A_candidates = candidate_logd.sum(axis=2)
            A_x_candidates = (2.0 * candidate_dx / candidate_dist).sum(axis=2)
            A_y_candidates = (2.0 * candidate_dy / candidate_dist).sum(axis=2)

            DeltaA = A_current[:, None] - A_candidates
            DeltaA_x = A_x_current[:, None] - A_x_candidates
            DeltaA_y = A_y_current[:, None] - A_y_candidates

            if second_derivatives:
                A_xx_current = (2.0 / current_dist - 4.0 * (current_dx / current_dist) ** 2).sum(axis=1)
                A_yy_current = (2.0 / current_dist - 4.0 * (current_dy / current_dist) ** 2).sum(axis=1)
                A_xx_candidates = (2.0 / candidate_dist - 4.0 * (candidate_dx / candidate_dist) ** 2).sum(axis=2)
                A_yy_candidates = (2.0 / candidate_dist - 4.0 * (candidate_dy / candidate_dist) ** 2).sum(axis=2)
                DeltaA_xx = A_xx_current[:, None] - A_xx_candidates
                DeltaA_yy = A_yy_current[:, None] - A_yy_candidates

            z = np.where(candidate_mask, mu * DeltaA, -np.inf)
            z_max = np.max(z, axis=1, keepdims=True)

            with np.errstate(under="ignore"):
                R_shift = np.exp(z - z_max)
            R_shift *= candidate_mask

            R_shift_sum = R_shift.sum(axis=1)
            normalized_R = R_shift / R_shift_sum[:, None]

            f_val_block = np.exp(-z_max.ravel()) / R_shift_sum

            beta_x = np.where(candidate_mask, mu * DeltaA_x, 0.0)
            beta_y = np.where(candidate_mask, mu * DeltaA_y, 0.0)
            log_derivative_x = (normalized_R * beta_x).sum(axis=1)
            log_derivative_y = (normalized_R * beta_y).sum(axis=1)

            f_x_block = -f_val_block * log_derivative_x
            f_y_block = -f_val_block * log_derivative_y

            f_val[blk] = f_val_block.reshape(B, m)
            f_x[blk] = f_x_block.reshape(B, m)
            f_y[blk] = f_y_block.reshape(B, m)

            if second_derivatives:
                beta_xx = np.where(candidate_mask, mu * DeltaA_xx, 0.0)
                beta_yy = np.where(candidate_mask, mu * DeltaA_yy, 0.0)
                curvature_x = (normalized_R * (beta_xx + beta_x ** 2)).sum(axis=1)
                curvature_y = (normalized_R * (beta_yy + beta_y ** 2)).sum(axis=1)

                f_xx[blk] = (
                    f_val_block * (2.0 * log_derivative_x ** 2 - curvature_x)
                ).reshape(B, m)
                f_yy[blk] = (
                    f_val_block * (2.0 * log_derivative_y ** 2 - curvature_y)
                ).reshape(B, m)

        if second_derivatives:
            return f_val, f_x, f_y, f_xx, f_yy

        return f_val, f_x, f_y

    def eval_weight_functions_at_nodes_nodal_limit(
        self,
        second_derivatives=True,
        block_s: int = 128
    ) -> Union[Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray],
               Tuple[np.ndarray, np.ndarray, np.ndarray]
               ]:
        """
        Compute source-node limiting Shepard weights and derivatives.

        For each source-node row, only subgrids containing that source node
        participate.  The common singular factor is cancelled analytically
        before forming the normalized Shepard fraction.  In the vectorized
        metric sums this is equivalent to using a neutral self-distance and
        zero self-contributions for first and second metric derivatives.
        """
        mu = self.mu * 0.5
        _, logd, A_x_data, A_y_data, A_xx_data, A_yy_data = self._nodal_limit_pairwise_data()

        idx_rows = self.subgrids_step_row
        S, m = idx_rows.shape

        f_val = np.empty((S, m))
        f_x = np.empty_like(f_val)
        f_y = np.empty_like(f_val)
        if second_derivatives:
            f_xx = np.empty_like(f_val)
            f_yy = np.empty_like(f_val)

        for s0 in range(0, S, block_s):
            s1 = min(s0 + block_s, S)
            blk = slice(s0, s1)
            B = s1 - s0

            rows = idx_rows[blk]
            flat_eval_nodes = rows.reshape(-1)
            current_subgrid_ids = np.repeat(np.arange(s0, s1), m)
            current_subgrid_nodes = idx_rows[current_subgrid_ids]

            current_row_index = flat_eval_nodes[:, None]
            current_logd = logd[current_row_index, current_subgrid_nodes]
            current_A_x = A_x_data[current_row_index, current_subgrid_nodes]
            current_A_y = A_y_data[current_row_index, current_subgrid_nodes]

            A_current = current_logd.sum(axis=1)
            A_x_current = current_A_x.sum(axis=1)
            A_y_current = current_A_y.sum(axis=1)

            candidate_subgrid_ids = self._node_subgrid_ids[flat_eval_nodes]
            candidate_mask = candidate_subgrid_ids != -1
            safe_candidate_ids = np.where(candidate_mask, candidate_subgrid_ids, 0)
            candidate_nodes = idx_rows[safe_candidate_ids]

            row_index = flat_eval_nodes[:, None, None]
            candidate_logd = logd[row_index, candidate_nodes]
            candidate_A_x = A_x_data[row_index, candidate_nodes]
            candidate_A_y = A_y_data[row_index, candidate_nodes]

            A_candidates = candidate_logd.sum(axis=2)
            A_x_candidates = candidate_A_x.sum(axis=2)
            A_y_candidates = candidate_A_y.sum(axis=2)

            DeltaA = A_current[:, None] - A_candidates
            DeltaA_x = A_x_current[:, None] - A_x_candidates
            DeltaA_y = A_y_current[:, None] - A_y_candidates

            if second_derivatives:
                current_A_xx = A_xx_data[current_row_index, current_subgrid_nodes]
                current_A_yy = A_yy_data[current_row_index, current_subgrid_nodes]
                candidate_A_xx = A_xx_data[row_index, candidate_nodes]
                candidate_A_yy = A_yy_data[row_index, candidate_nodes]
                A_xx_current = current_A_xx.sum(axis=1)
                A_yy_current = current_A_yy.sum(axis=1)
                A_xx_candidates = candidate_A_xx.sum(axis=2)
                A_yy_candidates = candidate_A_yy.sum(axis=2)
                DeltaA_xx = A_xx_current[:, None] - A_xx_candidates
                DeltaA_yy = A_yy_current[:, None] - A_yy_candidates

            z = np.where(candidate_mask, mu * DeltaA, -np.inf)
            z_max = np.max(z, axis=1, keepdims=True)

            with np.errstate(under="ignore"):
                R_shift = np.exp(z - z_max)
            R_shift *= candidate_mask

            R_shift_sum = R_shift.sum(axis=1)
            normalized_R = R_shift / R_shift_sum[:, None]

            f_val_block = np.exp(-z_max.ravel()) / R_shift_sum

            beta_x = np.where(candidate_mask, mu * DeltaA_x, 0.0)
            beta_y = np.where(candidate_mask, mu * DeltaA_y, 0.0)
            log_derivative_x = (normalized_R * beta_x).sum(axis=1)
            log_derivative_y = (normalized_R * beta_y).sum(axis=1)

            f_x_block = -f_val_block * log_derivative_x
            f_y_block = -f_val_block * log_derivative_y

            f_val[blk] = f_val_block.reshape(B, m)
            f_x[blk] = f_x_block.reshape(B, m)
            f_y[blk] = f_y_block.reshape(B, m)

            if second_derivatives:
                beta_xx = np.where(candidate_mask, mu * DeltaA_xx, 0.0)
                beta_yy = np.where(candidate_mask, mu * DeltaA_yy, 0.0)
                curvature_x = (normalized_R * (beta_xx + beta_x ** 2)).sum(axis=1)
                curvature_y = (normalized_R * (beta_yy + beta_y ** 2)).sum(axis=1)

                f_xx[blk] = (
                    f_val_block * (2.0 * log_derivative_x ** 2 - curvature_x)
                ).reshape(B, m)
                f_yy[blk] = (
                    f_val_block * (2.0 * log_derivative_y ** 2 - curvature_y)
                ).reshape(B, m)

        if second_derivatives:
            return f_val, f_x, f_y, f_xx, f_yy

        return f_val, f_x, f_y

__init__(grid, step=(1, 1), mu=2.005, eps=1e-12, support_mode='active')

Initialize the Grid-Based Shepard approximation.

Parameters:

Name Type Description Default
grid SourceGrid

Structured source grid providing source-node coordinates, local subgrids, and pairwise distances.

required
step tuple[int, int]

Sampling stride for local subgrid starts.

(1, 1)
mu float

Shepard exponent parameter. The implementation stores 2*mu so formulas based on squared distances recover the requested power.

2.005
eps float

Distance floor used to avoid division by zero and logarithms of zero.

1e-12
support_mode (active, all, nodal_limit)

Nodal PDE-operator support mode.

"active"

Raises:

Type Description
TypeError

If grid does not provide local subgrids.

ValueError

If step is invalid, mu <= 2, or support_mode is unknown.

Source code in src/gbmsc_pde/approximation/shepard.py
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
def __init__(
    self,
    grid: SourceGrid,
    step: Tuple[int, int] = (1, 1),
    mu: float = 2.005,
    eps: float = 1e-12,
    support_mode: str = "active",
) -> None:
    """
    Initialize the Grid-Based Shepard approximation.

    Parameters
    ----------
    grid : SourceGrid
        Structured source grid providing source-node coordinates, local subgrids,
        and pairwise distances.
    step : tuple[int, int], default=(1, 1)
        Sampling stride for local subgrid starts.
    mu : float, default=2.005
        Shepard exponent parameter.  The implementation stores ``2*mu`` so
        formulas based on squared distances recover the requested power.
    eps : float, default=1e-12
        Distance floor used to avoid division by zero and logarithms of
        zero.
    support_mode : {"active", "all", "nodal_limit"}, default="active"
        Nodal PDE-operator support mode.

    Raises
    ------
    TypeError
        If ``grid`` does not provide local subgrids.
    ValueError
        If ``step`` is invalid, ``mu <= 2``, or ``support_mode`` is
        unknown.
    """
    # Input validation
    if not hasattr(grid, 'subgrids'):
        raise TypeError("grid must have attribute 'subgrids'.")
    if any(s < 1 or not isinstance(s, int) for s in step):
        raise ValueError("step must be a tuple of positive integers.")

    if mu <= 2:
        raise ValueError("mu parameter must be greater than 2.")
    if support_mode not in ("active", "all", "nodal_limit"):
        raise ValueError("support_mode must be 'active', 'all', or 'nodal_limit'.")

    self.grid = grid
    self.step = step
    self.mu = float(2 * mu)
    self.eps = float(eps)
    self.support_mode = support_mode

    # Unpack shapes
    n_x, n_y = grid.subgrid_shape

    # Sample subgrids at the given stride, then flatten for vectorized ops
    subgrids_step, self.subgrids_x_step, self.subgrids_y_step = grid.subgrids_with_step(self.step)
    self.subgrids_step_grid = subgrids_step.reshape(-1, n_x, n_y)    # (S, n_x, n_y)
    self.subgrids_step_row = self.subgrids_step_grid.reshape(-1, n_x * n_y)  # (S, m)
    self._subgrid_x_coords = self.grid.x_coords_flat[self.subgrids_step_row]
    self._subgrid_y_coords = self.grid.y_coords_flat[self.subgrids_step_row]
    self._x_lines = self.grid.X[self.subgrids_x_step, 0]
    self._y_lines = self.grid.Y[0, self.subgrids_y_step]
    self._x_lagrange_weights = _barycentric_weights_batch(self._x_lines)
    self._y_lagrange_weights = _barycentric_weights_batch(self._y_lines)
    self._lagrange_derivative_cache = {}
    self._node_subgrid_ids, self._node_subgrid_counts = self._build_node_subgrid_lookup()
    self._safe_dist = None
    self._safe_logd = None
    self._nodal_limit_data = None
    self._all_node_subgrid_metric_cache = {}

eval_weight_functions_at_nodes_all_denominator_minmax_shift(second_derivatives=True, block_s=64)

Compute nodal Shepard weights with active contributors and all denominator.

The returned arrays have the same (S, m) shape as :meth:eval_weight_functions_at_nodes_data_minmax_shift: one row for each retained/sampled subgrid and one column for each local node. Only the normalization denominator is enlarged to all sampled subgrids.

Parameters:

Name Type Description Default
second_derivatives bool

Whether to also return second derivatives of the weights.

True
block_s int

Number of sampled subgrids processed per vectorized block.

64

Returns:

Type Description
tuple[ndarray, ...]

(f, f_x, f_y, f_xx, f_yy) when second_derivatives is true, otherwise (f, f_x, f_y). Each array has shape (S, m).

Source code in src/gbmsc_pde/approximation/shepard.py
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
def eval_weight_functions_at_nodes_all_denominator_minmax_shift(
    self,
    second_derivatives=True,
    block_s: int = 64,
) -> Union[Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray],
           Tuple[np.ndarray, np.ndarray, np.ndarray]
           ]:
    """
    Compute nodal Shepard weights with active contributors and all denominator.

    The returned arrays have the same ``(S, m)`` shape as
    :meth:`eval_weight_functions_at_nodes_data_minmax_shift`: one row for
    each retained/sampled subgrid and one column for each local node.  Only
    the normalization denominator is enlarged to all sampled subgrids.

    Parameters
    ----------
    second_derivatives : bool, default=True
        Whether to also return second derivatives of the weights.
    block_s : int, default=64
        Number of sampled subgrids processed per vectorized block.

    Returns
    -------
    tuple[ndarray, ...]
        ``(f, f_x, f_y, f_xx, f_yy)`` when ``second_derivatives`` is true,
        otherwise ``(f, f_x, f_y)``.  Each array has shape ``(S, m)``.
    """
    mu = self.mu * 0.5
    idx_rows = self.subgrids_step_row
    S, m = idx_rows.shape

    metrics = self._all_node_subgrid_metric_sums(second_derivatives=second_derivatives)
    if second_derivatives:
        A, A_x, A_y, A_xx, A_yy = metrics
    else:
        A, A_x, A_y = metrics

    f_val = np.empty((S, m))
    f_x = np.empty_like(f_val)
    f_y = np.empty_like(f_val)
    if second_derivatives:
        f_xx = np.empty_like(f_val)
        f_yy = np.empty_like(f_val)

    for s0 in range(0, S, block_s):
        s1 = min(s0 + block_s, S)
        blk = slice(s0, s1)
        B = s1 - s0

        flat_eval_nodes = idx_rows[blk].reshape(-1)
        current_subgrid_ids = np.repeat(np.arange(s0, s1, dtype=int), m)

        A_current = A[flat_eval_nodes, current_subgrid_ids]
        A_candidates = A[flat_eval_nodes]
        DeltaA = A_current[:, None] - A_candidates

        z = mu * DeltaA
        z_max = np.max(z, axis=1, keepdims=True)
        with np.errstate(under="ignore"):
            R_shift = np.exp(z - z_max)
        R_shift_sum = R_shift.sum(axis=1)
        normalized_R = R_shift / R_shift_sum[:, None]

        f_val_block = np.exp(-z_max.ravel()) / R_shift_sum

        A_x_current = A_x[flat_eval_nodes, current_subgrid_ids]
        A_y_current = A_y[flat_eval_nodes, current_subgrid_ids]
        beta_x = mu * (A_x_current[:, None] - A_x[flat_eval_nodes])
        beta_y = mu * (A_y_current[:, None] - A_y[flat_eval_nodes])
        log_derivative_x = (normalized_R * beta_x).sum(axis=1)
        log_derivative_y = (normalized_R * beta_y).sum(axis=1)

        f_val[blk] = f_val_block.reshape(B, m)
        f_x[blk] = (-f_val_block * log_derivative_x).reshape(B, m)
        f_y[blk] = (-f_val_block * log_derivative_y).reshape(B, m)

        if second_derivatives:
            A_xx_current = A_xx[flat_eval_nodes, current_subgrid_ids]
            A_yy_current = A_yy[flat_eval_nodes, current_subgrid_ids]
            beta_xx = mu * (A_xx_current[:, None] - A_xx[flat_eval_nodes])
            beta_yy = mu * (A_yy_current[:, None] - A_yy[flat_eval_nodes])
            curvature_x = (normalized_R * (beta_xx + beta_x ** 2)).sum(axis=1)
            curvature_y = (normalized_R * (beta_yy + beta_y ** 2)).sum(axis=1)

            f_xx[blk] = (
                f_val_block * (2.0 * log_derivative_x ** 2 - curvature_x)
            ).reshape(B, m)
            f_yy[blk] = (
                f_val_block * (2.0 * log_derivative_y ** 2 - curvature_y)
            ).reshape(B, m)

    if second_derivatives:
        return f_val, f_x, f_y, f_xx, f_yy

    return f_val, f_x, f_y

eval_weight_functions_at_nodes_data_minmax_shift(second_derivatives=True, block_s=128)

Compute active-mode nodal Shepard weights and derivatives.

For each source-node row, only subgrids containing that source node participate in both the contributors and the denominator. The implementation uses shifted log-ratios,

f_i = 1 / sum_j exp(z_j),  z_j = mu * (A_i - A_j)

and evaluates exp(z_j - max(z)) instead of directly forming exp(z_j).

Parameters:

Name Type Description Default
second_derivatives bool

Whether to also return second derivatives of the weights.

True
block_s int

Number of sampled subgrids processed per vectorized block.

128

Returns:

Type Description
tuple[ndarray, ...]

(f, f_x, f_y, f_xx, f_yy) when second_derivatives is true, otherwise (f, f_x, f_y). Each array has shape (S, m).

Source code in src/gbmsc_pde/approximation/shepard.py
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
def eval_weight_functions_at_nodes_data_minmax_shift(
    self,
    second_derivatives=True,
    block_s: int = 128
) -> Union[Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray],
           Tuple[np.ndarray, np.ndarray, np.ndarray]
           ]:
    """
    Compute active-mode nodal Shepard weights and derivatives.

    For each source-node row, only subgrids containing that source node
    participate in both the contributors and the denominator.  The
    implementation uses shifted log-ratios,

        f_i = 1 / sum_j exp(z_j),  z_j = mu * (A_i - A_j)

    and evaluates ``exp(z_j - max(z))`` instead of directly forming
    ``exp(z_j)``.

    Parameters
    ----------
    second_derivatives : bool, default=True
        Whether to also return second derivatives of the weights.
    block_s : int, default=128
        Number of sampled subgrids processed per vectorized block.

    Returns
    -------
    tuple[ndarray, ...]
        ``(f, f_x, f_y, f_xx, f_yy)`` when ``second_derivatives`` is true,
        otherwise ``(f, f_x, f_y)``.  Each array has shape ``(S, m)``.
    """
    mu = self.mu * 0.5
    diff_x, diff_y = self.grid.diff_x, self.grid.diff_y
    dist, logd = self._safe_pairwise_data()

    idx_rows = self.subgrids_step_row
    S, m = idx_rows.shape

    f_val = np.empty((S, m))
    f_x = np.empty_like(f_val)
    f_y = np.empty_like(f_val)
    if second_derivatives:
        f_xx = np.empty_like(f_val)
        f_yy = np.empty_like(f_val)

    for s0 in range(0, S, block_s):
        s1 = min(s0 + block_s, S)
        blk = slice(s0, s1)
        B = s1 - s0

        rows = idx_rows[blk]
        flat_eval_nodes = rows.reshape(-1)
        current_subgrid_ids = np.repeat(np.arange(s0, s1), m)
        current_subgrid_nodes = idx_rows[current_subgrid_ids]

        current_row_index = flat_eval_nodes[:, None]
        current_logd = logd[current_row_index, current_subgrid_nodes]
        current_dx = diff_x[current_row_index, current_subgrid_nodes]
        current_dy = diff_y[current_row_index, current_subgrid_nodes]
        current_dist = dist[current_row_index, current_subgrid_nodes]

        A_current = current_logd.sum(axis=1)
        A_x_current = (2.0 * current_dx / current_dist).sum(axis=1)
        A_y_current = (2.0 * current_dy / current_dist).sum(axis=1)

        candidate_subgrid_ids = self._node_subgrid_ids[flat_eval_nodes]
        candidate_mask = candidate_subgrid_ids != -1
        safe_candidate_ids = np.where(candidate_mask, candidate_subgrid_ids, 0)
        candidate_nodes = idx_rows[safe_candidate_ids]

        row_index = flat_eval_nodes[:, None, None]
        candidate_logd = logd[row_index, candidate_nodes]
        candidate_dx = diff_x[row_index, candidate_nodes]
        candidate_dy = diff_y[row_index, candidate_nodes]
        candidate_dist = dist[row_index, candidate_nodes]

        A_candidates = candidate_logd.sum(axis=2)
        A_x_candidates = (2.0 * candidate_dx / candidate_dist).sum(axis=2)
        A_y_candidates = (2.0 * candidate_dy / candidate_dist).sum(axis=2)

        DeltaA = A_current[:, None] - A_candidates
        DeltaA_x = A_x_current[:, None] - A_x_candidates
        DeltaA_y = A_y_current[:, None] - A_y_candidates

        if second_derivatives:
            A_xx_current = (2.0 / current_dist - 4.0 * (current_dx / current_dist) ** 2).sum(axis=1)
            A_yy_current = (2.0 / current_dist - 4.0 * (current_dy / current_dist) ** 2).sum(axis=1)
            A_xx_candidates = (2.0 / candidate_dist - 4.0 * (candidate_dx / candidate_dist) ** 2).sum(axis=2)
            A_yy_candidates = (2.0 / candidate_dist - 4.0 * (candidate_dy / candidate_dist) ** 2).sum(axis=2)
            DeltaA_xx = A_xx_current[:, None] - A_xx_candidates
            DeltaA_yy = A_yy_current[:, None] - A_yy_candidates

        z = np.where(candidate_mask, mu * DeltaA, -np.inf)
        z_max = np.max(z, axis=1, keepdims=True)

        with np.errstate(under="ignore"):
            R_shift = np.exp(z - z_max)
        R_shift *= candidate_mask

        R_shift_sum = R_shift.sum(axis=1)
        normalized_R = R_shift / R_shift_sum[:, None]

        f_val_block = np.exp(-z_max.ravel()) / R_shift_sum

        beta_x = np.where(candidate_mask, mu * DeltaA_x, 0.0)
        beta_y = np.where(candidate_mask, mu * DeltaA_y, 0.0)
        log_derivative_x = (normalized_R * beta_x).sum(axis=1)
        log_derivative_y = (normalized_R * beta_y).sum(axis=1)

        f_x_block = -f_val_block * log_derivative_x
        f_y_block = -f_val_block * log_derivative_y

        f_val[blk] = f_val_block.reshape(B, m)
        f_x[blk] = f_x_block.reshape(B, m)
        f_y[blk] = f_y_block.reshape(B, m)

        if second_derivatives:
            beta_xx = np.where(candidate_mask, mu * DeltaA_xx, 0.0)
            beta_yy = np.where(candidate_mask, mu * DeltaA_yy, 0.0)
            curvature_x = (normalized_R * (beta_xx + beta_x ** 2)).sum(axis=1)
            curvature_y = (normalized_R * (beta_yy + beta_y ** 2)).sum(axis=1)

            f_xx[blk] = (
                f_val_block * (2.0 * log_derivative_x ** 2 - curvature_x)
            ).reshape(B, m)
            f_yy[blk] = (
                f_val_block * (2.0 * log_derivative_y ** 2 - curvature_y)
            ).reshape(B, m)

    if second_derivatives:
        return f_val, f_x, f_y, f_xx, f_yy

    return f_val, f_x, f_y

eval_weight_functions_at_nodes_nodal_limit(second_derivatives=True, block_s=128)

Compute source-node limiting Shepard weights and derivatives.

For each source-node row, only subgrids containing that source node participate. The common singular factor is cancelled analytically before forming the normalized Shepard fraction. In the vectorized metric sums this is equivalent to using a neutral self-distance and zero self-contributions for first and second metric derivatives.

Source code in src/gbmsc_pde/approximation/shepard.py
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
def eval_weight_functions_at_nodes_nodal_limit(
    self,
    second_derivatives=True,
    block_s: int = 128
) -> Union[Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray],
           Tuple[np.ndarray, np.ndarray, np.ndarray]
           ]:
    """
    Compute source-node limiting Shepard weights and derivatives.

    For each source-node row, only subgrids containing that source node
    participate.  The common singular factor is cancelled analytically
    before forming the normalized Shepard fraction.  In the vectorized
    metric sums this is equivalent to using a neutral self-distance and
    zero self-contributions for first and second metric derivatives.
    """
    mu = self.mu * 0.5
    _, logd, A_x_data, A_y_data, A_xx_data, A_yy_data = self._nodal_limit_pairwise_data()

    idx_rows = self.subgrids_step_row
    S, m = idx_rows.shape

    f_val = np.empty((S, m))
    f_x = np.empty_like(f_val)
    f_y = np.empty_like(f_val)
    if second_derivatives:
        f_xx = np.empty_like(f_val)
        f_yy = np.empty_like(f_val)

    for s0 in range(0, S, block_s):
        s1 = min(s0 + block_s, S)
        blk = slice(s0, s1)
        B = s1 - s0

        rows = idx_rows[blk]
        flat_eval_nodes = rows.reshape(-1)
        current_subgrid_ids = np.repeat(np.arange(s0, s1), m)
        current_subgrid_nodes = idx_rows[current_subgrid_ids]

        current_row_index = flat_eval_nodes[:, None]
        current_logd = logd[current_row_index, current_subgrid_nodes]
        current_A_x = A_x_data[current_row_index, current_subgrid_nodes]
        current_A_y = A_y_data[current_row_index, current_subgrid_nodes]

        A_current = current_logd.sum(axis=1)
        A_x_current = current_A_x.sum(axis=1)
        A_y_current = current_A_y.sum(axis=1)

        candidate_subgrid_ids = self._node_subgrid_ids[flat_eval_nodes]
        candidate_mask = candidate_subgrid_ids != -1
        safe_candidate_ids = np.where(candidate_mask, candidate_subgrid_ids, 0)
        candidate_nodes = idx_rows[safe_candidate_ids]

        row_index = flat_eval_nodes[:, None, None]
        candidate_logd = logd[row_index, candidate_nodes]
        candidate_A_x = A_x_data[row_index, candidate_nodes]
        candidate_A_y = A_y_data[row_index, candidate_nodes]

        A_candidates = candidate_logd.sum(axis=2)
        A_x_candidates = candidate_A_x.sum(axis=2)
        A_y_candidates = candidate_A_y.sum(axis=2)

        DeltaA = A_current[:, None] - A_candidates
        DeltaA_x = A_x_current[:, None] - A_x_candidates
        DeltaA_y = A_y_current[:, None] - A_y_candidates

        if second_derivatives:
            current_A_xx = A_xx_data[current_row_index, current_subgrid_nodes]
            current_A_yy = A_yy_data[current_row_index, current_subgrid_nodes]
            candidate_A_xx = A_xx_data[row_index, candidate_nodes]
            candidate_A_yy = A_yy_data[row_index, candidate_nodes]
            A_xx_current = current_A_xx.sum(axis=1)
            A_yy_current = current_A_yy.sum(axis=1)
            A_xx_candidates = candidate_A_xx.sum(axis=2)
            A_yy_candidates = candidate_A_yy.sum(axis=2)
            DeltaA_xx = A_xx_current[:, None] - A_xx_candidates
            DeltaA_yy = A_yy_current[:, None] - A_yy_candidates

        z = np.where(candidate_mask, mu * DeltaA, -np.inf)
        z_max = np.max(z, axis=1, keepdims=True)

        with np.errstate(under="ignore"):
            R_shift = np.exp(z - z_max)
        R_shift *= candidate_mask

        R_shift_sum = R_shift.sum(axis=1)
        normalized_R = R_shift / R_shift_sum[:, None]

        f_val_block = np.exp(-z_max.ravel()) / R_shift_sum

        beta_x = np.where(candidate_mask, mu * DeltaA_x, 0.0)
        beta_y = np.where(candidate_mask, mu * DeltaA_y, 0.0)
        log_derivative_x = (normalized_R * beta_x).sum(axis=1)
        log_derivative_y = (normalized_R * beta_y).sum(axis=1)

        f_x_block = -f_val_block * log_derivative_x
        f_y_block = -f_val_block * log_derivative_y

        f_val[blk] = f_val_block.reshape(B, m)
        f_x[blk] = f_x_block.reshape(B, m)
        f_y[blk] = f_y_block.reshape(B, m)

        if second_derivatives:
            beta_xx = np.where(candidate_mask, mu * DeltaA_xx, 0.0)
            beta_yy = np.where(candidate_mask, mu * DeltaA_yy, 0.0)
            curvature_x = (normalized_R * (beta_xx + beta_x ** 2)).sum(axis=1)
            curvature_y = (normalized_R * (beta_yy + beta_y ** 2)).sum(axis=1)

            f_xx[blk] = (
                f_val_block * (2.0 * log_derivative_x ** 2 - curvature_x)
            ).reshape(B, m)
            f_yy[blk] = (
                f_val_block * (2.0 * log_derivative_y ** 2 - curvature_y)
            ).reshape(B, m)

    if second_derivatives:
        return f_val, f_x, f_y, f_xx, f_yy

    return f_val, f_x, f_y

interpolator(x, y, u, *, return_derivatives=False, chunk=1000, interpolation_mode='exact_nodal', tolerance=1e-12, Mx=None, My=None)

Interpolate a source-node field at arbitrary coordinates.

Query interpolation uses all sampled subgrids as contributors and normalizes the Shepard weights over all sampled subgrids. Computation is chunked and performed in log space to avoid overflow in the raw weights.

interpolation_mode="exact_nodal" returns exact nodal values when a query point coincides with a source node within tolerance. Other query points use true distances without an epsilon floor.

interpolation_mode="regularized" preserves the legacy epsilon-floor behavior for all query points.

Parameters:

Name Type Description Default
x (array_like, shape(n_eval))

Query coordinates.

required
y (array_like, shape(n_eval))

Query coordinates.

required
u (array_like, shape(N))

Source-node values ordered like grid.coords.

required
return_derivatives bool

If true, also return first derivatives du/dx and du/dy.

False
chunk int

Number of query points processed per block.

1000
interpolation_mode (exact_nodal, regularized)

Query distance policy.

"exact_nodal"
tolerance float

Source-node hit tolerance for "exact_nodal" mode.

1e-12
Mx sparse matrices

Existing first-derivative operators. When return_derivatives=True and source-node hits are present, these matrices are reused instead of rebuilding operators.

None
My sparse matrices

Existing first-derivative operators. When return_derivatives=True and source-node hits are present, these matrices are reused instead of rebuilding operators.

None

Returns:

Type Description
tuple

(u_eval,) or (u_eval, u_x, u_y).

Source code in src/gbmsc_pde/approximation/shepard.py
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
def interpolator(
    self,
    x: np.ndarray,
    y: np.ndarray,
    u: np.ndarray,
    *,
    return_derivatives: bool = False,
    chunk: int = 1000,
    interpolation_mode: str = "exact_nodal",
    tolerance: float = 1e-12,
    Mx=None,
    My=None,
) -> Union[
    Tuple[np.ndarray],
    Tuple[np.ndarray, np.ndarray, np.ndarray]
]:
    """
    Interpolate a source-node field at arbitrary coordinates.

    Query interpolation uses all sampled subgrids as contributors and
    normalizes the Shepard weights over all sampled subgrids.  Computation
    is chunked and performed in log space to avoid overflow in the raw
    weights.

    ``interpolation_mode="exact_nodal"`` returns exact nodal values when a
    query point coincides with a source node within ``tolerance``.  Other
    query points use true distances without an epsilon floor.

    ``interpolation_mode="regularized"`` preserves the legacy epsilon-floor
    behavior for all query points.

    Parameters
    ----------
    x, y : array_like, shape (n_eval,)
        Query coordinates.
    u : array_like, shape (grid.N,)
        Source-node values ordered like ``grid.coords``.
    return_derivatives : bool, default=False
        If true, also return first derivatives ``du/dx`` and ``du/dy``.
    chunk : int, default=1000
        Number of query points processed per block.
    interpolation_mode : {"exact_nodal", "regularized"}, default="exact_nodal"
        Query distance policy.
    tolerance : float, default=1e-12
        Source-node hit tolerance for ``"exact_nodal"`` mode.
    Mx, My : sparse matrices, optional
        Existing first-derivative operators.  When
        ``return_derivatives=True`` and source-node hits are present, these
        matrices are reused instead of rebuilding operators.

    Returns
    -------
    tuple
        ``(u_eval,)`` or ``(u_eval, u_x, u_y)``.
    """
    xq = np.asarray(x, dtype=float).ravel()
    yq = np.asarray(y, dtype=float).ravel()
    u = np.asarray(u, dtype=float).ravel()
    if xq.size != yq.size:
        raise ValueError("x and y arrays must have same length.")
    if u.size != self.grid.N:
        raise ValueError("`u` must have length grid.N")
    if interpolation_mode not in ("exact_nodal", "regularized"):
        raise ValueError("interpolation_mode must be 'exact_nodal' or 'regularized'.")
    if tolerance < 0:
        raise ValueError("tolerance must be non-negative.")

    l = xq.size
    chunk = max(chunk, 10)

    val = np.empty(l)
    if return_derivatives:
        ux = np.empty_like(val)
        uy = np.empty_like(val)

    hit_nodes = np.full(l, -1, dtype=int)
    if interpolation_mode == "exact_nodal":
        hit_nodes = self._source_node_hits(
            xq,
            yq,
            tolerance=tolerance,
            chunk=chunk,
        )
        hit_mask = hit_nodes != -1
        if np.any(hit_mask):
            val[hit_mask] = u[hit_nodes[hit_mask]]
            if return_derivatives:
                if Mx is None or My is None:
                    from ..operators.differential import build_differential_operators

                    Mx_built, My_built, _, _ = build_differential_operators(self)
                    if Mx is None:
                        Mx = Mx_built
                    if My is None:
                        My = My_built
                ux[hit_mask] = Mx.tocsr()[hit_nodes[hit_mask]].dot(u)
                uy[hit_mask] = My.tocsr()[hit_nodes[hit_mask]].dot(u)

    # Nodal values per sub-grid
    U = u[self.subgrids_step_row]  # (S, m)

    x_lines = self._x_lines
    y_lines = self._y_lines
    x_weights = self._x_lagrange_weights
    y_weights = self._y_lagrange_weights

    Sx, nx = x_lines.shape
    Sy, ny = y_lines.shape
    m = nx * ny
    S = Sx * Sy

    for q0 in range(0, l, chunk):
        q1 = min(q0 + chunk, l)
        block_indices = np.arange(q0, q1)
        if interpolation_mode == "exact_nodal":
            block_indices = block_indices[hit_nodes[q0:q1] == -1]
            if block_indices.size == 0:
                continue

        xs = xq[block_indices]
        ys = yq[block_indices]
        l_b = block_indices.size

        P_parts = self._normalized_weights_at_queries_stable(
            xs,
            ys,
            return_derivatives=return_derivatives,
            regularized=interpolation_mode == "regularized",
        )
        P = P_parts[0]
        if return_derivatives:
            Px, Py = P_parts[1], P_parts[2]

        Lx = np.empty((l_b, Sx, nx))
        Ly = np.empty((l_b, Sy, ny))
        if return_derivatives:
            dLx = np.empty_like(Lx)
            dLy = np.empty_like(Ly)

        for s in range(Sx):
            if return_derivatives:
                Lx[:, s], dLx[:, s] = lagrange_1d(
                    x_lines[s],
                    xs,
                    with_first_derivatives=True,
                    barycentric_weights=x_weights[s],
                )
            else:
                Lx[:, s] = lagrange_1d(
                    x_lines[s],
                    xs,
                    with_first_derivatives=False,
                    barycentric_weights=x_weights[s],
                )[0]

        for s in range(Sy):
            if return_derivatives:
                Ly[:, s], dLy[:, s] = lagrange_1d(
                    y_lines[s],
                    ys,
                    with_first_derivatives=True,
                    barycentric_weights=y_weights[s],
                )
            else:
                Ly[:, s] = lagrange_1d(
                    y_lines[s],
                    ys,
                    with_first_derivatives=False,
                    barycentric_weights=y_weights[s],
                )[0]

        Phi = (Lx[:, :, None, :, None] * Ly[:, None, :, None, :]).reshape(l_b, S, m)

        Li = np.einsum('qsm,sm->qs', Phi, U, optimize=True)
        val[block_indices] = (P * Li).sum(axis=1)

        if return_derivatives:
            Phi_x = (dLx[:, :, None, :, None] * Ly[:, None, :, None, :]).reshape(l_b, S, m)
            Phi_y = (Lx[:, :, None, :, None] * dLy[:, None, :, None, :]).reshape(l_b, S, m)
            Li_x = np.einsum('qsm,sm->qs', Phi_x, U, optimize=True)
            Li_y = np.einsum('qsm,sm->qs', Phi_y, U, optimize=True)
            ux[block_indices] = (P * Li_x + Px * Li).sum(axis=1)
            uy[block_indices] = (P * Li_y + Py * Li).sum(axis=1)

    if return_derivatives:
        return val, ux, uy
    return (val,)

lagrange_derivatives_x_direction()

Return repeated 1D Lagrange derivative matrices in the x direction.

Source code in src/gbmsc_pde/approximation/shepard.py
822
823
824
825
826
def lagrange_derivatives_x_direction(self):
    """Return repeated 1D Lagrange derivative matrices in the x direction."""
    l = len(self.subgrids_x_step) 
    (I, L1, L2) = self._lagrange_derivatives_one_subgrids_1dim(self.grid.subgrids_x_coords[0])
    return (I[None, :, :].repeat(l, axis=0), L1[None, :, :].repeat(l, axis=0), L2[None, :, :].repeat(l, axis=0))

lagrange_derivatives_y_direction()

Return repeated 1D Lagrange derivative matrices in the y direction.

Source code in src/gbmsc_pde/approximation/shepard.py
828
829
830
831
832
def lagrange_derivatives_y_direction(self):
    """Return repeated 1D Lagrange derivative matrices in the y direction."""
    (I, L1, L2) = self._lagrange_derivatives_one_subgrids_1dim(self.grid.subgrids_y_coords[0])
    l = len(self.subgrids_y_step)
    return (I[None, :, :].repeat(l, axis=0), L1[None, :, :].repeat(l, axis=0), L2[None, :, :].repeat(l, axis=0))

LinearPDE

Linear PDE builder on a structured rectangular source grid.

The assembled equation has the form

div(D grad u) + v . grad u + r u = f

where diffusion and convection coefficients may be scalar, two-component constants, or field callables. Boundary conditions are applied separately by the solver/boundary-condition layer.

Source code in src/gbmsc_pde/pde/problem.py
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
class LinearPDE:
    """
    Linear PDE builder on a structured rectangular source grid.

    The assembled equation has the form

    ``div(D grad u) + v . grad u + r u = f``

    where diffusion and convection coefficients may be scalar, two-component
    constants, or field callables.  Boundary conditions are applied separately
    by the solver/boundary-condition layer.
    """

    def __init__(self, approximation: GBMSCApproximation) -> None:
        self.approximation = approximation
        self.terms: Dict[str, object] = {
            "diffusion": None,
            "convection": None,
            "reaction": None,
            "source": None,
        }

    def add_diffusion_term(self, coeff) -> None:
        """Add diffusion coefficients for ``div(D grad u)``."""
        self.terms["diffusion"] = normalize_vector_coefficient(coeff)

    def add_convection_term(self, coeff) -> None:
        """Add convection coefficients for ``v . grad u``."""
        self.terms["convection"] = normalize_vector_coefficient(coeff)

    def add_reaction_term(self, coeff) -> None:
        """Add reaction coefficient ``r`` for ``r*u``."""
        self.terms["reaction"] = normalize_scalar_coefficient(coeff, name="coeff")

    def add_source_term(self, source) -> None:
        """Add right-hand side source field ``f``."""
        self.terms["source"] = normalize_scalar_coefficient(source, name="source")

    def assemble(self) -> tuple[spmatrix, np.ndarray, spmatrix, spmatrix, spmatrix, spmatrix]:
        """
        Assemble ``A u = b`` on all rectangular source nodes.

        Returns
        -------
        A, b, Mx, My, Mxx, Myy
            Sparse PDE matrix, right-hand side, first-derivative matrices, and
            second-derivative matrices.
        """
        return assemble_linear_system(self.approximation, self.terms)

add_convection_term(coeff)

Add convection coefficients for v . grad u.

Source code in src/gbmsc_pde/pde/problem.py
37
38
39
def add_convection_term(self, coeff) -> None:
    """Add convection coefficients for ``v . grad u``."""
    self.terms["convection"] = normalize_vector_coefficient(coeff)

add_diffusion_term(coeff)

Add diffusion coefficients for div(D grad u).

Source code in src/gbmsc_pde/pde/problem.py
33
34
35
def add_diffusion_term(self, coeff) -> None:
    """Add diffusion coefficients for ``div(D grad u)``."""
    self.terms["diffusion"] = normalize_vector_coefficient(coeff)

add_reaction_term(coeff)

Add reaction coefficient r for r*u.

Source code in src/gbmsc_pde/pde/problem.py
41
42
43
def add_reaction_term(self, coeff) -> None:
    """Add reaction coefficient ``r`` for ``r*u``."""
    self.terms["reaction"] = normalize_scalar_coefficient(coeff, name="coeff")

add_source_term(source)

Add right-hand side source field f.

Source code in src/gbmsc_pde/pde/problem.py
45
46
47
def add_source_term(self, source) -> None:
    """Add right-hand side source field ``f``."""
    self.terms["source"] = normalize_scalar_coefficient(source, name="source")

assemble()

Assemble A u = b on all rectangular source nodes.

Returns:

Type Description
(A, b, Mx, My, Mxx, Myy)

Sparse PDE matrix, right-hand side, first-derivative matrices, and second-derivative matrices.

Source code in src/gbmsc_pde/pde/problem.py
49
50
51
52
53
54
55
56
57
58
59
def assemble(self) -> tuple[spmatrix, np.ndarray, spmatrix, spmatrix, spmatrix, spmatrix]:
    """
    Assemble ``A u = b`` on all rectangular source nodes.

    Returns
    -------
    A, b, Mx, My, Mxx, Myy
        Sparse PDE matrix, right-hand side, first-derivative matrices, and
        second-derivative matrices.
    """
    return assemble_linear_system(self.approximation, self.terms)

LinearSolver

Linear-system solver for rectangular-domain PDE problems.

LinearSolver assembles the PDE rows from :class:LinearPDE, applies node-indexed boundary conditions, and solves the resulting square sparse system for the source-node vector.

Parameters:

Name Type Description Default
pde LinearPDE

Configured rectangular linear PDE builder.

required
bcs BoundaryConditions

Boundary conditions registered on flattened grid nodes.

required
Source code in src/gbmsc_pde/solvers/linear.py
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
class LinearSolver:
    """
    Linear-system solver for rectangular-domain PDE problems.

    ``LinearSolver`` assembles the PDE rows from :class:`LinearPDE`, applies
    node-indexed boundary conditions, and solves the resulting square sparse
    system for the source-node vector.

    Parameters
    ----------
    pde : LinearPDE
        Configured rectangular linear PDE builder.
    bcs : BoundaryConditions
        Boundary conditions registered on flattened grid nodes.
    """
    def __init__(self, pde: LinearPDE, bcs: BoundaryConditions) -> None:
        if not isinstance(pde, LinearPDE):
            raise TypeError("pde must be an instance of LinearPDE")
        if not isinstance(bcs, BoundaryConditions):
            raise TypeError("bcs must be an instance of BoundaryConditions")

        self.pde = pde
        self.bcs = bcs
        self.A = None
        self.b = None
        self.Mx = None
        self.My = None
        self.Mxx = None
        self.Myy = None
        self.solution = None
        self.last_data = None

    def assemble(self) -> Tuple[spmatrix, np.ndarray, spmatrix, spmatrix, spmatrix, spmatrix]:
        """
        Assemble and boundary-modify the rectangular collocation system.

        Returns
        -------
        A, b, Mx, My, Mxx, Myy
            Boundary-modified sparse system, right-hand side, and first
            and second derivative matrices.  The same objects are stored on
            ``self`` as ``A``, ``b``, ``Mx``, ``My``, ``Mxx``, and ``Myy`` for
            later inspection.
        """
        A, b, Mx, My, Mxx, Myy = self.pde.assemble()
        A, b = BoundaryConditionApplier(self.bcs).apply(A, b, Mx, My)
        self.A = A
        self.b = b
        self.Mx = Mx
        self.My = My
        self.Mxx = Mxx
        self.Myy = Myy
        return A, b, Mx, My, Mxx, Myy

    @staticmethod
    def _as_linear_operator(preconditioner: Optional[Any]):
        if preconditioner is None:
            return None
        if isinstance(preconditioner, spmatrix):
            return spla.LinearOperator(preconditioner.shape, preconditioner.dot)
        return preconditioner

    @staticmethod
    def _jacobi_preconditioner(A: spmatrix):
        diagonal = A.diagonal()
        if np.any(np.isclose(diagonal, 0.0)):
            raise ValueError("Jacobi preconditioner requires a nonzero matrix diagonal.")
        inv_diagonal = 1.0 / diagonal
        return spla.LinearOperator(A.shape, matvec=lambda x: inv_diagonal * x)

    @staticmethod
    def _iterative_call(method, A, b, *, tol, maxiter, M):
        try:
            return method(A, b, rtol=tol, atol=0.0, maxiter=maxiter, M=M)
        except TypeError:
            return method(A, b, tol=tol, maxiter=maxiter, M=M)

    def solve(
        self,
        solver: str = 'direct',
        tol: float = 1e-8,
        maxiter: Optional[int] = None,
        preconditioner: Optional[Any] = None,
        return_data: bool = False,
    ) -> Union[
        np.ndarray,
        Tuple[np.ndarray, Dict[str, object]],
    ]:
        """
        Assemble, apply boundary conditions, and solve the linear system.

        Parameters
        ----------
        solver : {'direct', 'cg', 'gmres', 'bicgstab'}
            Linear solver. ``"direct"`` uses sparse direct solve; ``"cg"`` and
            ``"gmres"`` and ``"bicgstab"`` use SciPy iterative solvers.
        tol : float, optional
            Tolerance for iterative solvers.
        maxiter : int, optional
            Maximum iterations (defaults to N).
        preconditioner : object, optional
            Preconditioner LinearOperator, sparse matrix, or ``"jacobi"``.
        return_data : bool
            If true, return ``(u, data)`` where ``data`` contains ``A``, ``b``,
            derivative matrices, ``nnz``, ``sparsity``, ``solve_time``,
            ``assembly_time``, and ``solver_info``.

        Returns
        -------
        ndarray or tuple
            Solution vector ``u`` with shape ``(grid.N,)``.  If
            ``return_data=True``, returns ``(u, data)``.
        """
        assembly_start = perf_counter()
        A, b, Mx, My, Mxx, Myy = self.assemble()
        assembly_time = perf_counter() - assembly_start

        if A.shape[0] != A.shape[1]:
            raise ValueError(f"Linear system must be square; got {A.shape}.")
        if not np.all(np.isfinite(A.data)):
            raise ValueError("Linear system matrix contains non-finite values.")
        if not np.all(np.isfinite(b)):
            raise ValueError("Right-hand side contains non-finite values.")

        solve_start = perf_counter()
        if solver == 'direct':
            sol = spla.spsolve(A, b)
            info = 0
        else:
            N = A.shape[0]
            maxiter = maxiter or N
            if preconditioner == "jacobi":
                M = self._jacobi_preconditioner(A)
            else:
                M = self._as_linear_operator(preconditioner)
            methods = {'cg': spla.cg, 'gmres': spla.gmres, 'bicgstab': spla.bicgstab}
            if solver not in methods:
                raise ValueError(
                    f"Unsupported solver '{solver}'. Choose 'direct', 'cg', 'gmres', or 'bicgstab'."
                )
            sol, info = self._iterative_call(
                methods[solver],
                A,
                b,
                tol=tol,
                maxiter=maxiter,
                M=M,
            )
            if info != 0:
                raise RuntimeError(f"Solver '{solver}' failed to converge (info={info}).")
        solve_time = perf_counter() - solve_start

        self.solution = sol

        if return_data:
            data: Dict[str, object] = {
                "A": A,
                "b": b,
                "first_derivatives": (Mx, My),
                "second_derivatives": (Mxx, Myy),
                "nnz": int(A.nnz),
                "sparsity": float((1.0 - A.nnz / (A.shape[0] * A.shape[1])) * 100.0),
                "solve_time": float(solve_time),
                "assembly_time": float(assembly_time),
                "solver_info": int(info),
            }
            self.last_data = data
            return sol, data

        return sol

assemble()

Assemble and boundary-modify the rectangular collocation system.

Returns:

Type Description
(A, b, Mx, My, Mxx, Myy)

Boundary-modified sparse system, right-hand side, and first and second derivative matrices. The same objects are stored on self as A, b, Mx, My, Mxx, and Myy for later inspection.

Source code in src/gbmsc_pde/solvers/linear.py
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
def assemble(self) -> Tuple[spmatrix, np.ndarray, spmatrix, spmatrix, spmatrix, spmatrix]:
    """
    Assemble and boundary-modify the rectangular collocation system.

    Returns
    -------
    A, b, Mx, My, Mxx, Myy
        Boundary-modified sparse system, right-hand side, and first
        and second derivative matrices.  The same objects are stored on
        ``self`` as ``A``, ``b``, ``Mx``, ``My``, ``Mxx``, and ``Myy`` for
        later inspection.
    """
    A, b, Mx, My, Mxx, Myy = self.pde.assemble()
    A, b = BoundaryConditionApplier(self.bcs).apply(A, b, Mx, My)
    self.A = A
    self.b = b
    self.Mx = Mx
    self.My = My
    self.Mxx = Mxx
    self.Myy = Myy
    return A, b, Mx, My, Mxx, Myy

solve(solver='direct', tol=1e-08, maxiter=None, preconditioner=None, return_data=False)

Assemble, apply boundary conditions, and solve the linear system.

Parameters:

Name Type Description Default
solver (direct, cg, gmres, bicgstab)

Linear solver. "direct" uses sparse direct solve; "cg" and "gmres" and "bicgstab" use SciPy iterative solvers.

'direct'
tol float

Tolerance for iterative solvers.

1e-08
maxiter int

Maximum iterations (defaults to N).

None
preconditioner object

Preconditioner LinearOperator, sparse matrix, or "jacobi".

None
return_data bool

If true, return (u, data) where data contains A, b, derivative matrices, nnz, sparsity, solve_time, assembly_time, and solver_info.

False

Returns:

Type Description
ndarray or tuple

Solution vector u with shape (grid.N,). If return_data=True, returns (u, data).

Source code in src/gbmsc_pde/solvers/linear.py
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
def solve(
    self,
    solver: str = 'direct',
    tol: float = 1e-8,
    maxiter: Optional[int] = None,
    preconditioner: Optional[Any] = None,
    return_data: bool = False,
) -> Union[
    np.ndarray,
    Tuple[np.ndarray, Dict[str, object]],
]:
    """
    Assemble, apply boundary conditions, and solve the linear system.

    Parameters
    ----------
    solver : {'direct', 'cg', 'gmres', 'bicgstab'}
        Linear solver. ``"direct"`` uses sparse direct solve; ``"cg"`` and
        ``"gmres"`` and ``"bicgstab"`` use SciPy iterative solvers.
    tol : float, optional
        Tolerance for iterative solvers.
    maxiter : int, optional
        Maximum iterations (defaults to N).
    preconditioner : object, optional
        Preconditioner LinearOperator, sparse matrix, or ``"jacobi"``.
    return_data : bool
        If true, return ``(u, data)`` where ``data`` contains ``A``, ``b``,
        derivative matrices, ``nnz``, ``sparsity``, ``solve_time``,
        ``assembly_time``, and ``solver_info``.

    Returns
    -------
    ndarray or tuple
        Solution vector ``u`` with shape ``(grid.N,)``.  If
        ``return_data=True``, returns ``(u, data)``.
    """
    assembly_start = perf_counter()
    A, b, Mx, My, Mxx, Myy = self.assemble()
    assembly_time = perf_counter() - assembly_start

    if A.shape[0] != A.shape[1]:
        raise ValueError(f"Linear system must be square; got {A.shape}.")
    if not np.all(np.isfinite(A.data)):
        raise ValueError("Linear system matrix contains non-finite values.")
    if not np.all(np.isfinite(b)):
        raise ValueError("Right-hand side contains non-finite values.")

    solve_start = perf_counter()
    if solver == 'direct':
        sol = spla.spsolve(A, b)
        info = 0
    else:
        N = A.shape[0]
        maxiter = maxiter or N
        if preconditioner == "jacobi":
            M = self._jacobi_preconditioner(A)
        else:
            M = self._as_linear_operator(preconditioner)
        methods = {'cg': spla.cg, 'gmres': spla.gmres, 'bicgstab': spla.bicgstab}
        if solver not in methods:
            raise ValueError(
                f"Unsupported solver '{solver}'. Choose 'direct', 'cg', 'gmres', or 'bicgstab'."
            )
        sol, info = self._iterative_call(
            methods[solver],
            A,
            b,
            tol=tol,
            maxiter=maxiter,
            M=M,
        )
        if info != 0:
            raise RuntimeError(f"Solver '{solver}' failed to converge (info={info}).")
    solve_time = perf_counter() - solve_start

    self.solution = sol

    if return_data:
        data: Dict[str, object] = {
            "A": A,
            "b": b,
            "first_derivatives": (Mx, My),
            "second_derivatives": (Mxx, Myy),
            "nnz": int(A.nnz),
            "sparsity": float((1.0 - A.nnz / (A.shape[0] * A.shape[1])) * 100.0),
            "solve_time": float(solve_time),
            "assembly_time": float(assembly_time),
            "solver_info": int(info),
        }
        self.last_data = data
        return sol, data

    return sol

SourceGrid

Structured two-dimensional tensor-product grid.

SourceGrid is the rectangular-domain source-node container used by the Grid-Based Multinode Shepard Collocation approximation. It stores the global source nodes, all sliding local tensor-product subgrids, flattened node coordinates, and pairwise coordinate differences used by the weight formulas.

Attributes:

Name Type Description
grid_shape tuple[int, int]

Number of grid nodes (N_x, N_y).

subgrid_shape tuple[int, int]

Number of nodes in each local interpolation window (n_x, n_y).

N int

Total number of source nodes, equal to N_x * N_y.

coords (ndarray, shape(N, 2))

Flattened source-node coordinates ordered consistently with grid.ravel().

subgrids (ndarray, shape(N_x - n_x + 1, N_y - n_y + 1, n_x, n_y))

Sliding-window node-index view.

diff_x, diff_y, dist (ndarray, shape(N, N))

Pairwise coordinate differences and squared Euclidean distances.

Source code in src/gbmsc_pde/source_grid/grid.py
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
class SourceGrid:
    """
    Structured two-dimensional tensor-product grid.

    ``SourceGrid`` is the rectangular-domain source-node container used by the
    Grid-Based Multinode Shepard Collocation approximation.  It stores the
    global source nodes, all sliding local tensor-product subgrids, flattened
    node coordinates, and pairwise coordinate differences used by the weight
    formulas.

    Attributes
    ----------
    grid_shape : tuple[int, int]
        Number of grid nodes ``(N_x, N_y)``.
    subgrid_shape : tuple[int, int]
        Number of nodes in each local interpolation window ``(n_x, n_y)``.
    N : int
        Total number of source nodes, equal to ``N_x * N_y``.
    coords : ndarray, shape (N, 2)
        Flattened source-node coordinates ordered consistently with
        ``grid.ravel()``.
    subgrids : ndarray, shape (N_x-n_x+1, N_y-n_y+1, n_x, n_y)
        Sliding-window node-index view.
    diff_x, diff_y, dist : ndarray, shape (N, N)
        Pairwise coordinate differences and squared Euclidean distances.
    """

    def __init__(self,
                 grid_shape: Tuple[int, int] = (10, 10),
                 subgrid_shape: Tuple[int, int] = (3, 3),
                 xlim: Tuple[float, float] = (0., 1.),
                 ylim: Tuple[float, float] = (0., 1.),
                 limits: Optional[Tuple[Tuple[float, float], Tuple[float, float]]] = None):
        """
        Initialize a rectangular structured grid.

        Parameters
        ----------
        grid_shape : tuple[int, int], default=(10, 10)
            Number of source nodes in the x and y directions.
        subgrid_shape : tuple[int, int], default=(3, 3)
            Size of each local tensor-product interpolation window.
        xlim, ylim : tuple[float, float]
            Coordinate limits of the rectangular domain.
        limits : tuple[tuple[float, float], tuple[float, float]], optional
            Compatibility alias for ``(xlim, ylim)``.

        Raises
        ------
        ValueError
            If either shape is not two-dimensional, if a local subgrid is
            larger than the global grid, or if ``limits`` is malformed.
        """
        if len(grid_shape) != 2 or len(subgrid_shape) != 2:
            raise ValueError("grid_shape and subgrid_shape must be of length 2.")
        if limits is not None:
            if len(limits) != 2:
                raise ValueError("limits must be ((x_min, x_max), (y_min, y_max)).")
            xlim, ylim = limits
        N_x, N_y = grid_shape
        self.N = N_x * N_y
        n_x, n_y = subgrid_shape
        if n_x > N_x or n_y > N_y:
            raise ValueError("subgrid_shape must be <= grid_shape in both dimensions.")

        self.grid_shape = (int(N_x), int(N_y))
        self.subgrid_shape = (int(n_x), int(n_y))
        self.xlim = tuple(float(v) for v in xlim)
        self.ylim = tuple(float(v) for v in ylim)

        # Generate grid indices and sliding subgrids
        self.grid, self.subgrids, self.subgrids_x, self.subgrids_y = self._generate_sliding_subgrids()

        # Generate coordinates
        (self.subgrids_x_coords,
         self.subgrids_y_coords,
         self.X, self.Y,
         self.x_coords_flat,
         self.y_coords_flat) = self._generate_coordinates()
        self.coords = np.column_stack((self.x_coords_flat, self.y_coords_flat))
        self.axes = (self.X[:, 0].copy(), self.Y[0, :].copy())
        self.dim = 2

        # Precompute pairwise differences and distances
        self.diff_x = self.x_coords_flat[:, None] - self.x_coords_flat[None, :]
        self.diff_y = self.y_coords_flat[:, None] - self.y_coords_flat[None, :]
        self.dist = self.diff_x**2 + self.diff_y**2

    def _generate_coordinates(self) -> Tuple[np.ndarray, ...]:
        """
        Compute global and subgrid coordinates.

        Returns:
            tuple containing:
             - subgrids_x_coords: x values for subgrid windows
             - subgrids_y_coords: y values for subgrid windows
             - X, Y: meshgrid arrays of shape (N_x, N_y)
             - x_coords_flat, y_coords_flat: flattened coords arrays of length N_x*N_y
        """
        N_x, N_y = self.grid_shape
        x_vals = np.linspace(self.xlim[0], self.xlim[1], N_x, dtype=float)
        y_vals = np.linspace(self.ylim[0], self.ylim[1], N_y, dtype=float)
        X, Y = np.meshgrid(x_vals, y_vals, indexing='ij')
        coords = np.vstack([X.ravel(), Y.ravel()]).T
        # Subgrid coordinate windows

        subgrids_x_coords = np.lib.stride_tricks.sliding_window_view(x_vals, self.subgrid_shape[0])
        subgrids_y_coords = np.lib.stride_tricks.sliding_window_view(y_vals, self.subgrid_shape[1])
        return subgrids_x_coords, subgrids_y_coords, X, Y, coords[:, 0], coords[:, 1]

    def _generate_sliding_subgrids(self) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
        """
        Create sliding-window index subgrids using stride_tricks.

        Returns:
            grid: index grid of shape (N_x, N_y)
            subgrids: view of shape (N_x - n_x + 1, N_y - n_y + 1, n_x, n_y)
            subgrids_x: x-index windows of shape (N_x - n_x + 1, n_x)
            subgrids_y: y-index windows of shape (N_y - n_y + 1, n_y)
        """
        N_x, N_y = self.grid_shape
        n_x, n_y = self.subgrid_shape
        # index grid
        grid = np.arange(N_x * N_y).reshape(N_x, N_y)
        # sliding windows
        subgrids = np.lib.stride_tricks.sliding_window_view(grid, (n_x, n_y))
        subgrids_x = np.lib.stride_tricks.sliding_window_view(np.arange(N_x), n_x)
        subgrids_y = np.lib.stride_tricks.sliding_window_view(np.arange(N_y), n_y)
        return grid, subgrids, subgrids_x, subgrids_y

    def subgrids_with_step(self, step: Tuple[int, int] = (1, 1)) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
        """
        Return sampled local subgrids at a fixed stride.

        Parameters
        ----------
        step : tuple[int, int], default=(1, 1)
            Sampling stride ``(step_x, step_y)`` over the sliding subgrid
            starts.  The stride must be compatible with the grid so the last
            sampled window reaches the upper/right boundary.

        Returns
        -------
        subgrids, subgrids_x, subgrids_y : tuple[ndarray, ndarray, ndarray]
            Sampled two-dimensional node windows and their one-dimensional
            x/y index windows.

        Raises
        ------
        ValueError
            If the stride is not positive or is incompatible with the grid and
            local-window sizes.
        """
        dx, dy = step
        N_x, N_y = self.grid_shape
        n_x, n_y = self.subgrid_shape

        if not isinstance(dx, int) or not isinstance(dy, int) or dx < 1 or dy < 1 or dx >= n_x or dy >= n_y:
            raise ValueError("step values must be positive integers.")

        if (N_x - n_x) % dx != 0 or (N_y - n_y) % dy != 0:
            raise ValueError(
                "step must satisfy N_x = step_x * k_x + n_x and "
                "N_y = step_y * k_y + n_y for integer k_x, k_y."
            )

        return (
            self.subgrids[::dx, ::dy, :, :],
            self.subgrids_x[::dx, :],
            self.subgrids_y[::dy, :]
        )

    def boundary_indices(self) -> Dict[str, np.ndarray]:
            """
            Return flattened node indices for the rectangular boundary.

            The returned dictionary includes both geometric names
            ``"left"``, ``"right"``, ``"bottom"``, ``"top"`` and coordinate
            aliases ``"x_min"``, ``"x_max"``, ``"y_min"``, ``"y_max"``.
            ``"all"`` contains the unique union of all four sides.
            """
            N_x, N_y = self.grid_shape
            total = N_x * N_y

            bottom = np.arange(0, total, N_y)

            top = np.arange(N_y - 1, total, N_y)

            left = np.arange(0, N_y)

            right = np.arange((N_x - 1) * N_y, total)

            return {
                'left':   left,
                'right':  right,
                'bottom': bottom,
                'top':    top,
                "x_min": left,
                "x_max": right,
                "y_min": bottom,
                "y_max": top,
                "all": np.unique(np.concatenate([left, right, bottom, top])),
            }

    def plot(
        self,
        solution: np.ndarray,
        view: str = "3d",
        cmap: str = "viridis",
        contour_levels=20,
        show_colorbar: bool = True,
        xlabel: str = "X",
        ylabel: str = "Y",
        zlabel: str = "",
        title: str = "",
        figsize: Tuple[int, int] = (5, 4),
        show: bool = True,
    ):
        """
        Plot a discrete scalar solution on this structured grid.

        Parameters
        ----------
        solution : ndarray
            Solution values as either a flat ``(N_x * N_y,)`` array or a
            ``(N_x, N_y)`` grid-shaped array.
        view : {"2d", "contour", "contourf", "3d"}
            Plot style for the discrete solution.
        show : bool
            Whether to display the plot with ``matplotlib.pyplot.show``.

        Returns
        -------
        fig, ax
            Matplotlib figure and axes objects.
        """
        nx, ny = self.grid_shape
        sol = np.asarray(solution)
        if sol.ndim == 1:
            if sol.size != nx * ny:
                raise ValueError(
                    f"1D solution length {sol.size} does not match grid size {nx * ny}"
                )
            sol = sol.reshape(nx, ny)
        elif sol.shape != (nx, ny):
            raise ValueError(f"solution array shape {sol.shape} != grid.grid_shape {(nx, ny)}")

        try:
            import matplotlib.pyplot as plt
        except ImportError as exc:
            raise ImportError(
                "SourceGrid.plot requires matplotlib. "
                "Install it with `pip install matplotlib` or `pip install .[plot]`."
            ) from exc

        fig = plt.figure(figsize=figsize)
        if view == "3d":
            ax = fig.add_subplot(111, projection="3d")
            surf = ax.plot_surface(
                self.X,
                self.Y,
                sol,
                cmap=cmap,
                edgecolor="none",
                antialiased=True,
            )
            if show_colorbar:
                fig.colorbar(surf, ax=ax, shrink=0.5)
            ax.set_zlabel(zlabel)
        else:
            ax = fig.add_subplot(111)
            if view == "2d":
                mappable = ax.imshow(
                    sol.T,
                    origin="lower",
                    extent=(self.xlim[0], self.xlim[1], self.ylim[0], self.ylim[1]),
                    cmap=cmap,
                    aspect="auto",
                )
            elif view in ("contour", "contourf"):
                levels = contour_levels or 10
                plot_fn = ax.contourf if view == "contourf" else ax.contour
                mappable = plot_fn(self.X, self.Y, sol, levels=levels, cmap=cmap)
            else:
                raise ValueError(
                    f"Unknown view '{view}'. Choose from '2d', 'contour', 'contourf', '3d'."
                )
            if show_colorbar:
                fig.colorbar(mappable, ax=ax)

        ax.set_xlabel(xlabel)
        ax.set_ylabel(ylabel)
        if title:
            ax.set_title(title)
        fig.tight_layout()

        if show:
            plt.show()

        return fig, ax

    def eval_function_at_nodes(self, f: Callable[[np.ndarray, np.ndarray], np.ndarray]) -> np.ndarray:
            """
            Evaluate a scalar field at every source node.

            Parameters
            ----------
            f : callable
                Function with signature ``f(x, y)`` where ``x`` and ``y`` are
                one-dimensional coordinate arrays of length ``N``.

            Returns
            -------
            ndarray, shape (N,)
                Field values ordered like ``x_coords_flat`` and
                ``y_coords_flat``.

            Raises
            ------
            TypeError
                If ``f`` is not callable.
            RuntimeError
                If ``f`` raises during evaluation.
            ValueError
                If the result cannot be converted to an array with shape
                ``(N,)``.
            """
            # 1. Check that f is callable
            if not callable(f):
                raise TypeError("`f` must be a callable taking two numpy arrays.")

            # 2. Grab the node coordinates
            try:
                x = self.x_coords_flat
                y = self.y_coords_flat
            except AttributeError as e:
                raise AttributeError(
                    "Grid node coordinates not found on `self`. "
                    "Expected `self.x_coords` and `self.y_coords`. "
                    f"Original error: {e}"
                )

            # 3. Attempt evaluation
            try:
                values = f(x, y)
            except Exception as e:
                raise RuntimeError(f"Error while evaluating `f` at nodes: {e}") from e

            # 4. Convert to numpy array if needed
            if not isinstance(values, np.ndarray):
                try:
                    values = np.asarray(values)
                except Exception:
                    raise ValueError(
                        "Output of `f` is not array-like or cannot be converted to numpy.ndarray."
                    )

            # 5. Validate shape
            if values.ndim != 1 or values.shape[0] != x.shape[0]:
                raise ValueError(
                    f"Function output has shape {values.shape}, "
                    f"but expected (N,) where N={x.shape[0]}."
                )

            return values

__init__(grid_shape=(10, 10), subgrid_shape=(3, 3), xlim=(0.0, 1.0), ylim=(0.0, 1.0), limits=None)

Initialize a rectangular structured grid.

Parameters:

Name Type Description Default
grid_shape tuple[int, int]

Number of source nodes in the x and y directions.

(10, 10)
subgrid_shape tuple[int, int]

Size of each local tensor-product interpolation window.

(3, 3)
xlim tuple[float, float]

Coordinate limits of the rectangular domain.

(0.0, 1.0)
ylim tuple[float, float]

Coordinate limits of the rectangular domain.

(0.0, 1.0)
limits tuple[tuple[float, float], tuple[float, float]]

Compatibility alias for (xlim, ylim).

None

Raises:

Type Description
ValueError

If either shape is not two-dimensional, if a local subgrid is larger than the global grid, or if limits is malformed.

Source code in src/gbmsc_pde/source_grid/grid.py
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
def __init__(self,
             grid_shape: Tuple[int, int] = (10, 10),
             subgrid_shape: Tuple[int, int] = (3, 3),
             xlim: Tuple[float, float] = (0., 1.),
             ylim: Tuple[float, float] = (0., 1.),
             limits: Optional[Tuple[Tuple[float, float], Tuple[float, float]]] = None):
    """
    Initialize a rectangular structured grid.

    Parameters
    ----------
    grid_shape : tuple[int, int], default=(10, 10)
        Number of source nodes in the x and y directions.
    subgrid_shape : tuple[int, int], default=(3, 3)
        Size of each local tensor-product interpolation window.
    xlim, ylim : tuple[float, float]
        Coordinate limits of the rectangular domain.
    limits : tuple[tuple[float, float], tuple[float, float]], optional
        Compatibility alias for ``(xlim, ylim)``.

    Raises
    ------
    ValueError
        If either shape is not two-dimensional, if a local subgrid is
        larger than the global grid, or if ``limits`` is malformed.
    """
    if len(grid_shape) != 2 or len(subgrid_shape) != 2:
        raise ValueError("grid_shape and subgrid_shape must be of length 2.")
    if limits is not None:
        if len(limits) != 2:
            raise ValueError("limits must be ((x_min, x_max), (y_min, y_max)).")
        xlim, ylim = limits
    N_x, N_y = grid_shape
    self.N = N_x * N_y
    n_x, n_y = subgrid_shape
    if n_x > N_x or n_y > N_y:
        raise ValueError("subgrid_shape must be <= grid_shape in both dimensions.")

    self.grid_shape = (int(N_x), int(N_y))
    self.subgrid_shape = (int(n_x), int(n_y))
    self.xlim = tuple(float(v) for v in xlim)
    self.ylim = tuple(float(v) for v in ylim)

    # Generate grid indices and sliding subgrids
    self.grid, self.subgrids, self.subgrids_x, self.subgrids_y = self._generate_sliding_subgrids()

    # Generate coordinates
    (self.subgrids_x_coords,
     self.subgrids_y_coords,
     self.X, self.Y,
     self.x_coords_flat,
     self.y_coords_flat) = self._generate_coordinates()
    self.coords = np.column_stack((self.x_coords_flat, self.y_coords_flat))
    self.axes = (self.X[:, 0].copy(), self.Y[0, :].copy())
    self.dim = 2

    # Precompute pairwise differences and distances
    self.diff_x = self.x_coords_flat[:, None] - self.x_coords_flat[None, :]
    self.diff_y = self.y_coords_flat[:, None] - self.y_coords_flat[None, :]
    self.dist = self.diff_x**2 + self.diff_y**2

boundary_indices()

Return flattened node indices for the rectangular boundary.

The returned dictionary includes both geometric names "left", "right", "bottom", "top" and coordinate aliases "x_min", "x_max", "y_min", "y_max". "all" contains the unique union of all four sides.

Source code in src/gbmsc_pde/source_grid/grid.py
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
def boundary_indices(self) -> Dict[str, np.ndarray]:
        """
        Return flattened node indices for the rectangular boundary.

        The returned dictionary includes both geometric names
        ``"left"``, ``"right"``, ``"bottom"``, ``"top"`` and coordinate
        aliases ``"x_min"``, ``"x_max"``, ``"y_min"``, ``"y_max"``.
        ``"all"`` contains the unique union of all four sides.
        """
        N_x, N_y = self.grid_shape
        total = N_x * N_y

        bottom = np.arange(0, total, N_y)

        top = np.arange(N_y - 1, total, N_y)

        left = np.arange(0, N_y)

        right = np.arange((N_x - 1) * N_y, total)

        return {
            'left':   left,
            'right':  right,
            'bottom': bottom,
            'top':    top,
            "x_min": left,
            "x_max": right,
            "y_min": bottom,
            "y_max": top,
            "all": np.unique(np.concatenate([left, right, bottom, top])),
        }

eval_function_at_nodes(f)

Evaluate a scalar field at every source node.

Parameters:

Name Type Description Default
f callable

Function with signature f(x, y) where x and y are one-dimensional coordinate arrays of length N.

required

Returns:

Type Description
(ndarray, shape(N))

Field values ordered like x_coords_flat and y_coords_flat.

Raises:

Type Description
TypeError

If f is not callable.

RuntimeError

If f raises during evaluation.

ValueError

If the result cannot be converted to an array with shape (N,).

Source code in src/gbmsc_pde/source_grid/grid.py
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
def eval_function_at_nodes(self, f: Callable[[np.ndarray, np.ndarray], np.ndarray]) -> np.ndarray:
        """
        Evaluate a scalar field at every source node.

        Parameters
        ----------
        f : callable
            Function with signature ``f(x, y)`` where ``x`` and ``y`` are
            one-dimensional coordinate arrays of length ``N``.

        Returns
        -------
        ndarray, shape (N,)
            Field values ordered like ``x_coords_flat`` and
            ``y_coords_flat``.

        Raises
        ------
        TypeError
            If ``f`` is not callable.
        RuntimeError
            If ``f`` raises during evaluation.
        ValueError
            If the result cannot be converted to an array with shape
            ``(N,)``.
        """
        # 1. Check that f is callable
        if not callable(f):
            raise TypeError("`f` must be a callable taking two numpy arrays.")

        # 2. Grab the node coordinates
        try:
            x = self.x_coords_flat
            y = self.y_coords_flat
        except AttributeError as e:
            raise AttributeError(
                "Grid node coordinates not found on `self`. "
                "Expected `self.x_coords` and `self.y_coords`. "
                f"Original error: {e}"
            )

        # 3. Attempt evaluation
        try:
            values = f(x, y)
        except Exception as e:
            raise RuntimeError(f"Error while evaluating `f` at nodes: {e}") from e

        # 4. Convert to numpy array if needed
        if not isinstance(values, np.ndarray):
            try:
                values = np.asarray(values)
            except Exception:
                raise ValueError(
                    "Output of `f` is not array-like or cannot be converted to numpy.ndarray."
                )

        # 5. Validate shape
        if values.ndim != 1 or values.shape[0] != x.shape[0]:
            raise ValueError(
                f"Function output has shape {values.shape}, "
                f"but expected (N,) where N={x.shape[0]}."
            )

        return values

plot(solution, view='3d', cmap='viridis', contour_levels=20, show_colorbar=True, xlabel='X', ylabel='Y', zlabel='', title='', figsize=(5, 4), show=True)

Plot a discrete scalar solution on this structured grid.

Parameters:

Name Type Description Default
solution ndarray

Solution values as either a flat (N_x * N_y,) array or a (N_x, N_y) grid-shaped array.

required
view ('2d', contour, contourf, '3d')

Plot style for the discrete solution.

"2d"
show bool

Whether to display the plot with matplotlib.pyplot.show.

True

Returns:

Type Description
(fig, ax)

Matplotlib figure and axes objects.

Source code in src/gbmsc_pde/source_grid/grid.py
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
def plot(
    self,
    solution: np.ndarray,
    view: str = "3d",
    cmap: str = "viridis",
    contour_levels=20,
    show_colorbar: bool = True,
    xlabel: str = "X",
    ylabel: str = "Y",
    zlabel: str = "",
    title: str = "",
    figsize: Tuple[int, int] = (5, 4),
    show: bool = True,
):
    """
    Plot a discrete scalar solution on this structured grid.

    Parameters
    ----------
    solution : ndarray
        Solution values as either a flat ``(N_x * N_y,)`` array or a
        ``(N_x, N_y)`` grid-shaped array.
    view : {"2d", "contour", "contourf", "3d"}
        Plot style for the discrete solution.
    show : bool
        Whether to display the plot with ``matplotlib.pyplot.show``.

    Returns
    -------
    fig, ax
        Matplotlib figure and axes objects.
    """
    nx, ny = self.grid_shape
    sol = np.asarray(solution)
    if sol.ndim == 1:
        if sol.size != nx * ny:
            raise ValueError(
                f"1D solution length {sol.size} does not match grid size {nx * ny}"
            )
        sol = sol.reshape(nx, ny)
    elif sol.shape != (nx, ny):
        raise ValueError(f"solution array shape {sol.shape} != grid.grid_shape {(nx, ny)}")

    try:
        import matplotlib.pyplot as plt
    except ImportError as exc:
        raise ImportError(
            "SourceGrid.plot requires matplotlib. "
            "Install it with `pip install matplotlib` or `pip install .[plot]`."
        ) from exc

    fig = plt.figure(figsize=figsize)
    if view == "3d":
        ax = fig.add_subplot(111, projection="3d")
        surf = ax.plot_surface(
            self.X,
            self.Y,
            sol,
            cmap=cmap,
            edgecolor="none",
            antialiased=True,
        )
        if show_colorbar:
            fig.colorbar(surf, ax=ax, shrink=0.5)
        ax.set_zlabel(zlabel)
    else:
        ax = fig.add_subplot(111)
        if view == "2d":
            mappable = ax.imshow(
                sol.T,
                origin="lower",
                extent=(self.xlim[0], self.xlim[1], self.ylim[0], self.ylim[1]),
                cmap=cmap,
                aspect="auto",
            )
        elif view in ("contour", "contourf"):
            levels = contour_levels or 10
            plot_fn = ax.contourf if view == "contourf" else ax.contour
            mappable = plot_fn(self.X, self.Y, sol, levels=levels, cmap=cmap)
        else:
            raise ValueError(
                f"Unknown view '{view}'. Choose from '2d', 'contour', 'contourf', '3d'."
            )
        if show_colorbar:
            fig.colorbar(mappable, ax=ax)

    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)
    if title:
        ax.set_title(title)
    fig.tight_layout()

    if show:
        plt.show()

    return fig, ax

subgrids_with_step(step=(1, 1))

Return sampled local subgrids at a fixed stride.

Parameters:

Name Type Description Default
step tuple[int, int]

Sampling stride (step_x, step_y) over the sliding subgrid starts. The stride must be compatible with the grid so the last sampled window reaches the upper/right boundary.

(1, 1)

Returns:

Type Description
subgrids, subgrids_x, subgrids_y : tuple[ndarray, ndarray, ndarray]

Sampled two-dimensional node windows and their one-dimensional x/y index windows.

Raises:

Type Description
ValueError

If the stride is not positive or is incompatible with the grid and local-window sizes.

Source code in src/gbmsc_pde/source_grid/grid.py
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
def subgrids_with_step(self, step: Tuple[int, int] = (1, 1)) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
    """
    Return sampled local subgrids at a fixed stride.

    Parameters
    ----------
    step : tuple[int, int], default=(1, 1)
        Sampling stride ``(step_x, step_y)`` over the sliding subgrid
        starts.  The stride must be compatible with the grid so the last
        sampled window reaches the upper/right boundary.

    Returns
    -------
    subgrids, subgrids_x, subgrids_y : tuple[ndarray, ndarray, ndarray]
        Sampled two-dimensional node windows and their one-dimensional
        x/y index windows.

    Raises
    ------
    ValueError
        If the stride is not positive or is incompatible with the grid and
        local-window sizes.
    """
    dx, dy = step
    N_x, N_y = self.grid_shape
    n_x, n_y = self.subgrid_shape

    if not isinstance(dx, int) or not isinstance(dy, int) or dx < 1 or dy < 1 or dx >= n_x or dy >= n_y:
        raise ValueError("step values must be positive integers.")

    if (N_x - n_x) % dx != 0 or (N_y - n_y) % dy != 0:
        raise ValueError(
            "step must satisfy N_x = step_x * k_x + n_x and "
            "N_y = step_y * k_y + n_y for integer k_x, k_y."
        )

    return (
        self.subgrids[::dx, ::dy, :, :],
        self.subgrids_x[::dx, :],
        self.subgrids_y[::dy, :]
    )

gbmsc_pde.source_grid.grid.SourceGrid

Structured two-dimensional tensor-product grid.

SourceGrid is the rectangular-domain source-node container used by the Grid-Based Multinode Shepard Collocation approximation. It stores the global source nodes, all sliding local tensor-product subgrids, flattened node coordinates, and pairwise coordinate differences used by the weight formulas.

Attributes:

Name Type Description
grid_shape tuple[int, int]

Number of grid nodes (N_x, N_y).

subgrid_shape tuple[int, int]

Number of nodes in each local interpolation window (n_x, n_y).

N int

Total number of source nodes, equal to N_x * N_y.

coords (ndarray, shape(N, 2))

Flattened source-node coordinates ordered consistently with grid.ravel().

subgrids (ndarray, shape(N_x - n_x + 1, N_y - n_y + 1, n_x, n_y))

Sliding-window node-index view.

diff_x, diff_y, dist (ndarray, shape(N, N))

Pairwise coordinate differences and squared Euclidean distances.

Source code in src/gbmsc_pde/source_grid/grid.py
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
class SourceGrid:
    """
    Structured two-dimensional tensor-product grid.

    ``SourceGrid`` is the rectangular-domain source-node container used by the
    Grid-Based Multinode Shepard Collocation approximation.  It stores the
    global source nodes, all sliding local tensor-product subgrids, flattened
    node coordinates, and pairwise coordinate differences used by the weight
    formulas.

    Attributes
    ----------
    grid_shape : tuple[int, int]
        Number of grid nodes ``(N_x, N_y)``.
    subgrid_shape : tuple[int, int]
        Number of nodes in each local interpolation window ``(n_x, n_y)``.
    N : int
        Total number of source nodes, equal to ``N_x * N_y``.
    coords : ndarray, shape (N, 2)
        Flattened source-node coordinates ordered consistently with
        ``grid.ravel()``.
    subgrids : ndarray, shape (N_x-n_x+1, N_y-n_y+1, n_x, n_y)
        Sliding-window node-index view.
    diff_x, diff_y, dist : ndarray, shape (N, N)
        Pairwise coordinate differences and squared Euclidean distances.
    """

    def __init__(self,
                 grid_shape: Tuple[int, int] = (10, 10),
                 subgrid_shape: Tuple[int, int] = (3, 3),
                 xlim: Tuple[float, float] = (0., 1.),
                 ylim: Tuple[float, float] = (0., 1.),
                 limits: Optional[Tuple[Tuple[float, float], Tuple[float, float]]] = None):
        """
        Initialize a rectangular structured grid.

        Parameters
        ----------
        grid_shape : tuple[int, int], default=(10, 10)
            Number of source nodes in the x and y directions.
        subgrid_shape : tuple[int, int], default=(3, 3)
            Size of each local tensor-product interpolation window.
        xlim, ylim : tuple[float, float]
            Coordinate limits of the rectangular domain.
        limits : tuple[tuple[float, float], tuple[float, float]], optional
            Compatibility alias for ``(xlim, ylim)``.

        Raises
        ------
        ValueError
            If either shape is not two-dimensional, if a local subgrid is
            larger than the global grid, or if ``limits`` is malformed.
        """
        if len(grid_shape) != 2 or len(subgrid_shape) != 2:
            raise ValueError("grid_shape and subgrid_shape must be of length 2.")
        if limits is not None:
            if len(limits) != 2:
                raise ValueError("limits must be ((x_min, x_max), (y_min, y_max)).")
            xlim, ylim = limits
        N_x, N_y = grid_shape
        self.N = N_x * N_y
        n_x, n_y = subgrid_shape
        if n_x > N_x or n_y > N_y:
            raise ValueError("subgrid_shape must be <= grid_shape in both dimensions.")

        self.grid_shape = (int(N_x), int(N_y))
        self.subgrid_shape = (int(n_x), int(n_y))
        self.xlim = tuple(float(v) for v in xlim)
        self.ylim = tuple(float(v) for v in ylim)

        # Generate grid indices and sliding subgrids
        self.grid, self.subgrids, self.subgrids_x, self.subgrids_y = self._generate_sliding_subgrids()

        # Generate coordinates
        (self.subgrids_x_coords,
         self.subgrids_y_coords,
         self.X, self.Y,
         self.x_coords_flat,
         self.y_coords_flat) = self._generate_coordinates()
        self.coords = np.column_stack((self.x_coords_flat, self.y_coords_flat))
        self.axes = (self.X[:, 0].copy(), self.Y[0, :].copy())
        self.dim = 2

        # Precompute pairwise differences and distances
        self.diff_x = self.x_coords_flat[:, None] - self.x_coords_flat[None, :]
        self.diff_y = self.y_coords_flat[:, None] - self.y_coords_flat[None, :]
        self.dist = self.diff_x**2 + self.diff_y**2

    def _generate_coordinates(self) -> Tuple[np.ndarray, ...]:
        """
        Compute global and subgrid coordinates.

        Returns:
            tuple containing:
             - subgrids_x_coords: x values for subgrid windows
             - subgrids_y_coords: y values for subgrid windows
             - X, Y: meshgrid arrays of shape (N_x, N_y)
             - x_coords_flat, y_coords_flat: flattened coords arrays of length N_x*N_y
        """
        N_x, N_y = self.grid_shape
        x_vals = np.linspace(self.xlim[0], self.xlim[1], N_x, dtype=float)
        y_vals = np.linspace(self.ylim[0], self.ylim[1], N_y, dtype=float)
        X, Y = np.meshgrid(x_vals, y_vals, indexing='ij')
        coords = np.vstack([X.ravel(), Y.ravel()]).T
        # Subgrid coordinate windows

        subgrids_x_coords = np.lib.stride_tricks.sliding_window_view(x_vals, self.subgrid_shape[0])
        subgrids_y_coords = np.lib.stride_tricks.sliding_window_view(y_vals, self.subgrid_shape[1])
        return subgrids_x_coords, subgrids_y_coords, X, Y, coords[:, 0], coords[:, 1]

    def _generate_sliding_subgrids(self) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
        """
        Create sliding-window index subgrids using stride_tricks.

        Returns:
            grid: index grid of shape (N_x, N_y)
            subgrids: view of shape (N_x - n_x + 1, N_y - n_y + 1, n_x, n_y)
            subgrids_x: x-index windows of shape (N_x - n_x + 1, n_x)
            subgrids_y: y-index windows of shape (N_y - n_y + 1, n_y)
        """
        N_x, N_y = self.grid_shape
        n_x, n_y = self.subgrid_shape
        # index grid
        grid = np.arange(N_x * N_y).reshape(N_x, N_y)
        # sliding windows
        subgrids = np.lib.stride_tricks.sliding_window_view(grid, (n_x, n_y))
        subgrids_x = np.lib.stride_tricks.sliding_window_view(np.arange(N_x), n_x)
        subgrids_y = np.lib.stride_tricks.sliding_window_view(np.arange(N_y), n_y)
        return grid, subgrids, subgrids_x, subgrids_y

    def subgrids_with_step(self, step: Tuple[int, int] = (1, 1)) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
        """
        Return sampled local subgrids at a fixed stride.

        Parameters
        ----------
        step : tuple[int, int], default=(1, 1)
            Sampling stride ``(step_x, step_y)`` over the sliding subgrid
            starts.  The stride must be compatible with the grid so the last
            sampled window reaches the upper/right boundary.

        Returns
        -------
        subgrids, subgrids_x, subgrids_y : tuple[ndarray, ndarray, ndarray]
            Sampled two-dimensional node windows and their one-dimensional
            x/y index windows.

        Raises
        ------
        ValueError
            If the stride is not positive or is incompatible with the grid and
            local-window sizes.
        """
        dx, dy = step
        N_x, N_y = self.grid_shape
        n_x, n_y = self.subgrid_shape

        if not isinstance(dx, int) or not isinstance(dy, int) or dx < 1 or dy < 1 or dx >= n_x or dy >= n_y:
            raise ValueError("step values must be positive integers.")

        if (N_x - n_x) % dx != 0 or (N_y - n_y) % dy != 0:
            raise ValueError(
                "step must satisfy N_x = step_x * k_x + n_x and "
                "N_y = step_y * k_y + n_y for integer k_x, k_y."
            )

        return (
            self.subgrids[::dx, ::dy, :, :],
            self.subgrids_x[::dx, :],
            self.subgrids_y[::dy, :]
        )

    def boundary_indices(self) -> Dict[str, np.ndarray]:
            """
            Return flattened node indices for the rectangular boundary.

            The returned dictionary includes both geometric names
            ``"left"``, ``"right"``, ``"bottom"``, ``"top"`` and coordinate
            aliases ``"x_min"``, ``"x_max"``, ``"y_min"``, ``"y_max"``.
            ``"all"`` contains the unique union of all four sides.
            """
            N_x, N_y = self.grid_shape
            total = N_x * N_y

            bottom = np.arange(0, total, N_y)

            top = np.arange(N_y - 1, total, N_y)

            left = np.arange(0, N_y)

            right = np.arange((N_x - 1) * N_y, total)

            return {
                'left':   left,
                'right':  right,
                'bottom': bottom,
                'top':    top,
                "x_min": left,
                "x_max": right,
                "y_min": bottom,
                "y_max": top,
                "all": np.unique(np.concatenate([left, right, bottom, top])),
            }

    def plot(
        self,
        solution: np.ndarray,
        view: str = "3d",
        cmap: str = "viridis",
        contour_levels=20,
        show_colorbar: bool = True,
        xlabel: str = "X",
        ylabel: str = "Y",
        zlabel: str = "",
        title: str = "",
        figsize: Tuple[int, int] = (5, 4),
        show: bool = True,
    ):
        """
        Plot a discrete scalar solution on this structured grid.

        Parameters
        ----------
        solution : ndarray
            Solution values as either a flat ``(N_x * N_y,)`` array or a
            ``(N_x, N_y)`` grid-shaped array.
        view : {"2d", "contour", "contourf", "3d"}
            Plot style for the discrete solution.
        show : bool
            Whether to display the plot with ``matplotlib.pyplot.show``.

        Returns
        -------
        fig, ax
            Matplotlib figure and axes objects.
        """
        nx, ny = self.grid_shape
        sol = np.asarray(solution)
        if sol.ndim == 1:
            if sol.size != nx * ny:
                raise ValueError(
                    f"1D solution length {sol.size} does not match grid size {nx * ny}"
                )
            sol = sol.reshape(nx, ny)
        elif sol.shape != (nx, ny):
            raise ValueError(f"solution array shape {sol.shape} != grid.grid_shape {(nx, ny)}")

        try:
            import matplotlib.pyplot as plt
        except ImportError as exc:
            raise ImportError(
                "SourceGrid.plot requires matplotlib. "
                "Install it with `pip install matplotlib` or `pip install .[plot]`."
            ) from exc

        fig = plt.figure(figsize=figsize)
        if view == "3d":
            ax = fig.add_subplot(111, projection="3d")
            surf = ax.plot_surface(
                self.X,
                self.Y,
                sol,
                cmap=cmap,
                edgecolor="none",
                antialiased=True,
            )
            if show_colorbar:
                fig.colorbar(surf, ax=ax, shrink=0.5)
            ax.set_zlabel(zlabel)
        else:
            ax = fig.add_subplot(111)
            if view == "2d":
                mappable = ax.imshow(
                    sol.T,
                    origin="lower",
                    extent=(self.xlim[0], self.xlim[1], self.ylim[0], self.ylim[1]),
                    cmap=cmap,
                    aspect="auto",
                )
            elif view in ("contour", "contourf"):
                levels = contour_levels or 10
                plot_fn = ax.contourf if view == "contourf" else ax.contour
                mappable = plot_fn(self.X, self.Y, sol, levels=levels, cmap=cmap)
            else:
                raise ValueError(
                    f"Unknown view '{view}'. Choose from '2d', 'contour', 'contourf', '3d'."
                )
            if show_colorbar:
                fig.colorbar(mappable, ax=ax)

        ax.set_xlabel(xlabel)
        ax.set_ylabel(ylabel)
        if title:
            ax.set_title(title)
        fig.tight_layout()

        if show:
            plt.show()

        return fig, ax

    def eval_function_at_nodes(self, f: Callable[[np.ndarray, np.ndarray], np.ndarray]) -> np.ndarray:
            """
            Evaluate a scalar field at every source node.

            Parameters
            ----------
            f : callable
                Function with signature ``f(x, y)`` where ``x`` and ``y`` are
                one-dimensional coordinate arrays of length ``N``.

            Returns
            -------
            ndarray, shape (N,)
                Field values ordered like ``x_coords_flat`` and
                ``y_coords_flat``.

            Raises
            ------
            TypeError
                If ``f`` is not callable.
            RuntimeError
                If ``f`` raises during evaluation.
            ValueError
                If the result cannot be converted to an array with shape
                ``(N,)``.
            """
            # 1. Check that f is callable
            if not callable(f):
                raise TypeError("`f` must be a callable taking two numpy arrays.")

            # 2. Grab the node coordinates
            try:
                x = self.x_coords_flat
                y = self.y_coords_flat
            except AttributeError as e:
                raise AttributeError(
                    "Grid node coordinates not found on `self`. "
                    "Expected `self.x_coords` and `self.y_coords`. "
                    f"Original error: {e}"
                )

            # 3. Attempt evaluation
            try:
                values = f(x, y)
            except Exception as e:
                raise RuntimeError(f"Error while evaluating `f` at nodes: {e}") from e

            # 4. Convert to numpy array if needed
            if not isinstance(values, np.ndarray):
                try:
                    values = np.asarray(values)
                except Exception:
                    raise ValueError(
                        "Output of `f` is not array-like or cannot be converted to numpy.ndarray."
                    )

            # 5. Validate shape
            if values.ndim != 1 or values.shape[0] != x.shape[0]:
                raise ValueError(
                    f"Function output has shape {values.shape}, "
                    f"but expected (N,) where N={x.shape[0]}."
                )

            return values

__init__(grid_shape=(10, 10), subgrid_shape=(3, 3), xlim=(0.0, 1.0), ylim=(0.0, 1.0), limits=None)

Initialize a rectangular structured grid.

Parameters:

Name Type Description Default
grid_shape tuple[int, int]

Number of source nodes in the x and y directions.

(10, 10)
subgrid_shape tuple[int, int]

Size of each local tensor-product interpolation window.

(3, 3)
xlim tuple[float, float]

Coordinate limits of the rectangular domain.

(0.0, 1.0)
ylim tuple[float, float]

Coordinate limits of the rectangular domain.

(0.0, 1.0)
limits tuple[tuple[float, float], tuple[float, float]]

Compatibility alias for (xlim, ylim).

None

Raises:

Type Description
ValueError

If either shape is not two-dimensional, if a local subgrid is larger than the global grid, or if limits is malformed.

Source code in src/gbmsc_pde/source_grid/grid.py
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
def __init__(self,
             grid_shape: Tuple[int, int] = (10, 10),
             subgrid_shape: Tuple[int, int] = (3, 3),
             xlim: Tuple[float, float] = (0., 1.),
             ylim: Tuple[float, float] = (0., 1.),
             limits: Optional[Tuple[Tuple[float, float], Tuple[float, float]]] = None):
    """
    Initialize a rectangular structured grid.

    Parameters
    ----------
    grid_shape : tuple[int, int], default=(10, 10)
        Number of source nodes in the x and y directions.
    subgrid_shape : tuple[int, int], default=(3, 3)
        Size of each local tensor-product interpolation window.
    xlim, ylim : tuple[float, float]
        Coordinate limits of the rectangular domain.
    limits : tuple[tuple[float, float], tuple[float, float]], optional
        Compatibility alias for ``(xlim, ylim)``.

    Raises
    ------
    ValueError
        If either shape is not two-dimensional, if a local subgrid is
        larger than the global grid, or if ``limits`` is malformed.
    """
    if len(grid_shape) != 2 or len(subgrid_shape) != 2:
        raise ValueError("grid_shape and subgrid_shape must be of length 2.")
    if limits is not None:
        if len(limits) != 2:
            raise ValueError("limits must be ((x_min, x_max), (y_min, y_max)).")
        xlim, ylim = limits
    N_x, N_y = grid_shape
    self.N = N_x * N_y
    n_x, n_y = subgrid_shape
    if n_x > N_x or n_y > N_y:
        raise ValueError("subgrid_shape must be <= grid_shape in both dimensions.")

    self.grid_shape = (int(N_x), int(N_y))
    self.subgrid_shape = (int(n_x), int(n_y))
    self.xlim = tuple(float(v) for v in xlim)
    self.ylim = tuple(float(v) for v in ylim)

    # Generate grid indices and sliding subgrids
    self.grid, self.subgrids, self.subgrids_x, self.subgrids_y = self._generate_sliding_subgrids()

    # Generate coordinates
    (self.subgrids_x_coords,
     self.subgrids_y_coords,
     self.X, self.Y,
     self.x_coords_flat,
     self.y_coords_flat) = self._generate_coordinates()
    self.coords = np.column_stack((self.x_coords_flat, self.y_coords_flat))
    self.axes = (self.X[:, 0].copy(), self.Y[0, :].copy())
    self.dim = 2

    # Precompute pairwise differences and distances
    self.diff_x = self.x_coords_flat[:, None] - self.x_coords_flat[None, :]
    self.diff_y = self.y_coords_flat[:, None] - self.y_coords_flat[None, :]
    self.dist = self.diff_x**2 + self.diff_y**2

boundary_indices()

Return flattened node indices for the rectangular boundary.

The returned dictionary includes both geometric names "left", "right", "bottom", "top" and coordinate aliases "x_min", "x_max", "y_min", "y_max". "all" contains the unique union of all four sides.

Source code in src/gbmsc_pde/source_grid/grid.py
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
def boundary_indices(self) -> Dict[str, np.ndarray]:
        """
        Return flattened node indices for the rectangular boundary.

        The returned dictionary includes both geometric names
        ``"left"``, ``"right"``, ``"bottom"``, ``"top"`` and coordinate
        aliases ``"x_min"``, ``"x_max"``, ``"y_min"``, ``"y_max"``.
        ``"all"`` contains the unique union of all four sides.
        """
        N_x, N_y = self.grid_shape
        total = N_x * N_y

        bottom = np.arange(0, total, N_y)

        top = np.arange(N_y - 1, total, N_y)

        left = np.arange(0, N_y)

        right = np.arange((N_x - 1) * N_y, total)

        return {
            'left':   left,
            'right':  right,
            'bottom': bottom,
            'top':    top,
            "x_min": left,
            "x_max": right,
            "y_min": bottom,
            "y_max": top,
            "all": np.unique(np.concatenate([left, right, bottom, top])),
        }

eval_function_at_nodes(f)

Evaluate a scalar field at every source node.

Parameters:

Name Type Description Default
f callable

Function with signature f(x, y) where x and y are one-dimensional coordinate arrays of length N.

required

Returns:

Type Description
(ndarray, shape(N))

Field values ordered like x_coords_flat and y_coords_flat.

Raises:

Type Description
TypeError

If f is not callable.

RuntimeError

If f raises during evaluation.

ValueError

If the result cannot be converted to an array with shape (N,).

Source code in src/gbmsc_pde/source_grid/grid.py
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
def eval_function_at_nodes(self, f: Callable[[np.ndarray, np.ndarray], np.ndarray]) -> np.ndarray:
        """
        Evaluate a scalar field at every source node.

        Parameters
        ----------
        f : callable
            Function with signature ``f(x, y)`` where ``x`` and ``y`` are
            one-dimensional coordinate arrays of length ``N``.

        Returns
        -------
        ndarray, shape (N,)
            Field values ordered like ``x_coords_flat`` and
            ``y_coords_flat``.

        Raises
        ------
        TypeError
            If ``f`` is not callable.
        RuntimeError
            If ``f`` raises during evaluation.
        ValueError
            If the result cannot be converted to an array with shape
            ``(N,)``.
        """
        # 1. Check that f is callable
        if not callable(f):
            raise TypeError("`f` must be a callable taking two numpy arrays.")

        # 2. Grab the node coordinates
        try:
            x = self.x_coords_flat
            y = self.y_coords_flat
        except AttributeError as e:
            raise AttributeError(
                "Grid node coordinates not found on `self`. "
                "Expected `self.x_coords` and `self.y_coords`. "
                f"Original error: {e}"
            )

        # 3. Attempt evaluation
        try:
            values = f(x, y)
        except Exception as e:
            raise RuntimeError(f"Error while evaluating `f` at nodes: {e}") from e

        # 4. Convert to numpy array if needed
        if not isinstance(values, np.ndarray):
            try:
                values = np.asarray(values)
            except Exception:
                raise ValueError(
                    "Output of `f` is not array-like or cannot be converted to numpy.ndarray."
                )

        # 5. Validate shape
        if values.ndim != 1 or values.shape[0] != x.shape[0]:
            raise ValueError(
                f"Function output has shape {values.shape}, "
                f"but expected (N,) where N={x.shape[0]}."
            )

        return values

plot(solution, view='3d', cmap='viridis', contour_levels=20, show_colorbar=True, xlabel='X', ylabel='Y', zlabel='', title='', figsize=(5, 4), show=True)

Plot a discrete scalar solution on this structured grid.

Parameters:

Name Type Description Default
solution ndarray

Solution values as either a flat (N_x * N_y,) array or a (N_x, N_y) grid-shaped array.

required
view ('2d', contour, contourf, '3d')

Plot style for the discrete solution.

"2d"
show bool

Whether to display the plot with matplotlib.pyplot.show.

True

Returns:

Type Description
(fig, ax)

Matplotlib figure and axes objects.

Source code in src/gbmsc_pde/source_grid/grid.py
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
def plot(
    self,
    solution: np.ndarray,
    view: str = "3d",
    cmap: str = "viridis",
    contour_levels=20,
    show_colorbar: bool = True,
    xlabel: str = "X",
    ylabel: str = "Y",
    zlabel: str = "",
    title: str = "",
    figsize: Tuple[int, int] = (5, 4),
    show: bool = True,
):
    """
    Plot a discrete scalar solution on this structured grid.

    Parameters
    ----------
    solution : ndarray
        Solution values as either a flat ``(N_x * N_y,)`` array or a
        ``(N_x, N_y)`` grid-shaped array.
    view : {"2d", "contour", "contourf", "3d"}
        Plot style for the discrete solution.
    show : bool
        Whether to display the plot with ``matplotlib.pyplot.show``.

    Returns
    -------
    fig, ax
        Matplotlib figure and axes objects.
    """
    nx, ny = self.grid_shape
    sol = np.asarray(solution)
    if sol.ndim == 1:
        if sol.size != nx * ny:
            raise ValueError(
                f"1D solution length {sol.size} does not match grid size {nx * ny}"
            )
        sol = sol.reshape(nx, ny)
    elif sol.shape != (nx, ny):
        raise ValueError(f"solution array shape {sol.shape} != grid.grid_shape {(nx, ny)}")

    try:
        import matplotlib.pyplot as plt
    except ImportError as exc:
        raise ImportError(
            "SourceGrid.plot requires matplotlib. "
            "Install it with `pip install matplotlib` or `pip install .[plot]`."
        ) from exc

    fig = plt.figure(figsize=figsize)
    if view == "3d":
        ax = fig.add_subplot(111, projection="3d")
        surf = ax.plot_surface(
            self.X,
            self.Y,
            sol,
            cmap=cmap,
            edgecolor="none",
            antialiased=True,
        )
        if show_colorbar:
            fig.colorbar(surf, ax=ax, shrink=0.5)
        ax.set_zlabel(zlabel)
    else:
        ax = fig.add_subplot(111)
        if view == "2d":
            mappable = ax.imshow(
                sol.T,
                origin="lower",
                extent=(self.xlim[0], self.xlim[1], self.ylim[0], self.ylim[1]),
                cmap=cmap,
                aspect="auto",
            )
        elif view in ("contour", "contourf"):
            levels = contour_levels or 10
            plot_fn = ax.contourf if view == "contourf" else ax.contour
            mappable = plot_fn(self.X, self.Y, sol, levels=levels, cmap=cmap)
        else:
            raise ValueError(
                f"Unknown view '{view}'. Choose from '2d', 'contour', 'contourf', '3d'."
            )
        if show_colorbar:
            fig.colorbar(mappable, ax=ax)

    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)
    if title:
        ax.set_title(title)
    fig.tight_layout()

    if show:
        plt.show()

    return fig, ax

subgrids_with_step(step=(1, 1))

Return sampled local subgrids at a fixed stride.

Parameters:

Name Type Description Default
step tuple[int, int]

Sampling stride (step_x, step_y) over the sliding subgrid starts. The stride must be compatible with the grid so the last sampled window reaches the upper/right boundary.

(1, 1)

Returns:

Type Description
subgrids, subgrids_x, subgrids_y : tuple[ndarray, ndarray, ndarray]

Sampled two-dimensional node windows and their one-dimensional x/y index windows.

Raises:

Type Description
ValueError

If the stride is not positive or is incompatible with the grid and local-window sizes.

Source code in src/gbmsc_pde/source_grid/grid.py
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
def subgrids_with_step(self, step: Tuple[int, int] = (1, 1)) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
    """
    Return sampled local subgrids at a fixed stride.

    Parameters
    ----------
    step : tuple[int, int], default=(1, 1)
        Sampling stride ``(step_x, step_y)`` over the sliding subgrid
        starts.  The stride must be compatible with the grid so the last
        sampled window reaches the upper/right boundary.

    Returns
    -------
    subgrids, subgrids_x, subgrids_y : tuple[ndarray, ndarray, ndarray]
        Sampled two-dimensional node windows and their one-dimensional
        x/y index windows.

    Raises
    ------
    ValueError
        If the stride is not positive or is incompatible with the grid and
        local-window sizes.
    """
    dx, dy = step
    N_x, N_y = self.grid_shape
    n_x, n_y = self.subgrid_shape

    if not isinstance(dx, int) or not isinstance(dy, int) or dx < 1 or dy < 1 or dx >= n_x or dy >= n_y:
        raise ValueError("step values must be positive integers.")

    if (N_x - n_x) % dx != 0 or (N_y - n_y) % dy != 0:
        raise ValueError(
            "step must satisfy N_x = step_x * k_x + n_x and "
            "N_y = step_y * k_y + n_y for integer k_x, k_y."
        )

    return (
        self.subgrids[::dx, ::dy, :, :],
        self.subgrids_x[::dx, :],
        self.subgrids_y[::dy, :]
    )

gbmsc_pde.approximation.shepard.GBMSCApproximation

Grid-Based Shepard approximation on a structured grid.

The approximation blends local tensor-product Lagrange polynomials defined on sampled subgrids of a :class:~gbmsc_pde.source_grid.grid.SourceGrid. It is used both for interpolation at arbitrary coordinates and for sparse nodal differential operators in the rectangular-domain PDE solver.

For nodal PDE operators, support_mode controls the normalization:

"active" Use only sampled subgrids that contain the evaluated source node. This is the original sparse rectangular-domain PDE mode. "all" Keep the sparse active contributors at source nodes, but normalize the Shepard denominator over all sampled subgrids. "nodal_limit" Use the source-node limiting formula. The common singular factor is cancelled from all active subgrids containing the source node before evaluating the weight values and derivatives.

Interpolation at arbitrary query coordinates uses all sampled subgrids.

Attributes:

Name Type Description
grid SourceGrid

Structured source grid.

step tuple[int, int]

Sampling stride for local subgrids.

subgrids_step_row (ndarray, shape(S, m))

Flattened sampled local subgrid node ids, where m = n_x * n_y.

support_mode {active, all, nodal_limit}

Nodal operator normalization mode.

Source code in src/gbmsc_pde/approximation/shepard.py
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
class GBMSCApproximation:
    """
    Grid-Based Shepard approximation on a structured grid.

    The approximation blends local tensor-product Lagrange polynomials defined
    on sampled subgrids of a :class:`~gbmsc_pde.source_grid.grid.SourceGrid`.  It is used
    both for interpolation at arbitrary coordinates and for sparse nodal
    differential operators in the rectangular-domain PDE solver.

    For nodal PDE operators, ``support_mode`` controls the normalization:

    ``"active"``
        Use only sampled subgrids that contain the evaluated source node.  This
        is the original sparse rectangular-domain PDE mode.
    ``"all"``
        Keep the sparse active contributors at source nodes, but normalize the
        Shepard denominator over all sampled subgrids.
    ``"nodal_limit"``
        Use the source-node limiting formula.  The common singular factor is
        cancelled from all active subgrids containing the source node before
        evaluating the weight values and derivatives.

    Interpolation at arbitrary query coordinates uses all sampled subgrids.

    Attributes
    ----------
    grid : SourceGrid
        Structured source grid.
    step : tuple[int, int]
        Sampling stride for local subgrids.
    subgrids_step_row : ndarray, shape (S, m)
        Flattened sampled local subgrid node ids, where
        ``m = n_x * n_y``.
    support_mode : {"active", "all", "nodal_limit"}
        Nodal operator normalization mode.
    """

    def __init__(
        self,
        grid: SourceGrid,
        step: Tuple[int, int] = (1, 1),
        mu: float = 2.005,
        eps: float = 1e-12,
        support_mode: str = "active",
    ) -> None:
        """
        Initialize the Grid-Based Shepard approximation.

        Parameters
        ----------
        grid : SourceGrid
            Structured source grid providing source-node coordinates, local subgrids,
            and pairwise distances.
        step : tuple[int, int], default=(1, 1)
            Sampling stride for local subgrid starts.
        mu : float, default=2.005
            Shepard exponent parameter.  The implementation stores ``2*mu`` so
            formulas based on squared distances recover the requested power.
        eps : float, default=1e-12
            Distance floor used to avoid division by zero and logarithms of
            zero.
        support_mode : {"active", "all", "nodal_limit"}, default="active"
            Nodal PDE-operator support mode.

        Raises
        ------
        TypeError
            If ``grid`` does not provide local subgrids.
        ValueError
            If ``step`` is invalid, ``mu <= 2``, or ``support_mode`` is
            unknown.
        """
        # Input validation
        if not hasattr(grid, 'subgrids'):
            raise TypeError("grid must have attribute 'subgrids'.")
        if any(s < 1 or not isinstance(s, int) for s in step):
            raise ValueError("step must be a tuple of positive integers.")

        if mu <= 2:
            raise ValueError("mu parameter must be greater than 2.")
        if support_mode not in ("active", "all", "nodal_limit"):
            raise ValueError("support_mode must be 'active', 'all', or 'nodal_limit'.")

        self.grid = grid
        self.step = step
        self.mu = float(2 * mu)
        self.eps = float(eps)
        self.support_mode = support_mode

        # Unpack shapes
        n_x, n_y = grid.subgrid_shape

        # Sample subgrids at the given stride, then flatten for vectorized ops
        subgrids_step, self.subgrids_x_step, self.subgrids_y_step = grid.subgrids_with_step(self.step)
        self.subgrids_step_grid = subgrids_step.reshape(-1, n_x, n_y)    # (S, n_x, n_y)
        self.subgrids_step_row = self.subgrids_step_grid.reshape(-1, n_x * n_y)  # (S, m)
        self._subgrid_x_coords = self.grid.x_coords_flat[self.subgrids_step_row]
        self._subgrid_y_coords = self.grid.y_coords_flat[self.subgrids_step_row]
        self._x_lines = self.grid.X[self.subgrids_x_step, 0]
        self._y_lines = self.grid.Y[0, self.subgrids_y_step]
        self._x_lagrange_weights = _barycentric_weights_batch(self._x_lines)
        self._y_lagrange_weights = _barycentric_weights_batch(self._y_lines)
        self._lagrange_derivative_cache = {}
        self._node_subgrid_ids, self._node_subgrid_counts = self._build_node_subgrid_lookup()
        self._safe_dist = None
        self._safe_logd = None
        self._nodal_limit_data = None
        self._all_node_subgrid_metric_cache = {}

    def _build_node_subgrid_lookup(self) -> Tuple[np.ndarray, np.ndarray]:
        """
        Build a padded lookup from global node id to sampled subgrids containing it.

        Returns
        -------
        node_subgrid_ids : (N, C) ndarray(int)
            Padded subgrid ids for each global node. Unused slots are ``-1``.
        node_subgrid_counts : (N,) ndarray(int)
            Number of valid sampled subgrids per global node.
        """
        flat_nodes = self.subgrids_step_row.ravel()
        node_subgrid_counts = np.bincount(flat_nodes, minlength=self.grid.N)
        max_count = int(node_subgrid_counts.max()) if node_subgrid_counts.size else 0
        node_subgrid_ids = np.full((self.grid.N, max_count), -1, dtype=int)
        offsets = np.zeros(self.grid.N, dtype=int)

        subgrid_ids = np.repeat(np.arange(self.subgrids_step_row.shape[0]), self.subgrids_step_row.shape[1])
        for node_id, subgrid_id in zip(flat_nodes, subgrid_ids):
            slot = offsets[node_id]
            node_subgrid_ids[node_id, slot] = subgrid_id
            offsets[node_id] = slot + 1

        return node_subgrid_ids, node_subgrid_counts

    def _safe_pairwise_data(self) -> Tuple[np.ndarray, np.ndarray]:
        """
        Return cached pairwise squared distances and their logarithm with epsilon floor.
        """
        if self._safe_dist is None or self._safe_logd is None:
            safe_dist = np.maximum(self.grid.dist, self.eps)
            self._safe_dist = safe_dist
            self._safe_logd = np.log(safe_dist)
        return self._safe_dist, self._safe_logd

    def _nodal_limit_pairwise_data(self) -> Tuple[np.ndarray, ...]:
        """
        Return pairwise data for source-node limiting weights.

        At a source node, every active subgrid contains the common singular
        factor associated with the collocation node.  The limiting formula
        cancels that factor before differentiating the normalized weight.  In
        vectorized pairwise arrays this is represented by a neutral diagonal:
        ``dist_ii = 1`` and zero diagonal derivative contributions.
        """
        if self._nodal_limit_data is not None:
            return self._nodal_limit_data

        dist = self.grid.dist.copy()
        np.fill_diagonal(dist, 1.0)
        logd = np.log(dist)

        diff_x = self.grid.diff_x
        diff_y = self.grid.diff_y
        A_x_data = 2.0 * diff_x / dist
        A_y_data = 2.0 * diff_y / dist
        A_xx_data = 2.0 / dist - 4.0 * (diff_x / dist) ** 2
        A_yy_data = 2.0 / dist - 4.0 * (diff_y / dist) ** 2
        np.fill_diagonal(A_xx_data, 0.0)
        np.fill_diagonal(A_yy_data, 0.0)

        self._nodal_limit_data = (
            dist,
            logd,
            A_x_data,
            A_y_data,
            A_xx_data,
            A_yy_data,
        )
        return self._nodal_limit_data

    def _all_node_subgrid_metric_sums(self, second_derivatives: bool = True):
        """
        Precompute node-to-subgrid metric sums for all-denominator nodal rows.

        The active-denominator path only needs the subgrids containing each
        row node.  The all-denominator path needs every sampled subgrid in the
        normalizing sum; using these ``(N, S)`` tables avoids repeatedly
        building much larger ``(block, S, m)`` distance tensors.
        """
        cache_key = bool(second_derivatives)
        cached = self._all_node_subgrid_metric_cache.get(cache_key)
        if cached is not None:
            return cached

        dist, logd = self._safe_pairwise_data()
        idx_rows = self.subgrids_step_row
        S, m = idx_rows.shape

        indicator = np.zeros((self.grid.N, S), dtype=float)
        indicator[
            idx_rows.ravel(),
            np.repeat(np.arange(S, dtype=int), m),
        ] = 1.0

        diff_x = self.grid.diff_x
        diff_y = self.grid.diff_y
        A = logd @ indicator
        A_x = (2.0 * diff_x / dist) @ indicator
        A_y = (2.0 * diff_y / dist) @ indicator

        if not second_derivatives:
            result = (A, A_x, A_y)
            self._all_node_subgrid_metric_cache[cache_key] = result
            return result

        A_xx = (2.0 / dist - 4.0 * (diff_x / dist) ** 2) @ indicator
        A_yy = (2.0 / dist - 4.0 * (diff_y / dist) ** 2) @ indicator
        result = (A, A_x, A_y, A_xx, A_yy)
        self._all_node_subgrid_metric_cache[cache_key] = result
        return result

    def eval_weight_functions_at_nodes_all_denominator_minmax_shift(
        self,
        second_derivatives=True,
        block_s: int = 64,
    ) -> Union[Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray],
               Tuple[np.ndarray, np.ndarray, np.ndarray]
               ]:
        """
        Compute nodal Shepard weights with active contributors and all denominator.

        The returned arrays have the same ``(S, m)`` shape as
        :meth:`eval_weight_functions_at_nodes_data_minmax_shift`: one row for
        each retained/sampled subgrid and one column for each local node.  Only
        the normalization denominator is enlarged to all sampled subgrids.

        Parameters
        ----------
        second_derivatives : bool, default=True
            Whether to also return second derivatives of the weights.
        block_s : int, default=64
            Number of sampled subgrids processed per vectorized block.

        Returns
        -------
        tuple[ndarray, ...]
            ``(f, f_x, f_y, f_xx, f_yy)`` when ``second_derivatives`` is true,
            otherwise ``(f, f_x, f_y)``.  Each array has shape ``(S, m)``.
        """
        mu = self.mu * 0.5
        idx_rows = self.subgrids_step_row
        S, m = idx_rows.shape

        metrics = self._all_node_subgrid_metric_sums(second_derivatives=second_derivatives)
        if second_derivatives:
            A, A_x, A_y, A_xx, A_yy = metrics
        else:
            A, A_x, A_y = metrics

        f_val = np.empty((S, m))
        f_x = np.empty_like(f_val)
        f_y = np.empty_like(f_val)
        if second_derivatives:
            f_xx = np.empty_like(f_val)
            f_yy = np.empty_like(f_val)

        for s0 in range(0, S, block_s):
            s1 = min(s0 + block_s, S)
            blk = slice(s0, s1)
            B = s1 - s0

            flat_eval_nodes = idx_rows[blk].reshape(-1)
            current_subgrid_ids = np.repeat(np.arange(s0, s1, dtype=int), m)

            A_current = A[flat_eval_nodes, current_subgrid_ids]
            A_candidates = A[flat_eval_nodes]
            DeltaA = A_current[:, None] - A_candidates

            z = mu * DeltaA
            z_max = np.max(z, axis=1, keepdims=True)
            with np.errstate(under="ignore"):
                R_shift = np.exp(z - z_max)
            R_shift_sum = R_shift.sum(axis=1)
            normalized_R = R_shift / R_shift_sum[:, None]

            f_val_block = np.exp(-z_max.ravel()) / R_shift_sum

            A_x_current = A_x[flat_eval_nodes, current_subgrid_ids]
            A_y_current = A_y[flat_eval_nodes, current_subgrid_ids]
            beta_x = mu * (A_x_current[:, None] - A_x[flat_eval_nodes])
            beta_y = mu * (A_y_current[:, None] - A_y[flat_eval_nodes])
            log_derivative_x = (normalized_R * beta_x).sum(axis=1)
            log_derivative_y = (normalized_R * beta_y).sum(axis=1)

            f_val[blk] = f_val_block.reshape(B, m)
            f_x[blk] = (-f_val_block * log_derivative_x).reshape(B, m)
            f_y[blk] = (-f_val_block * log_derivative_y).reshape(B, m)

            if second_derivatives:
                A_xx_current = A_xx[flat_eval_nodes, current_subgrid_ids]
                A_yy_current = A_yy[flat_eval_nodes, current_subgrid_ids]
                beta_xx = mu * (A_xx_current[:, None] - A_xx[flat_eval_nodes])
                beta_yy = mu * (A_yy_current[:, None] - A_yy[flat_eval_nodes])
                curvature_x = (normalized_R * (beta_xx + beta_x ** 2)).sum(axis=1)
                curvature_y = (normalized_R * (beta_yy + beta_y ** 2)).sum(axis=1)

                f_xx[blk] = (
                    f_val_block * (2.0 * log_derivative_x ** 2 - curvature_x)
                ).reshape(B, m)
                f_yy[blk] = (
                    f_val_block * (2.0 * log_derivative_y ** 2 - curvature_y)
                ).reshape(B, m)

        if second_derivatives:
            return f_val, f_x, f_y, f_xx, f_yy

        return f_val, f_x, f_y

    def _normalized_weights_at_queries_stable(
        self,
        xq: np.ndarray,
        yq: np.ndarray,
        *,
        return_derivatives: bool = False,
        regularized: bool = True,
    ) -> np.ndarray:
        """
        Stable normalized Shepard weights computed in log-space.

        This variant never forms the raw weights ``W = exp(log_w)`` directly.
        Instead it applies a max-shift per query so the largest exponent is 0,
        then normalizes the shifted weights.

        Parameters
        ----------
        xq, yq : (l,) 1-D arrays
            Query coordinates.
        return_derivatives : bool, default False
            If True, also return derivatives of the normalized weights.

        Returns
        -------
        P : (l, S) ndarray
            Normalized Shepard weights for each query and sampled sub-grid.
        Px, Py : (l, S) ndarray
            First derivatives of the normalized weights (only if requested).
        """
        xq = np.asarray(xq, dtype=float).ravel()
        yq = np.asarray(yq, dtype=float).ravel()
        if xq.size != yq.size:
            raise ValueError("x and y arrays must have same length.")

        Xn = self._subgrid_x_coords
        Yn = self._subgrid_y_coords

        # Broadcasted differences (l, S, m)
        dx = xq[:, None, None] - Xn[None, :, :]
        dy = yq[:, None, None] - Yn[None, :, :]

        # Squared distance.  The legacy path uses an epsilon floor; the
        # exact-nodal interpolation path passes only non-source queries and
        # therefore uses true distances.
        dist2 = dx * dx + dy * dy
        if regularized:
            dist2[dist2 < self.eps] = self.eps
        elif np.any(dist2 <= 0.0):
            raise ZeroDivisionError(
                "Exact non-regularized interpolation received a source-node query. "
                "Use interpolation_mode='exact_nodal' so node hits are handled separately."
            )

        log_w = (-self.mu * 0.5) * np.log(dist2).sum(axis=2)  # (l, S)

        # Stable normalization: exp(log_w - max(log_w))
        log_w_shift = log_w - np.max(log_w, axis=1, keepdims=True)
        W_shift = np.exp(log_w_shift)
        W_sum = W_shift.sum(axis=1, keepdims=True)
        P = W_shift / W_sum

        if not return_derivatives:
            return (P,)

        # alpha_x / alpha_y are derivatives of log_w
        alpha_x = -self.mu * (dx / dist2).sum(axis=2)  # (l, S)
        alpha_y = -self.mu * (dy / dist2).sum(axis=2)  # (l, S)
        mean_alpha_x = (P * alpha_x).sum(axis=1, keepdims=True)
        mean_alpha_y = (P * alpha_y).sum(axis=1, keepdims=True)

        # Derivatives of normalized weights:
        # p_i,x = p_i * (alpha_i,x - sum_j p_j alpha_j,x)
        Px = P * (alpha_x - mean_alpha_x)
        Py = P * (alpha_y - mean_alpha_y)

        return P, Px, Py

    def _source_node_hits(
        self,
        xq: np.ndarray,
        yq: np.ndarray,
        *,
        tolerance: float,
        chunk: int,
    ) -> np.ndarray:
        """Return source-node ids for query points within tolerance, else -1."""
        hits = np.full(xq.shape, -1, dtype=int)
        coords = self.grid.coords
        tol2 = float(tolerance) ** 2
        chunk = max(int(chunk), 1)

        for q0 in range(0, xq.size, chunk):
            q1 = min(q0 + chunk, xq.size)
            dx = xq[q0:q1, None] - coords[None, :, 0]
            dy = yq[q0:q1, None] - coords[None, :, 1]
            dist2 = dx * dx + dy * dy
            nearest = np.argmin(dist2, axis=1)
            nearest_dist2 = dist2[np.arange(q1 - q0), nearest]
            mask = nearest_dist2 <= tol2
            hits[q0:q1][mask] = nearest[mask]

        return hits

    def interpolator(
        self,
        x: np.ndarray,
        y: np.ndarray,
        u: np.ndarray,
        *,
        return_derivatives: bool = False,
        chunk: int = 1000,
        interpolation_mode: str = "exact_nodal",
        tolerance: float = 1e-12,
        Mx=None,
        My=None,
    ) -> Union[
        Tuple[np.ndarray],
        Tuple[np.ndarray, np.ndarray, np.ndarray]
    ]:
        """
        Interpolate a source-node field at arbitrary coordinates.

        Query interpolation uses all sampled subgrids as contributors and
        normalizes the Shepard weights over all sampled subgrids.  Computation
        is chunked and performed in log space to avoid overflow in the raw
        weights.

        ``interpolation_mode="exact_nodal"`` returns exact nodal values when a
        query point coincides with a source node within ``tolerance``.  Other
        query points use true distances without an epsilon floor.

        ``interpolation_mode="regularized"`` preserves the legacy epsilon-floor
        behavior for all query points.

        Parameters
        ----------
        x, y : array_like, shape (n_eval,)
            Query coordinates.
        u : array_like, shape (grid.N,)
            Source-node values ordered like ``grid.coords``.
        return_derivatives : bool, default=False
            If true, also return first derivatives ``du/dx`` and ``du/dy``.
        chunk : int, default=1000
            Number of query points processed per block.
        interpolation_mode : {"exact_nodal", "regularized"}, default="exact_nodal"
            Query distance policy.
        tolerance : float, default=1e-12
            Source-node hit tolerance for ``"exact_nodal"`` mode.
        Mx, My : sparse matrices, optional
            Existing first-derivative operators.  When
            ``return_derivatives=True`` and source-node hits are present, these
            matrices are reused instead of rebuilding operators.

        Returns
        -------
        tuple
            ``(u_eval,)`` or ``(u_eval, u_x, u_y)``.
        """
        xq = np.asarray(x, dtype=float).ravel()
        yq = np.asarray(y, dtype=float).ravel()
        u = np.asarray(u, dtype=float).ravel()
        if xq.size != yq.size:
            raise ValueError("x and y arrays must have same length.")
        if u.size != self.grid.N:
            raise ValueError("`u` must have length grid.N")
        if interpolation_mode not in ("exact_nodal", "regularized"):
            raise ValueError("interpolation_mode must be 'exact_nodal' or 'regularized'.")
        if tolerance < 0:
            raise ValueError("tolerance must be non-negative.")

        l = xq.size
        chunk = max(chunk, 10)

        val = np.empty(l)
        if return_derivatives:
            ux = np.empty_like(val)
            uy = np.empty_like(val)

        hit_nodes = np.full(l, -1, dtype=int)
        if interpolation_mode == "exact_nodal":
            hit_nodes = self._source_node_hits(
                xq,
                yq,
                tolerance=tolerance,
                chunk=chunk,
            )
            hit_mask = hit_nodes != -1
            if np.any(hit_mask):
                val[hit_mask] = u[hit_nodes[hit_mask]]
                if return_derivatives:
                    if Mx is None or My is None:
                        from ..operators.differential import build_differential_operators

                        Mx_built, My_built, _, _ = build_differential_operators(self)
                        if Mx is None:
                            Mx = Mx_built
                        if My is None:
                            My = My_built
                    ux[hit_mask] = Mx.tocsr()[hit_nodes[hit_mask]].dot(u)
                    uy[hit_mask] = My.tocsr()[hit_nodes[hit_mask]].dot(u)

        # Nodal values per sub-grid
        U = u[self.subgrids_step_row]  # (S, m)

        x_lines = self._x_lines
        y_lines = self._y_lines
        x_weights = self._x_lagrange_weights
        y_weights = self._y_lagrange_weights

        Sx, nx = x_lines.shape
        Sy, ny = y_lines.shape
        m = nx * ny
        S = Sx * Sy

        for q0 in range(0, l, chunk):
            q1 = min(q0 + chunk, l)
            block_indices = np.arange(q0, q1)
            if interpolation_mode == "exact_nodal":
                block_indices = block_indices[hit_nodes[q0:q1] == -1]
                if block_indices.size == 0:
                    continue

            xs = xq[block_indices]
            ys = yq[block_indices]
            l_b = block_indices.size

            P_parts = self._normalized_weights_at_queries_stable(
                xs,
                ys,
                return_derivatives=return_derivatives,
                regularized=interpolation_mode == "regularized",
            )
            P = P_parts[0]
            if return_derivatives:
                Px, Py = P_parts[1], P_parts[2]

            Lx = np.empty((l_b, Sx, nx))
            Ly = np.empty((l_b, Sy, ny))
            if return_derivatives:
                dLx = np.empty_like(Lx)
                dLy = np.empty_like(Ly)

            for s in range(Sx):
                if return_derivatives:
                    Lx[:, s], dLx[:, s] = lagrange_1d(
                        x_lines[s],
                        xs,
                        with_first_derivatives=True,
                        barycentric_weights=x_weights[s],
                    )
                else:
                    Lx[:, s] = lagrange_1d(
                        x_lines[s],
                        xs,
                        with_first_derivatives=False,
                        barycentric_weights=x_weights[s],
                    )[0]

            for s in range(Sy):
                if return_derivatives:
                    Ly[:, s], dLy[:, s] = lagrange_1d(
                        y_lines[s],
                        ys,
                        with_first_derivatives=True,
                        barycentric_weights=y_weights[s],
                    )
                else:
                    Ly[:, s] = lagrange_1d(
                        y_lines[s],
                        ys,
                        with_first_derivatives=False,
                        barycentric_weights=y_weights[s],
                    )[0]

            Phi = (Lx[:, :, None, :, None] * Ly[:, None, :, None, :]).reshape(l_b, S, m)

            Li = np.einsum('qsm,sm->qs', Phi, U, optimize=True)
            val[block_indices] = (P * Li).sum(axis=1)

            if return_derivatives:
                Phi_x = (dLx[:, :, None, :, None] * Ly[:, None, :, None, :]).reshape(l_b, S, m)
                Phi_y = (Lx[:, :, None, :, None] * dLy[:, None, :, None, :]).reshape(l_b, S, m)
                Li_x = np.einsum('qsm,sm->qs', Phi_x, U, optimize=True)
                Li_y = np.einsum('qsm,sm->qs', Phi_y, U, optimize=True)
                ux[block_indices] = (P * Li_x + Px * Li).sum(axis=1)
                uy[block_indices] = (P * Li_y + Py * Li).sum(axis=1)

        if return_derivatives:
            return val, ux, uy
        return (val,)

    def lagrange_derivatives_x_direction(self):
        """Return repeated 1D Lagrange derivative matrices in the x direction."""
        l = len(self.subgrids_x_step) 
        (I, L1, L2) = self._lagrange_derivatives_one_subgrids_1dim(self.grid.subgrids_x_coords[0])
        return (I[None, :, :].repeat(l, axis=0), L1[None, :, :].repeat(l, axis=0), L2[None, :, :].repeat(l, axis=0))

    def lagrange_derivatives_y_direction(self):
        """Return repeated 1D Lagrange derivative matrices in the y direction."""
        (I, L1, L2) = self._lagrange_derivatives_one_subgrids_1dim(self.grid.subgrids_y_coords[0])
        l = len(self.subgrids_y_step)
        return (I[None, :, :].repeat(l, axis=0), L1[None, :, :].repeat(l, axis=0), L2[None, :, :].repeat(l, axis=0))

    def _lagrange_derivatives_one_subgrids_1dim(self, X: np.ndarray) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
        """
        Compute nodal 1D Lagrange derivative matrices.

        Parameters
        ----------
        X : ndarray, shape (m,)
            Distinct interpolation nodes.

        Returns
        -------
        I, L1, L2 : tuple[ndarray, ndarray, ndarray]
            Basis, first-derivative, and second-derivative matrices evaluated
            at the nodes ``X``.
        """
        X = np.asarray(X, dtype=float)
        cache_key = tuple(X.tolist())
        cached = self._lagrange_derivative_cache.get(cache_key)
        if cached is not None:
            return cached

        m = X.size
        diff = X[:, None] - X[None, :]
        diag = np.eye(m, dtype=bool)

        # Barycentric weights
        diff[diag] = 1.0
        w = 1.0 / np.prod(diff, axis=1)

        # First derivative
        with np.errstate(divide='ignore', invalid='ignore'):
            L1 = np.where(
                diag, 
                0.0, 
                (w[None, :] / (w[:, None] * diff))
            )
        L1[diag] = -np.sum(L1, axis=1)

        # Compute S_vector for second derivative
        offdiag = ~diag
        with np.errstate(divide='ignore', invalid='ignore'):
            inv_diff = np.where(offdiag, 1.0 / diff, 0.0)
        S_vec = np.sum(inv_diff, axis=1)

        # Second derivative
        with np.errstate(divide='ignore', invalid='ignore'):
            L2 = np.where(
                offdiag,
                2 * L1 * (S_vec[:, None] - 1.0 / diff),
                0.0
            )
        L2[diag] = -np.sum(L2, axis=1)

        result = (np.eye(m), L1, L2)
        self._lagrange_derivative_cache[cache_key] = result
        return result

    def eval_weight_functions_at_nodes_data_minmax_shift(
        self,
        second_derivatives=True,
        block_s: int = 128
    ) -> Union[Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray],
               Tuple[np.ndarray, np.ndarray, np.ndarray]
               ]:
        """
        Compute active-mode nodal Shepard weights and derivatives.

        For each source-node row, only subgrids containing that source node
        participate in both the contributors and the denominator.  The
        implementation uses shifted log-ratios,

            f_i = 1 / sum_j exp(z_j),  z_j = mu * (A_i - A_j)

        and evaluates ``exp(z_j - max(z))`` instead of directly forming
        ``exp(z_j)``.

        Parameters
        ----------
        second_derivatives : bool, default=True
            Whether to also return second derivatives of the weights.
        block_s : int, default=128
            Number of sampled subgrids processed per vectorized block.

        Returns
        -------
        tuple[ndarray, ...]
            ``(f, f_x, f_y, f_xx, f_yy)`` when ``second_derivatives`` is true,
            otherwise ``(f, f_x, f_y)``.  Each array has shape ``(S, m)``.
        """
        mu = self.mu * 0.5
        diff_x, diff_y = self.grid.diff_x, self.grid.diff_y
        dist, logd = self._safe_pairwise_data()

        idx_rows = self.subgrids_step_row
        S, m = idx_rows.shape

        f_val = np.empty((S, m))
        f_x = np.empty_like(f_val)
        f_y = np.empty_like(f_val)
        if second_derivatives:
            f_xx = np.empty_like(f_val)
            f_yy = np.empty_like(f_val)

        for s0 in range(0, S, block_s):
            s1 = min(s0 + block_s, S)
            blk = slice(s0, s1)
            B = s1 - s0

            rows = idx_rows[blk]
            flat_eval_nodes = rows.reshape(-1)
            current_subgrid_ids = np.repeat(np.arange(s0, s1), m)
            current_subgrid_nodes = idx_rows[current_subgrid_ids]

            current_row_index = flat_eval_nodes[:, None]
            current_logd = logd[current_row_index, current_subgrid_nodes]
            current_dx = diff_x[current_row_index, current_subgrid_nodes]
            current_dy = diff_y[current_row_index, current_subgrid_nodes]
            current_dist = dist[current_row_index, current_subgrid_nodes]

            A_current = current_logd.sum(axis=1)
            A_x_current = (2.0 * current_dx / current_dist).sum(axis=1)
            A_y_current = (2.0 * current_dy / current_dist).sum(axis=1)

            candidate_subgrid_ids = self._node_subgrid_ids[flat_eval_nodes]
            candidate_mask = candidate_subgrid_ids != -1
            safe_candidate_ids = np.where(candidate_mask, candidate_subgrid_ids, 0)
            candidate_nodes = idx_rows[safe_candidate_ids]

            row_index = flat_eval_nodes[:, None, None]
            candidate_logd = logd[row_index, candidate_nodes]
            candidate_dx = diff_x[row_index, candidate_nodes]
            candidate_dy = diff_y[row_index, candidate_nodes]
            candidate_dist = dist[row_index, candidate_nodes]

            A_candidates = candidate_logd.sum(axis=2)
            A_x_candidates = (2.0 * candidate_dx / candidate_dist).sum(axis=2)
            A_y_candidates = (2.0 * candidate_dy / candidate_dist).sum(axis=2)

            DeltaA = A_current[:, None] - A_candidates
            DeltaA_x = A_x_current[:, None] - A_x_candidates
            DeltaA_y = A_y_current[:, None] - A_y_candidates

            if second_derivatives:
                A_xx_current = (2.0 / current_dist - 4.0 * (current_dx / current_dist) ** 2).sum(axis=1)
                A_yy_current = (2.0 / current_dist - 4.0 * (current_dy / current_dist) ** 2).sum(axis=1)
                A_xx_candidates = (2.0 / candidate_dist - 4.0 * (candidate_dx / candidate_dist) ** 2).sum(axis=2)
                A_yy_candidates = (2.0 / candidate_dist - 4.0 * (candidate_dy / candidate_dist) ** 2).sum(axis=2)
                DeltaA_xx = A_xx_current[:, None] - A_xx_candidates
                DeltaA_yy = A_yy_current[:, None] - A_yy_candidates

            z = np.where(candidate_mask, mu * DeltaA, -np.inf)
            z_max = np.max(z, axis=1, keepdims=True)

            with np.errstate(under="ignore"):
                R_shift = np.exp(z - z_max)
            R_shift *= candidate_mask

            R_shift_sum = R_shift.sum(axis=1)
            normalized_R = R_shift / R_shift_sum[:, None]

            f_val_block = np.exp(-z_max.ravel()) / R_shift_sum

            beta_x = np.where(candidate_mask, mu * DeltaA_x, 0.0)
            beta_y = np.where(candidate_mask, mu * DeltaA_y, 0.0)
            log_derivative_x = (normalized_R * beta_x).sum(axis=1)
            log_derivative_y = (normalized_R * beta_y).sum(axis=1)

            f_x_block = -f_val_block * log_derivative_x
            f_y_block = -f_val_block * log_derivative_y

            f_val[blk] = f_val_block.reshape(B, m)
            f_x[blk] = f_x_block.reshape(B, m)
            f_y[blk] = f_y_block.reshape(B, m)

            if second_derivatives:
                beta_xx = np.where(candidate_mask, mu * DeltaA_xx, 0.0)
                beta_yy = np.where(candidate_mask, mu * DeltaA_yy, 0.0)
                curvature_x = (normalized_R * (beta_xx + beta_x ** 2)).sum(axis=1)
                curvature_y = (normalized_R * (beta_yy + beta_y ** 2)).sum(axis=1)

                f_xx[blk] = (
                    f_val_block * (2.0 * log_derivative_x ** 2 - curvature_x)
                ).reshape(B, m)
                f_yy[blk] = (
                    f_val_block * (2.0 * log_derivative_y ** 2 - curvature_y)
                ).reshape(B, m)

        if second_derivatives:
            return f_val, f_x, f_y, f_xx, f_yy

        return f_val, f_x, f_y

    def eval_weight_functions_at_nodes_nodal_limit(
        self,
        second_derivatives=True,
        block_s: int = 128
    ) -> Union[Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray],
               Tuple[np.ndarray, np.ndarray, np.ndarray]
               ]:
        """
        Compute source-node limiting Shepard weights and derivatives.

        For each source-node row, only subgrids containing that source node
        participate.  The common singular factor is cancelled analytically
        before forming the normalized Shepard fraction.  In the vectorized
        metric sums this is equivalent to using a neutral self-distance and
        zero self-contributions for first and second metric derivatives.
        """
        mu = self.mu * 0.5
        _, logd, A_x_data, A_y_data, A_xx_data, A_yy_data = self._nodal_limit_pairwise_data()

        idx_rows = self.subgrids_step_row
        S, m = idx_rows.shape

        f_val = np.empty((S, m))
        f_x = np.empty_like(f_val)
        f_y = np.empty_like(f_val)
        if second_derivatives:
            f_xx = np.empty_like(f_val)
            f_yy = np.empty_like(f_val)

        for s0 in range(0, S, block_s):
            s1 = min(s0 + block_s, S)
            blk = slice(s0, s1)
            B = s1 - s0

            rows = idx_rows[blk]
            flat_eval_nodes = rows.reshape(-1)
            current_subgrid_ids = np.repeat(np.arange(s0, s1), m)
            current_subgrid_nodes = idx_rows[current_subgrid_ids]

            current_row_index = flat_eval_nodes[:, None]
            current_logd = logd[current_row_index, current_subgrid_nodes]
            current_A_x = A_x_data[current_row_index, current_subgrid_nodes]
            current_A_y = A_y_data[current_row_index, current_subgrid_nodes]

            A_current = current_logd.sum(axis=1)
            A_x_current = current_A_x.sum(axis=1)
            A_y_current = current_A_y.sum(axis=1)

            candidate_subgrid_ids = self._node_subgrid_ids[flat_eval_nodes]
            candidate_mask = candidate_subgrid_ids != -1
            safe_candidate_ids = np.where(candidate_mask, candidate_subgrid_ids, 0)
            candidate_nodes = idx_rows[safe_candidate_ids]

            row_index = flat_eval_nodes[:, None, None]
            candidate_logd = logd[row_index, candidate_nodes]
            candidate_A_x = A_x_data[row_index, candidate_nodes]
            candidate_A_y = A_y_data[row_index, candidate_nodes]

            A_candidates = candidate_logd.sum(axis=2)
            A_x_candidates = candidate_A_x.sum(axis=2)
            A_y_candidates = candidate_A_y.sum(axis=2)

            DeltaA = A_current[:, None] - A_candidates
            DeltaA_x = A_x_current[:, None] - A_x_candidates
            DeltaA_y = A_y_current[:, None] - A_y_candidates

            if second_derivatives:
                current_A_xx = A_xx_data[current_row_index, current_subgrid_nodes]
                current_A_yy = A_yy_data[current_row_index, current_subgrid_nodes]
                candidate_A_xx = A_xx_data[row_index, candidate_nodes]
                candidate_A_yy = A_yy_data[row_index, candidate_nodes]
                A_xx_current = current_A_xx.sum(axis=1)
                A_yy_current = current_A_yy.sum(axis=1)
                A_xx_candidates = candidate_A_xx.sum(axis=2)
                A_yy_candidates = candidate_A_yy.sum(axis=2)
                DeltaA_xx = A_xx_current[:, None] - A_xx_candidates
                DeltaA_yy = A_yy_current[:, None] - A_yy_candidates

            z = np.where(candidate_mask, mu * DeltaA, -np.inf)
            z_max = np.max(z, axis=1, keepdims=True)

            with np.errstate(under="ignore"):
                R_shift = np.exp(z - z_max)
            R_shift *= candidate_mask

            R_shift_sum = R_shift.sum(axis=1)
            normalized_R = R_shift / R_shift_sum[:, None]

            f_val_block = np.exp(-z_max.ravel()) / R_shift_sum

            beta_x = np.where(candidate_mask, mu * DeltaA_x, 0.0)
            beta_y = np.where(candidate_mask, mu * DeltaA_y, 0.0)
            log_derivative_x = (normalized_R * beta_x).sum(axis=1)
            log_derivative_y = (normalized_R * beta_y).sum(axis=1)

            f_x_block = -f_val_block * log_derivative_x
            f_y_block = -f_val_block * log_derivative_y

            f_val[blk] = f_val_block.reshape(B, m)
            f_x[blk] = f_x_block.reshape(B, m)
            f_y[blk] = f_y_block.reshape(B, m)

            if second_derivatives:
                beta_xx = np.where(candidate_mask, mu * DeltaA_xx, 0.0)
                beta_yy = np.where(candidate_mask, mu * DeltaA_yy, 0.0)
                curvature_x = (normalized_R * (beta_xx + beta_x ** 2)).sum(axis=1)
                curvature_y = (normalized_R * (beta_yy + beta_y ** 2)).sum(axis=1)

                f_xx[blk] = (
                    f_val_block * (2.0 * log_derivative_x ** 2 - curvature_x)
                ).reshape(B, m)
                f_yy[blk] = (
                    f_val_block * (2.0 * log_derivative_y ** 2 - curvature_y)
                ).reshape(B, m)

        if second_derivatives:
            return f_val, f_x, f_y, f_xx, f_yy

        return f_val, f_x, f_y

__init__(grid, step=(1, 1), mu=2.005, eps=1e-12, support_mode='active')

Initialize the Grid-Based Shepard approximation.

Parameters:

Name Type Description Default
grid SourceGrid

Structured source grid providing source-node coordinates, local subgrids, and pairwise distances.

required
step tuple[int, int]

Sampling stride for local subgrid starts.

(1, 1)
mu float

Shepard exponent parameter. The implementation stores 2*mu so formulas based on squared distances recover the requested power.

2.005
eps float

Distance floor used to avoid division by zero and logarithms of zero.

1e-12
support_mode (active, all, nodal_limit)

Nodal PDE-operator support mode.

"active"

Raises:

Type Description
TypeError

If grid does not provide local subgrids.

ValueError

If step is invalid, mu <= 2, or support_mode is unknown.

Source code in src/gbmsc_pde/approximation/shepard.py
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
def __init__(
    self,
    grid: SourceGrid,
    step: Tuple[int, int] = (1, 1),
    mu: float = 2.005,
    eps: float = 1e-12,
    support_mode: str = "active",
) -> None:
    """
    Initialize the Grid-Based Shepard approximation.

    Parameters
    ----------
    grid : SourceGrid
        Structured source grid providing source-node coordinates, local subgrids,
        and pairwise distances.
    step : tuple[int, int], default=(1, 1)
        Sampling stride for local subgrid starts.
    mu : float, default=2.005
        Shepard exponent parameter.  The implementation stores ``2*mu`` so
        formulas based on squared distances recover the requested power.
    eps : float, default=1e-12
        Distance floor used to avoid division by zero and logarithms of
        zero.
    support_mode : {"active", "all", "nodal_limit"}, default="active"
        Nodal PDE-operator support mode.

    Raises
    ------
    TypeError
        If ``grid`` does not provide local subgrids.
    ValueError
        If ``step`` is invalid, ``mu <= 2``, or ``support_mode`` is
        unknown.
    """
    # Input validation
    if not hasattr(grid, 'subgrids'):
        raise TypeError("grid must have attribute 'subgrids'.")
    if any(s < 1 or not isinstance(s, int) for s in step):
        raise ValueError("step must be a tuple of positive integers.")

    if mu <= 2:
        raise ValueError("mu parameter must be greater than 2.")
    if support_mode not in ("active", "all", "nodal_limit"):
        raise ValueError("support_mode must be 'active', 'all', or 'nodal_limit'.")

    self.grid = grid
    self.step = step
    self.mu = float(2 * mu)
    self.eps = float(eps)
    self.support_mode = support_mode

    # Unpack shapes
    n_x, n_y = grid.subgrid_shape

    # Sample subgrids at the given stride, then flatten for vectorized ops
    subgrids_step, self.subgrids_x_step, self.subgrids_y_step = grid.subgrids_with_step(self.step)
    self.subgrids_step_grid = subgrids_step.reshape(-1, n_x, n_y)    # (S, n_x, n_y)
    self.subgrids_step_row = self.subgrids_step_grid.reshape(-1, n_x * n_y)  # (S, m)
    self._subgrid_x_coords = self.grid.x_coords_flat[self.subgrids_step_row]
    self._subgrid_y_coords = self.grid.y_coords_flat[self.subgrids_step_row]
    self._x_lines = self.grid.X[self.subgrids_x_step, 0]
    self._y_lines = self.grid.Y[0, self.subgrids_y_step]
    self._x_lagrange_weights = _barycentric_weights_batch(self._x_lines)
    self._y_lagrange_weights = _barycentric_weights_batch(self._y_lines)
    self._lagrange_derivative_cache = {}
    self._node_subgrid_ids, self._node_subgrid_counts = self._build_node_subgrid_lookup()
    self._safe_dist = None
    self._safe_logd = None
    self._nodal_limit_data = None
    self._all_node_subgrid_metric_cache = {}

eval_weight_functions_at_nodes_all_denominator_minmax_shift(second_derivatives=True, block_s=64)

Compute nodal Shepard weights with active contributors and all denominator.

The returned arrays have the same (S, m) shape as :meth:eval_weight_functions_at_nodes_data_minmax_shift: one row for each retained/sampled subgrid and one column for each local node. Only the normalization denominator is enlarged to all sampled subgrids.

Parameters:

Name Type Description Default
second_derivatives bool

Whether to also return second derivatives of the weights.

True
block_s int

Number of sampled subgrids processed per vectorized block.

64

Returns:

Type Description
tuple[ndarray, ...]

(f, f_x, f_y, f_xx, f_yy) when second_derivatives is true, otherwise (f, f_x, f_y). Each array has shape (S, m).

Source code in src/gbmsc_pde/approximation/shepard.py
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
def eval_weight_functions_at_nodes_all_denominator_minmax_shift(
    self,
    second_derivatives=True,
    block_s: int = 64,
) -> Union[Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray],
           Tuple[np.ndarray, np.ndarray, np.ndarray]
           ]:
    """
    Compute nodal Shepard weights with active contributors and all denominator.

    The returned arrays have the same ``(S, m)`` shape as
    :meth:`eval_weight_functions_at_nodes_data_minmax_shift`: one row for
    each retained/sampled subgrid and one column for each local node.  Only
    the normalization denominator is enlarged to all sampled subgrids.

    Parameters
    ----------
    second_derivatives : bool, default=True
        Whether to also return second derivatives of the weights.
    block_s : int, default=64
        Number of sampled subgrids processed per vectorized block.

    Returns
    -------
    tuple[ndarray, ...]
        ``(f, f_x, f_y, f_xx, f_yy)`` when ``second_derivatives`` is true,
        otherwise ``(f, f_x, f_y)``.  Each array has shape ``(S, m)``.
    """
    mu = self.mu * 0.5
    idx_rows = self.subgrids_step_row
    S, m = idx_rows.shape

    metrics = self._all_node_subgrid_metric_sums(second_derivatives=second_derivatives)
    if second_derivatives:
        A, A_x, A_y, A_xx, A_yy = metrics
    else:
        A, A_x, A_y = metrics

    f_val = np.empty((S, m))
    f_x = np.empty_like(f_val)
    f_y = np.empty_like(f_val)
    if second_derivatives:
        f_xx = np.empty_like(f_val)
        f_yy = np.empty_like(f_val)

    for s0 in range(0, S, block_s):
        s1 = min(s0 + block_s, S)
        blk = slice(s0, s1)
        B = s1 - s0

        flat_eval_nodes = idx_rows[blk].reshape(-1)
        current_subgrid_ids = np.repeat(np.arange(s0, s1, dtype=int), m)

        A_current = A[flat_eval_nodes, current_subgrid_ids]
        A_candidates = A[flat_eval_nodes]
        DeltaA = A_current[:, None] - A_candidates

        z = mu * DeltaA
        z_max = np.max(z, axis=1, keepdims=True)
        with np.errstate(under="ignore"):
            R_shift = np.exp(z - z_max)
        R_shift_sum = R_shift.sum(axis=1)
        normalized_R = R_shift / R_shift_sum[:, None]

        f_val_block = np.exp(-z_max.ravel()) / R_shift_sum

        A_x_current = A_x[flat_eval_nodes, current_subgrid_ids]
        A_y_current = A_y[flat_eval_nodes, current_subgrid_ids]
        beta_x = mu * (A_x_current[:, None] - A_x[flat_eval_nodes])
        beta_y = mu * (A_y_current[:, None] - A_y[flat_eval_nodes])
        log_derivative_x = (normalized_R * beta_x).sum(axis=1)
        log_derivative_y = (normalized_R * beta_y).sum(axis=1)

        f_val[blk] = f_val_block.reshape(B, m)
        f_x[blk] = (-f_val_block * log_derivative_x).reshape(B, m)
        f_y[blk] = (-f_val_block * log_derivative_y).reshape(B, m)

        if second_derivatives:
            A_xx_current = A_xx[flat_eval_nodes, current_subgrid_ids]
            A_yy_current = A_yy[flat_eval_nodes, current_subgrid_ids]
            beta_xx = mu * (A_xx_current[:, None] - A_xx[flat_eval_nodes])
            beta_yy = mu * (A_yy_current[:, None] - A_yy[flat_eval_nodes])
            curvature_x = (normalized_R * (beta_xx + beta_x ** 2)).sum(axis=1)
            curvature_y = (normalized_R * (beta_yy + beta_y ** 2)).sum(axis=1)

            f_xx[blk] = (
                f_val_block * (2.0 * log_derivative_x ** 2 - curvature_x)
            ).reshape(B, m)
            f_yy[blk] = (
                f_val_block * (2.0 * log_derivative_y ** 2 - curvature_y)
            ).reshape(B, m)

    if second_derivatives:
        return f_val, f_x, f_y, f_xx, f_yy

    return f_val, f_x, f_y

eval_weight_functions_at_nodes_data_minmax_shift(second_derivatives=True, block_s=128)

Compute active-mode nodal Shepard weights and derivatives.

For each source-node row, only subgrids containing that source node participate in both the contributors and the denominator. The implementation uses shifted log-ratios,

f_i = 1 / sum_j exp(z_j),  z_j = mu * (A_i - A_j)

and evaluates exp(z_j - max(z)) instead of directly forming exp(z_j).

Parameters:

Name Type Description Default
second_derivatives bool

Whether to also return second derivatives of the weights.

True
block_s int

Number of sampled subgrids processed per vectorized block.

128

Returns:

Type Description
tuple[ndarray, ...]

(f, f_x, f_y, f_xx, f_yy) when second_derivatives is true, otherwise (f, f_x, f_y). Each array has shape (S, m).

Source code in src/gbmsc_pde/approximation/shepard.py
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
def eval_weight_functions_at_nodes_data_minmax_shift(
    self,
    second_derivatives=True,
    block_s: int = 128
) -> Union[Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray],
           Tuple[np.ndarray, np.ndarray, np.ndarray]
           ]:
    """
    Compute active-mode nodal Shepard weights and derivatives.

    For each source-node row, only subgrids containing that source node
    participate in both the contributors and the denominator.  The
    implementation uses shifted log-ratios,

        f_i = 1 / sum_j exp(z_j),  z_j = mu * (A_i - A_j)

    and evaluates ``exp(z_j - max(z))`` instead of directly forming
    ``exp(z_j)``.

    Parameters
    ----------
    second_derivatives : bool, default=True
        Whether to also return second derivatives of the weights.
    block_s : int, default=128
        Number of sampled subgrids processed per vectorized block.

    Returns
    -------
    tuple[ndarray, ...]
        ``(f, f_x, f_y, f_xx, f_yy)`` when ``second_derivatives`` is true,
        otherwise ``(f, f_x, f_y)``.  Each array has shape ``(S, m)``.
    """
    mu = self.mu * 0.5
    diff_x, diff_y = self.grid.diff_x, self.grid.diff_y
    dist, logd = self._safe_pairwise_data()

    idx_rows = self.subgrids_step_row
    S, m = idx_rows.shape

    f_val = np.empty((S, m))
    f_x = np.empty_like(f_val)
    f_y = np.empty_like(f_val)
    if second_derivatives:
        f_xx = np.empty_like(f_val)
        f_yy = np.empty_like(f_val)

    for s0 in range(0, S, block_s):
        s1 = min(s0 + block_s, S)
        blk = slice(s0, s1)
        B = s1 - s0

        rows = idx_rows[blk]
        flat_eval_nodes = rows.reshape(-1)
        current_subgrid_ids = np.repeat(np.arange(s0, s1), m)
        current_subgrid_nodes = idx_rows[current_subgrid_ids]

        current_row_index = flat_eval_nodes[:, None]
        current_logd = logd[current_row_index, current_subgrid_nodes]
        current_dx = diff_x[current_row_index, current_subgrid_nodes]
        current_dy = diff_y[current_row_index, current_subgrid_nodes]
        current_dist = dist[current_row_index, current_subgrid_nodes]

        A_current = current_logd.sum(axis=1)
        A_x_current = (2.0 * current_dx / current_dist).sum(axis=1)
        A_y_current = (2.0 * current_dy / current_dist).sum(axis=1)

        candidate_subgrid_ids = self._node_subgrid_ids[flat_eval_nodes]
        candidate_mask = candidate_subgrid_ids != -1
        safe_candidate_ids = np.where(candidate_mask, candidate_subgrid_ids, 0)
        candidate_nodes = idx_rows[safe_candidate_ids]

        row_index = flat_eval_nodes[:, None, None]
        candidate_logd = logd[row_index, candidate_nodes]
        candidate_dx = diff_x[row_index, candidate_nodes]
        candidate_dy = diff_y[row_index, candidate_nodes]
        candidate_dist = dist[row_index, candidate_nodes]

        A_candidates = candidate_logd.sum(axis=2)
        A_x_candidates = (2.0 * candidate_dx / candidate_dist).sum(axis=2)
        A_y_candidates = (2.0 * candidate_dy / candidate_dist).sum(axis=2)

        DeltaA = A_current[:, None] - A_candidates
        DeltaA_x = A_x_current[:, None] - A_x_candidates
        DeltaA_y = A_y_current[:, None] - A_y_candidates

        if second_derivatives:
            A_xx_current = (2.0 / current_dist - 4.0 * (current_dx / current_dist) ** 2).sum(axis=1)
            A_yy_current = (2.0 / current_dist - 4.0 * (current_dy / current_dist) ** 2).sum(axis=1)
            A_xx_candidates = (2.0 / candidate_dist - 4.0 * (candidate_dx / candidate_dist) ** 2).sum(axis=2)
            A_yy_candidates = (2.0 / candidate_dist - 4.0 * (candidate_dy / candidate_dist) ** 2).sum(axis=2)
            DeltaA_xx = A_xx_current[:, None] - A_xx_candidates
            DeltaA_yy = A_yy_current[:, None] - A_yy_candidates

        z = np.where(candidate_mask, mu * DeltaA, -np.inf)
        z_max = np.max(z, axis=1, keepdims=True)

        with np.errstate(under="ignore"):
            R_shift = np.exp(z - z_max)
        R_shift *= candidate_mask

        R_shift_sum = R_shift.sum(axis=1)
        normalized_R = R_shift / R_shift_sum[:, None]

        f_val_block = np.exp(-z_max.ravel()) / R_shift_sum

        beta_x = np.where(candidate_mask, mu * DeltaA_x, 0.0)
        beta_y = np.where(candidate_mask, mu * DeltaA_y, 0.0)
        log_derivative_x = (normalized_R * beta_x).sum(axis=1)
        log_derivative_y = (normalized_R * beta_y).sum(axis=1)

        f_x_block = -f_val_block * log_derivative_x
        f_y_block = -f_val_block * log_derivative_y

        f_val[blk] = f_val_block.reshape(B, m)
        f_x[blk] = f_x_block.reshape(B, m)
        f_y[blk] = f_y_block.reshape(B, m)

        if second_derivatives:
            beta_xx = np.where(candidate_mask, mu * DeltaA_xx, 0.0)
            beta_yy = np.where(candidate_mask, mu * DeltaA_yy, 0.0)
            curvature_x = (normalized_R * (beta_xx + beta_x ** 2)).sum(axis=1)
            curvature_y = (normalized_R * (beta_yy + beta_y ** 2)).sum(axis=1)

            f_xx[blk] = (
                f_val_block * (2.0 * log_derivative_x ** 2 - curvature_x)
            ).reshape(B, m)
            f_yy[blk] = (
                f_val_block * (2.0 * log_derivative_y ** 2 - curvature_y)
            ).reshape(B, m)

    if second_derivatives:
        return f_val, f_x, f_y, f_xx, f_yy

    return f_val, f_x, f_y

eval_weight_functions_at_nodes_nodal_limit(second_derivatives=True, block_s=128)

Compute source-node limiting Shepard weights and derivatives.

For each source-node row, only subgrids containing that source node participate. The common singular factor is cancelled analytically before forming the normalized Shepard fraction. In the vectorized metric sums this is equivalent to using a neutral self-distance and zero self-contributions for first and second metric derivatives.

Source code in src/gbmsc_pde/approximation/shepard.py
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
def eval_weight_functions_at_nodes_nodal_limit(
    self,
    second_derivatives=True,
    block_s: int = 128
) -> Union[Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray],
           Tuple[np.ndarray, np.ndarray, np.ndarray]
           ]:
    """
    Compute source-node limiting Shepard weights and derivatives.

    For each source-node row, only subgrids containing that source node
    participate.  The common singular factor is cancelled analytically
    before forming the normalized Shepard fraction.  In the vectorized
    metric sums this is equivalent to using a neutral self-distance and
    zero self-contributions for first and second metric derivatives.
    """
    mu = self.mu * 0.5
    _, logd, A_x_data, A_y_data, A_xx_data, A_yy_data = self._nodal_limit_pairwise_data()

    idx_rows = self.subgrids_step_row
    S, m = idx_rows.shape

    f_val = np.empty((S, m))
    f_x = np.empty_like(f_val)
    f_y = np.empty_like(f_val)
    if second_derivatives:
        f_xx = np.empty_like(f_val)
        f_yy = np.empty_like(f_val)

    for s0 in range(0, S, block_s):
        s1 = min(s0 + block_s, S)
        blk = slice(s0, s1)
        B = s1 - s0

        rows = idx_rows[blk]
        flat_eval_nodes = rows.reshape(-1)
        current_subgrid_ids = np.repeat(np.arange(s0, s1), m)
        current_subgrid_nodes = idx_rows[current_subgrid_ids]

        current_row_index = flat_eval_nodes[:, None]
        current_logd = logd[current_row_index, current_subgrid_nodes]
        current_A_x = A_x_data[current_row_index, current_subgrid_nodes]
        current_A_y = A_y_data[current_row_index, current_subgrid_nodes]

        A_current = current_logd.sum(axis=1)
        A_x_current = current_A_x.sum(axis=1)
        A_y_current = current_A_y.sum(axis=1)

        candidate_subgrid_ids = self._node_subgrid_ids[flat_eval_nodes]
        candidate_mask = candidate_subgrid_ids != -1
        safe_candidate_ids = np.where(candidate_mask, candidate_subgrid_ids, 0)
        candidate_nodes = idx_rows[safe_candidate_ids]

        row_index = flat_eval_nodes[:, None, None]
        candidate_logd = logd[row_index, candidate_nodes]
        candidate_A_x = A_x_data[row_index, candidate_nodes]
        candidate_A_y = A_y_data[row_index, candidate_nodes]

        A_candidates = candidate_logd.sum(axis=2)
        A_x_candidates = candidate_A_x.sum(axis=2)
        A_y_candidates = candidate_A_y.sum(axis=2)

        DeltaA = A_current[:, None] - A_candidates
        DeltaA_x = A_x_current[:, None] - A_x_candidates
        DeltaA_y = A_y_current[:, None] - A_y_candidates

        if second_derivatives:
            current_A_xx = A_xx_data[current_row_index, current_subgrid_nodes]
            current_A_yy = A_yy_data[current_row_index, current_subgrid_nodes]
            candidate_A_xx = A_xx_data[row_index, candidate_nodes]
            candidate_A_yy = A_yy_data[row_index, candidate_nodes]
            A_xx_current = current_A_xx.sum(axis=1)
            A_yy_current = current_A_yy.sum(axis=1)
            A_xx_candidates = candidate_A_xx.sum(axis=2)
            A_yy_candidates = candidate_A_yy.sum(axis=2)
            DeltaA_xx = A_xx_current[:, None] - A_xx_candidates
            DeltaA_yy = A_yy_current[:, None] - A_yy_candidates

        z = np.where(candidate_mask, mu * DeltaA, -np.inf)
        z_max = np.max(z, axis=1, keepdims=True)

        with np.errstate(under="ignore"):
            R_shift = np.exp(z - z_max)
        R_shift *= candidate_mask

        R_shift_sum = R_shift.sum(axis=1)
        normalized_R = R_shift / R_shift_sum[:, None]

        f_val_block = np.exp(-z_max.ravel()) / R_shift_sum

        beta_x = np.where(candidate_mask, mu * DeltaA_x, 0.0)
        beta_y = np.where(candidate_mask, mu * DeltaA_y, 0.0)
        log_derivative_x = (normalized_R * beta_x).sum(axis=1)
        log_derivative_y = (normalized_R * beta_y).sum(axis=1)

        f_x_block = -f_val_block * log_derivative_x
        f_y_block = -f_val_block * log_derivative_y

        f_val[blk] = f_val_block.reshape(B, m)
        f_x[blk] = f_x_block.reshape(B, m)
        f_y[blk] = f_y_block.reshape(B, m)

        if second_derivatives:
            beta_xx = np.where(candidate_mask, mu * DeltaA_xx, 0.0)
            beta_yy = np.where(candidate_mask, mu * DeltaA_yy, 0.0)
            curvature_x = (normalized_R * (beta_xx + beta_x ** 2)).sum(axis=1)
            curvature_y = (normalized_R * (beta_yy + beta_y ** 2)).sum(axis=1)

            f_xx[blk] = (
                f_val_block * (2.0 * log_derivative_x ** 2 - curvature_x)
            ).reshape(B, m)
            f_yy[blk] = (
                f_val_block * (2.0 * log_derivative_y ** 2 - curvature_y)
            ).reshape(B, m)

    if second_derivatives:
        return f_val, f_x, f_y, f_xx, f_yy

    return f_val, f_x, f_y

interpolator(x, y, u, *, return_derivatives=False, chunk=1000, interpolation_mode='exact_nodal', tolerance=1e-12, Mx=None, My=None)

Interpolate a source-node field at arbitrary coordinates.

Query interpolation uses all sampled subgrids as contributors and normalizes the Shepard weights over all sampled subgrids. Computation is chunked and performed in log space to avoid overflow in the raw weights.

interpolation_mode="exact_nodal" returns exact nodal values when a query point coincides with a source node within tolerance. Other query points use true distances without an epsilon floor.

interpolation_mode="regularized" preserves the legacy epsilon-floor behavior for all query points.

Parameters:

Name Type Description Default
x (array_like, shape(n_eval))

Query coordinates.

required
y (array_like, shape(n_eval))

Query coordinates.

required
u (array_like, shape(N))

Source-node values ordered like grid.coords.

required
return_derivatives bool

If true, also return first derivatives du/dx and du/dy.

False
chunk int

Number of query points processed per block.

1000
interpolation_mode (exact_nodal, regularized)

Query distance policy.

"exact_nodal"
tolerance float

Source-node hit tolerance for "exact_nodal" mode.

1e-12
Mx sparse matrices

Existing first-derivative operators. When return_derivatives=True and source-node hits are present, these matrices are reused instead of rebuilding operators.

None
My sparse matrices

Existing first-derivative operators. When return_derivatives=True and source-node hits are present, these matrices are reused instead of rebuilding operators.

None

Returns:

Type Description
tuple

(u_eval,) or (u_eval, u_x, u_y).

Source code in src/gbmsc_pde/approximation/shepard.py
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
def interpolator(
    self,
    x: np.ndarray,
    y: np.ndarray,
    u: np.ndarray,
    *,
    return_derivatives: bool = False,
    chunk: int = 1000,
    interpolation_mode: str = "exact_nodal",
    tolerance: float = 1e-12,
    Mx=None,
    My=None,
) -> Union[
    Tuple[np.ndarray],
    Tuple[np.ndarray, np.ndarray, np.ndarray]
]:
    """
    Interpolate a source-node field at arbitrary coordinates.

    Query interpolation uses all sampled subgrids as contributors and
    normalizes the Shepard weights over all sampled subgrids.  Computation
    is chunked and performed in log space to avoid overflow in the raw
    weights.

    ``interpolation_mode="exact_nodal"`` returns exact nodal values when a
    query point coincides with a source node within ``tolerance``.  Other
    query points use true distances without an epsilon floor.

    ``interpolation_mode="regularized"`` preserves the legacy epsilon-floor
    behavior for all query points.

    Parameters
    ----------
    x, y : array_like, shape (n_eval,)
        Query coordinates.
    u : array_like, shape (grid.N,)
        Source-node values ordered like ``grid.coords``.
    return_derivatives : bool, default=False
        If true, also return first derivatives ``du/dx`` and ``du/dy``.
    chunk : int, default=1000
        Number of query points processed per block.
    interpolation_mode : {"exact_nodal", "regularized"}, default="exact_nodal"
        Query distance policy.
    tolerance : float, default=1e-12
        Source-node hit tolerance for ``"exact_nodal"`` mode.
    Mx, My : sparse matrices, optional
        Existing first-derivative operators.  When
        ``return_derivatives=True`` and source-node hits are present, these
        matrices are reused instead of rebuilding operators.

    Returns
    -------
    tuple
        ``(u_eval,)`` or ``(u_eval, u_x, u_y)``.
    """
    xq = np.asarray(x, dtype=float).ravel()
    yq = np.asarray(y, dtype=float).ravel()
    u = np.asarray(u, dtype=float).ravel()
    if xq.size != yq.size:
        raise ValueError("x and y arrays must have same length.")
    if u.size != self.grid.N:
        raise ValueError("`u` must have length grid.N")
    if interpolation_mode not in ("exact_nodal", "regularized"):
        raise ValueError("interpolation_mode must be 'exact_nodal' or 'regularized'.")
    if tolerance < 0:
        raise ValueError("tolerance must be non-negative.")

    l = xq.size
    chunk = max(chunk, 10)

    val = np.empty(l)
    if return_derivatives:
        ux = np.empty_like(val)
        uy = np.empty_like(val)

    hit_nodes = np.full(l, -1, dtype=int)
    if interpolation_mode == "exact_nodal":
        hit_nodes = self._source_node_hits(
            xq,
            yq,
            tolerance=tolerance,
            chunk=chunk,
        )
        hit_mask = hit_nodes != -1
        if np.any(hit_mask):
            val[hit_mask] = u[hit_nodes[hit_mask]]
            if return_derivatives:
                if Mx is None or My is None:
                    from ..operators.differential import build_differential_operators

                    Mx_built, My_built, _, _ = build_differential_operators(self)
                    if Mx is None:
                        Mx = Mx_built
                    if My is None:
                        My = My_built
                ux[hit_mask] = Mx.tocsr()[hit_nodes[hit_mask]].dot(u)
                uy[hit_mask] = My.tocsr()[hit_nodes[hit_mask]].dot(u)

    # Nodal values per sub-grid
    U = u[self.subgrids_step_row]  # (S, m)

    x_lines = self._x_lines
    y_lines = self._y_lines
    x_weights = self._x_lagrange_weights
    y_weights = self._y_lagrange_weights

    Sx, nx = x_lines.shape
    Sy, ny = y_lines.shape
    m = nx * ny
    S = Sx * Sy

    for q0 in range(0, l, chunk):
        q1 = min(q0 + chunk, l)
        block_indices = np.arange(q0, q1)
        if interpolation_mode == "exact_nodal":
            block_indices = block_indices[hit_nodes[q0:q1] == -1]
            if block_indices.size == 0:
                continue

        xs = xq[block_indices]
        ys = yq[block_indices]
        l_b = block_indices.size

        P_parts = self._normalized_weights_at_queries_stable(
            xs,
            ys,
            return_derivatives=return_derivatives,
            regularized=interpolation_mode == "regularized",
        )
        P = P_parts[0]
        if return_derivatives:
            Px, Py = P_parts[1], P_parts[2]

        Lx = np.empty((l_b, Sx, nx))
        Ly = np.empty((l_b, Sy, ny))
        if return_derivatives:
            dLx = np.empty_like(Lx)
            dLy = np.empty_like(Ly)

        for s in range(Sx):
            if return_derivatives:
                Lx[:, s], dLx[:, s] = lagrange_1d(
                    x_lines[s],
                    xs,
                    with_first_derivatives=True,
                    barycentric_weights=x_weights[s],
                )
            else:
                Lx[:, s] = lagrange_1d(
                    x_lines[s],
                    xs,
                    with_first_derivatives=False,
                    barycentric_weights=x_weights[s],
                )[0]

        for s in range(Sy):
            if return_derivatives:
                Ly[:, s], dLy[:, s] = lagrange_1d(
                    y_lines[s],
                    ys,
                    with_first_derivatives=True,
                    barycentric_weights=y_weights[s],
                )
            else:
                Ly[:, s] = lagrange_1d(
                    y_lines[s],
                    ys,
                    with_first_derivatives=False,
                    barycentric_weights=y_weights[s],
                )[0]

        Phi = (Lx[:, :, None, :, None] * Ly[:, None, :, None, :]).reshape(l_b, S, m)

        Li = np.einsum('qsm,sm->qs', Phi, U, optimize=True)
        val[block_indices] = (P * Li).sum(axis=1)

        if return_derivatives:
            Phi_x = (dLx[:, :, None, :, None] * Ly[:, None, :, None, :]).reshape(l_b, S, m)
            Phi_y = (Lx[:, :, None, :, None] * dLy[:, None, :, None, :]).reshape(l_b, S, m)
            Li_x = np.einsum('qsm,sm->qs', Phi_x, U, optimize=True)
            Li_y = np.einsum('qsm,sm->qs', Phi_y, U, optimize=True)
            ux[block_indices] = (P * Li_x + Px * Li).sum(axis=1)
            uy[block_indices] = (P * Li_y + Py * Li).sum(axis=1)

    if return_derivatives:
        return val, ux, uy
    return (val,)

lagrange_derivatives_x_direction()

Return repeated 1D Lagrange derivative matrices in the x direction.

Source code in src/gbmsc_pde/approximation/shepard.py
822
823
824
825
826
def lagrange_derivatives_x_direction(self):
    """Return repeated 1D Lagrange derivative matrices in the x direction."""
    l = len(self.subgrids_x_step) 
    (I, L1, L2) = self._lagrange_derivatives_one_subgrids_1dim(self.grid.subgrids_x_coords[0])
    return (I[None, :, :].repeat(l, axis=0), L1[None, :, :].repeat(l, axis=0), L2[None, :, :].repeat(l, axis=0))

lagrange_derivatives_y_direction()

Return repeated 1D Lagrange derivative matrices in the y direction.

Source code in src/gbmsc_pde/approximation/shepard.py
828
829
830
831
832
def lagrange_derivatives_y_direction(self):
    """Return repeated 1D Lagrange derivative matrices in the y direction."""
    (I, L1, L2) = self._lagrange_derivatives_one_subgrids_1dim(self.grid.subgrids_y_coords[0])
    l = len(self.subgrids_y_step)
    return (I[None, :, :].repeat(l, axis=0), L1[None, :, :].repeat(l, axis=0), L2[None, :, :].repeat(l, axis=0))

gbmsc_pde.approximation.shepard.lagrange_1d(X_nodes, xq=None, *, with_first_derivatives=True, with_second_derivatives=False, barycentric_weights=None)

Barycentric Lagrange basis — log-stable and unified.

Parameters:

Name Type Description Default
X_nodes (m,) ndarray(float)

Distinct node coordinates.

required
xq Optional[ndarray]

Query points. If None, the function treats xq = X_nodes (nodal mode). Returned L is then the identity matrix I.

None
with_first_derivatives bool

Return first derivatives L' as well.

True
with_second_derivatives bool

Return second derivatives L'' in addition (only valid if with_first_derivatives is True).

False

Returns:

Type Description
Query mode (`xq` not None)

L : (l, m) L, Lp : if with_first_derivatives L, Lp, Lpp : if with_second_derivatives

Nodal mode (`xq` is None → treated as `xq=X_nodes`)

I, L1 : if with_first_derivatives I, L1, L2 : if with_second_derivatives I : if both derivative flags are False

Source code in src/gbmsc_pde/approximation/shepard.py
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
def lagrange_1d(
        X_nodes: np.ndarray,                                # (m,) nodal abscissae
        xq: Optional[np.ndarray] = None,                    # (l,) query points
        *,
        with_first_derivatives: bool  = True,
        with_second_derivatives: bool = False,
        barycentric_weights: Optional[np.ndarray] = None,
    ) -> Union[
        Tuple[np.ndarray],                               # L
        Tuple[np.ndarray, np.ndarray],                   # L,  L'
        Tuple[np.ndarray, np.ndarray, np.ndarray]        # L,  L', L''
    ]:
        """
        Barycentric Lagrange basis — **log-stable** and unified.

        Parameters
        ----------
        X_nodes : (m,) ndarray(float)
            Distinct node coordinates.
        xq      : (l,) ndarray or *None*
            Query points.  If *None*, the function **treats `xq = X_nodes`**
            (nodal mode).  Returned `L` is then the identity matrix `I`.
        with_first_derivatives  : bool, default False
            Return first derivatives  L'  as well.
        with_second_derivatives : bool, default False
            Return second derivatives L''  in addition (only valid if
            `with_first_derivatives` is True).

        Returns
        -------
        Query mode  (`xq` not None)
            L            : (l, m)
            L, Lp        : if `with_first_derivatives`
            L, Lp, Lpp   : if `with_second_derivatives`

        Nodal mode   (`xq` is None → treated as `xq=X_nodes`)
            I, L1                : if `with_first_derivatives`
            I, L1, L2            : if `with_second_derivatives`
            I                    : if both derivative flags are False
        """
        X_nodes = np.asarray(X_nodes, dtype=float)
        m = X_nodes.size
        nodal_mode = xq is None

        if barycentric_weights is None:
            w = _barycentric_weights_1d(X_nodes)
        else:
            w = np.asarray(barycentric_weights, dtype=float)
            if w.shape != (m,):
                raise ValueError("barycentric_weights must have shape (len(X_nodes),).")

        # ============================================================
        # === nodal mode  (use X_nodes as queries) ===================
        # ============================================================
        if nodal_mode:
            diff_mat = X_nodes[:, None] - X_nodes[None, :]
            np.fill_diagonal(diff_mat, 1.0)
            diag = np.eye(m, dtype=bool)
            L = np.eye(m)                                  

            if not with_first_derivatives:
                return L

            # First derivative
            with np.errstate(divide='ignore', invalid='ignore'):
                L1 = np.where(
                    diag, 
                    0.0, 
                    (w[None, :] / (w[:, None] * diff_mat))
                )
            L1[diag] = -L1.sum(axis=1)

            if not with_second_derivatives:
                return (L, L1)

            # Second derivative
            inv  = 1.0/diff_mat
            np.fill_diagonal(inv, 0.0)
            Svec = inv.sum(axis=1)

            with np.errstate(divide="ignore", invalid="ignore"):
                L2 = np.where(
                    diag, 
                    0.0,
                    2 * L1 * (Svec[:, None] - inv)
                )
            L2[diag] = -L2.sum(axis=1)

            return L, L1, L2
        else:
            xq = np.asarray(xq, dtype=float).ravel()
            l  = xq.size
            L  = np.zeros((l, m))
            tol   = 1e-14 * max(1.0, np.abs(X_nodes).max())      # scale-aware tol
            # ------------------------------------------------------------
            # Basis values at queries
            # ------------------------------------------------------------
            diff_q = xq[:, None] - X_nodes[None, :]                 # (l,m)
            hits = np.isclose(diff_q, 0.0, atol=tol)               # (l,m) bool mask

            if hits.any():
                rows, cols = np.nonzero(hits)                    # indices of coincidences

                # ----- pre-compute nodal derivative matrices once ----------
                _, L1, L2 = lagrange_1d(
                    X_nodes,
                    xq=None,
                    with_first_derivatives=True,
                    with_second_derivatives=True,
                    barycentric_weights=w,
                )

                # overwrite rows that contain a hit with exact values
                # value basis:
                L[rows, cols] = 1.0

                # first derivative if needed
                if with_first_derivatives:
                    Lp            = np.zeros_like(L)
                    Lp[rows, :]   = L1[cols, :]

                # second derivative if needed
                if with_second_derivatives:
                    Lpp            = np.zeros_like(L)
                    Lpp[rows, :]   = L2[cols, :]

                # for all **other** rows we can safely compute with the standard formula
                safe_mask = ~hits.any(axis=1)        # rows without any zero diff
                if safe_mask.any():
                    i_ok = np.nonzero(safe_mask)[0]          # row indices
                    diff_ok = diff_q[i_ok]                   # (l_ok, m)
                    bary_ok  = w / diff_ok
                    denom   = bary_ok.sum(axis=1, keepdims=True)
                    L[i_ok] = bary_ok / denom

                    if with_first_derivatives:
                        B = (bary_ok / diff_ok).sum(axis=1, keepdims=True)
                        A = B / denom
                        Lp[i_ok] = L[i_ok] * (A - 1.0 / diff_ok)

                        if with_second_derivatives:
                            C = (bary_ok / diff_ok**2).sum(axis=1, keepdims=True)
                            Lpp[i_ok] = L[i_ok] * (
                                2.0 / diff_ok**2
                                - 2.0 * C / denom
                                - 2.0 * A / diff_ok
                                + 2.0 * A**2
                            )
                #
                if not with_first_derivatives:
                    return (L,)

                if not with_second_derivatives:
                    return (L, Lp)
                return L, Lp, Lpp
            else:
                # no coincidences – original fast path
                bary_q  = w / diff_q                                    # (l,m)
                denom  = bary_q.sum(axis=1, keepdims=True)              # (l,1)
                L      = bary_q / denom                                 # (l,m)

                if not with_first_derivatives:
                    return (L,)

                # ------------------------------------------------------------
                # First derivatives
                # ------------------------------------------------------------
                B = (bary_q / diff_q).sum(axis=1, keepdims=True)
                A = B / denom
                Lp = L * (A - 1.0 / diff_q)                             # (l,m)

                if not with_second_derivatives:
                    return (L, Lp)

                # ------------------------------------------------------------
                # Second derivatives
                # ------------------------------------------------------------
                C = (bary_q / diff_q**2).sum(axis=1, keepdims=True)
                Lpp = L * (
                    2.0 / diff_q**2
                    - 2.0 * C / denom
                    - 2.0 * A / diff_q
                    + 2.0 * A**2
                )
                return L, Lp, Lpp

gbmsc_pde.operators.differential.build_differential_operators(approximation)

Build sparse nodal derivative operators on the source grid.

The returned matrices act on flattened source-node vectors ordered like approximation.grid.coords. Rows are evaluated at source nodes. The row support is determined by approximation.support_mode:

"active" Active contributors and active denominator; this is the original rectangular sparse PDE mode. "all" Active contributors with an all-subgrid denominator for nodal rows. "nodal_limit" Active source-node contributors with the common singular factor cancelled before weight derivatives are evaluated.

Parameters:

Name Type Description Default
approximation GBMSCApproximation

Prepared Grid-Based Shepard approximation.

required

Returns:

Type Description
Mx, My, Mxx, Myy : tuple[spmatrix, spmatrix, spmatrix, spmatrix]

Sparse first- and second-derivative matrices.

Source code in src/gbmsc_pde/operators/differential.py
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
def build_differential_operators(
    approximation: GBMSCApproximation,
) -> Tuple[spmatrix, spmatrix, spmatrix, spmatrix]:
    """
    Build sparse nodal derivative operators on the source grid.

    The returned matrices act on flattened source-node vectors ordered like
    ``approximation.grid.coords``.  Rows are evaluated at source nodes.  The
    row support is determined by ``approximation.support_mode``:

    ``"active"``
        Active contributors and active denominator; this is the original
        rectangular sparse PDE mode.
    ``"all"``
        Active contributors with an all-subgrid denominator for nodal rows.
    ``"nodal_limit"``
        Active source-node contributors with the common singular factor
        cancelled before weight derivatives are evaluated.

    Parameters
    ----------
    approximation : GBMSCApproximation
        Prepared Grid-Based Shepard approximation.

    Returns
    -------
    Mx, My, Mxx, Myy : tuple[spmatrix, spmatrix, spmatrix, spmatrix]
        Sparse first- and second-derivative matrices.
    """
    support_mode = getattr(approximation, "support_mode", "active")
    cache_name = f"_differential_operator_cache_{support_mode}"
    cached = getattr(approximation, cache_name, None)
    if cached is not None:
        return cached

    grid = approximation.grid
    n_global_x, n_global_y = grid.grid_shape
    n_local_x, n_local_y = grid.subgrid_shape

    L0_x, L1_x, L2_x = approximation._lagrange_derivatives_one_subgrids_1dim(
        grid.subgrids_x_coords[0]
    )
    L0_y, L1_y, L2_y = approximation._lagrange_derivatives_one_subgrids_1dim(
        grid.subgrids_y_coords[0]
    )

    L0_x = np.tile(L0_x, (n_local_y, 1, 1)).reshape(-1, n_local_x)[None, :]
    L1_x = np.tile(L1_x, (n_local_y, 1, 1)).reshape(-1, n_local_x)[None, :]
    L2_x = np.tile(L2_x, (n_local_y, 1, 1)).reshape(-1, n_local_x)[None, :]

    L0_y = np.tile(L0_y, (n_local_x, 1, 1)).reshape(-1, n_local_y)[None, :]
    L1_y = np.tile(L1_y, (n_local_x, 1, 1)).reshape(-1, n_local_y)[None, :]
    L2_y = np.tile(L2_y, (n_local_x, 1, 1)).reshape(-1, n_local_y)[None, :]

    idx0 = approximation.subgrids_step_row
    if support_mode == "nodal_limit":
        f_val, f_x, f_y, f_xx, f_yy = approximation.eval_weight_functions_at_nodes_nodal_limit()
    elif support_mode == "all":
        f_val, f_x, f_y, f_xx, f_yy = (
            approximation.eval_weight_functions_at_nodes_all_denominator_minmax_shift()
        )
    else:
        f_val, f_x, f_y, f_xx, f_yy = approximation.eval_weight_functions_at_nodes_data_minmax_shift()

    idxy = idx0.reshape(-1, n_local_x, n_local_y)
    idxy_row, idxy_column = _construct_3d_from_list_of_matrices(idxy)
    f_val_toy = f_val.reshape(-1, n_local_y * n_local_x)[:, :, None]
    f_y = f_y.reshape(-1, n_local_y * n_local_x)[:, :, None]
    f_yy = f_yy.reshape(-1, n_local_y * n_local_x)[:, :, None]
    M_values_yy = f_yy * L0_y + 2 * f_y * L1_y + f_val_toy * L2_y
    M_values_y = f_y * L0_y + f_val_toy * L1_y

    Myy = coo_matrix(
        (
            M_values_yy.ravel(),
            (idxy_row.ravel(), idxy_column.ravel()),
        ),
        shape=(n_global_x * n_global_y, n_global_x * n_global_y),
    ).tocsr()
    My = coo_matrix(
        (
            M_values_y.ravel(),
            (idxy_row.ravel(), idxy_column.ravel()),
        ),
        shape=(n_global_x * n_global_y, n_global_x * n_global_y),
    ).tocsr()

    idxx = idx0.reshape(-1, n_local_y, n_local_x, order="F")
    idxx_row, idxx_column = _construct_3d_from_list_of_matrices(idxx)
    f_val_tox = f_val.reshape(-1, n_local_y, n_local_x, order="F").reshape(-1, n_local_y * n_local_x)[
        :, :, None
    ]
    f_x = f_x.reshape(-1, n_local_y, n_local_x, order="F").reshape(-1, n_local_y * n_local_x)[:, :, None]
    f_xx = f_xx.reshape(-1, n_local_y, n_local_x, order="F").reshape(-1, n_local_y * n_local_x)[:, :, None]
    M_values_xx = f_xx * L0_x + 2 * f_x * L1_x + f_val_tox * L2_x
    M_values_x = f_x * L0_x + f_val_tox * L1_x

    Mxx = coo_matrix(
        (
            M_values_xx.ravel(),
            (idxx_row.ravel(), idxx_column.ravel()),
        ),
        shape=(n_global_x * n_global_y, n_global_x * n_global_y),
    ).tocsr()
    Mx = coo_matrix(
        (
            M_values_x.ravel(),
            (idxx_row.ravel(), idxx_column.ravel()),
        ),
        shape=(n_global_x * n_global_y, n_global_x * n_global_y),
    ).tocsr()

    setattr(approximation, cache_name, (Mx, My, Mxx, Myy))
    return getattr(approximation, cache_name)

gbmsc_pde.pde.problem.LinearPDE

Linear PDE builder on a structured rectangular source grid.

The assembled equation has the form

div(D grad u) + v . grad u + r u = f

where diffusion and convection coefficients may be scalar, two-component constants, or field callables. Boundary conditions are applied separately by the solver/boundary-condition layer.

Source code in src/gbmsc_pde/pde/problem.py
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
class LinearPDE:
    """
    Linear PDE builder on a structured rectangular source grid.

    The assembled equation has the form

    ``div(D grad u) + v . grad u + r u = f``

    where diffusion and convection coefficients may be scalar, two-component
    constants, or field callables.  Boundary conditions are applied separately
    by the solver/boundary-condition layer.
    """

    def __init__(self, approximation: GBMSCApproximation) -> None:
        self.approximation = approximation
        self.terms: Dict[str, object] = {
            "diffusion": None,
            "convection": None,
            "reaction": None,
            "source": None,
        }

    def add_diffusion_term(self, coeff) -> None:
        """Add diffusion coefficients for ``div(D grad u)``."""
        self.terms["diffusion"] = normalize_vector_coefficient(coeff)

    def add_convection_term(self, coeff) -> None:
        """Add convection coefficients for ``v . grad u``."""
        self.terms["convection"] = normalize_vector_coefficient(coeff)

    def add_reaction_term(self, coeff) -> None:
        """Add reaction coefficient ``r`` for ``r*u``."""
        self.terms["reaction"] = normalize_scalar_coefficient(coeff, name="coeff")

    def add_source_term(self, source) -> None:
        """Add right-hand side source field ``f``."""
        self.terms["source"] = normalize_scalar_coefficient(source, name="source")

    def assemble(self) -> tuple[spmatrix, np.ndarray, spmatrix, spmatrix, spmatrix, spmatrix]:
        """
        Assemble ``A u = b`` on all rectangular source nodes.

        Returns
        -------
        A, b, Mx, My, Mxx, Myy
            Sparse PDE matrix, right-hand side, first-derivative matrices, and
            second-derivative matrices.
        """
        return assemble_linear_system(self.approximation, self.terms)

add_convection_term(coeff)

Add convection coefficients for v . grad u.

Source code in src/gbmsc_pde/pde/problem.py
37
38
39
def add_convection_term(self, coeff) -> None:
    """Add convection coefficients for ``v . grad u``."""
    self.terms["convection"] = normalize_vector_coefficient(coeff)

add_diffusion_term(coeff)

Add diffusion coefficients for div(D grad u).

Source code in src/gbmsc_pde/pde/problem.py
33
34
35
def add_diffusion_term(self, coeff) -> None:
    """Add diffusion coefficients for ``div(D grad u)``."""
    self.terms["diffusion"] = normalize_vector_coefficient(coeff)

add_reaction_term(coeff)

Add reaction coefficient r for r*u.

Source code in src/gbmsc_pde/pde/problem.py
41
42
43
def add_reaction_term(self, coeff) -> None:
    """Add reaction coefficient ``r`` for ``r*u``."""
    self.terms["reaction"] = normalize_scalar_coefficient(coeff, name="coeff")

add_source_term(source)

Add right-hand side source field f.

Source code in src/gbmsc_pde/pde/problem.py
45
46
47
def add_source_term(self, source) -> None:
    """Add right-hand side source field ``f``."""
    self.terms["source"] = normalize_scalar_coefficient(source, name="source")

assemble()

Assemble A u = b on all rectangular source nodes.

Returns:

Type Description
(A, b, Mx, My, Mxx, Myy)

Sparse PDE matrix, right-hand side, first-derivative matrices, and second-derivative matrices.

Source code in src/gbmsc_pde/pde/problem.py
49
50
51
52
53
54
55
56
57
58
59
def assemble(self) -> tuple[spmatrix, np.ndarray, spmatrix, spmatrix, spmatrix, spmatrix]:
    """
    Assemble ``A u = b`` on all rectangular source nodes.

    Returns
    -------
    A, b, Mx, My, Mxx, Myy
        Sparse PDE matrix, right-hand side, first-derivative matrices, and
        second-derivative matrices.
    """
    return assemble_linear_system(self.approximation, self.terms)

gbmsc_pde.boundary.conditions.BoundaryConditions

Boundary-condition container for rectangular source-node rows.

Conditions are registered by flattened source-node id. Dirichlet rows replace the corresponding PDE row by u_i = value. Neumann and Robin rows use the derivative matrices assembled by the PDE solver. Scalars are broadcast to all supplied nodes; arrays must have the same length as nodes.

Source code in src/gbmsc_pde/boundary/conditions.py
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
class BoundaryConditions:
    """
    Boundary-condition container for rectangular source-node rows.

    Conditions are registered by flattened source-node id.  Dirichlet rows
    replace the corresponding PDE row by ``u_i = value``.  Neumann and Robin
    rows use the derivative matrices assembled by the PDE solver.  Scalars are
    broadcast to all supplied nodes; arrays must have the same length as
    ``nodes``.
    """

    def __init__(self, grid: SourceGrid) -> None:
        self.grid = grid
        self.dirichlet: Dict[int, float] = {}
        self.neumann: Dict[int, Dict[str, Union[Tuple[float, float], float]]] = {}
        self.robin: Dict[int, Dict[str, Union[Tuple[float, float], float]]] = {}
        self.second_neumann: Dict[int, Dict[str, Union[Tuple[float, float], float, int]]] = {}

    def add_dirichlet(
        self,
        nodes: Union[int, np.ndarray],
        values: Union[float, np.ndarray],
    ) -> None:
        """
        Add Dirichlet conditions ``u_i = value`` on rectangular grid nodes.

        Parameters
        ----------
        nodes : int or ndarray
            Flattened source-node ids.
        values : float or ndarray
            Scalar value or one value per node.
        """
        nodes_arr = np.atleast_1d(nodes).astype(int)
        vals_arr = np.atleast_1d(values).astype(float)
        if vals_arr.size == 1:
            vals_arr = np.full(nodes_arr.shape, vals_arr.item(), dtype=float)
        if nodes_arr.size != vals_arr.size:
            raise ValueError(f"Mismatched nodes ({nodes_arr.size}) and values ({vals_arr.size}).")

        n_nodes = getattr(self.grid, "N", None)
        if n_nodes is None:
            raise AttributeError("SourceGrid must define total node count 'N'.")
        if np.any(nodes_arr < 0) or np.any(nodes_arr >= n_nodes):
            raise ValueError(f"Dirichlet indices out of [0, {n_nodes}): {nodes_arr}")

        for node, val in zip(nodes_arr, vals_arr):
            self.dirichlet[int(node)] = float(val)

    def add_neumann(
        self,
        nodes: Union[int, np.ndarray],
        outwardnormal: Union[Tuple[float, float], Tuple[np.ndarray, np.ndarray]],
        fluxes: Union[float, np.ndarray],
    ) -> None:
        """
        Add Neumann conditions ``du/dn = flux`` on grid nodes.

        Parameters
        ----------
        nodes : int or ndarray
            Flattened source-node ids.
        outwardnormal : tuple
            Normal components ``(n_x, n_y)`` as scalars or arrays.
        fluxes : float or ndarray
            Scalar flux or one flux per node.
        """
        nodes_arr = np.atleast_1d(nodes).astype(int)
        k = nodes_arr.size

        if not (isinstance(outwardnormal, tuple) and len(outwardnormal) == 2):
            raise TypeError("`outwardnormal` must be a tuple of length 2.")
        nx, ny = outwardnormal

        if np.isscalar(nx) and np.isscalar(ny):
            nx_arr = np.full(k, float(nx))
            ny_arr = np.full(k, float(ny))
        else:
            nx_arr = np.atleast_1d(nx).astype(float)
            ny_arr = np.atleast_1d(ny).astype(float)
        if nx_arr.shape != (k,) or ny_arr.shape != (k,):
            raise ValueError("`outwardnormal` components must match length of `nodes`.")

        flux_arr = np.atleast_1d(fluxes).astype(float)
        if flux_arr.size == 1:
            flux_arr = np.full(k, flux_arr.item())
        if flux_arr.shape != (k,):
            raise ValueError("`fluxes` must be scalar or match length of `nodes`.")

        n_nodes = getattr(self.grid, "N", None)
        if n_nodes is None:
            raise AttributeError("BoundaryConditions requires `self.grid.N`.")
        if np.any(nodes_arr < 0) or np.any(nodes_arr >= n_nodes):
            raise ValueError(f"Node indices must be in [0, {n_nodes}); got {nodes_arr}.")

        for node, nx_val, ny_val, flux_val in zip(nodes_arr, nx_arr, ny_arr, flux_arr):
            self.neumann[int(node)] = {
                "normal": (float(nx_val), float(ny_val)),
                "flux": float(flux_val),
            }

    def add_robin(
        self,
        nodes: Union[int, np.ndarray],
        outwardnormal: Union[Tuple[float, float], Tuple[np.ndarray, np.ndarray]],
        alphas: Union[float, np.ndarray],
        betas: Union[float, np.ndarray],
        values: Union[float, np.ndarray],
    ) -> None:
        """
        Add Robin conditions ``alpha*u + beta*du/dn = value`` on grid nodes.

        ``alphas``, ``betas``, and ``values`` may be scalars or arrays with
        one entry per node.
        """
        nodes_arr = np.atleast_1d(nodes).astype(int)
        k = nodes_arr.size

        if not (isinstance(outwardnormal, tuple) and len(outwardnormal) == 2):
            raise TypeError("`outwardnormal` must be a tuple (nx, ny).")
        nx, ny = outwardnormal
        nx_arr = np.full(k, nx, dtype=float) if np.isscalar(nx) else np.atleast_1d(nx).astype(float)
        ny_arr = np.full(k, ny, dtype=float) if np.isscalar(ny) else np.atleast_1d(ny).astype(float)
        if nx_arr.shape != (k,) or ny_arr.shape != (k,):
            raise ValueError("`outwardnormal` components must match length of `nodes`.")

        alpha_arr = np.atleast_1d(alphas).astype(float)
        beta_arr = np.atleast_1d(betas).astype(float)
        value_arr = np.atleast_1d(values).astype(float)

        if alpha_arr.size == 1:
            alpha_arr = np.full(k, alpha_arr.item(), dtype=float)
        if beta_arr.size == 1:
            beta_arr = np.full(k, beta_arr.item(), dtype=float)
        if value_arr.size == 1:
            value_arr = np.full(k, value_arr.item(), dtype=float)

        if not (alpha_arr.size == beta_arr.size == value_arr.size == k):
            raise ValueError(
                f"Sizes must match: nodes({k}), alphas({alpha_arr.size}), "
                f"betas({beta_arr.size}), values({value_arr.size})."
            )

        n_nodes = getattr(self.grid, "N", None)
        if n_nodes is None:
            raise AttributeError("SourceGrid must define total node count 'N'.")
        if np.any(nodes_arr < 0) or np.any(nodes_arr >= n_nodes):
            raise ValueError(f"Node indices out of [0, {n_nodes}): {nodes_arr}")

        for node, nx_val, ny_val, alpha, beta, value in zip(
            nodes_arr, nx_arr, ny_arr, alpha_arr, beta_arr, value_arr
        ):
            self.robin[int(node)] = {
                "normal": (float(nx_val), float(ny_val)),
                "alpha": float(alpha),
                "beta": float(beta),
                "value": float(value),
            }

    def add_neumann_as_second_condition(
        self,
        nodes: Union[int, np.ndarray],
        outwardnormal: Union[Tuple[float, float], Tuple[np.ndarray, np.ndarray]],
        fluxes: Union[float, np.ndarray],
        rows: Union[int, np.ndarray],
    ) -> None:
        """
        Add Neumann equations on user-selected matrix rows.

        This compatibility method is for augmented systems where a Neumann
        boundary equation should be imposed as an additional/second condition
        rather than replacing the row associated with ``node``.
        """
        if not hasattr(self.grid, "N"):
            raise AttributeError("BoundaryConditions.grid must define integer `.N`")

        nodes_arr = np.atleast_1d(nodes).astype(int)
        rows_arr = np.atleast_1d(rows).astype(int)

        if nodes_arr.ndim != 1 or rows_arr.ndim != 1:
            raise TypeError("`nodes` and `rows` must be scalars or 1D sequences")

        n = nodes_arr.size
        if rows_arr.size != n:
            raise ValueError(f"`rows` length ({rows_arr.size}) != `nodes` length ({n})")

        if not (isinstance(outwardnormal, tuple) and len(outwardnormal) == 2):
            raise TypeError("`outwardnormal` must be a tuple of two elements")
        nx_in, ny_in = outwardnormal

        try:
            nx_arr = np.broadcast_to(nx_in, (n,)).astype(float)
            ny_arr = np.broadcast_to(ny_in, (n,)).astype(float)
        except Exception as exc:
            raise ValueError(
                "Cannot broadcast `outwardnormal` components to match `nodes` length"
            ) from exc

        try:
            flux_arr = np.broadcast_to(fluxes, (n,)).astype(float)
        except Exception as exc:
            raise ValueError("Cannot broadcast `fluxes` to match `nodes` length") from exc

        if np.any(nodes_arr < 0) or np.any(nodes_arr >= self.grid.N):
            raise ValueError(f"All `nodes` must be in [0, {self.grid.N})")

        for node, row, nx_val, ny_val, flux in zip(nodes_arr, rows_arr, nx_arr, ny_arr, flux_arr):
            self.second_neumann[int(node)] = {
                "normal": (float(nx_val), float(ny_val)),
                "flux": float(flux),
                "row": int(row),
            }

    def apply(
        self,
        A: spmatrix,
        b: np.ndarray,
        Mx: spmatrix,
        My: spmatrix,
    ) -> tuple[spmatrix, np.ndarray]:
        """Apply all registered conditions to an assembled rectangular system."""
        return apply_boundary_conditions(self, A, b, Mx, My)

add_dirichlet(nodes, values)

Add Dirichlet conditions u_i = value on rectangular grid nodes.

Parameters:

Name Type Description Default
nodes int or ndarray

Flattened source-node ids.

required
values float or ndarray

Scalar value or one value per node.

required
Source code in src/gbmsc_pde/boundary/conditions.py
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
def add_dirichlet(
    self,
    nodes: Union[int, np.ndarray],
    values: Union[float, np.ndarray],
) -> None:
    """
    Add Dirichlet conditions ``u_i = value`` on rectangular grid nodes.

    Parameters
    ----------
    nodes : int or ndarray
        Flattened source-node ids.
    values : float or ndarray
        Scalar value or one value per node.
    """
    nodes_arr = np.atleast_1d(nodes).astype(int)
    vals_arr = np.atleast_1d(values).astype(float)
    if vals_arr.size == 1:
        vals_arr = np.full(nodes_arr.shape, vals_arr.item(), dtype=float)
    if nodes_arr.size != vals_arr.size:
        raise ValueError(f"Mismatched nodes ({nodes_arr.size}) and values ({vals_arr.size}).")

    n_nodes = getattr(self.grid, "N", None)
    if n_nodes is None:
        raise AttributeError("SourceGrid must define total node count 'N'.")
    if np.any(nodes_arr < 0) or np.any(nodes_arr >= n_nodes):
        raise ValueError(f"Dirichlet indices out of [0, {n_nodes}): {nodes_arr}")

    for node, val in zip(nodes_arr, vals_arr):
        self.dirichlet[int(node)] = float(val)

add_neumann(nodes, outwardnormal, fluxes)

Add Neumann conditions du/dn = flux on grid nodes.

Parameters:

Name Type Description Default
nodes int or ndarray

Flattened source-node ids.

required
outwardnormal tuple

Normal components (n_x, n_y) as scalars or arrays.

required
fluxes float or ndarray

Scalar flux or one flux per node.

required
Source code in src/gbmsc_pde/boundary/conditions.py
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
def add_neumann(
    self,
    nodes: Union[int, np.ndarray],
    outwardnormal: Union[Tuple[float, float], Tuple[np.ndarray, np.ndarray]],
    fluxes: Union[float, np.ndarray],
) -> None:
    """
    Add Neumann conditions ``du/dn = flux`` on grid nodes.

    Parameters
    ----------
    nodes : int or ndarray
        Flattened source-node ids.
    outwardnormal : tuple
        Normal components ``(n_x, n_y)`` as scalars or arrays.
    fluxes : float or ndarray
        Scalar flux or one flux per node.
    """
    nodes_arr = np.atleast_1d(nodes).astype(int)
    k = nodes_arr.size

    if not (isinstance(outwardnormal, tuple) and len(outwardnormal) == 2):
        raise TypeError("`outwardnormal` must be a tuple of length 2.")
    nx, ny = outwardnormal

    if np.isscalar(nx) and np.isscalar(ny):
        nx_arr = np.full(k, float(nx))
        ny_arr = np.full(k, float(ny))
    else:
        nx_arr = np.atleast_1d(nx).astype(float)
        ny_arr = np.atleast_1d(ny).astype(float)
    if nx_arr.shape != (k,) or ny_arr.shape != (k,):
        raise ValueError("`outwardnormal` components must match length of `nodes`.")

    flux_arr = np.atleast_1d(fluxes).astype(float)
    if flux_arr.size == 1:
        flux_arr = np.full(k, flux_arr.item())
    if flux_arr.shape != (k,):
        raise ValueError("`fluxes` must be scalar or match length of `nodes`.")

    n_nodes = getattr(self.grid, "N", None)
    if n_nodes is None:
        raise AttributeError("BoundaryConditions requires `self.grid.N`.")
    if np.any(nodes_arr < 0) or np.any(nodes_arr >= n_nodes):
        raise ValueError(f"Node indices must be in [0, {n_nodes}); got {nodes_arr}.")

    for node, nx_val, ny_val, flux_val in zip(nodes_arr, nx_arr, ny_arr, flux_arr):
        self.neumann[int(node)] = {
            "normal": (float(nx_val), float(ny_val)),
            "flux": float(flux_val),
        }

add_neumann_as_second_condition(nodes, outwardnormal, fluxes, rows)

Add Neumann equations on user-selected matrix rows.

This compatibility method is for augmented systems where a Neumann boundary equation should be imposed as an additional/second condition rather than replacing the row associated with node.

Source code in src/gbmsc_pde/boundary/conditions.py
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
def add_neumann_as_second_condition(
    self,
    nodes: Union[int, np.ndarray],
    outwardnormal: Union[Tuple[float, float], Tuple[np.ndarray, np.ndarray]],
    fluxes: Union[float, np.ndarray],
    rows: Union[int, np.ndarray],
) -> None:
    """
    Add Neumann equations on user-selected matrix rows.

    This compatibility method is for augmented systems where a Neumann
    boundary equation should be imposed as an additional/second condition
    rather than replacing the row associated with ``node``.
    """
    if not hasattr(self.grid, "N"):
        raise AttributeError("BoundaryConditions.grid must define integer `.N`")

    nodes_arr = np.atleast_1d(nodes).astype(int)
    rows_arr = np.atleast_1d(rows).astype(int)

    if nodes_arr.ndim != 1 or rows_arr.ndim != 1:
        raise TypeError("`nodes` and `rows` must be scalars or 1D sequences")

    n = nodes_arr.size
    if rows_arr.size != n:
        raise ValueError(f"`rows` length ({rows_arr.size}) != `nodes` length ({n})")

    if not (isinstance(outwardnormal, tuple) and len(outwardnormal) == 2):
        raise TypeError("`outwardnormal` must be a tuple of two elements")
    nx_in, ny_in = outwardnormal

    try:
        nx_arr = np.broadcast_to(nx_in, (n,)).astype(float)
        ny_arr = np.broadcast_to(ny_in, (n,)).astype(float)
    except Exception as exc:
        raise ValueError(
            "Cannot broadcast `outwardnormal` components to match `nodes` length"
        ) from exc

    try:
        flux_arr = np.broadcast_to(fluxes, (n,)).astype(float)
    except Exception as exc:
        raise ValueError("Cannot broadcast `fluxes` to match `nodes` length") from exc

    if np.any(nodes_arr < 0) or np.any(nodes_arr >= self.grid.N):
        raise ValueError(f"All `nodes` must be in [0, {self.grid.N})")

    for node, row, nx_val, ny_val, flux in zip(nodes_arr, rows_arr, nx_arr, ny_arr, flux_arr):
        self.second_neumann[int(node)] = {
            "normal": (float(nx_val), float(ny_val)),
            "flux": float(flux),
            "row": int(row),
        }

add_robin(nodes, outwardnormal, alphas, betas, values)

Add Robin conditions alpha*u + beta*du/dn = value on grid nodes.

alphas, betas, and values may be scalars or arrays with one entry per node.

Source code in src/gbmsc_pde/boundary/conditions.py
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
def add_robin(
    self,
    nodes: Union[int, np.ndarray],
    outwardnormal: Union[Tuple[float, float], Tuple[np.ndarray, np.ndarray]],
    alphas: Union[float, np.ndarray],
    betas: Union[float, np.ndarray],
    values: Union[float, np.ndarray],
) -> None:
    """
    Add Robin conditions ``alpha*u + beta*du/dn = value`` on grid nodes.

    ``alphas``, ``betas``, and ``values`` may be scalars or arrays with
    one entry per node.
    """
    nodes_arr = np.atleast_1d(nodes).astype(int)
    k = nodes_arr.size

    if not (isinstance(outwardnormal, tuple) and len(outwardnormal) == 2):
        raise TypeError("`outwardnormal` must be a tuple (nx, ny).")
    nx, ny = outwardnormal
    nx_arr = np.full(k, nx, dtype=float) if np.isscalar(nx) else np.atleast_1d(nx).astype(float)
    ny_arr = np.full(k, ny, dtype=float) if np.isscalar(ny) else np.atleast_1d(ny).astype(float)
    if nx_arr.shape != (k,) or ny_arr.shape != (k,):
        raise ValueError("`outwardnormal` components must match length of `nodes`.")

    alpha_arr = np.atleast_1d(alphas).astype(float)
    beta_arr = np.atleast_1d(betas).astype(float)
    value_arr = np.atleast_1d(values).astype(float)

    if alpha_arr.size == 1:
        alpha_arr = np.full(k, alpha_arr.item(), dtype=float)
    if beta_arr.size == 1:
        beta_arr = np.full(k, beta_arr.item(), dtype=float)
    if value_arr.size == 1:
        value_arr = np.full(k, value_arr.item(), dtype=float)

    if not (alpha_arr.size == beta_arr.size == value_arr.size == k):
        raise ValueError(
            f"Sizes must match: nodes({k}), alphas({alpha_arr.size}), "
            f"betas({beta_arr.size}), values({value_arr.size})."
        )

    n_nodes = getattr(self.grid, "N", None)
    if n_nodes is None:
        raise AttributeError("SourceGrid must define total node count 'N'.")
    if np.any(nodes_arr < 0) or np.any(nodes_arr >= n_nodes):
        raise ValueError(f"Node indices out of [0, {n_nodes}): {nodes_arr}")

    for node, nx_val, ny_val, alpha, beta, value in zip(
        nodes_arr, nx_arr, ny_arr, alpha_arr, beta_arr, value_arr
    ):
        self.robin[int(node)] = {
            "normal": (float(nx_val), float(ny_val)),
            "alpha": float(alpha),
            "beta": float(beta),
            "value": float(value),
        }

apply(A, b, Mx, My)

Apply all registered conditions to an assembled rectangular system.

Source code in src/gbmsc_pde/boundary/conditions.py
223
224
225
226
227
228
229
230
231
def apply(
    self,
    A: spmatrix,
    b: np.ndarray,
    Mx: spmatrix,
    My: spmatrix,
) -> tuple[spmatrix, np.ndarray]:
    """Apply all registered conditions to an assembled rectangular system."""
    return apply_boundary_conditions(self, A, b, Mx, My)

gbmsc_pde.boundary.applier.BoundaryConditionApplier

Apply a boundary-condition container to a linear system.

Source code in src/gbmsc_pde/boundary/applier.py
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
class BoundaryConditionApplier:
    """Apply a boundary-condition container to a linear system."""

    def __init__(self, boundary_conditions) -> None:
        self.boundary_conditions = boundary_conditions

    def apply(
        self,
        A: spmatrix,
        b: np.ndarray,
        Mx: spmatrix,
        My: spmatrix,
    ) -> Tuple[spmatrix, np.ndarray]:
        """Return a system with all registered boundary conditions enforced."""
        bcs = self.boundary_conditions
        n_nodes = getattr(bcs.grid, "N", None)
        if n_nodes is None:
            raise AttributeError("SourceGrid must define total node count 'N'.")

        has_derivative_bcs = bool(bcs.neumann or bcs.robin or bcs.second_neumann)
        if not has_derivative_bcs and not bcs.dirichlet:
            return A.tocsr(), b.copy()

        A_bc = A.tolil()
        b_bc = b.copy()

        if has_derivative_bcs:
            Mx_csr = Mx.tocsr()
            My_csr = My.tocsr()

        for node, bc in bcs.neumann.items():
            nx, ny = bc["normal"]
            flux = bc["flux"]
            row_n = nx * Mx_csr.getrow(node) + ny * My_csr.getrow(node)
            A_bc[node, :] = row_n
            b_bc[node] = flux

        for node, bc in bcs.robin.items():
            nx, ny = bc["normal"]
            alpha = bc["alpha"]
            beta = bc["beta"]
            value = bc["value"]
            row_n = nx * Mx_csr.getrow(node) + ny * My_csr.getrow(node)
            row_r = (beta * row_n).tolil()
            row_r[0, node] += alpha
            A_bc[node, :] = row_r
            b_bc[node] = value

        for node, info in bcs.second_neumann.items():
            row = info["row"]
            nx, ny = info["normal"]
            flux = info["flux"]
            row_n = nx * Mx_csr.getrow(node) + ny * My_csr.getrow(node)
            A_bc[row, :] = row_n
            b_bc[row] = flux

        for node, value in bcs.dirichlet.items():
            A_bc.rows[node] = [node]
            A_bc.data[node] = [1.0]
            b_bc[node] = value

        return A_bc.tocsr(), b_bc

apply(A, b, Mx, My)

Return a system with all registered boundary conditions enforced.

Source code in src/gbmsc_pde/boundary/applier.py
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
def apply(
    self,
    A: spmatrix,
    b: np.ndarray,
    Mx: spmatrix,
    My: spmatrix,
) -> Tuple[spmatrix, np.ndarray]:
    """Return a system with all registered boundary conditions enforced."""
    bcs = self.boundary_conditions
    n_nodes = getattr(bcs.grid, "N", None)
    if n_nodes is None:
        raise AttributeError("SourceGrid must define total node count 'N'.")

    has_derivative_bcs = bool(bcs.neumann or bcs.robin or bcs.second_neumann)
    if not has_derivative_bcs and not bcs.dirichlet:
        return A.tocsr(), b.copy()

    A_bc = A.tolil()
    b_bc = b.copy()

    if has_derivative_bcs:
        Mx_csr = Mx.tocsr()
        My_csr = My.tocsr()

    for node, bc in bcs.neumann.items():
        nx, ny = bc["normal"]
        flux = bc["flux"]
        row_n = nx * Mx_csr.getrow(node) + ny * My_csr.getrow(node)
        A_bc[node, :] = row_n
        b_bc[node] = flux

    for node, bc in bcs.robin.items():
        nx, ny = bc["normal"]
        alpha = bc["alpha"]
        beta = bc["beta"]
        value = bc["value"]
        row_n = nx * Mx_csr.getrow(node) + ny * My_csr.getrow(node)
        row_r = (beta * row_n).tolil()
        row_r[0, node] += alpha
        A_bc[node, :] = row_r
        b_bc[node] = value

    for node, info in bcs.second_neumann.items():
        row = info["row"]
        nx, ny = info["normal"]
        flux = info["flux"]
        row_n = nx * Mx_csr.getrow(node) + ny * My_csr.getrow(node)
        A_bc[row, :] = row_n
        b_bc[row] = flux

    for node, value in bcs.dirichlet.items():
        A_bc.rows[node] = [node]
        A_bc.data[node] = [1.0]
        b_bc[node] = value

    return A_bc.tocsr(), b_bc

gbmsc_pde.solvers.linear.LinearSolver

Linear-system solver for rectangular-domain PDE problems.

LinearSolver assembles the PDE rows from :class:LinearPDE, applies node-indexed boundary conditions, and solves the resulting square sparse system for the source-node vector.

Parameters:

Name Type Description Default
pde LinearPDE

Configured rectangular linear PDE builder.

required
bcs BoundaryConditions

Boundary conditions registered on flattened grid nodes.

required
Source code in src/gbmsc_pde/solvers/linear.py
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
class LinearSolver:
    """
    Linear-system solver for rectangular-domain PDE problems.

    ``LinearSolver`` assembles the PDE rows from :class:`LinearPDE`, applies
    node-indexed boundary conditions, and solves the resulting square sparse
    system for the source-node vector.

    Parameters
    ----------
    pde : LinearPDE
        Configured rectangular linear PDE builder.
    bcs : BoundaryConditions
        Boundary conditions registered on flattened grid nodes.
    """
    def __init__(self, pde: LinearPDE, bcs: BoundaryConditions) -> None:
        if not isinstance(pde, LinearPDE):
            raise TypeError("pde must be an instance of LinearPDE")
        if not isinstance(bcs, BoundaryConditions):
            raise TypeError("bcs must be an instance of BoundaryConditions")

        self.pde = pde
        self.bcs = bcs
        self.A = None
        self.b = None
        self.Mx = None
        self.My = None
        self.Mxx = None
        self.Myy = None
        self.solution = None
        self.last_data = None

    def assemble(self) -> Tuple[spmatrix, np.ndarray, spmatrix, spmatrix, spmatrix, spmatrix]:
        """
        Assemble and boundary-modify the rectangular collocation system.

        Returns
        -------
        A, b, Mx, My, Mxx, Myy
            Boundary-modified sparse system, right-hand side, and first
            and second derivative matrices.  The same objects are stored on
            ``self`` as ``A``, ``b``, ``Mx``, ``My``, ``Mxx``, and ``Myy`` for
            later inspection.
        """
        A, b, Mx, My, Mxx, Myy = self.pde.assemble()
        A, b = BoundaryConditionApplier(self.bcs).apply(A, b, Mx, My)
        self.A = A
        self.b = b
        self.Mx = Mx
        self.My = My
        self.Mxx = Mxx
        self.Myy = Myy
        return A, b, Mx, My, Mxx, Myy

    @staticmethod
    def _as_linear_operator(preconditioner: Optional[Any]):
        if preconditioner is None:
            return None
        if isinstance(preconditioner, spmatrix):
            return spla.LinearOperator(preconditioner.shape, preconditioner.dot)
        return preconditioner

    @staticmethod
    def _jacobi_preconditioner(A: spmatrix):
        diagonal = A.diagonal()
        if np.any(np.isclose(diagonal, 0.0)):
            raise ValueError("Jacobi preconditioner requires a nonzero matrix diagonal.")
        inv_diagonal = 1.0 / diagonal
        return spla.LinearOperator(A.shape, matvec=lambda x: inv_diagonal * x)

    @staticmethod
    def _iterative_call(method, A, b, *, tol, maxiter, M):
        try:
            return method(A, b, rtol=tol, atol=0.0, maxiter=maxiter, M=M)
        except TypeError:
            return method(A, b, tol=tol, maxiter=maxiter, M=M)

    def solve(
        self,
        solver: str = 'direct',
        tol: float = 1e-8,
        maxiter: Optional[int] = None,
        preconditioner: Optional[Any] = None,
        return_data: bool = False,
    ) -> Union[
        np.ndarray,
        Tuple[np.ndarray, Dict[str, object]],
    ]:
        """
        Assemble, apply boundary conditions, and solve the linear system.

        Parameters
        ----------
        solver : {'direct', 'cg', 'gmres', 'bicgstab'}
            Linear solver. ``"direct"`` uses sparse direct solve; ``"cg"`` and
            ``"gmres"`` and ``"bicgstab"`` use SciPy iterative solvers.
        tol : float, optional
            Tolerance for iterative solvers.
        maxiter : int, optional
            Maximum iterations (defaults to N).
        preconditioner : object, optional
            Preconditioner LinearOperator, sparse matrix, or ``"jacobi"``.
        return_data : bool
            If true, return ``(u, data)`` where ``data`` contains ``A``, ``b``,
            derivative matrices, ``nnz``, ``sparsity``, ``solve_time``,
            ``assembly_time``, and ``solver_info``.

        Returns
        -------
        ndarray or tuple
            Solution vector ``u`` with shape ``(grid.N,)``.  If
            ``return_data=True``, returns ``(u, data)``.
        """
        assembly_start = perf_counter()
        A, b, Mx, My, Mxx, Myy = self.assemble()
        assembly_time = perf_counter() - assembly_start

        if A.shape[0] != A.shape[1]:
            raise ValueError(f"Linear system must be square; got {A.shape}.")
        if not np.all(np.isfinite(A.data)):
            raise ValueError("Linear system matrix contains non-finite values.")
        if not np.all(np.isfinite(b)):
            raise ValueError("Right-hand side contains non-finite values.")

        solve_start = perf_counter()
        if solver == 'direct':
            sol = spla.spsolve(A, b)
            info = 0
        else:
            N = A.shape[0]
            maxiter = maxiter or N
            if preconditioner == "jacobi":
                M = self._jacobi_preconditioner(A)
            else:
                M = self._as_linear_operator(preconditioner)
            methods = {'cg': spla.cg, 'gmres': spla.gmres, 'bicgstab': spla.bicgstab}
            if solver not in methods:
                raise ValueError(
                    f"Unsupported solver '{solver}'. Choose 'direct', 'cg', 'gmres', or 'bicgstab'."
                )
            sol, info = self._iterative_call(
                methods[solver],
                A,
                b,
                tol=tol,
                maxiter=maxiter,
                M=M,
            )
            if info != 0:
                raise RuntimeError(f"Solver '{solver}' failed to converge (info={info}).")
        solve_time = perf_counter() - solve_start

        self.solution = sol

        if return_data:
            data: Dict[str, object] = {
                "A": A,
                "b": b,
                "first_derivatives": (Mx, My),
                "second_derivatives": (Mxx, Myy),
                "nnz": int(A.nnz),
                "sparsity": float((1.0 - A.nnz / (A.shape[0] * A.shape[1])) * 100.0),
                "solve_time": float(solve_time),
                "assembly_time": float(assembly_time),
                "solver_info": int(info),
            }
            self.last_data = data
            return sol, data

        return sol

assemble()

Assemble and boundary-modify the rectangular collocation system.

Returns:

Type Description
(A, b, Mx, My, Mxx, Myy)

Boundary-modified sparse system, right-hand side, and first and second derivative matrices. The same objects are stored on self as A, b, Mx, My, Mxx, and Myy for later inspection.

Source code in src/gbmsc_pde/solvers/linear.py
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
def assemble(self) -> Tuple[spmatrix, np.ndarray, spmatrix, spmatrix, spmatrix, spmatrix]:
    """
    Assemble and boundary-modify the rectangular collocation system.

    Returns
    -------
    A, b, Mx, My, Mxx, Myy
        Boundary-modified sparse system, right-hand side, and first
        and second derivative matrices.  The same objects are stored on
        ``self`` as ``A``, ``b``, ``Mx``, ``My``, ``Mxx``, and ``Myy`` for
        later inspection.
    """
    A, b, Mx, My, Mxx, Myy = self.pde.assemble()
    A, b = BoundaryConditionApplier(self.bcs).apply(A, b, Mx, My)
    self.A = A
    self.b = b
    self.Mx = Mx
    self.My = My
    self.Mxx = Mxx
    self.Myy = Myy
    return A, b, Mx, My, Mxx, Myy

solve(solver='direct', tol=1e-08, maxiter=None, preconditioner=None, return_data=False)

Assemble, apply boundary conditions, and solve the linear system.

Parameters:

Name Type Description Default
solver (direct, cg, gmres, bicgstab)

Linear solver. "direct" uses sparse direct solve; "cg" and "gmres" and "bicgstab" use SciPy iterative solvers.

'direct'
tol float

Tolerance for iterative solvers.

1e-08
maxiter int

Maximum iterations (defaults to N).

None
preconditioner object

Preconditioner LinearOperator, sparse matrix, or "jacobi".

None
return_data bool

If true, return (u, data) where data contains A, b, derivative matrices, nnz, sparsity, solve_time, assembly_time, and solver_info.

False

Returns:

Type Description
ndarray or tuple

Solution vector u with shape (grid.N,). If return_data=True, returns (u, data).

Source code in src/gbmsc_pde/solvers/linear.py
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
def solve(
    self,
    solver: str = 'direct',
    tol: float = 1e-8,
    maxiter: Optional[int] = None,
    preconditioner: Optional[Any] = None,
    return_data: bool = False,
) -> Union[
    np.ndarray,
    Tuple[np.ndarray, Dict[str, object]],
]:
    """
    Assemble, apply boundary conditions, and solve the linear system.

    Parameters
    ----------
    solver : {'direct', 'cg', 'gmres', 'bicgstab'}
        Linear solver. ``"direct"`` uses sparse direct solve; ``"cg"`` and
        ``"gmres"`` and ``"bicgstab"`` use SciPy iterative solvers.
    tol : float, optional
        Tolerance for iterative solvers.
    maxiter : int, optional
        Maximum iterations (defaults to N).
    preconditioner : object, optional
        Preconditioner LinearOperator, sparse matrix, or ``"jacobi"``.
    return_data : bool
        If true, return ``(u, data)`` where ``data`` contains ``A``, ``b``,
        derivative matrices, ``nnz``, ``sparsity``, ``solve_time``,
        ``assembly_time``, and ``solver_info``.

    Returns
    -------
    ndarray or tuple
        Solution vector ``u`` with shape ``(grid.N,)``.  If
        ``return_data=True``, returns ``(u, data)``.
    """
    assembly_start = perf_counter()
    A, b, Mx, My, Mxx, Myy = self.assemble()
    assembly_time = perf_counter() - assembly_start

    if A.shape[0] != A.shape[1]:
        raise ValueError(f"Linear system must be square; got {A.shape}.")
    if not np.all(np.isfinite(A.data)):
        raise ValueError("Linear system matrix contains non-finite values.")
    if not np.all(np.isfinite(b)):
        raise ValueError("Right-hand side contains non-finite values.")

    solve_start = perf_counter()
    if solver == 'direct':
        sol = spla.spsolve(A, b)
        info = 0
    else:
        N = A.shape[0]
        maxiter = maxiter or N
        if preconditioner == "jacobi":
            M = self._jacobi_preconditioner(A)
        else:
            M = self._as_linear_operator(preconditioner)
        methods = {'cg': spla.cg, 'gmres': spla.gmres, 'bicgstab': spla.bicgstab}
        if solver not in methods:
            raise ValueError(
                f"Unsupported solver '{solver}'. Choose 'direct', 'cg', 'gmres', or 'bicgstab'."
            )
        sol, info = self._iterative_call(
            methods[solver],
            A,
            b,
            tol=tol,
            maxiter=maxiter,
            M=M,
        )
        if info != 0:
            raise RuntimeError(f"Solver '{solver}' failed to converge (info={info}).")
    solve_time = perf_counter() - solve_start

    self.solution = sol

    if return_data:
        data: Dict[str, object] = {
            "A": A,
            "b": b,
            "first_derivatives": (Mx, My),
            "second_derivatives": (Mxx, Myy),
            "nnz": int(A.nnz),
            "sparsity": float((1.0 - A.nnz / (A.shape[0] * A.shape[1])) * 100.0),
            "solve_time": float(solve_time),
            "assembly_time": float(assembly_time),
            "solver_info": int(info),
        }
        self.last_data = data
        return sol, data

    return sol