[a84a0ca] | 1 | # -*- coding: utf-8 -*- |
---|
| 2 | """ |
---|
| 3 | Run model unit tests. |
---|
| 4 | |
---|
| 5 | Usage:: |
---|
| 6 | |
---|
| 7 | python -m sasmodels.model_test [opencl|dll|opencl_and_dll] model1 model2 ... |
---|
| 8 | |
---|
| 9 | if model1 is 'all', then all except the remaining models will be tested |
---|
| 10 | |
---|
| 11 | Each model is tested using the default parameters at q=0.1, (qx, qy)=(0.1, 0.1), |
---|
| 12 | and the ER and VR are computed. The return values at these points are not |
---|
| 13 | considered. The test is only to verify that the models run to completion, |
---|
| 14 | and do not produce inf or NaN. |
---|
| 15 | |
---|
| 16 | Tests are defined with the *tests* attribute in the model.py file. *tests* |
---|
| 17 | is a list of individual tests to run, where each test consists of the |
---|
| 18 | parameter values for the test, the q-values and the expected results. For |
---|
| 19 | the effective radius test, the q-value should be 'ER'. For the VR test, |
---|
| 20 | the q-value should be 'VR'. For 1-D tests, either specify the q value or |
---|
| 21 | a list of q-values, and the corresponding I(q) value, or list of I(q) values. |
---|
| 22 | |
---|
| 23 | That is:: |
---|
| 24 | |
---|
| 25 | tests = [ |
---|
| 26 | [ {parameters}, q, I(q)], |
---|
| 27 | [ {parameters}, [q], [I(q)] ], |
---|
| 28 | [ {parameters}, [q1, q2, ...], [I(q1), I(q2), ...]], |
---|
| 29 | |
---|
| 30 | [ {parameters}, (qx, qy), I(qx, Iqy)], |
---|
| 31 | [ {parameters}, [(qx1, qy1), (qx2, qy2), ...], |
---|
| 32 | [I(qx1, qy1), I(qx2, qy2), ...]], |
---|
| 33 | |
---|
| 34 | [ {parameters}, 'ER', ER(pars) ], |
---|
| 35 | [ {parameters}, 'VR', VR(pars) ], |
---|
| 36 | ... |
---|
| 37 | ] |
---|
| 38 | |
---|
| 39 | Parameters are *key:value* pairs, where key is one of the parameters of the |
---|
| 40 | model and value is the value to use for the test. Any parameters not given |
---|
| 41 | in the parameter list will take on the default parameter value. |
---|
| 42 | |
---|
| 43 | Precision defaults to 5 digits (relative). |
---|
| 44 | """ |
---|
| 45 | from __future__ import print_function |
---|
| 46 | |
---|
| 47 | import sys |
---|
| 48 | import unittest |
---|
| 49 | |
---|
[7ae2b7f] | 50 | import numpy as np # type: ignore |
---|
[a84a0ca] | 51 | |
---|
| 52 | from .core import list_models, load_model_info, build_model, HAVE_OPENCL |
---|
[0ff62d4] | 53 | from .kernel import dispersion_mesh |
---|
[6d6508e] | 54 | from .direct_model import call_kernel, get_weights |
---|
[a84a0ca] | 55 | from .exception import annotate_exception |
---|
[4bfd277] | 56 | from .modelinfo import expand_pars |
---|
[a84a0ca] | 57 | |
---|
[e62a134] | 58 | try: |
---|
| 59 | from typing import List, Iterator, Callable |
---|
| 60 | except ImportError: |
---|
| 61 | pass |
---|
| 62 | else: |
---|
| 63 | from .modelinfo import ParameterTable, ParameterSet, TestCondition, ModelInfo |
---|
[0ff62d4] | 64 | from .kernel import KernelModel |
---|
[e62a134] | 65 | |
---|
[4bfd277] | 66 | def call_ER(model_info, pars): |
---|
[e62a134] | 67 | # type: (ModelInfo, ParameterSet) -> float |
---|
[6d6508e] | 68 | """ |
---|
[f619de7] | 69 | Call the model ER function using *values*. |
---|
| 70 | |
---|
| 71 | *model_info* is either *model.info* if you have a loaded model, |
---|
| 72 | or *kernel.info* if you have a model kernel prepared for evaluation. |
---|
[6d6508e] | 73 | """ |
---|
| 74 | if model_info.ER is None: |
---|
| 75 | return 1.0 |
---|
| 76 | else: |
---|
[4bfd277] | 77 | value, weight = _vol_pars(model_info, pars) |
---|
[6d6508e] | 78 | individual_radii = model_info.ER(*value) |
---|
| 79 | return np.sum(weight*individual_radii) / np.sum(weight) |
---|
| 80 | |
---|
[4bfd277] | 81 | def call_VR(model_info, pars): |
---|
[e62a134] | 82 | # type: (ModelInfo, ParameterSet) -> float |
---|
[6d6508e] | 83 | """ |
---|
| 84 | Call the model VR function using *pars*. |
---|
[f619de7] | 85 | |
---|
| 86 | *model_info* is either *model.info* if you have a loaded model, |
---|
| 87 | or *kernel.info* if you have a model kernel prepared for evaluation. |
---|
[6d6508e] | 88 | """ |
---|
| 89 | if model_info.VR is None: |
---|
| 90 | return 1.0 |
---|
| 91 | else: |
---|
[4bfd277] | 92 | value, weight = _vol_pars(model_info, pars) |
---|
[6d6508e] | 93 | whole, part = model_info.VR(*value) |
---|
| 94 | return np.sum(weight*part)/np.sum(weight*whole) |
---|
| 95 | |
---|
[4bfd277] | 96 | def _vol_pars(model_info, pars): |
---|
[e62a134] | 97 | # type: (ModelInfo, ParameterSet) -> Tuple[np.ndarray, np.ndarray] |
---|
[4bfd277] | 98 | vol_pars = [get_weights(p, pars) |
---|
| 99 | for p in model_info.parameters.call_parameters |
---|
| 100 | if p.type == 'volume'] |
---|
| 101 | value, weight = dispersion_mesh(model_info, vol_pars) |
---|
| 102 | return value, weight |
---|
| 103 | |
---|
[a84a0ca] | 104 | |
---|
| 105 | def make_suite(loaders, models): |
---|
[e62a134] | 106 | # type: (List[str], List[str]) -> unittest.TestSuite |
---|
[a84a0ca] | 107 | """ |
---|
| 108 | Construct the pyunit test suite. |
---|
| 109 | |
---|
| 110 | *loaders* is the list of kernel drivers to use, which is one of |
---|
| 111 | *["dll", "opencl"]*, *["dll"]* or *["opencl"]*. For python models, |
---|
| 112 | the python driver is always used. |
---|
| 113 | |
---|
| 114 | *models* is the list of models to test, or *["all"]* to test all models. |
---|
| 115 | """ |
---|
[e62a134] | 116 | ModelTestCase = _hide_model_case_from_nose() |
---|
[a84a0ca] | 117 | suite = unittest.TestSuite() |
---|
| 118 | |
---|
| 119 | if models[0] == 'all': |
---|
| 120 | skip = models[1:] |
---|
| 121 | models = list_models() |
---|
| 122 | else: |
---|
| 123 | skip = [] |
---|
| 124 | for model_name in models: |
---|
| 125 | if model_name in skip: continue |
---|
| 126 | model_info = load_model_info(model_name) |
---|
| 127 | |
---|
| 128 | #print('------') |
---|
| 129 | #print('found tests in', model_name) |
---|
| 130 | #print('------') |
---|
| 131 | |
---|
| 132 | # if ispy then use the dll loader to call pykernel |
---|
| 133 | # don't try to call cl kernel since it will not be |
---|
| 134 | # available in some environmentes. |
---|
[6d6508e] | 135 | is_py = callable(model_info.Iq) |
---|
[a84a0ca] | 136 | |
---|
| 137 | if is_py: # kernel implemented in python |
---|
| 138 | test_name = "Model: %s, Kernel: python"%model_name |
---|
| 139 | test_method_name = "test_%s_python" % model_name |
---|
| 140 | test = ModelTestCase(test_name, model_info, |
---|
| 141 | test_method_name, |
---|
| 142 | platform="dll", # so that |
---|
| 143 | dtype="double") |
---|
| 144 | suite.addTest(test) |
---|
| 145 | else: # kernel implemented in C |
---|
| 146 | # test using opencl if desired and available |
---|
| 147 | if 'opencl' in loaders and HAVE_OPENCL: |
---|
| 148 | test_name = "Model: %s, Kernel: OpenCL"%model_name |
---|
| 149 | test_method_name = "test_%s_opencl" % model_name |
---|
| 150 | # Using dtype=None so that the models that are only |
---|
| 151 | # correct for double precision are not tested using |
---|
| 152 | # single precision. The choice is determined by the |
---|
| 153 | # presence of *single=False* in the model file. |
---|
| 154 | test = ModelTestCase(test_name, model_info, |
---|
| 155 | test_method_name, |
---|
| 156 | platform="ocl", dtype=None) |
---|
| 157 | #print("defining", test_name) |
---|
| 158 | suite.addTest(test) |
---|
| 159 | |
---|
| 160 | # test using dll if desired |
---|
| 161 | if 'dll' in loaders: |
---|
| 162 | test_name = "Model: %s, Kernel: dll"%model_name |
---|
| 163 | test_method_name = "test_%s_dll" % model_name |
---|
| 164 | test = ModelTestCase(test_name, model_info, |
---|
| 165 | test_method_name, |
---|
| 166 | platform="dll", |
---|
| 167 | dtype="double") |
---|
| 168 | suite.addTest(test) |
---|
| 169 | |
---|
| 170 | return suite |
---|
| 171 | |
---|
| 172 | |
---|
[e62a134] | 173 | def _hide_model_case_from_nose(): |
---|
| 174 | # type: () -> type |
---|
[a84a0ca] | 175 | class ModelTestCase(unittest.TestCase): |
---|
| 176 | """ |
---|
| 177 | Test suit for a particular model with a particular kernel driver. |
---|
| 178 | |
---|
| 179 | The test suite runs a simple smoke test to make sure the model |
---|
| 180 | functions, then runs the list of tests at the bottom of the model |
---|
| 181 | description file. |
---|
| 182 | """ |
---|
| 183 | def __init__(self, test_name, model_info, test_method_name, |
---|
| 184 | platform, dtype): |
---|
[e62a134] | 185 | # type: (str, ModelInfo, str, str, DType) -> None |
---|
[a84a0ca] | 186 | self.test_name = test_name |
---|
| 187 | self.info = model_info |
---|
| 188 | self.platform = platform |
---|
| 189 | self.dtype = dtype |
---|
| 190 | |
---|
[4bfd277] | 191 | setattr(self, test_method_name, self.run_all) |
---|
[a84a0ca] | 192 | unittest.TestCase.__init__(self, test_method_name) |
---|
| 193 | |
---|
[4bfd277] | 194 | def run_all(self): |
---|
[e62a134] | 195 | # type: () -> None |
---|
[a84a0ca] | 196 | smoke_tests = [ |
---|
[e78edc4] | 197 | # test validity at reasonable values |
---|
[e62a134] | 198 | ({}, 0.1, None), |
---|
| 199 | ({}, (0.1, 0.1), None), |
---|
[e78edc4] | 200 | # test validity at q = 0 |
---|
[b151003] | 201 | #({}, 0.0, None), |
---|
| 202 | #({}, (0.0, 0.0), None), |
---|
[e78edc4] | 203 | # test that ER/VR will run if they exist |
---|
[e62a134] | 204 | ({}, 'ER', None), |
---|
| 205 | ({}, 'VR', None), |
---|
[a84a0ca] | 206 | ] |
---|
| 207 | |
---|
[6d6508e] | 208 | tests = self.info.tests |
---|
[a84a0ca] | 209 | try: |
---|
| 210 | model = build_model(self.info, dtype=self.dtype, |
---|
| 211 | platform=self.platform) |
---|
| 212 | for test in smoke_tests + tests: |
---|
[4bfd277] | 213 | self.run_one(model, test) |
---|
[a84a0ca] | 214 | |
---|
| 215 | if not tests and self.platform == "dll": |
---|
| 216 | ## Uncomment the following to make forgetting the test |
---|
| 217 | ## values an error. Only do so for the "dll" tests |
---|
| 218 | ## to reduce noise from both opencl and dll, and because |
---|
| 219 | ## python kernels use platform="dll". |
---|
| 220 | #raise Exception("No test cases provided") |
---|
| 221 | pass |
---|
| 222 | |
---|
[4d76711] | 223 | except: |
---|
| 224 | annotate_exception(self.test_name) |
---|
[a84a0ca] | 225 | raise |
---|
| 226 | |
---|
[4bfd277] | 227 | def run_one(self, model, test): |
---|
[0ff62d4] | 228 | # type: (KernelModel, TestCondition) -> None |
---|
[e62a134] | 229 | user_pars, x, y = test |
---|
| 230 | pars = expand_pars(self.info.parameters, user_pars) |
---|
[a84a0ca] | 231 | |
---|
| 232 | if not isinstance(y, list): |
---|
| 233 | y = [y] |
---|
| 234 | if not isinstance(x, list): |
---|
| 235 | x = [x] |
---|
| 236 | |
---|
| 237 | self.assertEqual(len(y), len(x)) |
---|
| 238 | |
---|
| 239 | if x[0] == 'ER': |
---|
| 240 | actual = [call_ER(model.info, pars)] |
---|
| 241 | elif x[0] == 'VR': |
---|
| 242 | actual = [call_VR(model.info, pars)] |
---|
| 243 | elif isinstance(x[0], tuple): |
---|
[e62a134] | 244 | qx, qy = zip(*x) |
---|
| 245 | q_vectors = [np.array(qx), np.array(qy)] |
---|
[4d76711] | 246 | kernel = model.make_kernel(q_vectors) |
---|
[a84a0ca] | 247 | actual = call_kernel(kernel, pars) |
---|
| 248 | else: |
---|
| 249 | q_vectors = [np.array(x)] |
---|
[4d76711] | 250 | kernel = model.make_kernel(q_vectors) |
---|
[a84a0ca] | 251 | actual = call_kernel(kernel, pars) |
---|
| 252 | |
---|
[4bfd277] | 253 | self.assertTrue(len(actual) > 0) |
---|
[a84a0ca] | 254 | self.assertEqual(len(y), len(actual)) |
---|
| 255 | |
---|
| 256 | for xi, yi, actual_yi in zip(x, y, actual): |
---|
| 257 | if yi is None: |
---|
| 258 | # smoke test --- make sure it runs and produces a value |
---|
| 259 | self.assertTrue(np.isfinite(actual_yi), |
---|
| 260 | 'invalid f(%s): %s' % (xi, actual_yi)) |
---|
[82923a6] | 261 | elif np.isnan(yi): |
---|
| 262 | self.assertTrue(np.isnan(actual_yi), |
---|
| 263 | 'f(%s): expected:%s; actual:%s' |
---|
| 264 | % (xi, yi, actual_yi)) |
---|
[a84a0ca] | 265 | else: |
---|
[82923a6] | 266 | # is_near does not work for infinite values, so also test |
---|
| 267 | # for exact values. Note that this will not |
---|
| 268 | self.assertTrue(yi==actual_yi or is_near(yi, actual_yi, 5), |
---|
[a84a0ca] | 269 | 'f(%s); expected:%s; actual:%s' |
---|
| 270 | % (xi, yi, actual_yi)) |
---|
| 271 | |
---|
| 272 | return ModelTestCase |
---|
| 273 | |
---|
| 274 | def is_near(target, actual, digits=5): |
---|
[e62a134] | 275 | # type: (float, float, int) -> bool |
---|
[a84a0ca] | 276 | """ |
---|
| 277 | Returns true if *actual* is within *digits* significant digits of *target*. |
---|
| 278 | """ |
---|
| 279 | import math |
---|
| 280 | shift = 10**math.ceil(math.log10(abs(target))) |
---|
| 281 | return abs(target-actual)/shift < 1.5*10**-digits |
---|
| 282 | |
---|
| 283 | def main(): |
---|
[e62a134] | 284 | # type: () -> int |
---|
[a84a0ca] | 285 | """ |
---|
| 286 | Run tests given is sys.argv. |
---|
| 287 | |
---|
| 288 | Returns 0 if success or 1 if any tests fail. |
---|
| 289 | """ |
---|
[3434240] | 290 | try: |
---|
[81cd2a2] | 291 | from xmlrunner import XMLTestRunner as TestRunner |
---|
| 292 | test_args = { 'output': 'logs' } |
---|
| 293 | except ImportError: |
---|
| 294 | from unittest import TextTestRunner as TestRunner |
---|
| 295 | test_args = { } |
---|
[a84a0ca] | 296 | |
---|
| 297 | models = sys.argv[1:] |
---|
| 298 | if models and models[0] == '-v': |
---|
| 299 | verbosity = 2 |
---|
| 300 | models = models[1:] |
---|
| 301 | else: |
---|
| 302 | verbosity = 1 |
---|
| 303 | if models and models[0] == 'opencl': |
---|
| 304 | if not HAVE_OPENCL: |
---|
| 305 | print("opencl is not available") |
---|
| 306 | return 1 |
---|
| 307 | loaders = ['opencl'] |
---|
| 308 | models = models[1:] |
---|
| 309 | elif models and models[0] == 'dll': |
---|
| 310 | # TODO: test if compiler is available? |
---|
| 311 | loaders = ['dll'] |
---|
| 312 | models = models[1:] |
---|
| 313 | elif models and models[0] == 'opencl_and_dll': |
---|
| 314 | loaders = ['opencl', 'dll'] |
---|
| 315 | models = models[1:] |
---|
| 316 | else: |
---|
| 317 | loaders = ['opencl', 'dll'] |
---|
| 318 | if not models: |
---|
| 319 | print("""\ |
---|
| 320 | usage: |
---|
| 321 | python -m sasmodels.model_test [-v] [opencl|dll] model1 model2 ... |
---|
| 322 | |
---|
[e62a134] | 323 | If -v is included on the command line, then use verbose output. |
---|
[a84a0ca] | 324 | |
---|
| 325 | If neither opencl nor dll is specified, then models will be tested with |
---|
[e62a134] | 326 | both OpenCL and dll; the compute target is ignored for pure python models. |
---|
[a84a0ca] | 327 | |
---|
| 328 | If model1 is 'all', then all except the remaining models will be tested. |
---|
| 329 | |
---|
| 330 | """) |
---|
| 331 | |
---|
| 332 | return 1 |
---|
| 333 | |
---|
[81cd2a2] | 334 | runner = TestRunner(verbosity=verbosity, **test_args) |
---|
[a84a0ca] | 335 | result = runner.run(make_suite(loaders, models)) |
---|
| 336 | return 1 if result.failures or result.errors else 0 |
---|
| 337 | |
---|
| 338 | |
---|
| 339 | def model_tests(): |
---|
[c1a888b] | 340 | # type: () -> Iterator[Callable[[], None]] |
---|
[a84a0ca] | 341 | """ |
---|
| 342 | Test runner visible to nosetests. |
---|
| 343 | |
---|
| 344 | Run "nosetests sasmodels" on the command line to invoke it. |
---|
| 345 | """ |
---|
| 346 | tests = make_suite(['opencl', 'dll'], ['all']) |
---|
| 347 | for test_i in tests: |
---|
[4bfd277] | 348 | yield test_i.run_all |
---|
[a84a0ca] | 349 | |
---|
| 350 | |
---|
| 351 | if __name__ == "__main__": |
---|
| 352 | sys.exit(main()) |
---|