|
| 1 | +"""Experimental iterative ``MultiLCA`` backend for Pathways. |
| 2 | +
|
| 3 | +This backend keeps Pathways on the standard ``bw2calc.MultiLCA`` lifecycle, |
| 4 | +but swaps the direct sparse solve for GMRES with a Jacobi preconditioner. |
| 5 | +Whenever available, it reuses the matrix-preparation and preconditioner |
| 6 | +helpers from ``bw2calc.JacobiGMRESLCA``. |
| 7 | +""" |
| 8 | + |
| 9 | +from __future__ import annotations |
| 10 | + |
| 11 | +import logging |
| 12 | +from typing import Optional |
| 13 | + |
| 14 | +import bw2calc as bc |
| 15 | +import matrix_utils as mu |
| 16 | +import numpy as np |
| 17 | +from scipy import sparse |
| 18 | +from scipy.sparse.linalg import LinearOperator, gmres |
| 19 | + |
| 20 | +logger = logging.getLogger(__name__) |
| 21 | + |
| 22 | +try: |
| 23 | + _BW_JACOBI_GMRES_LCA = bc.JacobiGMRESLCA |
| 24 | +except AttributeError: # pragma: no cover - older bw2calc versions |
| 25 | + _BW_JACOBI_GMRES_LCA = None |
| 26 | + |
| 27 | + |
| 28 | +class JacobiGMRESMultiLCA(bc.MultiLCA): |
| 29 | + """Solve multi-demand LCI systems with GMRES and Jacobi preconditioning.""" |
| 30 | + |
| 31 | + def __init__( |
| 32 | + self, |
| 33 | + *args, |
| 34 | + rtol: float = 1e-8, |
| 35 | + atol: float = 0.0, |
| 36 | + restart: Optional[int] = 50, |
| 37 | + maxiter: Optional[int] = 300, |
| 38 | + use_guess: bool = True, |
| 39 | + direct_fallback: bool = True, |
| 40 | + **kwargs, |
| 41 | + ): |
| 42 | + super().__init__(*args, **kwargs) |
| 43 | + self.rtol = rtol |
| 44 | + self.atol = atol |
| 45 | + self.restart = restart |
| 46 | + self.maxiter = maxiter |
| 47 | + self.use_guess = use_guess |
| 48 | + self.direct_fallback = direct_fallback |
| 49 | + |
| 50 | + self._matrix_prepared = False |
| 51 | + self._cached_preconditioner: Optional[LinearOperator] = None |
| 52 | + self.guesses: dict[str, np.ndarray] = {} |
| 53 | + |
| 54 | + def __next__(self) -> None: |
| 55 | + # Matrix values can change on each Monte Carlo draw. |
| 56 | + self._matrix_prepared = False |
| 57 | + self._cached_preconditioner = None |
| 58 | + self.guesses = {} |
| 59 | + super().__next__() |
| 60 | + |
| 61 | + def load_lci_data(self, nonsquare_ok=False) -> None: |
| 62 | + super().load_lci_data(nonsquare_ok=nonsquare_ok) |
| 63 | + self._matrix_prepared = False |
| 64 | + self._cached_preconditioner = None |
| 65 | + self.guesses = {} |
| 66 | + |
| 67 | + def _prepare_matrix(self) -> None: |
| 68 | + # ``MappedMatrix`` updates ``technosphere_mm.matrix`` across MC draws. |
| 69 | + # Rebind here so GMRES always sees the current technosphere values instead |
| 70 | + # of a stale CSC conversion from an earlier draw. |
| 71 | + if hasattr(self, "technosphere_mm"): |
| 72 | + self.technosphere_matrix = self.technosphere_mm.matrix |
| 73 | + |
| 74 | + if _BW_JACOBI_GMRES_LCA is not None: |
| 75 | + _BW_JACOBI_GMRES_LCA._prepare_matrix(self) |
| 76 | + return |
| 77 | + |
| 78 | + if self._matrix_prepared: |
| 79 | + return |
| 80 | + |
| 81 | + self.technosphere_matrix = self.technosphere_matrix.tocsc(copy=False) |
| 82 | + self.technosphere_matrix.sum_duplicates() |
| 83 | + self.technosphere_matrix.eliminate_zeros() |
| 84 | + self.technosphere_matrix.sort_indices() |
| 85 | + self._matrix_prepared = True |
| 86 | + |
| 87 | + def _build_jacobi_preconditioner(self) -> Optional[LinearOperator]: |
| 88 | + if _BW_JACOBI_GMRES_LCA is not None: |
| 89 | + return _BW_JACOBI_GMRES_LCA._build_jacobi_preconditioner(self) |
| 90 | + |
| 91 | + if self._cached_preconditioner is not None: |
| 92 | + return self._cached_preconditioner |
| 93 | + |
| 94 | + diagonal = self.technosphere_matrix.diagonal() |
| 95 | + if np.any(diagonal == 0): |
| 96 | + return None |
| 97 | + |
| 98 | + inverse_diagonal = 1.0 / diagonal |
| 99 | + self._cached_preconditioner = LinearOperator( |
| 100 | + shape=self.technosphere_matrix.shape, |
| 101 | + matvec=lambda x: inverse_diagonal * x, |
| 102 | + dtype=self.technosphere_matrix.dtype, |
| 103 | + ) |
| 104 | + return self._cached_preconditioner |
| 105 | + |
| 106 | + def _solve_with_gmres( |
| 107 | + self, |
| 108 | + demand: np.ndarray, |
| 109 | + *, |
| 110 | + x0: np.ndarray | None = None, |
| 111 | + demand_name: str | None = None, |
| 112 | + ) -> np.ndarray: |
| 113 | + self._prepare_matrix() |
| 114 | + preconditioner = self._build_jacobi_preconditioner() |
| 115 | + |
| 116 | + try: |
| 117 | + solution, info = gmres( |
| 118 | + self.technosphere_matrix, |
| 119 | + demand, |
| 120 | + x0=x0, |
| 121 | + rtol=self.rtol, |
| 122 | + atol=self.atol, |
| 123 | + restart=self.restart, |
| 124 | + maxiter=self.maxiter, |
| 125 | + M=preconditioner, |
| 126 | + ) |
| 127 | + except TypeError: # pragma: no cover - SciPy compatibility fallback |
| 128 | + solution, info = gmres( |
| 129 | + self.technosphere_matrix, |
| 130 | + demand, |
| 131 | + x0=x0, |
| 132 | + tol=self.rtol, |
| 133 | + atol=self.atol, |
| 134 | + restart=self.restart, |
| 135 | + maxiter=self.maxiter, |
| 136 | + M=preconditioner, |
| 137 | + ) |
| 138 | + |
| 139 | + solution = np.asarray(solution, dtype=np.float64) |
| 140 | + if not solution.shape: |
| 141 | + solution = solution.reshape((1,)) |
| 142 | + |
| 143 | + if info != 0: |
| 144 | + if not self.direct_fallback: |
| 145 | + raise RuntimeError( |
| 146 | + "GMRES failed to converge " |
| 147 | + f"(demand={demand_name!r}, info={info}, rtol={self.rtol}, maxiter={self.maxiter})" |
| 148 | + ) |
| 149 | + |
| 150 | + logger.warning( |
| 151 | + "GMRES failed to converge for demand %s; falling back to direct solve.", |
| 152 | + demand_name, |
| 153 | + ) |
| 154 | + solution = np.asarray(bc.spsolve(self.technosphere_matrix, demand)) |
| 155 | + if not solution.shape: |
| 156 | + solution = solution.reshape((1,)) |
| 157 | + |
| 158 | + return solution |
| 159 | + |
| 160 | + def lci_calculation(self) -> None: |
| 161 | + """Calculate inventories for many demands using iterative solves.""" |
| 162 | + count = len(self.dicts.activity) |
| 163 | + demand_items = list(self.demand_arrays.items()) |
| 164 | + if not demand_items: |
| 165 | + self.supply_arrays = {} |
| 166 | + self.inventories = mu.SparseMatrixDict([]) |
| 167 | + return |
| 168 | + |
| 169 | + supply_arrays: dict[str, np.ndarray] = {} |
| 170 | + previous_solution: np.ndarray | None = None |
| 171 | + |
| 172 | + for name, demand in demand_items: |
| 173 | + x0 = None |
| 174 | + if self.use_guess: |
| 175 | + x0 = self.guesses.get(name) |
| 176 | + if x0 is None: |
| 177 | + x0 = previous_solution |
| 178 | + |
| 179 | + solution = self._solve_with_gmres(demand, x0=x0, demand_name=name) |
| 180 | + supply_arrays[name] = solution |
| 181 | + previous_solution = solution |
| 182 | + |
| 183 | + if self.use_guess: |
| 184 | + self.guesses[name] = solution |
| 185 | + |
| 186 | + self.supply_arrays = supply_arrays |
| 187 | + self.inventories = mu.SparseMatrixDict( |
| 188 | + [ |
| 189 | + ( |
| 190 | + name, |
| 191 | + self.biosphere_matrix |
| 192 | + @ sparse.spdiags([arr], [0], count, count), |
| 193 | + ) |
| 194 | + for name, arr in self.supply_arrays.items() |
| 195 | + ] |
| 196 | + ) |
0 commit comments