Skip to content
Snippets Groups Projects
Commit 20e018f2 authored by Daniel Sali's avatar Daniel Sali
Browse files

Remove wait on .jls file, define DynareError

parent ae4c20e2
No related branches found
No related tags found
1 merge request!3Remove async wait
// cyclic reduction algorithm
var y, c, k, a, h, b;
varexo e, u;
verbatim;
% I want these comments included in
% example1.m 1999q1 1999y
%
var = 1;
end;
parameters beta, rho, alpha, delta, theta, psi, tau;
alpha = 0.36;
rho = 0.95;
tau = 0.025;
beta = 0.99;
delta = 0.025;
psi = 0;
theta = 2.95;
phi = 0.1;
model;
c*theta*h^(1+psi)=(1-alpha)*y;
k = beta*(((exp(b)*c)/(exp(b(+1))*c(+1)))
*(exp(b(+1))*alpha*y(+1)+(1-delta)*k));
y = exp(a)*(k(-1)^alpha)*(h^(1-alpha));
k = exp(b)*(y-c)+(1-delta)*k(-1);
a = rho*a(-1)+tau*b(-1) + e;
b = tau*a(-1)+rho*b(-1) + u;
end;
steady_state_model;
K_Y = beta*alpha /(1 - beta*(1 - delta));
H_Y = K_Y^(-alpha/(1 - alpha));
C_Y = 1 - delta*K_Y;
y = (theta*C_Y*H_Y^(1 + psi)/(1 - alpha))^(-1/(1 + psi));
c = C_Y*y;
k = K_Y*y;
h = H_Y*y;
a = 0;
b = 0;
end;
spooky;
shocks;
var e;
periods 1;
values 0.01;
var u;
periods 2;
values 0.015;
end;
perfect_foresight_setup(periods = 100);
perfect_foresight_solver;
import logging
import time
import os
from pathlib import Path
from juliacall import Main as jl
from juliacall import Main as jl, JuliaError
from .dynare_context import Context
from .errors import DynareError
logger = logging.getLogger("dynare.dynare")
def dynare(model: str | Path) -> Context:
try:
if isinstance(model, str):
model = Path(model)
jl.seval("using Serialization")
jl.seval("using Dynare")
# Double-escape '\' as julia will also interpret the string. Only relevant on Windows
resolved_path = str(model.resolve()).replace("\\", "\\\\")
jl.seval(f'@dynare "{resolved_path}"')
jls_path = model.parent / model.stem / "output" / f"{model.stem}.jls"
timeout = int(os.getenv("DYNARE_WAIT", 600))
start_time = time.time()
while not jls_path.exists():
if time.time() - start_time > timeout:
logger.error(
f"Timeout reached: {timeout} seconds. The file {jls_path.resolve()} was not created."
)
raise TimeoutError(
f"Timeout reached: {timeout} seconds. The file {jls_path.resolve()} was not created."
jl.seval(
"using DataFrames, Tables, PythonCall, Dynare, LinearRationalExpectations"
)
logger.debug(f"Waiting for the file {jls_path.resolve()} to be created")
time.sleep(1)
jl.seval("using DataFrames, Tables, PythonCall, Dynare, LinearRationalExpectations")
# Convert the Julia AxisArrayTable fields of a Context to a Pandas DataFrame with PythonCall.pytable
jl.seval(
......@@ -197,8 +182,21 @@ def dynare(model: str | Path) -> Context:
end
"""
)
jl.seval(f'@dynare "{resolved_path}"')
jls_path = model.parent / model.stem / "output" / f"{model.stem}.jls"
if not jls_path.exists():
raise DynareError(
f"Model evaluation failed. No JLS file found at {jls_path}"
)
context = jl.seval(
f"""ctx = Serialization.deserialize("{jls_path.resolve()}");
convert_to_pycontext(ctx)"""
)
return Context.from_julia(context)
except JuliaError as e:
raise DynareError.from_julia_error(e)
except Exception as e:
raise DynareError(f"An unexpected error occurred: {e}") from e
from typing import Self
class DynareError(Exception):
"""Exception raised for errors occurring during the execution of the dynare Julia command."""
def __init__(self, message):
self.message = message
super().__init__(self.message)
def __str__(self):
return f"DynareError: {self.message}"
@classmethod
def from_julia_error(cls, julia_error) -> Self:
message = f"JuliaError:\n{str(julia_error)}"
return cls(message)
from pathlib import Path
from dynare import dynare
def test_dynare():
print(dynare(Path(__file__).parent.parent / "examples" / "example1pf_bad.mod"))
if __name__ == "__main__":
test_dynare()
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment