Skip to content

Commit

Permalink
Move from setup.py to pyproject.toml and fix a lot of errors
Browse files Browse the repository at this point in the history
  • Loading branch information
finsberg committed Jun 29, 2024
1 parent 1eac171 commit 38adc46
Show file tree
Hide file tree
Showing 46 changed files with 265 additions and 750 deletions.
3 changes: 1 addition & 2 deletions bench/winslow_python.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,7 @@
"import time",
"t0 = time.time()",
f"for i in range({times}):",
" dy = rhs(init_states, 0.0"
+ (")" if gen.oderepr.optimization.parameter_numerals else ", parameters)"),
" dy = rhs(init_states, 0.0" + (")" if gen.oderepr.optimization.parameter_numerals else ", parameters)"),
f"""print ""\"
keep_intermediates = {keep}
use_cse = {use_cse}
Expand Down
4 changes: 2 additions & 2 deletions demo/gotran2c/demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,10 +61,10 @@ def init_parameters():
def solve(t_start, t_end, dt, num_steps=None, method="fe"):
parameters = init_parameters()

if type(dt) is not float:
if not isinstance(t_start, float):
dt = float(dt)
if num_steps is not None:
assert type(num_steps) is int
assert isinstance(num_steps, int)
t_end = dt * num_steps
else:
num_steps = round((t_end - t_start) / dt)
Expand Down
4 changes: 1 addition & 3 deletions gotran/algorithms/symbolicnewtonsolution.py
Original file line number Diff line number Diff line change
Expand Up @@ -257,9 +257,7 @@ def sum_ders(ders):

# Generate F using theta rule
F_expr = [
theta * expr
+ (1 - theta) * expr.subs(subs)
- (sum_ders(ders) - sum_ders(ders).subs(subs)) / ode.dt
theta * expr + (1 - theta) * expr.subs(subs) - (sum_ders(ders) - sum_ders(ders).subs(subs)) / ode.dt
for ders, expr in ode.get_derivative_expr(True)
]

Expand Down
43 changes: 10 additions & 33 deletions gotran/codegeneration/algorithmcomponents.py
Original file line number Diff line number Diff line change
Expand Up @@ -173,8 +173,7 @@ def componentwise_derivative(ode, indices, params=None, result_name="dy"):
for index in indices:
if index < 0 or index >= ode.num_full_states:
error(
"Expected the passed indices to be between 0 and the "
"number of states in the ode, got {0}.".format(index),
"Expected the passed indices to be between 0 and the " "number of states in the ode, got {0}.".format(index),
)
if index in registered:
error(f"Index {index} appeared twice.")
Expand Down Expand Up @@ -496,11 +495,7 @@ def __init__(
sys.stdout.flush()

for i, expr in enumerate(state_exprs):
states_syms = sorted(
(state_dict[sym], sym)
for sym in ode_primitives(expr.expr, time_sym)
if sym in state_dict
)
states_syms = sorted((state_dict[sym], sym) for sym in ode_primitives(expr.expr, time_sym) if sym in state_dict)

self.add_comment(
f"Expressions for the sparse jacobian of state {expr.state.name}",
Expand Down Expand Up @@ -559,10 +554,7 @@ def __init__(
"""
check_arg(jacobian, JacobianComponent)

descr = (
"Compute the diagonal jacobian of the right hand side of the "
"{0} ODE".format(jacobian.root)
)
descr = "Compute the diagonal jacobian of the right hand side of the " "{0} ODE".format(jacobian.root)
super(DiagonalJacobianComponent, self).__init__(
"DiagonalJacobian",
jacobian.root,
Expand Down Expand Up @@ -628,10 +620,7 @@ def __init__(
"""
timer = Timer("Computing jacobian action component") # noqa: F841
check_arg(jacobian, JacobianComponent)
descr = (
"Compute the jacobian action of the right hand side of the "
"{0} ODE".format(jacobian.root)
)
descr = "Compute the jacobian action of the right hand side of the " "{0} ODE".format(jacobian.root)
super(JacobianActionComponent, self).__init__(
"JacobianAction",
jacobian.root,
Expand Down Expand Up @@ -696,9 +685,8 @@ def __init__(
"""
timer = Timer("Computing jacobian action component") # noqa: F841
check_arg(diagonal_jacobian, DiagonalJacobianComponent)
descr = (
"Compute the diagonal jacobian action of the right hand side "
"of the {0} ODE".format(diagonal_jacobian.root)
descr = "Compute the diagonal jacobian action of the right hand side " "of the {0} ODE".format(
diagonal_jacobian.root
)
super(DiagonalJacobianActionComponent, self).__init__(
"DiagonalJacobianAction",
Expand Down Expand Up @@ -851,9 +839,7 @@ def add_intermediate_if_changed(jac, jac_ij, i, j):

# Store factorized jacobian
self.factorized_jacobian = jac
self.num_nonzero = sum(
not jac[i, j].is_zero for i in range(n) for j in range(n)
)
self.num_nonzero = sum(not jac[i, j].is_zero for i in range(n) for j in range(n))

# No need to call recreate body expressions
self.body_expressions = self.ode_objects
Expand Down Expand Up @@ -895,10 +881,7 @@ def __init__(
timer = Timer("Computing forward backward substituion component") # noqa: F841
check_arg(factorized, FactorizedJacobianComponent)
jacobian_name = list(factorized.shapes.keys())[0]
descr = (
"Symbolically forward backward substitute linear system "
"of {0} ODE".format(factorized.root)
)
descr = "Symbolically forward backward substitute linear system " "of {0} ODE".format(factorized.root)
super(ForwardBackwardSubstitutionComponent, self).__init__(
"ForwardBackwardSubst",
factorized.root,
Expand Down Expand Up @@ -969,11 +952,7 @@ def __init__(
dx[i] = self.add_indexed_expression(result_name, i, dx[i] / jac[i, i])

# No need to call recreate body expressions
self.body_expressions = [
obj
for obj in self.ode_objects
if isinstance(obj, (IndexedExpression, Comment))
]
self.body_expressions = [obj for obj in self.ode_objects if isinstance(obj, (IndexedExpression, Comment))]

self.results = [result_name]
self.used_states = set()
Expand Down Expand Up @@ -1106,9 +1085,7 @@ def __init__(self, ode):

# Collect all expanded state expressions
org_state_expressions = ode.state_expressions
expanded_state_exprs = [
ode.expanded_expressions[obj.name] for obj in org_state_expressions
]
expanded_state_exprs = [ode.expanded_expressions[obj.name] for obj in org_state_expressions]

# Call sympy common sub expression reduction
cse_exprs, cse_state_exprs = cse(
Expand Down
5 changes: 1 addition & 4 deletions gotran/codegeneration/avoidsympycontractions.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,10 +83,7 @@ def _function_new(cls, *args, **options):
# it work with NumPy's functions like vectorize(). The ideal
# solution would be just to attach metadata to the exception
# and change NumPy to take advantage of this.
temp = (
"%(name)s takes exactly %(args)s "
"argument%(plural)s (%(given)s given)"
)
temp = "%(name)s takes exactly %(args)s " "argument%(plural)s (%(given)s given)"
raise TypeError(
temp
% {
Expand Down
71 changes: 24 additions & 47 deletions gotran/codegeneration/codecomponent.py
Original file line number Diff line number Diff line change
Expand Up @@ -197,15 +197,17 @@ def add_indexed_expression(
# Check that provided indices fit with the registered shape
if len(self.shapes[basename]) > len(indices):
error(
"Shape mismatch between indices {0} and registered "
"shape for {1}{2}".format(indices, basename, self.shapes[basename]),
"Shape mismatch between indices {0} and registered " "shape for {1}{2}".format(
indices, basename, self.shapes[basename]
),
)

for dim, (index, shape_ind) in enumerate(zip(indices, self.shapes[basename])):
if index >= shape_ind:
error(
"Indices must be smaller or equal to the shape. Mismatch "
"in dim {0}: {1}>={2}".format(dim + 1, index, shape_ind),
"Indices must be smaller or equal to the shape. Mismatch " "in dim {0}: {1}>={2}".format(
dim + 1, index, shape_ind
),
)

# Create the indexed expression
Expand Down Expand Up @@ -270,15 +272,17 @@ def add_indexed_object(self, basename, indices, add_offset=False):
# Check that provided indices fit with the registered shape
if len(self.shapes[basename]) > len(indices):
error(
"Shape mismatch between indices {0} and registered "
"shape for {1}{2}".format(indices, basename, self.shapes[basename]),
"Shape mismatch between indices {0} and registered " "shape for {1}{2}".format(
indices, basename, self.shapes[basename]
),
)

for dim, (index, shape_ind) in enumerate(zip(indices, self.shapes[basename])):
if index >= shape_ind:
error(
"Indices must be smaller or equal to the shape. Mismatch "
"in dim {0}: {1}>={2}".format(dim + 1, index, shape_ind),
"Indices must be smaller or equal to the shape. Mismatch " "in dim {0}: {1}>={2}".format(
dim + 1, index, shape_ind
),
)

# Create IndexedObject
Expand All @@ -301,11 +305,7 @@ def indexed_objects(self, *basenames):
"""
if not basenames:
basenames = list(self.shapes.keys())
return [
obj
for obj in self.ode_objects
if isinstance(obj, IndexedObject) and obj.basename in basenames
]
return [obj for obj in self.ode_objects if isinstance(obj, IndexedObject) and obj.basename in basenames]

def _init_param_state_replace_dict(self):
"""
Expand Down Expand Up @@ -383,23 +383,19 @@ def _init_param_state_replace_dict(self):

# If not having named parameters
if param_repr == "numerals":
param_state_replace_dict.update(
(param.sym, param.init) for param in self.root.parameters
)
param_state_replace_dict.update((param.sym, param.init) for param in self.root.parameters)
elif param_repr == "array":
self.shapes[param_name] = (self.root.num_parameters,)
if field_parameters:
self.shapes["field_" + param_name] = (len(field_parameters),)
param_state_replace_dict.update(
(param.sym, indexed.sym)
for param, indexed in list(param_state_map["parameters"].items())
(param.sym, indexed.sym) for param, indexed in list(param_state_map["parameters"].items())
)

if state_repr == "array":
self.shapes[state_name] = (self.root.num_full_states,)
param_state_replace_dict.update(
(state.sym, indexed.sym)
for state, indexed in list(param_state_map["states"].items())
(state.sym, indexed.sym) for state, indexed in list(param_state_map["states"].items())
)

param_state_replace_dict[self.root._time.sym] = sp.Symbol(time_name)
Expand Down Expand Up @@ -433,15 +429,11 @@ def _expanded_result_expressions(self, **results):

# A map between result expression and result name
result_names = dict(
(result_expr, result_name)
for result_name, result_exprs in list(results.items())
for result_expr in result_exprs
(result_expr, result_name) for result_name, result_exprs in list(results.items()) for result_expr in result_exprs
)

# The expanded result expressions
expanded_result_exprs = [
self.root.expanded_expression(obj) for obj in orig_result_expressions
]
expanded_result_exprs = [self.root.expanded_expression(obj) for obj in orig_result_expressions]

# Set shape for result expressions
for result_name, result_expressions in list(results.items()):
Expand Down Expand Up @@ -476,8 +468,7 @@ def _body_from_cse(self, **results):

if might_take_time:
info(
"Computing common sub expressions for {0}. Might take "
"some time...".format(self.name),
"Computing common sub expressions for {0}. Might take " "some time...".format(self.name),
)
sys.stdout.flush()

Expand Down Expand Up @@ -521,11 +512,7 @@ def _body_from_cse(self, **results):
result_expr_map[result_expr].append(
(
result_names[orig_result_expr],
(
orig_result_expr.indices
if isinstance(orig_result_expr, IndexedExpression)
else ind
),
(orig_result_expr.indices if isinstance(orig_result_expr, IndexedExpression) else ind),
),
)

Expand Down Expand Up @@ -716,9 +703,7 @@ def _recreate_body(self, body_expressions, **results):

# A map between result expression and result name
result_names = dict(
(result_expr, result_name)
for result_name, result_exprs in list(results.items())
for result_expr in result_exprs
(result_expr, result_name) for result_name, result_exprs in list(results.items()) for result_expr in result_exprs
)

timer = Timer(f"Recreate body expressions for {self.name}") # noqa: F841
Expand Down Expand Up @@ -760,12 +745,8 @@ def _recreate_body(self, body_expressions, **results):
replaced_expr_map = OrderedDict()
new_body_expressions = []

present_ode_objects = dict(
(state.name, state) for state in self.root.full_states
)
present_ode_objects.update(
(param.name, param) for param in self.root.parameters
)
present_ode_objects = dict((state.name, state) for state in self.root.full_states)
present_ode_objects.update((param.name, param) for param in self.root.parameters)
old_present_ode_objects = present_ode_objects.copy()

def store_expressions(expr, new_expr):
Expand Down Expand Up @@ -858,11 +839,7 @@ def store_expressions(expr, new_expr):
# index information so that the index previously available
# for this expressions gets available at the last expressions
# the present expression is used in.
if (
isinstance(dep_expr, IndexedExpression)
and dep_expr.basename == body_name
and "reused" in body_repr
):
if isinstance(dep_expr, IndexedExpression) and dep_expr.basename == body_name and "reused" in body_repr:
ind = dep_expr.indices[0]

# Remove available index information
Expand Down
Loading

0 comments on commit 38adc46

Please sign in to comment.