Skip to content

Commit acf7955

Browse files
committed
style: black the files left unformatted by the dyno-importer branch
`pixi run black . --check` (CI "Code Quality") failed on 10 files added or reworked on the merged feature branch. Reformat with the pinned black (26.5.1); `black . --check` is now clean (91 files). No functional change.
1 parent 721df6a commit acf7955

10 files changed

Lines changed: 102 additions & 47 deletions

File tree

‎src/dolo/algos/newton.py‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -344,7 +344,12 @@ def newton(
344344
if linsolve_cfg["method"] == "iti":
345345
linsolve_cfg["method"] = "neumann"
346346
else:
347-
linsolve_cfg = {"method": "gmres", "maxit": 50, "tol": 1e-8, "precondition": True}
347+
linsolve_cfg = {
348+
"method": "gmres",
349+
"maxit": 50,
350+
"tol": 1e-8,
351+
"precondition": True,
352+
}
348353

349354
if invmethod is not None:
350355
linsolve_cfg["method"] = "neumann" if invmethod == "iti" else invmethod

‎src/dolo/algos/time_iteration.py‎

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,10 @@
1111
from dolo.numeric.decision_rule import DecisionRule
1212
from dolo.numeric.grids import CartesianGrid
1313
from dolo.numeric.optimize.ncpsolve import ncpsolve
14-
from dolo.numeric.optimize.newton import SerialDifferentiableFunction, newton as serial_newton
14+
from dolo.numeric.optimize.newton import (
15+
SerialDifferentiableFunction,
16+
newton as serial_newton,
17+
)
1518
from dolo.numeric.processes import DiscretizedIIDProcess
1619

1720
from dolo.numeric import DiscretizedModel, GArray
@@ -27,7 +30,9 @@
2730
from .results import AlgoResult, TimeIterationResult
2831

2932

30-
def euler_residuals_tau(dmodel: DiscretizedModel, controls: GArray, dr: DecisionRule) -> GArray:
33+
def euler_residuals_tau(
34+
dmodel: DiscretizedModel, controls: GArray, dr: DecisionRule
35+
) -> GArray:
3136
"""Universal Euler residuals written entirely in terms of GArray and Tau."""
3237
res = GArray.zeros_like(controls)
3338
for i_m, m_val, s_endo in dmodel.regimes():
@@ -175,7 +180,9 @@ def time_iteration(
175180
dprocess_options = kwargs.pop("dprocess_options", {})
176181
if dprocess is not None:
177182
dprocess_options["dprocess"] = dprocess
178-
dmodel = DiscretizedModel(model, grid_options=grid_options, dprocess_options=dprocess_options)
183+
dmodel = DiscretizedModel(
184+
model, grid_options=grid_options, dprocess_options=dprocess_options
185+
)
179186

180187
grid = dmodel.grid
181188
dprocess = dmodel.dprocess
@@ -273,9 +280,11 @@ def time_iteration(
273280
if trace:
274281
trace_details.append({"dr": copy.deepcopy(mdr)})
275282

276-
fn = lambda x_val: euler_residuals_tau(
277-
dmodel, controls_ga.unravel(x_val), mdr
278-
).ravel().reshape((-1, n_x))
283+
fn = (
284+
lambda x_val: euler_residuals_tau(dmodel, controls_ga.unravel(x_val), mdr)
285+
.ravel()
286+
.reshape((-1, n_x))
287+
)
279288
dfn = SerialDifferentiableFunction(fn)
280289

281290
res_0 = fn(controls_0)
@@ -305,7 +314,6 @@ def time_iteration(
305314
err_SA = err_step / err_0 if not numpy.isnan(err_0) and err_0 > 0 else numpy.nan
306315
err_0 = err_step
307316

308-
309317
# Policy acceleration step
310318
if acc_cfg is not None and it > acc_cfg["wait"]:
311319
d = (controls - controls_0).reshape(sh_c)

‎src/dolo/misc/itprinter.py‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
try:
55
from rich.console import Console
6+
67
HAS_RICH = True
78
except ImportError:
89
HAS_RICH = False
@@ -82,9 +83,7 @@ def print_header(self, msg=None):
8283
if msg:
8384
self.console.print(f"[bold cyan]{msg:^{self.table_width}}[/bold cyan]")
8485
self.console.print(self.box_top)
85-
hdr_cells = [
86-
f" {h:>{w}} " for h, w in zip(self.names, self.col_widths)
87-
]
86+
hdr_cells = [f" {h:>{w}} " for h, w in zip(self.names, self.col_widths)]
8887
self.console.print("[bold]│" + "│".join(hdr_cells) + "│[/bold]")
8988
self.console.print(self.box_sep)
9089
self._header_printed = True
@@ -153,7 +152,9 @@ def print_finished(self):
153152
elapsed = time.time() - self.t_start
154153

155154
if self.use_rich:
156-
if getattr(self, "_header_printed", False) and not getattr(self, "_closed", False):
155+
if getattr(self, "_header_printed", False) and not getattr(
156+
self, "_closed", False
157+
):
157158
self.console.print(self.box_bot)
158159
self._closed = True
159160
self.console.print(

‎src/dolo/numeric/__init__.py‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,4 +20,3 @@
2020
"trembling_hand",
2121
"DiscretizedModel",
2222
]
23-

‎src/dolo/numeric/decision_rule.py‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -58,14 +58,18 @@ def __call__(self, *args):
5858

5959
if len(args) == 1 and isinstance(args[0], SliceQP):
6060
sqp = args[0]
61-
is_empty_exo = hasattr(self, "exo_grid") and isinstance(self.exo_grid, EmptyGrid)
61+
is_empty_exo = hasattr(self, "exo_grid") and isinstance(
62+
self.exo_grid, EmptyGrid
63+
)
6264
if sqp.loc is not None and not is_empty_exo:
6365
return self.eval_is(sqp.loc, sqp.endo)
6466
return self.eval_s(sqp.endo)
6567

6668
if len(args) == 1 and isinstance(args[0], QP):
6769
qp = args[0]
68-
is_empty_exo = hasattr(self, "exo_grid") and isinstance(self.exo_grid, EmptyGrid)
70+
is_empty_exo = hasattr(self, "exo_grid") and isinstance(
71+
self.exo_grid, EmptyGrid
72+
)
6973
if isinstance(qp.loc, tuple) and len(qp.loc) >= 2 and not is_empty_exo:
7074
i, s_endo = qp.loc[0], qp.loc[1]
7175
s_arr = np.asarray(s_endo)
@@ -139,6 +143,7 @@ def __init__(
139143

140144
def set_values(self, x):
141145
from dolo.numeric.garray import GArray
146+
142147
if isinstance(x, GArray):
143148
x = x.data
144149
self.coefficients = self.__get_coefficients__(

‎src/dolo/numeric/discretized_model.py‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,9 @@ def lower_bounds(self) -> Optional[GArray]:
8989
if "arbitrage_lb" not in self.model.functions:
9090
return None
9191
lb_fun = self.model.functions["arbitrage_lb"]
92-
controls_lb = GArray.zeros(self.grid, len(self.model.symbols["controls"]), self.n_regimes)
92+
controls_lb = GArray.zeros(
93+
self.grid, len(self.model.symbols["controls"]), self.n_regimes
94+
)
9395
N = self.N_endo
9496
p = np.repeat(self.parms[None, :], N, axis=0)
9597

@@ -103,7 +105,9 @@ def upper_bounds(self) -> Optional[GArray]:
103105
if "arbitrage_ub" not in self.model.functions:
104106
return None
105107
ub_fun = self.model.functions["arbitrage_ub"]
106-
controls_ub = GArray.zeros(self.grid, len(self.model.symbols["controls"]), self.n_regimes)
108+
controls_ub = GArray.zeros(
109+
self.grid, len(self.model.symbols["controls"]), self.n_regimes
110+
)
107111
N = self.N_endo
108112
p = np.repeat(self.parms[None, :], N, axis=0)
109113

@@ -158,7 +162,7 @@ def ergodic_distribution(self, controls: GArray) -> GArray:
158162
"""
159163
P = self.transition_matrix(controls)
160164
# Solve mu P = mu <=> (P^T - I) mu = 0 with sum(mu) = 1
161-
A = (P.T - np.eye(self.N_total))
165+
A = P.T - np.eye(self.N_total)
162166
A[-1, :] = 1.0
163167
b = np.zeros(self.N_total)
164168
b[-1] = 1.0
@@ -168,4 +172,3 @@ def ergodic_distribution(self, controls: GArray) -> GArray:
168172

169173
mu = GArray.zeros(self.grid, 1, self.n_regimes)
170174
return mu.unravel(mu_flat)
171-

‎src/dolo/numeric/garray.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ class QualifiedPoint:
3737
val : np.ndarray
3838
Evaluated economic coordinates / values.
3939
"""
40+
4041
loc: Any
4142
val: np.ndarray
4243

@@ -73,6 +74,7 @@ class QualifiedBatch:
7374
endo : np.ndarray
7475
Endogenous state matrix, shape (N, n_s).
7576
"""
77+
7678
loc: Any
7779
exo: np.ndarray
7880
endo: np.ndarray
@@ -201,4 +203,3 @@ def __neg__(self) -> GArray:
201203
def __repr__(self) -> str:
202204
grid_name = type(self.grid).__name__
203205
return f"GArray(grid={grid_name}, shape={self.data.shape})"
204-

‎src/dolo/numeric/tau.py‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -130,9 +130,7 @@ def slice_transitions(
130130
target_regime = 0 if self.dprocess.n_nodes == 1 else I_m
131131
yield prob, SliceQP(loc=target_regime, exo=M_val, endo=S_endo)
132132

133-
def point_transitions(
134-
self, s: QP, x: np.ndarray
135-
) -> Iterator[Tuple[float, QP]]:
133+
def point_transitions(self, s: QP, x: np.ndarray) -> Iterator[Tuple[float, QP]]:
136134
"""Point-level transition (pure Julia-style).
137135
138136
Given a single state point QP(loc, val) and control vector x,

‎tests/test_tau_garray.py‎

Lines changed: 56 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,12 @@
88
from dolo.compiler.model_v2 import ModelV2, yaml_compose
99
from dolo.numeric.decision_rule import DecisionRule
1010
from dolo.numeric.garray import GArray, QP, SliceQP
11-
from dolo.numeric.grids import UniformCartesianGrid, ProductGrid, UnstructuredGrid, EmptyGrid
11+
from dolo.numeric.grids import (
12+
UniformCartesianGrid,
13+
ProductGrid,
14+
UnstructuredGrid,
15+
EmptyGrid,
16+
)
1217
from dolo.numeric.tau import Tau, trembling_hand
1318
from dolo.numeric.discretized_model import DiscretizedModel
1419
from dolo.algos.time_iteration import residuals_simple, time_iteration
@@ -25,6 +30,7 @@ def _load_v2(path: str) -> ModelV2:
2530
# 1. GArray and QP Unit Tests
2631
# ---------------------------------------------------------------------------
2732

33+
2834
def test_garray_cartesian():
2935
grid = UniformCartesianGrid(min=[0.1, 1.0], max=[0.5, 5.0], n=[10, 20])
3036
ga = GArray.zeros(grid, n_vars=3)
@@ -79,7 +85,9 @@ def test_qualified_point_and_batch():
7985
assert "QualifiedPoint" in repr(qp)
8086

8187
# Construct QualifiedBatch
82-
batch = QualifiedBatch(loc=1, exo=np.array([0.02]), endo=np.array([[1.0, 2.0], [1.5, 2.5]]))
88+
batch = QualifiedBatch(
89+
loc=1, exo=np.array([0.02]), endo=np.array([[1.0, 2.0], [1.5, 2.5]])
90+
)
8391
assert batch.val.shape == (2, 3)
8492
assert np.allclose(batch.val[0], [0.02, 1.0, 2.0])
8593
assert np.allclose(batch.val[1], [0.02, 1.5, 2.5])
@@ -106,7 +114,10 @@ def test_trembling_hand_1d():
106114
# 2. Universal Euler Residuals & Parity
107115
# ---------------------------------------------------------------------------
108116

109-
def euler_residuals(dmodel: DiscretizedModel, controls: GArray, dr: DecisionRule) -> GArray:
117+
118+
def euler_residuals(
119+
dmodel: DiscretizedModel, controls: GArray, dr: DecisionRule
120+
) -> GArray:
110121
"""Universal Euler residuals using Tau, GArray, and direct dr(SliceQP) calls."""
111122
res = GArray.zeros_like(controls)
112123
for i, m_val, s_endo in dmodel.regimes():
@@ -119,10 +130,13 @@ def euler_residuals(dmodel: DiscretizedModel, controls: GArray, dr: DecisionRule
119130
return res
120131

121132

122-
@pytest.mark.parametrize("model_path", [
123-
"examples/models/rbc_mc.yaml",
124-
"examples/models/rbc_iid.yaml",
125-
])
133+
@pytest.mark.parametrize(
134+
"model_path",
135+
[
136+
"examples/models/rbc_mc.yaml",
137+
"examples/models/rbc_iid.yaml",
138+
],
139+
)
126140
def test_tau_euler_parity(model_path: str):
127141
model = _load_v2(model_path)
128142
dmodel = DiscretizedModel(model)
@@ -156,6 +170,7 @@ def test_tau_euler_parity(model_path: str):
156170
# 3. DecisionRule with QP and SliceQP
157171
# ---------------------------------------------------------------------------
158172

173+
159174
def test_decision_rule_qp_dispatch():
160175
model = _load_v2("examples/models/rbc_mc.yaml")
161176
dmodel = DiscretizedModel(model)
@@ -185,10 +200,14 @@ def test_decision_rule_qp_dispatch():
185200
# 4. Transition Matrix & Ergodic Distribution
186201
# ---------------------------------------------------------------------------
187202

188-
@pytest.mark.parametrize("model_path", [
189-
"examples/models/rbc_mc.yaml",
190-
"examples/models/rbc_iid.yaml",
191-
])
203+
204+
@pytest.mark.parametrize(
205+
"model_path",
206+
[
207+
"examples/models/rbc_mc.yaml",
208+
"examples/models/rbc_iid.yaml",
209+
],
210+
)
192211
def test_transition_matrix_and_ergodic(model_path: str):
193212
model = _load_v2(model_path)
194213
dmodel = DiscretizedModel(model)
@@ -205,18 +224,24 @@ def test_transition_matrix_and_ergodic(model_path: str):
205224
# Ergodic distribution
206225
mu = dmodel.ergodic_distribution(controls)
207226
assert isinstance(mu, GArray)
208-
assert np.isclose(mu.data.sum(), 1.0), f"Ergodic distribution does not sum to 1: {mu.data.sum()}"
227+
assert np.isclose(
228+
mu.data.sum(), 1.0
229+
), f"Ergodic distribution does not sum to 1: {mu.data.sum()}"
209230
assert np.all(mu.data >= 0.0), "Negative stationary probabilities!"
210231

211232

212233
# ---------------------------------------------------------------------------
213234
# 5. Full Time Iteration Solver Parity
214235
# ---------------------------------------------------------------------------
215236

216-
@pytest.mark.parametrize("model_path", [
217-
"examples/models/rbc_mc.yaml",
218-
"examples/models/rbc_iid.yaml",
219-
])
237+
238+
@pytest.mark.parametrize(
239+
"model_path",
240+
[
241+
"examples/models/rbc_mc.yaml",
242+
"examples/models/rbc_iid.yaml",
243+
],
244+
)
220245
def test_full_solver_parity(model_path: str):
221246
model = _load_v2(model_path)
222247
dmodel = DiscretizedModel(model)
@@ -243,22 +268,30 @@ def test_full_solver_parity(model_path: str):
243268
it += 1
244269
dr.set_values(controls)
245270

246-
fn = lambda flat_x: euler_residuals(
247-
dmodel, controls.unravel(flat_x), dr
248-
).ravel().reshape((-1, n_x))
271+
fn = (
272+
lambda flat_x: euler_residuals(dmodel, controls.unravel(flat_x), dr)
273+
.ravel()
274+
.reshape((-1, n_x))
275+
)
249276

250277
dfn = SerialDifferentiableFunction(fn)
251-
flat_controls, _ = newton(dfn, controls.ravel().reshape((-1, n_x)), verbose=False, maxit=10)
278+
flat_controls, _ = newton(
279+
dfn, controls.ravel().reshape((-1, n_x)), verbose=False, maxit=10
280+
)
252281
new_controls = controls.unravel(flat_controls)
253282

254283
err = (new_controls - controls).norm()
255284
controls = new_controls
256285

257286
# Parity check on final decision rule coefficients
258287
if isinstance(sol_legacy.dr.coefficients, list):
259-
dr_diff = max(float(np.max(np.abs(c1 - c2))) for c1, c2 in zip(sol_legacy.dr.coefficients, dr.coefficients))
288+
dr_diff = max(
289+
float(np.max(np.abs(c1 - c2)))
290+
for c1, c2 in zip(sol_legacy.dr.coefficients, dr.coefficients)
291+
)
260292
else:
261293
dr_diff = float(np.max(np.abs(sol_legacy.dr.coefficients - dr.coefficients)))
262294

263-
assert dr_diff < 1e-5, f"Decision rule parity failed on {model_path}! diff={dr_diff}"
264-
295+
assert (
296+
dr_diff < 1e-5
297+
), f"Decision rule parity failed on {model_path}! diff={dr_diff}"

‎tests/test_time_iteration_newton.py‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,9 @@ def test_time_iteration_inner_options(rbc_model):
4242

4343

4444
def test_newton_gmres_backtracking(rbc_model):
45-
sol = dolo.newton(rbc_model, linsolve="gmres", linesearch="backtracking", verbose=False)
45+
sol = dolo.newton(
46+
rbc_model, linsolve="gmres", linesearch="backtracking", verbose=False
47+
)
4648
assert sol.converged
4749
assert sol.iterations < 15
4850
assert sol.error_res < 1e-7

0 commit comments

Comments
 (0)