Skip to content

Commit a721088

Browse files
committed
move test_model and test_resource to resource_tests.py
1 parent 7f30507 commit a721088

File tree

2 files changed

+84
-85
lines changed

2 files changed

+84
-85
lines changed

bioimageio/core/prediction.py

Lines changed: 3 additions & 85 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,9 @@
11
import collections
22
import os
3-
import traceback
4-
import warnings
53
from copy import deepcopy
64
from itertools import product
75
from pathlib import Path
8-
from typing import Dict, List, Optional, OrderedDict, Sequence, Tuple, Union
6+
from typing import Dict, List, OrderedDict, Sequence, Tuple, Union
97

108
import imageio
119
import numpy as np
@@ -14,22 +12,12 @@
1412

1513
from bioimageio.core import load_resource_description
1614
from bioimageio.core.prediction_pipeline import PredictionPipeline, create_prediction_pipeline
15+
from bioimageio.core.resource_io.nodes import ImplicitOutputShape, InputTensor, Model, OutputTensor
16+
1717

1818
#
1919
# utility functions for prediction
2020
#
21-
from bioimageio.core.resource_io.nodes import (
22-
ImplicitOutputShape,
23-
InputTensor,
24-
Model,
25-
OutputTensor,
26-
ResourceDescription,
27-
URI,
28-
)
29-
from bioimageio.spec.model.raw_nodes import WeightsFormat
30-
from bioimageio.spec.shared.raw_nodes import ResourceDescription as RawResourceDescription
31-
32-
3321
def require_axes(im, axes):
3422
is_volume = "z" in axes
3523
# we assume images / volumes are loaded as one of
@@ -482,73 +470,3 @@ def predict_images(
482470
outp = [outp]
483471

484472
_predict_sample(prediction_pipeline, inp, outp, padding, tiling)
485-
486-
487-
def test_model(
488-
model_rdf: Union[URI, Path, str],
489-
weight_format: Optional[WeightsFormat] = None,
490-
devices: Optional[List[str]] = None,
491-
decimal: int = 4,
492-
) -> bool:
493-
"""Test whether the test output(s) of a model can be reproduced.
494-
495-
Returns True if the test passes, otherwise returns False and issues a warning.
496-
"""
497-
model = load_resource_description(model_rdf)
498-
assert isinstance(model, Model)
499-
summary = test_resource(model, weight_format=weight_format, devices=devices, decimal=decimal)
500-
if summary["error"] is None:
501-
return True
502-
else:
503-
warnings.warn(summary["error"])
504-
return False
505-
506-
507-
def test_resource(
508-
model_rdf: Union[RawResourceDescription, ResourceDescription, URI, Path, str],
509-
*,
510-
weight_format: Optional[WeightsFormat] = None,
511-
devices: Optional[List[str]] = None,
512-
decimal: int = 4,
513-
):
514-
"""Test RDF dynamically
515-
516-
Returns summary dict with "error" and "traceback" key; summary["error"] is None if no errors were encountered.
517-
"""
518-
error: Optional[str] = None
519-
tb: Optional = None
520-
521-
try:
522-
model = load_resource_description(model_rdf)
523-
except Exception as e:
524-
error = str(e)
525-
tb = traceback.format_tb(e.__traceback__)
526-
else:
527-
if isinstance(model, Model):
528-
try:
529-
prediction_pipeline = create_prediction_pipeline(
530-
bioimageio_model=model, devices=devices, weight_format=weight_format
531-
)
532-
inputs = [np.load(str(in_path)) for in_path in model.test_inputs]
533-
results = predict(prediction_pipeline, inputs)
534-
if isinstance(results, (np.ndarray, xr.DataArray)):
535-
results = [results]
536-
537-
expected = [np.load(str(out_path)) for out_path in model.test_outputs]
538-
if len(results) != len(expected):
539-
error = (
540-
f"Number of outputs and number of expected outputs disagree: {len(results)} != {len(expected)}"
541-
)
542-
else:
543-
for res, exp in zip(results, expected):
544-
try:
545-
np.testing.assert_array_almost_equal(res, exp, decimal=decimal)
546-
except AssertionError as e:
547-
error = f"Output and expected output disagree:\n {e}"
548-
except Exception as e:
549-
error = str(e)
550-
tb = traceback.format_tb(e.__traceback__)
551-
552-
# todo: add tests for non-model resources
553-
554-
return {"error": error, "traceback": tb}

bioimageio/core/resource_tests.py

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
import traceback
2+
import warnings
3+
from pathlib import Path
4+
from typing import List, Optional, Union
5+
6+
import numpy as np
7+
import xarray as xr
8+
9+
from bioimageio.core import load_resource_description
10+
from bioimageio.core.prediction import predict
11+
from bioimageio.core.prediction_pipeline import create_prediction_pipeline
12+
from bioimageio.core.resource_io.nodes import Model, ResourceDescription, URI
13+
from bioimageio.spec.model.raw_nodes import WeightsFormat
14+
from bioimageio.spec.shared.raw_nodes import ResourceDescription as RawResourceDescription
15+
16+
17+
def test_model(
18+
model_rdf: Union[URI, Path, str],
19+
weight_format: Optional[WeightsFormat] = None,
20+
devices: Optional[List[str]] = None,
21+
decimal: int = 4,
22+
) -> dict:
23+
"""Test whether the test output(s) of a model can be reproduced.
24+
25+
Returns summary dict with "error" and "traceback" key; summary["error"] is None if no errors were encountered.
26+
"""
27+
model = load_resource_description(model_rdf)
28+
if isinstance(model, Model):
29+
return test_resource(model, weight_format=weight_format, devices=devices, decimal=decimal)
30+
else:
31+
return {"error": f"Expected RDF type Model, got {type(model)} instead.", "traceback": None}
32+
33+
34+
def test_resource(
35+
model_rdf: Union[RawResourceDescription, ResourceDescription, URI, Path, str],
36+
*,
37+
weight_format: Optional[WeightsFormat] = None,
38+
devices: Optional[List[str]] = None,
39+
decimal: int = 4,
40+
):
41+
"""Test RDF dynamically
42+
43+
Returns summary dict with "error" and "traceback" key; summary["error"] is None if no errors were encountered.
44+
"""
45+
error: Optional[str] = None
46+
tb: Optional = None
47+
48+
try:
49+
model = load_resource_description(model_rdf)
50+
except Exception as e:
51+
error = str(e)
52+
tb = traceback.format_tb(e.__traceback__)
53+
else:
54+
if isinstance(model, Model):
55+
try:
56+
prediction_pipeline = create_prediction_pipeline(
57+
bioimageio_model=model, devices=devices, weight_format=weight_format
58+
)
59+
inputs = [np.load(str(in_path)) for in_path in model.test_inputs]
60+
results = predict(prediction_pipeline, inputs)
61+
if isinstance(results, (np.ndarray, xr.DataArray)):
62+
results = [results]
63+
64+
expected = [np.load(str(out_path)) for out_path in model.test_outputs]
65+
if len(results) != len(expected):
66+
error = (
67+
f"Number of outputs and number of expected outputs disagree: {len(results)} != {len(expected)}"
68+
)
69+
else:
70+
for res, exp in zip(results, expected):
71+
try:
72+
np.testing.assert_array_almost_equal(res, exp, decimal=decimal)
73+
except AssertionError as e:
74+
error = f"Output and expected output disagree:\n {e}"
75+
except Exception as e:
76+
error = str(e)
77+
tb = traceback.format_tb(e.__traceback__)
78+
79+
# todo: add tests for non-model resources
80+
81+
return {"error": error, "traceback": tb}

0 commit comments

Comments
 (0)