source: sasmodels/sasmodels/model_test.py @ c1a888b

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

fix type signature errors

  • Property mode set to 100644
File size: 11.9 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"""
45#TODO: rename to tests so that tab completion works better for models directory
46
47from __future__ import print_function
48
49import sys
50import unittest
51
52import numpy as np
53
54from .core import list_models, load_model_info, build_model, HAVE_OPENCL
55from .details import dispersion_mesh
56from .direct_model import call_kernel, get_weights
57from .exception import annotate_exception
58from .modelinfo import expand_pars
59
60try:
61    from typing import List, Iterator, Callable
62except ImportError:
63    pass
64else:
65    from .modelinfo import ParameterTable, ParameterSet, TestCondition, ModelInfo
66    from .kernelpy import PyModel, PyInput, PyKernel, DType
67
68def call_ER(model_info, pars):
69    # type: (ModelInfo, ParameterSet) -> float
70    """
71    Call the model ER function using *values*. *model_info* is either
72    *model.info* if you have a loaded model, or *kernel.info* if you
73    have a model kernel prepared for evaluation.
74    """
75    if model_info.ER is None:
76        return 1.0
77    else:
78        value, weight = _vol_pars(model_info, pars)
79        individual_radii = model_info.ER(*value)
80        return np.sum(weight*individual_radii) / np.sum(weight)
81
82def call_VR(model_info, pars):
83    # type: (ModelInfo, ParameterSet) -> float
84    """
85    Call the model VR function using *pars*.
86    *info* is either *model.info* if you have a loaded model, or *kernel.info*
87    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                ({}, 0.1, None),
198                ({}, (0.1, 0.1), None),
199                ({}, 'ER', None),
200                ({}, 'VR', None),
201                ]
202
203            tests = self.info.tests
204            try:
205                model = build_model(self.info, dtype=self.dtype,
206                                    platform=self.platform)
207                for test in smoke_tests + tests:
208                    self.run_one(model, test)
209
210                if not tests and self.platform == "dll":
211                    ## Uncomment the following to make forgetting the test
212                    ## values an error.  Only do so for the "dll" tests
213                    ## to reduce noise from both opencl and dll, and because
214                    ## python kernels use platform="dll".
215                    #raise Exception("No test cases provided")
216                    pass
217
218            except:
219                annotate_exception(self.test_name)
220                raise
221
222        def run_one(self, model, test):
223            # type: (PyModel, TestCondition) -> None
224            user_pars, x, y = test
225            pars = expand_pars(self.info.parameters, user_pars)
226
227            if not isinstance(y, list):
228                y = [y]
229            if not isinstance(x, list):
230                x = [x]
231
232            self.assertEqual(len(y), len(x))
233
234            if x[0] == 'ER':
235                actual = [call_ER(model.info, pars)]
236            elif x[0] == 'VR':
237                actual = [call_VR(model.info, pars)]
238            elif isinstance(x[0], tuple):
239                qx, qy = zip(*x)
240                q_vectors = [np.array(qx), np.array(qy)]
241                kernel = model.make_kernel(q_vectors)
242                actual = call_kernel(kernel, pars)
243            else:
244                q_vectors = [np.array(x)]
245                kernel = model.make_kernel(q_vectors)
246                actual = call_kernel(kernel, pars)
247
248            self.assertTrue(len(actual) > 0)
249            self.assertEqual(len(y), len(actual))
250
251            for xi, yi, actual_yi in zip(x, y, actual):
252                if yi is None:
253                    # smoke test --- make sure it runs and produces a value
254                    self.assertTrue(np.isfinite(actual_yi),
255                                    'invalid f(%s): %s' % (xi, actual_yi))
256                else:
257                    self.assertTrue(is_near(yi, actual_yi, 5),
258                                    'f(%s); expected:%s; actual:%s'
259                                    % (xi, yi, actual_yi))
260
261    return ModelTestCase
262
263def is_near(target, actual, digits=5):
264    # type: (float, float, int) -> bool
265    """
266    Returns true if *actual* is within *digits* significant digits of *target*.
267    """
268    import math
269    shift = 10**math.ceil(math.log10(abs(target)))
270    return abs(target-actual)/shift < 1.5*10**-digits
271
272def main():
273    # type: () -> int
274    """
275    Run tests given is sys.argv.
276
277    Returns 0 if success or 1 if any tests fail.
278    """
279    import xmlrunner
280
281    models = sys.argv[1:]
282    if models and models[0] == '-v':
283        verbosity = 2
284        models = models[1:]
285    else:
286        verbosity = 1
287    if models and models[0] == 'opencl':
288        if not HAVE_OPENCL:
289            print("opencl is not available")
290            return 1
291        loaders = ['opencl']
292        models = models[1:]
293    elif models and models[0] == 'dll':
294        # TODO: test if compiler is available?
295        loaders = ['dll']
296        models = models[1:]
297    elif models and models[0] == 'opencl_and_dll':
298        loaders = ['opencl', 'dll']
299        models = models[1:]
300    else:
301        loaders = ['opencl', 'dll']
302    if not models:
303        print("""\
304usage:
305  python -m sasmodels.model_test [-v] [opencl|dll] model1 model2 ...
306
307If -v is included on the command line, then use verbose output.
308
309If neither opencl nor dll is specified, then models will be tested with
310both OpenCL and dll; the compute target is ignored for pure python models.
311
312If model1 is 'all', then all except the remaining models will be tested.
313
314""")
315
316        return 1
317
318    #runner = unittest.TextTestRunner()
319    runner = xmlrunner.XMLTestRunner(output='logs', verbosity=verbosity)
320    result = runner.run(make_suite(loaders, models))
321    return 1 if result.failures or result.errors else 0
322
323
324def model_tests():
325    # type: () -> Iterator[Callable[[], None]]
326    """
327    Test runner visible to nosetests.
328
329    Run "nosetests sasmodels" on the command line to invoke it.
330    """
331    tests = make_suite(['opencl', 'dll'], ['all'])
332    for test_i in tests:
333        yield test_i.run_all
334
335
336if __name__ == "__main__":
337    sys.exit(main())
Note: See TracBrowser for help on using the repository browser.