Matrix Ops¶
matrix_ops
¶
Matrix operations and linear solvers for multiphysics modeling.
This module provides small, performance-oriented numerical utilities used by multiphysics engines:
- Construction of common 1D linear operators (e.g., Laplacian, Crank-Nicolson).
- Cached implicit solves for repeated linear systems with fixed operators.
- High-throughput aggregation utilities for large numbers of subpopulations.
- Optional Kronecker composition utilities for separable multi-axis operators.
Design notes
- CPU-first: dense paths rely on NumPy/SciPy BLAS/LAPACK; sparse paths rely on SciPy sparse factorizations.
- Backend-friendly surface: public APIs operate on plain ndarrays or CSR matrices and avoid leaking SciPy-specific solver objects.
- Cache semantics: implicit solver caching is keyed by (id(left_op), id(right_op)). For caching to be effective, operator objects must be constructed once and reused.
Stage operator factories (IMEX/TR-BDF2 support): TR-BDF2 and similar IMEX methods can require stage-specific implicit operators that depend on: - dt (time step) - scale (method stage scalar) - t (stage time) - y (stage state) - stage (a label, e.g. "tr" or "bdf2")
This module supports dynamic base operators via a builder:
base_builder(t, y, stage) -> Operator
Then the stage-operator factory produces (L, R) to solve:
L @ y_next = R @ y_in
where (L, R) follow schemes like implicit Euler or trapezoidal.
DiffusionConfig(coeff, dtype=np.float64, bc='neumann')
dataclass
¶
Configuration for diffusion-like linear operators.
Attributes:
| Name | Type | Description |
|---|---|---|
coeff |
float
|
Physical diffusion coefficient D (units length^2 / time). |
dtype |
DTypeLike
|
Floating dtype (e.g. np.float64). |
bc |
str
|
Boundary condition; either "neumann" or "absorbing". |
GridGeometry(n, dx)
dataclass
¶
Geometry of a 1D spatial grid.
Attributes:
| Name | Type | Description |
|---|---|---|
n |
int
|
Number of grid points. |
dx |
float
|
Grid spacing. |
StageOperatorContext(t, y, stage=None, extra=None)
dataclass
¶
Context passed to time/state-dependent operator builders.
Attributes:
| Name | Type | Description |
|---|---|---|
t |
float
|
Stage time. |
y |
NDArray[floating]
|
Stage state as a 1D float array (flattened along solver operator axis). |
stage |
StageName
|
Optional stage label (e.g. "tr", "bdf2"). |
extra |
Any | None
|
Optional extra payload for future use (kept generic). |
build_crank_nicolson_operator(geom, cfg, dt)
¶
Build Crank-Nicolson operators with dense/sparse autodispatch.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
geom
|
GridGeometry
|
Grid geometry. |
required |
cfg
|
DiffusionConfig
|
Diffusion configuration. |
required |
dt
|
float
|
Time step. |
required |
Returns:
| Type | Description |
|---|---|
tuple[Operator, Operator]
|
Tuple of (L, R) operators for Crank-Nicolson scheme. |
Source code in src/op_engine/matrix_ops.py
318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 | |
build_identity_operator(n, *, dtype=np.float64, prefer_sparse=None)
¶
Build an identity operator with dense/sparse autodispatch.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n
|
int
|
Size of the identity operator (n x n). |
required |
dtype
|
DTypeLike
|
Floating dtype (e.g. np.float64). |
float64
|
prefer_sparse
|
bool | None
|
If True, always return a sparse operator; if False, always return a dense operator; if None, autodispatch based on n. |
None
|
Returns:
| Type | Description |
|---|---|
Operator
|
Identity operator of shape (n, n) as either a dense ndarray or CSR matrix. |
Source code in src/op_engine/matrix_ops.py
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 | |
build_implicit_euler_operators(base_op, dt_scale)
¶
Build implicit Euler operators for a time-scaled linear operator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
base_op
|
Operator
|
Base linear operator A. |
required |
dt_scale
|
float
|
Time-step scaling factor (dt * scale). |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If dt_scale is not finite. |
Returns:
| Type | Description |
|---|---|
tuple[Operator, Operator]
|
Tuple of (L, R) operators for implicit Euler scheme. |
Source code in src/op_engine/matrix_ops.py
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 | |
build_laplacian_tridiag(n, dx, coeff, dtype=np.float64, bc='neumann')
¶
Build a Laplacian tridiagonal matrix for a given boundary condition.
The resulting operator corresponds to coeff * Δ_h, where Δ_h is the
standard second-order central-difference Laplacian in 1D. No time-step
scaling is applied here; coeff is interpreted as the physical diffusion
coefficient D or a generic spatial scaling.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n
|
int
|
Number of grid points. |
required |
dx
|
float
|
Grid spacing. |
required |
coeff
|
float
|
Physical diffusion coefficient D (units length^2 / time). |
required |
dtype
|
DTypeLike
|
Floating dtype (e.g. np.float64). |
float64
|
bc
|
str
|
Boundary condition; either "neumann" or "absorbing". |
'neumann'
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If an unknown boundary condition is provided. |
Returns:
| Type | Description |
|---|---|
csr_matrix
|
Sparse CSR matrix representing the Laplacian operator. |
Source code in src/op_engine/matrix_ops.py
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 | |
build_predictor_corrector(base_matrix)
¶
Build predictor-corrector matrices with dense/sparse autodispatch.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
base_matrix
|
DenseOperator | csr_matrix
|
Base linear operator A. |
required |
Returns:
| Type | Description |
|---|---|
tuple[Operator, Operator, Operator]
|
Tuple of (predictor, L, R) operators for predictor-corrector scheme. |
Source code in src/op_engine/matrix_ops.py
387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 | |
build_trapezoidal_operators(base_op, dt_scale)
¶
Build trapezoidal operators for a time-scaled linear operator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
base_op
|
Operator
|
Base linear operator A. |
required |
dt_scale
|
float
|
Time-step scaling factor (dt * scale). |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If dt_scale is not finite. |
Returns:
| Type | Description |
|---|---|
tuple[Operator, Operator]
|
Tuple of (L, R) operators for trapezoidal scheme. |
Source code in src/op_engine/matrix_ops.py
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 | |
clear_implicit_solver_cache()
¶
Clear the internal implicit solver cache.
Source code in src/op_engine/matrix_ops.py
672 673 674 | |
encode_groups(group_ids, n_groups, *, prefer_sparse=None, dtype=np.float64)
¶
Encode group IDs into a one-hot group membership matrix.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
group_ids
|
NDArray[integer]
|
1D array of integer group IDs for each item. |
required |
n_groups
|
int
|
Total number of groups. |
required |
prefer_sparse
|
bool | None
|
If True, always return a sparse matrix; if False, always return a dense array; if None, autodispatch based on n_groups. |
None
|
dtype
|
DTypeLike
|
Data type for the output matrix. |
float64
|
Returns:
| Type | Description |
|---|---|
csr_matrix | DenseOperator
|
A (n_groups, n_items) one-hot encoded group membership matrix. |
Source code in src/op_engine/matrix_ops.py
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 | |
grouped_count_ids(group_ids, n_groups)
¶
Perform grouped count using group IDs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
group_ids
|
NDArray[integer]
|
1D array of integer group IDs. |
required |
n_groups
|
int
|
Total number of groups. |
required |
Returns:
| Type | Description |
|---|---|
NDArray[floating]
|
A 1D array of length n_groups where each element contains the count of |
NDArray[floating]
|
occurrences of the corresponding group ID. |
Source code in src/op_engine/matrix_ops.py
997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 | |
grouped_sum_ids(values, group_ids, n_groups)
¶
Perform grouped sum over 1D values array using group IDs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
values
|
NDArray[floating]
|
1D array of values. |
required |
group_ids
|
NDArray[integer]
|
1D array of integer group IDs. |
required |
n_groups
|
int
|
Total number of groups. |
required |
Returns:
| Type | Description |
|---|---|
NDArray[floating]
|
A 1D array of length n_groups where each element contains the sum of values |
NDArray[floating]
|
for the corresponding group ID. |
Source code in src/op_engine/matrix_ops.py
1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 | |
grouped_sum_ids_2d(values, group_ids, n_groups)
¶
Perform grouped sum over 2D values array using group IDs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
values
|
NDArray[floating]
|
2D (N, K) array where N is num of items and K is num of features. |
required |
group_ids
|
NDArray[integer]
|
1D array of integer group IDs of length N. |
required |
n_groups
|
int
|
Total number of groups. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If values is not 2D or if group_ids length does not match the number of items in values. |
Returns:
| Type | Description |
|---|---|
NDArray[floating]
|
A 2D array of shape (n_groups, K) where each row contains the sum of values |
NDArray[floating]
|
for the corresponding group ID. |
Source code in src/op_engine/matrix_ops.py
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 | |
implicit_solve(left_op, right_op, x)
¶
Perform an implicit solve with dense/sparse dispatch and caching.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
left_op
|
Operator
|
Left operator L in the equation L @ y = R @ x. |
required |
right_op
|
Operator
|
Right operator R in the equation L @ y = R @ x. |
required |
x
|
NDArray[floating]
|
1D or 2D array representing the input vector(s). |
required |
Returns:
| Type | Description |
|---|---|
NDArray[floating]
|
A 1D or 2D array containing the solution vector(s) y. |
Source code in src/op_engine/matrix_ops.py
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 | |
kron_prod(a, b)
¶
Compute the Kronecker product of two operators.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a
|
Operator
|
First operator. |
required |
b
|
Operator
|
Second operator. |
required |
Returns:
| Type | Description |
|---|---|
Operator
|
The Kronecker product operator. |
Source code in src/op_engine/matrix_ops.py
594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 | |
kron_sum(ops)
¶
Compute a Kronecker sum of square operators.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ops
|
list[Operator]
|
List of 2D square operators. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If ops is empty or if operators are not square or have incompatible shapes. |
Returns:
| Type | Description |
|---|---|
Operator
|
The Kronecker sum operator. |
Source code in src/op_engine/matrix_ops.py
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 | |
make_constant_base_builder(operator)
¶
Convenience: wrap a constant operator as a BaseOperatorBuilder.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
operator
|
Operator
|
Constant operator to wrap. |
required |
Returns:
| Type | Description |
|---|---|
BaseOperatorBuilder
|
A BaseOperatorBuilder that always returns the given operator. |
Source code in src/op_engine/matrix_ops.py
571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 | |
make_stage_operator_factory(base_builder, *, scheme='implicit-euler')
¶
Create a stage operator factory supporting time/state dependent base ops.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
base_builder
|
BaseOperatorBuilder
|
Function that builds a base operator given stage context. |
required |
scheme
|
str
|
Implicit scheme; either "implicit-euler" or "trapezoidal". |
'implicit-euler'
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If an unknown scheme is provided. |
Returns:
| Type | Description |
|---|---|
StageOperatorFactory
|
A StageOperatorFactory that builds (L, R) operators for the given scheme. |
Source code in src/op_engine/matrix_ops.py
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 | |
matrix_grouped_count(group_matrix)
¶
Perform grouped count using a group matrix.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
group_matrix
|
csr_matrix | DenseOperator
|
2D group matrix (csr_matrix or dense ndarray). |
required |
Returns:
| Type | Description |
|---|---|
NDArray[floating]
|
A 1D array containing the counts for each group. |
Source code in src/op_engine/matrix_ops.py
932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 | |
matrix_grouped_sum(group_matrix, values)
¶
Perform grouped sum using a group matrix.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
group_matrix
|
csr_matrix | DenseOperator
|
2D group matrix (csr_matrix or dense ndarray). |
required |
values
|
NDArray[floating]
|
1D array of values to be summed. |
required |
Returns:
| Type | Description |
|---|---|
NDArray[floating]
|
A 1D array containing the grouped sums. |
Source code in src/op_engine/matrix_ops.py
898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 | |
matrix_masked_sum(mask_matrix, data)
¶
Perform masked sum using a mask matrix and data array.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mask_matrix
|
csr_matrix | DenseOperator
|
2D mask matrix (csr_matrix or dense ndarray). |
required |
data
|
NDArray[floating]
|
1D or 2D data array to be masked and summed. |
required |
Returns:
| Type | Description |
|---|---|
NDArray[floating]
|
A 1D or 2D array containing the masked sums. |
Source code in src/op_engine/matrix_ops.py
968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 | |
smooth(x, alpha=0.02, out=None)
¶
Apply simple smoothing along the last axis.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
NDArray[floating]
|
Input array to smooth. |
required |
alpha
|
float
|
Smoothing factor between 0 and 1. |
0.02
|
out
|
NDArray[floating] | None
|
Optional output array to store the result. |
None
|
Returns:
| Type | Description |
|---|---|
NDArray[floating]
|
Smoothed array with the same shape as x. |
Source code in src/op_engine/matrix_ops.py
1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 | |