disslucc 0.5.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
disslucc/__init__.py ADDED
@@ -0,0 +1,54 @@
1
+ """
2
+ disslucc -- raster-only, "script-first" port of disslucc-continuous
3
+ (main branch). See README for what was simplified and what wasn't
4
+ (the CLUE algorithm itself is faithful to the original).
5
+ """
6
+ from .components.allocation import AllocationClueLike, AllocationClueLikeSaturation, AllocationDClueSLike
7
+ from .components.demand import (
8
+ DemandComputeThreeDates,
9
+ DemandComputeTwoDates,
10
+ DemandInline,
11
+ DemandPreComputedValues,
12
+ load_demand_csv,
13
+ )
14
+ from .components.potential import (
15
+ PotentialDLogisticRegression,
16
+ PotentialLinearRegression,
17
+ PotentialSpatialLagRegression,
18
+ )
19
+ from .protocols import DemandProtocol, PotentialProtocol, RegionalPotentialProtocol
20
+ from .schemas import (
21
+ AllocationSpec,
22
+ LogisticRegressionSpec,
23
+ RegressionSpec,
24
+ SaturationAllocationSpec,
25
+ SpatialLagRegressionSpec,
26
+ )
27
+ from .validation import confusion_metrics, pontius_millones
28
+
29
+ # Explicit public API: these are re-exports (nothing here is used within
30
+ # this module itself), so without __all__ ruff's default rule set flags
31
+ # every one of them as an unused import.
32
+ __all__ = [
33
+ "AllocationClueLike",
34
+ "AllocationClueLikeSaturation",
35
+ "AllocationDClueSLike",
36
+ "AllocationSpec",
37
+ "DemandComputeThreeDates",
38
+ "DemandComputeTwoDates",
39
+ "DemandInline",
40
+ "DemandPreComputedValues",
41
+ "DemandProtocol",
42
+ "LogisticRegressionSpec",
43
+ "PotentialDLogisticRegression",
44
+ "PotentialLinearRegression",
45
+ "PotentialProtocol",
46
+ "PotentialSpatialLagRegression",
47
+ "RegionalPotentialProtocol",
48
+ "RegressionSpec",
49
+ "SaturationAllocationSpec",
50
+ "SpatialLagRegressionSpec",
51
+ "confusion_metrics",
52
+ "load_demand_csv",
53
+ "pontius_millones",
54
+ ]
File without changes
@@ -0,0 +1,5 @@
1
+ from .clue import AllocationClueLike
2
+ from .clue_s import AllocationDClueSLike
3
+ from .saturation import AllocationClueLikeSaturation
4
+
5
+ __all__ = ["AllocationClueLike", "AllocationClueLikeSaturation", "AllocationDClueSLike"]
@@ -0,0 +1,293 @@
1
+ """
2
+ disslucc.allocation
3
+ ---------------------
4
+ Faithful port of disslucc_continuous.components.allocation.raster.clue,
5
+ `main` branch (not `decoupling` -- that one was experimental). Raster
6
+ only. The algorithm (CLUE, Verburg et al. 1999 -- elasticity +
7
+ convergence + proportional correction + complementary class) was not
8
+ simplified: it's the same, cell by cell, vectorized with NumPy. What
9
+ got simpler was only what's around it (no Pipeline/Registry-class/
10
+ from_spec/TOML) -- see README.
11
+
12
+ Note: Allocation reads `<lu>_pot` directly from the shared backend
13
+ (not via a Potential method) -- that's how main does it; the
14
+ indirection through PotentialProtocol.get_potential() was only on
15
+ decoupling.
16
+
17
+ Deviation from TerraME: LuccME's correctCellChange never runs. Its guard
18
+ is `if (cell.regionregionAloc == rNumber)` (AllocationCClueLike.lua:503,
19
+ a typo for `regionAloc`), which is always false. `_correct_cell_change`
20
+ implements what that step was meant to do and runs by default
21
+ (`cell_correction=True`). With `cell_correction=False` this component
22
+ reproduces TerraME year by year, iteration counts included
23
+ (tests/test_goldens_per_year.py).
24
+ """
25
+ from __future__ import annotations
26
+
27
+ from typing import cast
28
+
29
+ import numpy as np
30
+ from dissmodel.geo import SyncRasterModel
31
+
32
+ from ...protocols import DemandProtocol, PotentialProtocol
33
+ from ...schemas import AllocationSpec
34
+
35
+
36
+ class AllocationClueLike(SyncRasterModel):
37
+ """
38
+ Raster CLUE allocation (Verburg et al. 1999).
39
+
40
+ All per-cell operations are vectorized with NumPy -- no per-cell
41
+ loop.
42
+ """
43
+
44
+ def setup(
45
+ self,
46
+ backend,
47
+ demand: DemandProtocol,
48
+ potential: PotentialProtocol,
49
+ land_use_types: list[str],
50
+ static: dict[str, int],
51
+ complementar_lu: str,
52
+ cell_area: float,
53
+ max_difference: float = 1643,
54
+ max_iteration: int = 1000,
55
+ initial_elasticity: float = 0.1,
56
+ min_elasticity: float = 0.001,
57
+ max_elasticity: float = 1.5,
58
+ allocation_data: list[AllocationSpec] | None = None,
59
+ cell_correction: bool = True,
60
+ ) -> None:
61
+ super().setup(backend)
62
+ self.demand = demand
63
+ self.potential = potential
64
+ self.land_use_types = land_use_types
65
+ self.static = static
66
+ self.complementar_lu = complementar_lu
67
+ self.cell_area = cell_area
68
+ self.max_difference = max_difference
69
+ self.max_iteration = max_iteration
70
+ self.initial_elasticity = initial_elasticity
71
+ self.min_elasticity = min_elasticity
72
+ self.max_elasticity = max_elasticity
73
+ # False reproduces TerraME, where correctCellChange never runs (see module docstring).
74
+ self.cell_correction = cell_correction
75
+ # Iterations of the convergence loop at each step, same meaning as
76
+ # LuccME's "Number of iterations" (0 = first allocation accepted).
77
+ self.iterations_per_step: list[int] = []
78
+
79
+ default = AllocationSpec()
80
+ self.allocation_data = (
81
+ list(allocation_data) if allocation_data is not None
82
+ else [default for _ in range(len(land_use_types))]
83
+ )
84
+
85
+ # ── helpers ───────────────────────────────────────────────────────────────
86
+
87
+ def _mask(self) -> np.ndarray:
88
+ """Boolean mask: True = valid cell. Cached reference, not a copy."""
89
+ arr = self.backend.arrays.get("mask", np.ones(self.shape, dtype=bool))
90
+ return cast(np.ndarray, arr.astype(bool))
91
+
92
+ def execute(self) -> None:
93
+ step = int(self.env.now())
94
+ elasticity = [self.initial_elasticity] * len(self.land_use_types)
95
+ n_iter = 0
96
+ max_adjust = self.max_difference
97
+ flag_flex = False
98
+
99
+ while True:
100
+ if step != 0:
101
+ self._compute_change(elasticity)
102
+ if self.cell_correction:
103
+ self._correct_cell_change()
104
+
105
+ max_diff = self._compare_to_demand(step, elasticity)
106
+ if max_diff <= max_adjust:
107
+ self.iterations_per_step.append(n_iter)
108
+ break
109
+
110
+ n_iter += 1
111
+ if n_iter > self.max_iteration * 0.5 and not flag_flex:
112
+ max_adjust *= 2
113
+ flag_flex = True
114
+ if n_iter >= self.max_iteration:
115
+ raise RuntimeError(
116
+ f"Allocation did not converge at step {step} (error={max_diff:.1f})"
117
+ )
118
+
119
+ self._apply_complementar()
120
+
121
+ def _compute_change(self, elasticity: list[float]) -> None:
122
+ mask = self._mask()
123
+
124
+ for lu_idx, lu in enumerate(self.land_use_types):
125
+ lu_dir = self.demand.get_current_lu_direction(lu_idx)
126
+ pot = self.backend.get(lu + "_pot").astype(np.float32)
127
+ past = self.backend.get(lu + "_past").astype(np.float32)
128
+ alloc = self.allocation_data[lu_idx]
129
+ lu_stat = self.static[lu]
130
+
131
+ min_ch = alloc.min_change
132
+ max_ch = alloc.max_change
133
+ min_val = alloc.min_value
134
+ max_val = alloc.max_value
135
+
136
+ if lu_stat == 1:
137
+ self.backend.arrays[lu] = np.where(mask, past, self.backend.get(lu))
138
+ continue
139
+
140
+ change = pot * elasticity[lu_idx]
141
+ change = np.where(np.abs(change) >= min_ch, change, 0.0)
142
+ sign = np.sign(change)
143
+ change = np.clip(np.abs(change), 0.0, max_ch) * sign
144
+
145
+ if lu_stat == 0:
146
+ new_val = past + change
147
+ else:
148
+ cond = ((pot >= 0) & (lu_dir == 1)) | ((pot <= 0) & (lu_dir == -1))
149
+ new_val = past + np.where(cond, change, 0.0)
150
+
151
+ new_val = np.clip(new_val, 0.0, 1.0)
152
+
153
+ below_min = new_val <= min_val
154
+ new_val = np.where(below_min, np.where(past >= min_val, min_val, past), new_val)
155
+ above_max = new_val > max_val
156
+ new_val = np.where(above_max, np.where(past <= max_val, max_val, past), new_val)
157
+
158
+ self.backend.arrays[lu] = np.where(mask, new_val, self.backend.get(lu))
159
+
160
+ def _correct_cell_change(self) -> None:
161
+ lus = self.land_use_types
162
+ TOL = 0.005
163
+ MAX_L = 25
164
+
165
+ alloc_min = np.array([spec.min_value for spec in self.allocation_data])
166
+ alloc_max = np.array([spec.max_value for spec in self.allocation_data])
167
+ static = np.array([self.static[lu] for lu in lus])
168
+
169
+ mask = self._mask()
170
+ shape = self.shape
171
+ flat_mask = mask.ravel()
172
+
173
+ def flat(lu: str) -> np.ndarray:
174
+ return cast(np.ndarray, self.backend.get(lu).ravel().astype(np.float32))
175
+
176
+ originals = {lu: flat(lu) for lu in lus}
177
+ vals = np.stack([flat(lu) for lu in lus], axis=1)
178
+ pasts = np.stack([flat(lu + "_past") for lu in lus], axis=1)
179
+
180
+ for _ in range(MAX_L):
181
+ totcov = vals.sum(axis=1, keepdims=True)
182
+ needs = (np.abs(totcov - 1.0) > TOL).ravel() & flat_mask
183
+ if not needs.any():
184
+ break
185
+
186
+ is_static = (static >= 1) | (vals <= alloc_min) | (vals >= alloc_max)
187
+ static_sum = (vals * is_static).sum(axis=1, keepdims=True)
188
+ free_sum = (vals * ~is_static).sum(axis=1, keepdims=True)
189
+ target = 1.0 - static_sum
190
+ excess = free_sum - target
191
+
192
+ diffs = (vals - pasts) * ~is_static
193
+ totchange = np.abs(diffs).sum(axis=1, keepdims=True)
194
+
195
+ needs_b = needs[:, None]
196
+
197
+ with_change = (totchange > 0) & needs_b
198
+ correction = np.where(
199
+ with_change,
200
+ np.abs(diffs) * excess / np.where(totchange > 0, totchange, 1.0),
201
+ 0.0,
202
+ )
203
+
204
+ no_change = (totchange == 0) & needs_b & ~is_static
205
+ scale = np.where(
206
+ no_change & (free_sum > 0),
207
+ target / np.where(free_sum > 0, free_sum, 1.0),
208
+ 1.0,
209
+ )
210
+
211
+ new_vals = np.where(no_change, vals * scale, vals - correction)
212
+ new_vals = np.where(is_static, vals, new_vals)
213
+ vals = np.clip(new_vals, 0.0, 1.0)
214
+
215
+ for i, lu in enumerate(lus):
216
+ self.backend.arrays[lu] = np.where(flat_mask, vals[:, i], originals[lu]).reshape(shape)
217
+
218
+ def _compare_to_demand(self, step: int, elasticity: list[float]) -> float:
219
+ mask = self._mask()
220
+ max_diff = 0.0
221
+
222
+ for lu_idx, lu in enumerate(self.land_use_types):
223
+ area = float(self.backend.get(lu)[mask].sum()) * self.cell_area
224
+ demand = self.demand.get_current_lu_demand(lu_idx)
225
+ lu_dir = self.demand.get_current_lu_direction(lu_idx)
226
+
227
+ if area == 0:
228
+ continue
229
+ if lu_dir == 0 and step == 0:
230
+ lu_dir = 1 if demand >= area else -1
231
+
232
+ elasticity[lu_idx] *= demand / area if lu_dir == 1 else area / demand
233
+
234
+ if elasticity[lu_idx] > self.max_elasticity:
235
+ elasticity[lu_idx] = self.max_elasticity
236
+ self.potential.modify(1, lu_idx, lu_dir)
237
+ elif elasticity[lu_idx] < self.min_elasticity:
238
+ if self.static[lu] < 0:
239
+ elasticity[lu_idx] = self.min_elasticity
240
+ self.potential.modify(1, lu_idx, -lu_dir)
241
+ else:
242
+ self.demand.change_lu_direction(lu_idx)
243
+
244
+ max_diff = max(max_diff, abs(area - demand))
245
+
246
+ return max_diff
247
+
248
+ def _apply_complementar(self) -> None:
249
+ mask = self._mask()
250
+ lus = self.land_use_types
251
+ others = [lu for lu in lus if lu != self.complementar_lu]
252
+
253
+ total = sum(self.backend.get(lu).astype(np.float32) for lu in others)
254
+ comp = np.clip(1.0 - total, 0.0, 1.0)
255
+
256
+ comp_original = self.backend.get(self.complementar_lu).astype(np.float32)
257
+ self.backend.arrays[self.complementar_lu] = np.where(mask, comp, comp_original)
258
+
259
+ # NOTE: this whole branch is unexercised by every scenario in this
260
+ # repository -- instrumented Lab1's 7 steps and `deficit.any()` was
261
+ # never True. No test proves it behaves correctly, as-is or fixed.
262
+ #
263
+ # `no_data` is also dead on arrival: `land_use_no_data` is a
264
+ # PotentialLinearRegression.setup() parameter (see potential/linear.py)
265
+ # that AllocationClueLike.setup() never accepts, so
266
+ # `getattr(self, "land_use_no_data", None)` is always None here, and
267
+ # `lu != None` is always True -- the filter below never actually
268
+ # excludes anything. In Lab1, `land_use_no_data="outros"` and
269
+ # `static["outros"] == 1` happen to name the same class, which is
270
+ # almost certainly the real intent: protect the region's fixed/static
271
+ # class from being reduced just to close this deficit, the same way
272
+ # `_compute_change`/`_correct_cell_change` already protect it via
273
+ # `self.static[lu] == 1` / `is_static`. If this branch is ever made
274
+ # reachable (a synthetic scenario that forces `deficit.any()`), fix
275
+ # the criterion to `self.static[lu] != 1`, not to wiring
276
+ # `land_use_no_data` through -- that would still be the wrong
277
+ # protection, just no longer silently broken.
278
+ deficit = np.maximum(0.0, total - 1.0)
279
+ if deficit.any():
280
+ no_data = getattr(self, "land_use_no_data", None)
281
+ eligible = [lu for lu in others if lu != no_data]
282
+ if eligible:
283
+ stacked = np.stack(
284
+ [self.backend.get(lu).astype(np.float32) for lu in eligible], axis=0
285
+ )
286
+ biggest = np.argmax(stacked, axis=0)
287
+ for i, lu in enumerate(eligible):
288
+ deficit_mask = (biggest == i) & (deficit > 0) & mask
289
+ self.backend.arrays[lu] = np.where(
290
+ deficit_mask,
291
+ np.maximum(0.0, self.backend.get(lu) - deficit),
292
+ self.backend.get(lu),
293
+ )
@@ -0,0 +1,145 @@
1
+ """
2
+ disslucc.allocation.clue_s
3
+ -----------------------------
4
+ Discrete CLUE-S allocation (Verburg et al. 2002) -- cell-by-cell
5
+ competition. RASTER port of
6
+ disslucc_discrete.components.allocation.vector.clue_s (only vector
7
+ exists in the original -- new raster version, following the
8
+ mask/backend pattern already used in allocation/clue.py, algorithm
9
+ identical to the vector one).
10
+
11
+ Each cell belongs to exactly one class (binary 0/1 columns/arrays).
12
+ Each step, adjusts a global correction vector (iter_vec) per class
13
+ until the difference between demand and allocated area is within
14
+ max_difference.
15
+ """
16
+ from __future__ import annotations
17
+
18
+ from typing import cast
19
+
20
+ import numpy as np
21
+ from dissmodel.geo import SyncRasterModel
22
+
23
+ from ...protocols import DemandProtocol
24
+
25
+
26
+ class AllocationDClueSLike(SyncRasterModel):
27
+ """
28
+ Algorithm (per step)
29
+ -----------------------
30
+ 1. iter_vec[lu] = 0 for each lu (reset each step)
31
+ 2. For each cell: best_lu = argmax{(1+tau_lu)*pot_lu + iter_lu},
32
+ restricted to transitions allowed by transition_matrix.
33
+ 3. diff[lu] = demand[lu] - allocated_area[lu]
34
+ 4. iter_vec[lu] += diff[lu] * factor_iteration
35
+ 5. Repeats 2-4 until max(|diff|) <= max_difference or max_iteration.
36
+
37
+ tau_<lu> (optional): per-cell/class attraction/repulsion array --
38
+ if absent, tau=0 (default behavior).
39
+ """
40
+
41
+ def setup(
42
+ self,
43
+ backend,
44
+ demand: DemandProtocol,
45
+ land_use_types: list[str],
46
+ transition_matrix: list[list[list[int]]],
47
+ cell_area: float = 1.0,
48
+ max_difference: float = 10.0,
49
+ max_iteration: int = 2000,
50
+ factor_iteration: float = 0.0001,
51
+ region_attr: str = "region",
52
+ ) -> None:
53
+ super().setup(backend)
54
+ self.demand = demand
55
+ self.land_use_types = land_use_types
56
+ self.cell_area = cell_area
57
+ self.max_difference = max_difference
58
+ self.max_iteration = max_iteration
59
+ self.factor_iteration = factor_iteration
60
+ self.region_attr = region_attr
61
+ # Iterations of the convergence loop at each step, same meaning as
62
+ # the largest n in LuccME's "Iteration -> n" log (0 = first pass accepted).
63
+ self.iterations_per_step: list[int] = []
64
+
65
+ # (n_regions, n_lu, n_lu) -- O(1) access in the inner loop
66
+ self._tm = np.array(transition_matrix, dtype=np.int8)
67
+
68
+ if region_attr not in self.backend.arrays:
69
+ self.backend.set(region_attr, np.ones(self.shape, dtype=np.int32))
70
+
71
+ def _mask(self) -> np.ndarray:
72
+ arr = self.backend.arrays.get("mask", np.ones(self.shape, dtype=bool))
73
+ return cast(np.ndarray, arr.astype(bool))
74
+
75
+ def execute(self) -> None:
76
+ lu_types = self.land_use_types
77
+ n_lu = len(lu_types)
78
+ mask = self._mask()
79
+
80
+ # 0-based regions for numpy indexing
81
+ regions = (self.backend.get(self.region_attr).ravel().astype(int) - 1)
82
+ regions = np.clip(regions, 0, self._tm.shape[0] - 1)
83
+
84
+ # INITIAL STATE of the step -- the transition matrix uses each
85
+ # cell's class at the START of the step, not whatever is being
86
+ # tested during the equilibrium search (allows oscillating
87
+ # between allowed classes until convergence).
88
+ lu_matrix_start = np.stack([self.backend.get(lu).ravel() for lu in lu_types], axis=1)
89
+ initial_lu_idx = np.argmax(lu_matrix_start, axis=1)
90
+ allowed = self._tm[regions, initial_lu_idx, :] # (n_cells, n_lu)
91
+
92
+ n_cells = lu_matrix_start.shape[0]
93
+ tau = np.zeros((n_cells, n_lu), dtype=np.float64)
94
+ for j, lu in enumerate(lu_types):
95
+ col = f"tau_{lu}"
96
+ if col in self.backend.arrays:
97
+ tau[:, j] = self.backend.get(col).ravel()
98
+
99
+ iter_vec = np.zeros(n_lu, dtype=np.float64)
100
+
101
+ # `<lu>_pot` is written once by Potential.execute(), before this
102
+ # component runs, and nothing in this loop ever writes it back --
103
+ # only iter_vec changes between iterations. Hoisting both `pot` and
104
+ # `1.0 + tau` out of the loop skips re-reading/re-stacking backend
105
+ # arrays on every one of the (often dozens of) convergence
106
+ # iterations, for the same result every time.
107
+ pot = np.stack([self.backend.get(lu + "_pot").ravel() for lu in lu_types], axis=1)
108
+ one_plus_tau = 1.0 + tau
109
+
110
+ for n_iter in range(self.max_iteration + 1):
111
+ scores = one_plus_tau * pot + iter_vec[np.newaxis, :]
112
+ scores = np.where(allowed, scores, -np.inf)
113
+
114
+ best_lu_idx = np.argmax(scores, axis=1) # (n_cells,)
115
+
116
+ for j, lu in enumerate(lu_types):
117
+ new_arr = (best_lu_idx == j).astype(np.float32).reshape(self.shape)
118
+ self.backend.arrays[lu] = np.where(mask, new_arr, self.backend.get(lu))
119
+
120
+ diff = self._calc_diff(mask)
121
+ # diff has one scalar per land-use class (a handful) -- plain
122
+ # max()/abs() is the idiomatic way to reduce that, no need to
123
+ # round-trip through a NumPy array for a handful of Python floats.
124
+ max_diff = max(abs(v) for v in diff.values())
125
+
126
+ if max_diff <= self.max_difference:
127
+ self.iterations_per_step.append(n_iter)
128
+ break
129
+ if n_iter >= self.max_iteration:
130
+ raise RuntimeError(
131
+ f"Allocation did not converge at step {int(self.env.now())} "
132
+ f"after {self.max_iteration} iterations (max error={max_diff:.2f})"
133
+ )
134
+
135
+ for j, lu in enumerate(lu_types):
136
+ iter_vec[j] += diff[lu] * self.factor_iteration
137
+
138
+ def _calc_diff(self, mask: np.ndarray) -> dict[str, float]:
139
+ return {
140
+ lu: (
141
+ self.demand.get_current_lu_demand(i)
142
+ - float((self.backend.get(lu)[mask] == 1).sum()) * self.cell_area
143
+ )
144
+ for i, lu in enumerate(self.land_use_types)
145
+ }