source: sasmodels/sasmodels/model_test.py @ b151003

core_shell_microgelscostrafo411magnetic_modelrelease_v0.94release_v0.95ticket-1257-vesicle-productticket_1156ticket_1265_superballticket_822_more_unit_tests
Last change on this file since b151003 was b151003, checked in by Paul Kienzle <pkienzle@…>, 8 years ago

Merge remote-tracking branch 'origin/master' into polydisp

Conflicts:

sasmodels/model_test.py

  • Property mode set to 100644
File size: 12.0 KB
Line 
1# -*- coding: utf-8 -*-
2"""
3Run model unit tests.
4
5Usage::
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
11Each model is tested using the default parameters at q=0.1, (qx, qy)=(0.1, 0.1),
12and the ER and VR are computed.  The return values at these points are not
13considered.  The test is only to verify that the models run to completion,
14and do not produce inf or NaN.
15
16Tests are defined with the *tests* attribute in the model.py file.  *tests*
17is a list of individual tests to run, where each test consists of the
18parameter values for the test, the q-values and the expected results.  For
19the effective radius test, the q-value should be 'ER'.  For the VR test,
20the q-value should be 'VR'.  For 1-D tests, either specify the q value or
21a list of q-values, and the corresponding I(q) value, or list of I(q) values.
22
23That 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
39Parameters are *key:value* pairs, where key is one of the parameters of the
40model and value is the value to use for the test.  Any parameters not given
41in the parameter list will take on the default parameter value.
42
43Precision defaults to 5 digits (relative).
44"""
45from __future__ import print_function
46
47import sys
48import unittest
49
50import numpy as np  # type: ignore
51
52from .core import list_models, load_model_info, build_model, HAVE_OPENCL
53from .details import dispersion_mesh
54from .direct_model import call_kernel, get_weights
55from .exception import annotate_exception
56from .modelinfo import expand_pars
57
58try:
59    from typing import List, Iterator, Callable
60except ImportError:
61    pass
62else:
63    from .modelinfo import ParameterTable, ParameterSet, TestCondition, ModelInfo
64    from .kernelpy import PyModel, PyInput, PyKernel, DType
65
66def call_ER(model_info, pars):
67    # type: (ModelInfo, ParameterSet) -> float
68    """
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.
73    """
74    if model_info.ER is None:
75        return 1.0
76    else:
77        value, weight = _vol_pars(model_info, pars)
78        individual_radii = model_info.ER(*value)
79        return np.sum(weight*individual_radii) / np.sum(weight)
80
81def call_VR(model_info, pars):
82    # type: (ModelInfo, ParameterSet) -> float
83    """
84    Call the model VR function using *pars*.
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.
88    """
89    if model_info.VR is None:
90        return 1.0
91    else:
92        value, weight = _vol_pars(model_info, pars)
93        whole, part = model_info.VR(*value)
94        return np.sum(weight*part)/np.sum(weight*whole)
95
96def _vol_pars(model_info, pars):
97    # type: (ModelInfo, ParameterSet) -> Tuple[np.ndarray, np.ndarray]
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
104
105def make_suite(loaders, models):
106    # type: (List[str], List[str]) -> unittest.TestSuite
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    """
116    ModelTestCase = _hide_model_case_from_nose()
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.
135        is_py = callable(model_info.Iq)
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
173def _hide_model_case_from_nose():
174    # type: () -> type
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):
185            # type: (str, ModelInfo, str, str, DType) -> None
186            self.test_name = test_name
187            self.info = model_info
188            self.platform = platform
189            self.dtype = dtype
190
191            setattr(self, test_method_name, self.run_all)
192            unittest.TestCase.__init__(self, test_method_name)
193
194        def run_all(self):
195            # type: () -> None
196            smoke_tests = [
197                # test validity at reasonable values
198                ({}, 0.1, None),
199                ({}, (0.1, 0.1), None),
200                # test validity at q = 0
201                #({}, 0.0, None),
202                #({}, (0.0, 0.0), None),
203                # test that ER/VR will run if they exist
204                ({}, 'ER', None),
205                ({}, 'VR', None),
206                ]
207
208            tests = self.info.tests
209            try:
210                model = build_model(self.info, dtype=self.dtype,
211                                    platform=self.platform)
212                for test in smoke_tests + tests:
213                    self.run_one(model, test)
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
223            except:
224                annotate_exception(self.test_name)
225                raise
226
227        def run_one(self, model, test):
228            # type: (PyModel, TestCondition) -> None
229            user_pars, x, y = test
230            pars = expand_pars(self.info.parameters, user_pars)
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):
244                qx, qy = zip(*x)
245                q_vectors = [np.array(qx), np.array(qy)]
246                kernel = model.make_kernel(q_vectors)
247                actual = call_kernel(kernel, pars)
248            else:
249                q_vectors = [np.array(x)]
250                kernel = model.make_kernel(q_vectors)
251                actual = call_kernel(kernel, pars)
252
253            self.assertTrue(len(actual) > 0)
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))
261                else:
262                    self.assertTrue(is_near(yi, actual_yi, 5),
263                                    'f(%s); expected:%s; actual:%s'
264                                    % (xi, yi, actual_yi))
265
266    return ModelTestCase
267
268def is_near(target, actual, digits=5):
269    # type: (float, float, int) -> bool
270    """
271    Returns true if *actual* is within *digits* significant digits of *target*.
272    """
273    import math
274    shift = 10**math.ceil(math.log10(abs(target)))
275    return abs(target-actual)/shift < 1.5*10**-digits
276
277def main():
278    # type: () -> int
279    """
280    Run tests given is sys.argv.
281
282    Returns 0 if success or 1 if any tests fail.
283    """
284    import xmlrunner
285
286    models = sys.argv[1:]
287    if models and models[0] == '-v':
288        verbosity = 2
289        models = models[1:]
290    else:
291        verbosity = 1
292    if models and models[0] == 'opencl':
293        if not HAVE_OPENCL:
294            print("opencl is not available")
295            return 1
296        loaders = ['opencl']
297        models = models[1:]
298    elif models and models[0] == 'dll':
299        # TODO: test if compiler is available?
300        loaders = ['dll']
301        models = models[1:]
302    elif models and models[0] == 'opencl_and_dll':
303        loaders = ['opencl', 'dll']
304        models = models[1:]
305    else:
306        loaders = ['opencl', 'dll']
307    if not models:
308        print("""\
309usage:
310  python -m sasmodels.model_test [-v] [opencl|dll] model1 model2 ...
311
312If -v is included on the command line, then use verbose output.
313
314If neither opencl nor dll is specified, then models will be tested with
315both OpenCL and dll; the compute target is ignored for pure python models.
316
317If model1 is 'all', then all except the remaining models will be tested.
318
319""")
320
321        return 1
322
323    #runner = unittest.TextTestRunner()
324    runner = xmlrunner.XMLTestRunner(output='logs', verbosity=verbosity)
325    result = runner.run(make_suite(loaders, models))
326    return 1 if result.failures or result.errors else 0
327
328
329def model_tests():
330    # type: () -> Iterator[Callable[[], None]]
331    """
332    Test runner visible to nosetests.
333
334    Run "nosetests sasmodels" on the command line to invoke it.
335    """
336    tests = make_suite(['opencl', 'dll'], ['all'])
337    for test_i in tests:
338        yield test_i.run_all
339
340
341if __name__ == "__main__":
342    sys.exit(main())
Note: See TracBrowser for help on using the repository browser.