Skip to content

Commit

Permalink
100% test coverage: add test for unsupported correction type
Browse files Browse the repository at this point in the history
  • Loading branch information
eguiraud committed Oct 11, 2023
1 parent 73683d0 commit 5189c74
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 8 deletions.
22 changes: 15 additions & 7 deletions src/correctionlib_gradients/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,21 +14,29 @@
Value: TypeAlias = float | np.ndarray | jax.Array


def apply_ast(ast: schema.Content, correction_name: str, _inputs: dict[str, Value]) -> Value:
def apply_ast(ast: schema.Content, _inputs: dict[str, Value]) -> Value:
match ast:
case float(x):
return x
case _: # pragma: no cover
msg = "Unsupported type of node in the computation graph. This should never happen."
raise RuntimeError(msg)


def assert_supported(c: schema.Correction, name: str) -> None:
match c.data:
case float():
return
case _:
msg = (
f"Cannot compute gradients of correction '{correction_name}': "
f"it contains the unsupported operation type '{type(ast).__name__}'"
)
raise NotImplementedError(msg)
msg = f"Correction '{name}' contains the unsupported operation type '{type(c.data).__name__}'"
raise ValueError(msg)


class CorrectionWithGradient:
def __init__(self, c: schema.Correction):
self._evaluator = partial(apply_ast, c.data, c.name)
assert_supported(c, c.name)

self._evaluator = partial(apply_ast, c.data)
self._input_names = [v.name for v in c.inputs]
self._name = c.name

Expand Down
19 changes: 18 additions & 1 deletion tests/test_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,19 @@
inputs=[schemav2.Variable(name="x", type="real")],
output=schemav2.Variable(name="a scale", type="real"),
data=1.234,
)
),
# this type of correction is unsupported
"categorical": schemav2.Correction(
name="categorical",
version=2,
inputs=[schemav2.Variable(name="c", type="int")],
output=schemav2.Variable(name="a scale", type="real"),
data=schemav2.Category(
nodetype="category",
input="x",
content=[schemav2.CategoryItem(key=0, value=1.234)],
),
),
}


Expand All @@ -41,6 +53,11 @@ def test_missing_input():
cg.eval_dict({})


def test_unsupported_correction():
with pytest.raises(ValueError, match="Correction 'categorical' contains the unsupported operation type 'Category'"):
CorrectionWithGradient(schemas["categorical"])


@pytest.mark.parametrize("jit", [False, True])
def test_evaluate_scale(jit):
cg = CorrectionWithGradient(schemas["scale"])
Expand Down

0 comments on commit 5189c74

Please sign in to comment.