Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Check type of inputs in eval, eval_dict #33

Merged
merged 1 commit into from
Oct 30, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 24 additions & 7 deletions src/correctionlib_gradients/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,17 +127,34 @@ def _get_result_size(self, inputs: dict[str, jax.Array]) -> int:
class CorrectionWithGradient:
def __init__(self, c: schema.Correction):
self._dag = CorrectionDAG(c)
self._input_names = [v.name for v in c.inputs]
self._input_vars = c.inputs
self._name = c.name

def evaluate(self, *inputs: Value) -> Value:
if (n_in := len(inputs)) != (n_expected := len(self._input_names)):
def evaluate(self, *inputs: Value) -> jax.Array:
self._check_num_inputs(inputs)
inputs_as_jax = tuple(jax.numpy.array(i) for i in inputs)
self._check_input_types(inputs_as_jax)
input_names = (v.name for v in self._input_vars)

input_dict = dict(zip(input_names, inputs_as_jax))
return self._dag.evaluate(input_dict)

def _check_num_inputs(self, inputs: tuple[Value, ...]) -> None:
if (n_in := len(inputs)) != (n_expected := len(self._input_vars)):
msg = (
f"This correction requires {n_expected} input(s), {n_in} provided."
f" Required inputs are {self._input_names}"
f" Required inputs are {[v.name for v in self._input_vars]}"
)
raise ValueError(msg)

inputs_as_jax = (jax.numpy.array(i) for i in inputs)
input_dict = dict(zip(self._input_names, inputs_as_jax))
return self._dag.evaluate(input_dict)
def _check_input_types(self, inputs: tuple[jax.Array, ...]) -> None:
for i, v in enumerate(inputs):
in_type = v.dtype
expected_type_str = self._input_vars[i].type
expected_type = {"real": np.floating, "int": np.integer}[expected_type_str]
if not np.issubdtype(in_type, expected_type):
msg = (
f"Variable '{self._input_vars[i].name}' has type {in_type}"
f" instead of the expected {expected_type.__name__}"
)
raise ValueError(msg)
7 changes: 7 additions & 0 deletions tests/test_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,13 @@ def test_wrong_input_length():
cg.evaluate(0.0, 1.0)


def test_wrong_input_type():
cg = CorrectionWithGradient(schemas["scale"])

with pytest.raises(ValueError, match="Variable 'x' has type int64 instead of the expected float"):
cg.evaluate(0)


def test_missing_input():
cg = CorrectionWithGradient(schemas["scale"])

Expand Down