1 | #!/usr/bin/env python |
---|
2 | # -*- coding: utf-8 -*- |
---|
3 | """ |
---|
4 | Program to compare models using different compute engines. |
---|
5 | |
---|
6 | This program lets you compare results between OpenCL and DLL versions |
---|
7 | of the code and between precision (half, fast, single, double, quad), |
---|
8 | where fast precision is single precision using native functions for |
---|
9 | trig, etc., and may not be completely IEEE 754 compliant. This lets |
---|
10 | make sure that the model calculations are stable, or if you need to |
---|
11 | tag the model as double precision only. |
---|
12 | |
---|
13 | Run using ./compare.sh (Linux, Mac) or compare.bat (Windows) in the |
---|
14 | sasmodels root to see the command line options. |
---|
15 | |
---|
16 | Note that there is no way within sasmodels to select between an |
---|
17 | OpenCL CPU device and a GPU device, but you can do so by setting the |
---|
18 | PYOPENCL_CTX environment variable ahead of time. Start a python |
---|
19 | interpreter and enter:: |
---|
20 | |
---|
21 | import pyopencl as cl |
---|
22 | cl.create_some_context() |
---|
23 | |
---|
24 | This will prompt you to select from the available OpenCL devices |
---|
25 | and tell you which string to use for the PYOPENCL_CTX variable. |
---|
26 | On Windows you will need to remove the quotes. |
---|
27 | """ |
---|
28 | |
---|
29 | from __future__ import print_function |
---|
30 | |
---|
31 | import sys |
---|
32 | import math |
---|
33 | import datetime |
---|
34 | import traceback |
---|
35 | |
---|
36 | import numpy as np |
---|
37 | |
---|
38 | from . import core |
---|
39 | from . import kerneldll |
---|
40 | from . import product |
---|
41 | from .data import plot_theory, empty_data1D, empty_data2D |
---|
42 | from .direct_model import DirectModel |
---|
43 | from .convert import revert_pars, constrain_new_to_old |
---|
44 | |
---|
45 | USAGE = """ |
---|
46 | usage: compare.py model N1 N2 [options...] [key=val] |
---|
47 | |
---|
48 | Compare the speed and value for a model between the SasView original and the |
---|
49 | sasmodels rewrite. |
---|
50 | |
---|
51 | model is the name of the model to compare (see below). |
---|
52 | N1 is the number of times to run sasmodels (default=1). |
---|
53 | N2 is the number times to run sasview (default=1). |
---|
54 | |
---|
55 | Options (* for default): |
---|
56 | |
---|
57 | -plot*/-noplot plots or suppress the plot of the model |
---|
58 | -lowq*/-midq/-highq/-exq use q values up to 0.05, 0.2, 1.0, 10.0 |
---|
59 | -nq=128 sets the number of Q points in the data set |
---|
60 | -1d*/-2d computes 1d or 2d data |
---|
61 | -preset*/-random[=seed] preset or random parameters |
---|
62 | -mono/-poly* force monodisperse/polydisperse |
---|
63 | -cutoff=1e-5* cutoff value for including a point in polydispersity |
---|
64 | -pars/-nopars* prints the parameter set or not |
---|
65 | -abs/-rel* plot relative or absolute error |
---|
66 | -linear/-log*/-q4 intensity scaling |
---|
67 | -hist/-nohist* plot histogram of relative error |
---|
68 | -res=0 sets the resolution width dQ/Q if calculating with resolution |
---|
69 | -accuracy=Low accuracy of the resolution calculation Low, Mid, High, Xhigh |
---|
70 | -edit starts the parameter explorer |
---|
71 | |
---|
72 | Any two calculation engines can be selected for comparison: |
---|
73 | |
---|
74 | -single/-double/-half/-fast sets an OpenCL calculation engine |
---|
75 | -single!/-double!/-quad! sets an OpenMP calculation engine |
---|
76 | -sasview sets the sasview calculation engine |
---|
77 | |
---|
78 | The default is -single -sasview. Note that the interpretation of quad |
---|
79 | precision depends on architecture, and may vary from 64-bit to 128-bit, |
---|
80 | with 80-bit floats being common (1e-19 precision). |
---|
81 | |
---|
82 | Key=value pairs allow you to set specific values for the model parameters. |
---|
83 | """ |
---|
84 | |
---|
85 | # Update docs with command line usage string. This is separate from the usual |
---|
86 | # doc string so that we can display it at run time if there is an error. |
---|
87 | # lin |
---|
88 | __doc__ = (__doc__ # pylint: disable=redefined-builtin |
---|
89 | + """ |
---|
90 | Program description |
---|
91 | ------------------- |
---|
92 | |
---|
93 | """ |
---|
94 | + USAGE) |
---|
95 | |
---|
96 | kerneldll.ALLOW_SINGLE_PRECISION_DLLS = True |
---|
97 | |
---|
98 | MODELS = core.list_models() |
---|
99 | |
---|
100 | # CRUFT python 2.6 |
---|
101 | if not hasattr(datetime.timedelta, 'total_seconds'): |
---|
102 | def delay(dt): |
---|
103 | """Return number date-time delta as number seconds""" |
---|
104 | return dt.days * 86400 + dt.seconds + 1e-6 * dt.microseconds |
---|
105 | else: |
---|
106 | def delay(dt): |
---|
107 | """Return number date-time delta as number seconds""" |
---|
108 | return dt.total_seconds() |
---|
109 | |
---|
110 | |
---|
111 | class push_seed(object): |
---|
112 | """ |
---|
113 | Set the seed value for the random number generator. |
---|
114 | |
---|
115 | When used in a with statement, the random number generator state is |
---|
116 | restored after the with statement is complete. |
---|
117 | |
---|
118 | :Parameters: |
---|
119 | |
---|
120 | *seed* : int or array_like, optional |
---|
121 | Seed for RandomState |
---|
122 | |
---|
123 | :Example: |
---|
124 | |
---|
125 | Seed can be used directly to set the seed:: |
---|
126 | |
---|
127 | >>> from numpy.random import randint |
---|
128 | >>> push_seed(24) |
---|
129 | <...push_seed object at...> |
---|
130 | >>> print(randint(0,1000000,3)) |
---|
131 | [242082 899 211136] |
---|
132 | |
---|
133 | Seed can also be used in a with statement, which sets the random |
---|
134 | number generator state for the enclosed computations and restores |
---|
135 | it to the previous state on completion:: |
---|
136 | |
---|
137 | >>> with push_seed(24): |
---|
138 | ... print(randint(0,1000000,3)) |
---|
139 | [242082 899 211136] |
---|
140 | |
---|
141 | Using nested contexts, we can demonstrate that state is indeed |
---|
142 | restored after the block completes:: |
---|
143 | |
---|
144 | >>> with push_seed(24): |
---|
145 | ... print(randint(0,1000000)) |
---|
146 | ... with push_seed(24): |
---|
147 | ... print(randint(0,1000000,3)) |
---|
148 | ... print(randint(0,1000000)) |
---|
149 | 242082 |
---|
150 | [242082 899 211136] |
---|
151 | 899 |
---|
152 | |
---|
153 | The restore step is protected against exceptions in the block:: |
---|
154 | |
---|
155 | >>> with push_seed(24): |
---|
156 | ... print(randint(0,1000000)) |
---|
157 | ... try: |
---|
158 | ... with push_seed(24): |
---|
159 | ... print(randint(0,1000000,3)) |
---|
160 | ... raise Exception() |
---|
161 | ... except: |
---|
162 | ... print("Exception raised") |
---|
163 | ... print(randint(0,1000000)) |
---|
164 | 242082 |
---|
165 | [242082 899 211136] |
---|
166 | Exception raised |
---|
167 | 899 |
---|
168 | """ |
---|
169 | def __init__(self, seed=None): |
---|
170 | self._state = np.random.get_state() |
---|
171 | np.random.seed(seed) |
---|
172 | |
---|
173 | def __enter__(self): |
---|
174 | return None |
---|
175 | |
---|
176 | def __exit__(self, *args): |
---|
177 | np.random.set_state(self._state) |
---|
178 | |
---|
179 | def tic(): |
---|
180 | """ |
---|
181 | Timer function. |
---|
182 | |
---|
183 | Use "toc=tic()" to start the clock and "toc()" to measure |
---|
184 | a time interval. |
---|
185 | """ |
---|
186 | then = datetime.datetime.now() |
---|
187 | return lambda: delay(datetime.datetime.now() - then) |
---|
188 | |
---|
189 | |
---|
190 | def set_beam_stop(data, radius, outer=None): |
---|
191 | """ |
---|
192 | Add a beam stop of the given *radius*. If *outer*, make an annulus. |
---|
193 | |
---|
194 | Note: this function does not use the sasview package |
---|
195 | """ |
---|
196 | if hasattr(data, 'qx_data'): |
---|
197 | q = np.sqrt(data.qx_data**2 + data.qy_data**2) |
---|
198 | data.mask = (q < radius) |
---|
199 | if outer is not None: |
---|
200 | data.mask |= (q >= outer) |
---|
201 | else: |
---|
202 | data.mask = (data.x < radius) |
---|
203 | if outer is not None: |
---|
204 | data.mask |= (data.x >= outer) |
---|
205 | |
---|
206 | |
---|
207 | def parameter_range(p, v): |
---|
208 | """ |
---|
209 | Choose a parameter range based on parameter name and initial value. |
---|
210 | """ |
---|
211 | if p.endswith('_pd_n'): |
---|
212 | return [0, 100] |
---|
213 | elif p.endswith('_pd_nsigma'): |
---|
214 | return [0, 5] |
---|
215 | elif p.endswith('_pd_type'): |
---|
216 | return v |
---|
217 | elif any(s in p for s in ('theta', 'phi', 'psi')): |
---|
218 | # orientation in [-180,180], orientation pd in [0,45] |
---|
219 | if p.endswith('_pd'): |
---|
220 | return [0, 45] |
---|
221 | else: |
---|
222 | return [-180, 180] |
---|
223 | elif 'sld' in p: |
---|
224 | return [-0.5, 10] |
---|
225 | elif p.endswith('_pd'): |
---|
226 | return [0, 1] |
---|
227 | elif p == 'background': |
---|
228 | return [0, 10] |
---|
229 | elif p == 'scale': |
---|
230 | return [0, 1e3] |
---|
231 | elif p == 'case_num': |
---|
232 | # RPA hack |
---|
233 | return [0, 10] |
---|
234 | elif v < 0: |
---|
235 | # Kxy parameters in rpa model can be negative |
---|
236 | return [2*v, -2*v] |
---|
237 | else: |
---|
238 | return [0, (2*v if v > 0 else 1)] |
---|
239 | |
---|
240 | |
---|
241 | def _randomize_one(p, v): |
---|
242 | """ |
---|
243 | Randomize a single parameter. |
---|
244 | """ |
---|
245 | if any(p.endswith(s) for s in ('_pd_n', '_pd_nsigma', '_pd_type')): |
---|
246 | return v |
---|
247 | else: |
---|
248 | return np.random.uniform(*parameter_range(p, v)) |
---|
249 | |
---|
250 | |
---|
251 | def randomize_pars(pars, seed=None): |
---|
252 | """ |
---|
253 | Generate random values for all of the parameters. |
---|
254 | |
---|
255 | Valid ranges for the random number generator are guessed from the name of |
---|
256 | the parameter; this will not account for constraints such as cap radius |
---|
257 | greater than cylinder radius in the capped_cylinder model, so |
---|
258 | :func:`constrain_pars` needs to be called afterward.. |
---|
259 | """ |
---|
260 | with push_seed(seed): |
---|
261 | # Note: the sort guarantees order `of calls to random number generator |
---|
262 | pars = dict((p, _randomize_one(p, v)) |
---|
263 | for p, v in sorted(pars.items())) |
---|
264 | return pars |
---|
265 | |
---|
266 | def constrain_pars(model_info, pars): |
---|
267 | """ |
---|
268 | Restrict parameters to valid values. |
---|
269 | |
---|
270 | This includes model specific code for models such as capped_cylinder |
---|
271 | which need to support within model constraints (cap radius more than |
---|
272 | cylinder radius in this case). |
---|
273 | """ |
---|
274 | name = model_info['id'] |
---|
275 | # if it is a product model, then just look at the form factor since |
---|
276 | # none of the structure factors need any constraints. |
---|
277 | if '*' in name: |
---|
278 | name = name.split('*')[0] |
---|
279 | |
---|
280 | if name == 'capped_cylinder' and pars['cap_radius'] < pars['radius']: |
---|
281 | pars['radius'], pars['cap_radius'] = pars['cap_radius'], pars['radius'] |
---|
282 | if name == 'barbell' and pars['bell_radius'] < pars['radius']: |
---|
283 | pars['radius'], pars['bell_radius'] = pars['bell_radius'], pars['radius'] |
---|
284 | |
---|
285 | # Limit guinier to an Rg such that Iq > 1e-30 (single precision cutoff) |
---|
286 | if name == 'guinier': |
---|
287 | #q_max = 0.2 # mid q maximum |
---|
288 | q_max = 1.0 # high q maximum |
---|
289 | rg_max = np.sqrt(90*np.log(10) + 3*np.log(pars['scale']))/q_max |
---|
290 | pars['rg'] = min(pars['rg'], rg_max) |
---|
291 | |
---|
292 | if name == 'rpa': |
---|
293 | # Make sure phi sums to 1.0 |
---|
294 | if pars['case_num'] < 2: |
---|
295 | pars['Phia'] = 0. |
---|
296 | pars['Phib'] = 0. |
---|
297 | elif pars['case_num'] < 5: |
---|
298 | pars['Phia'] = 0. |
---|
299 | total = sum(pars['Phi'+c] for c in 'abcd') |
---|
300 | for c in 'abcd': |
---|
301 | pars['Phi'+c] /= total |
---|
302 | |
---|
303 | def parlist(pars): |
---|
304 | """ |
---|
305 | Format the parameter list for printing. |
---|
306 | """ |
---|
307 | active = None |
---|
308 | fields = {} |
---|
309 | lines = [] |
---|
310 | for k, v in sorted(pars.items()): |
---|
311 | parts = k.split('_pd') |
---|
312 | #print(k, active, parts) |
---|
313 | if len(parts) == 1: |
---|
314 | if active: lines.append(_format_par(active, **fields)) |
---|
315 | active = k |
---|
316 | fields = {'value': v} |
---|
317 | else: |
---|
318 | assert parts[0] == active |
---|
319 | if parts[1]: |
---|
320 | fields[parts[1][1:]] = v |
---|
321 | else: |
---|
322 | fields['pd'] = v |
---|
323 | if active: lines.append(_format_par(active, **fields)) |
---|
324 | return "\n".join(lines) |
---|
325 | |
---|
326 | #return "\n".join("%s: %s"%(p, v) for p, v in sorted(pars.items())) |
---|
327 | |
---|
328 | def _format_par(name, value=0., pd=0., n=0, nsigma=3., type='gaussian'): |
---|
329 | line = "%s: %g"%(name, value) |
---|
330 | if pd != 0. and n != 0: |
---|
331 | line += " +/- %g (%d points in [-%g,%g] sigma %s)"\ |
---|
332 | % (pd, n, nsigma, nsigma, type) |
---|
333 | return line |
---|
334 | |
---|
335 | def suppress_pd(pars): |
---|
336 | """ |
---|
337 | Suppress theta_pd for now until the normalization is resolved. |
---|
338 | |
---|
339 | May also suppress complete polydispersity of the model to test |
---|
340 | models more quickly. |
---|
341 | """ |
---|
342 | pars = pars.copy() |
---|
343 | for p in pars: |
---|
344 | if p.endswith("_pd_n"): pars[p] = 0 |
---|
345 | return pars |
---|
346 | |
---|
347 | def eval_sasview(model_info, data): |
---|
348 | """ |
---|
349 | Return a model calculator using the SasView fitting engine. |
---|
350 | """ |
---|
351 | # importing sas here so that the error message will be that sas failed to |
---|
352 | # import rather than the more obscure smear_selection not imported error |
---|
353 | import sas |
---|
354 | from sas.models.qsmearing import smear_selection |
---|
355 | |
---|
356 | def get_model(name): |
---|
357 | #print("new",sorted(_pars.items())) |
---|
358 | sas = __import__('sas.models.' + name) |
---|
359 | ModelClass = getattr(getattr(sas.models, name, None), name, None) |
---|
360 | if ModelClass is None: |
---|
361 | raise ValueError("could not find model %r in sas.models"%name) |
---|
362 | return ModelClass() |
---|
363 | |
---|
364 | # grab the sasview model, or create it if it is a product model |
---|
365 | if model_info['composition']: |
---|
366 | composition_type, parts = model_info['composition'] |
---|
367 | if composition_type == 'product': |
---|
368 | from sas.models.MultiplicationModel import MultiplicationModel |
---|
369 | P, S = [get_model(p) for p in model_info['oldname']] |
---|
370 | model = MultiplicationModel(P, S) |
---|
371 | else: |
---|
372 | raise ValueError("mixture models not handled yet") |
---|
373 | else: |
---|
374 | model = get_model(model_info['oldname']) |
---|
375 | |
---|
376 | # build a smearer with which to call the model, if necessary |
---|
377 | smearer = smear_selection(data, model=model) |
---|
378 | if hasattr(data, 'qx_data'): |
---|
379 | q = np.sqrt(data.qx_data**2 + data.qy_data**2) |
---|
380 | index = ((~data.mask) & (~np.isnan(data.data)) |
---|
381 | & (q >= data.qmin) & (q <= data.qmax)) |
---|
382 | if smearer is not None: |
---|
383 | smearer.model = model # because smear_selection has a bug |
---|
384 | smearer.accuracy = data.accuracy |
---|
385 | smearer.set_index(index) |
---|
386 | theory = lambda: smearer.get_value() |
---|
387 | else: |
---|
388 | theory = lambda: model.evalDistribution([data.qx_data[index], |
---|
389 | data.qy_data[index]]) |
---|
390 | elif smearer is not None: |
---|
391 | theory = lambda: smearer(model.evalDistribution(data.x)) |
---|
392 | else: |
---|
393 | theory = lambda: model.evalDistribution(data.x) |
---|
394 | |
---|
395 | def calculator(**pars): |
---|
396 | """ |
---|
397 | Sasview calculator for model. |
---|
398 | """ |
---|
399 | # paying for parameter conversion each time to keep life simple, if not fast |
---|
400 | pars = revert_pars(model_info, pars) |
---|
401 | for k, v in pars.items(): |
---|
402 | parts = k.split('.') # polydispersity components |
---|
403 | if len(parts) == 2: |
---|
404 | model.dispersion[parts[0]][parts[1]] = v |
---|
405 | else: |
---|
406 | model.setParam(k, v) |
---|
407 | return theory() |
---|
408 | |
---|
409 | calculator.engine = "sasview" |
---|
410 | return calculator |
---|
411 | |
---|
412 | DTYPE_MAP = { |
---|
413 | 'half': '16', |
---|
414 | 'fast': 'fast', |
---|
415 | 'single': '32', |
---|
416 | 'double': '64', |
---|
417 | 'quad': '128', |
---|
418 | 'f16': '16', |
---|
419 | 'f32': '32', |
---|
420 | 'f64': '64', |
---|
421 | 'longdouble': '128', |
---|
422 | } |
---|
423 | def eval_opencl(model_info, data, dtype='single', cutoff=0.): |
---|
424 | """ |
---|
425 | Return a model calculator using the OpenCL calculation engine. |
---|
426 | """ |
---|
427 | def builder(model_info): |
---|
428 | try: |
---|
429 | return core.build_model(model_info, dtype=dtype, platform="ocl") |
---|
430 | except Exception as exc: |
---|
431 | print(exc) |
---|
432 | print("... trying again with single precision") |
---|
433 | return core.build_model(model_info, dtype='single', platform="ocl") |
---|
434 | if model_info['composition']: |
---|
435 | composition_type, parts = model_info['composition'] |
---|
436 | if composition_type == 'product': |
---|
437 | P, S = [builder(p) for p in parts] |
---|
438 | model = product.ProductModel(P, S) |
---|
439 | else: |
---|
440 | raise ValueError("mixture models not handled yet") |
---|
441 | else: |
---|
442 | model = builder(model_info) |
---|
443 | calculator = DirectModel(data, model, cutoff=cutoff) |
---|
444 | calculator.engine = "OCL%s"%DTYPE_MAP[dtype] |
---|
445 | return calculator |
---|
446 | |
---|
447 | def eval_ctypes(model_info, data, dtype='double', cutoff=0.): |
---|
448 | """ |
---|
449 | Return a model calculator using the DLL calculation engine. |
---|
450 | """ |
---|
451 | if dtype == 'quad': |
---|
452 | dtype = 'longdouble' |
---|
453 | def builder(model_info): |
---|
454 | return core.build_model(model_info, dtype=dtype, platform="dll") |
---|
455 | |
---|
456 | if model_info['composition']: |
---|
457 | composition_type, parts = model_info['composition'] |
---|
458 | if composition_type == 'product': |
---|
459 | P, S = [builder(p) for p in parts] |
---|
460 | model = product.ProductModel(P, S) |
---|
461 | else: |
---|
462 | raise ValueError("mixture models not handled yet") |
---|
463 | else: |
---|
464 | model = builder(model_info) |
---|
465 | calculator = DirectModel(data, model, cutoff=cutoff) |
---|
466 | calculator.engine = "OMP%s"%DTYPE_MAP[dtype] |
---|
467 | return calculator |
---|
468 | |
---|
469 | def time_calculation(calculator, pars, Nevals=1): |
---|
470 | """ |
---|
471 | Compute the average calculation time over N evaluations. |
---|
472 | |
---|
473 | An additional call is generated without polydispersity in order to |
---|
474 | initialize the calculation engine, and make the average more stable. |
---|
475 | """ |
---|
476 | # initialize the code so time is more accurate |
---|
477 | value = calculator(**suppress_pd(pars)) |
---|
478 | toc = tic() |
---|
479 | for _ in range(max(Nevals, 1)): # make sure there is at least one eval |
---|
480 | value = calculator(**pars) |
---|
481 | average_time = toc()*1000./Nevals |
---|
482 | return value, average_time |
---|
483 | |
---|
484 | def make_data(opts): |
---|
485 | """ |
---|
486 | Generate an empty dataset, used with the model to set Q points |
---|
487 | and resolution. |
---|
488 | |
---|
489 | *opts* contains the options, with 'qmax', 'nq', 'res', |
---|
490 | 'accuracy', 'is2d' and 'view' parsed from the command line. |
---|
491 | """ |
---|
492 | qmax, nq, res = opts['qmax'], opts['nq'], opts['res'] |
---|
493 | if opts['is2d']: |
---|
494 | data = empty_data2D(np.linspace(-qmax, qmax, nq), resolution=res) |
---|
495 | data.accuracy = opts['accuracy'] |
---|
496 | set_beam_stop(data, 0.004) |
---|
497 | index = ~data.mask |
---|
498 | else: |
---|
499 | if opts['view'] == 'log': |
---|
500 | qmax = math.log10(qmax) |
---|
501 | q = np.logspace(qmax-3, qmax, nq) |
---|
502 | else: |
---|
503 | q = np.linspace(0.001*qmax, qmax, nq) |
---|
504 | data = empty_data1D(q, resolution=res) |
---|
505 | index = slice(None, None) |
---|
506 | return data, index |
---|
507 | |
---|
508 | def make_engine(model_info, data, dtype, cutoff): |
---|
509 | """ |
---|
510 | Generate the appropriate calculation engine for the given datatype. |
---|
511 | |
---|
512 | Datatypes with '!' appended are evaluated using external C DLLs rather |
---|
513 | than OpenCL. |
---|
514 | """ |
---|
515 | if dtype == 'sasview': |
---|
516 | return eval_sasview(model_info, data) |
---|
517 | elif dtype.endswith('!'): |
---|
518 | return eval_ctypes(model_info, data, dtype=dtype[:-1], cutoff=cutoff) |
---|
519 | else: |
---|
520 | return eval_opencl(model_info, data, dtype=dtype, cutoff=cutoff) |
---|
521 | |
---|
522 | def compare(opts, limits=None): |
---|
523 | """ |
---|
524 | Preform a comparison using options from the command line. |
---|
525 | |
---|
526 | *limits* are the limits on the values to use, either to set the y-axis |
---|
527 | for 1D or to set the colormap scale for 2D. If None, then they are |
---|
528 | inferred from the data and returned. When exploring using Bumps, |
---|
529 | the limits are set when the model is initially called, and maintained |
---|
530 | as the values are adjusted, making it easier to see the effects of the |
---|
531 | parameters. |
---|
532 | """ |
---|
533 | Nbase, Ncomp = opts['n1'], opts['n2'] |
---|
534 | pars = opts['pars'] |
---|
535 | data = opts['data'] |
---|
536 | |
---|
537 | # Base calculation |
---|
538 | if Nbase > 0: |
---|
539 | base = opts['engines'][0] |
---|
540 | try: |
---|
541 | base_value, base_time = time_calculation(base, pars, Nbase) |
---|
542 | print("%s t=%.1f ms, intensity=%.0f" |
---|
543 | % (base.engine, base_time, sum(base_value))) |
---|
544 | except ImportError: |
---|
545 | traceback.print_exc() |
---|
546 | Nbase = 0 |
---|
547 | |
---|
548 | # Comparison calculation |
---|
549 | if Ncomp > 0: |
---|
550 | comp = opts['engines'][1] |
---|
551 | try: |
---|
552 | comp_value, comp_time = time_calculation(comp, pars, Ncomp) |
---|
553 | print("%s t=%.1f ms, intensity=%.0f" |
---|
554 | % (comp.engine, comp_time, sum(comp_value))) |
---|
555 | except ImportError: |
---|
556 | traceback.print_exc() |
---|
557 | Ncomp = 0 |
---|
558 | |
---|
559 | # Compare, but only if computing both forms |
---|
560 | if Nbase > 0 and Ncomp > 0: |
---|
561 | resid = (base_value - comp_value) |
---|
562 | relerr = resid/comp_value |
---|
563 | _print_stats("|%s-%s|" |
---|
564 | % (base.engine, comp.engine) + (" "*(3+len(comp.engine))), |
---|
565 | resid) |
---|
566 | _print_stats("|(%s-%s)/%s|" |
---|
567 | % (base.engine, comp.engine, comp.engine), |
---|
568 | relerr) |
---|
569 | |
---|
570 | # Plot if requested |
---|
571 | if not opts['plot'] and not opts['explore']: return |
---|
572 | view = opts['view'] |
---|
573 | import matplotlib.pyplot as plt |
---|
574 | if limits is None: |
---|
575 | vmin, vmax = np.Inf, -np.Inf |
---|
576 | if Nbase > 0: |
---|
577 | vmin = min(vmin, min(base_value)) |
---|
578 | vmax = max(vmax, max(base_value)) |
---|
579 | if Ncomp > 0: |
---|
580 | vmin = min(vmin, min(comp_value)) |
---|
581 | vmax = max(vmax, max(comp_value)) |
---|
582 | limits = vmin, vmax |
---|
583 | |
---|
584 | if Nbase > 0: |
---|
585 | if Ncomp > 0: plt.subplot(131) |
---|
586 | plot_theory(data, base_value, view=view, use_data=False, limits=limits) |
---|
587 | plt.title("%s t=%.1f ms"%(base.engine, base_time)) |
---|
588 | #cbar_title = "log I" |
---|
589 | if Ncomp > 0: |
---|
590 | if Nbase > 0: plt.subplot(132) |
---|
591 | plot_theory(data, comp_value, view=view, use_data=False, limits=limits) |
---|
592 | plt.title("%s t=%.1f ms"%(comp.engine, comp_time)) |
---|
593 | #cbar_title = "log I" |
---|
594 | if Ncomp > 0 and Nbase > 0: |
---|
595 | plt.subplot(133) |
---|
596 | if not opts['rel_err']: |
---|
597 | err, errstr, errview = resid, "abs err", "linear" |
---|
598 | else: |
---|
599 | err, errstr, errview = abs(relerr), "rel err", "log" |
---|
600 | #err,errstr = base/comp,"ratio" |
---|
601 | plot_theory(data, None, resid=err, view=errview, use_data=False) |
---|
602 | if view == 'linear': |
---|
603 | plt.xscale('linear') |
---|
604 | plt.title("max %s = %.3g"%(errstr, max(abs(err)))) |
---|
605 | #cbar_title = errstr if errview=="linear" else "log "+errstr |
---|
606 | #if is2D: |
---|
607 | # h = plt.colorbar() |
---|
608 | # h.ax.set_title(cbar_title) |
---|
609 | |
---|
610 | if Ncomp > 0 and Nbase > 0 and '-hist' in opts: |
---|
611 | plt.figure() |
---|
612 | v = relerr |
---|
613 | v[v == 0] = 0.5*np.min(np.abs(v[v != 0])) |
---|
614 | plt.hist(np.log10(np.abs(v)), normed=1, bins=50) |
---|
615 | plt.xlabel('log10(err), err = |(%s - %s) / %s|' |
---|
616 | % (base.engine, comp.engine, comp.engine)) |
---|
617 | plt.ylabel('P(err)') |
---|
618 | plt.title('Distribution of relative error between calculation engines') |
---|
619 | |
---|
620 | if not opts['explore']: |
---|
621 | plt.show() |
---|
622 | |
---|
623 | return limits |
---|
624 | |
---|
625 | def _print_stats(label, err): |
---|
626 | sorted_err = np.sort(abs(err)) |
---|
627 | p50 = int((len(err)-1)*0.50) |
---|
628 | p98 = int((len(err)-1)*0.98) |
---|
629 | data = [ |
---|
630 | "max:%.3e"%sorted_err[-1], |
---|
631 | "median:%.3e"%sorted_err[p50], |
---|
632 | "98%%:%.3e"%sorted_err[p98], |
---|
633 | "rms:%.3e"%np.sqrt(np.mean(err**2)), |
---|
634 | "zero-offset:%+.3e"%np.mean(err), |
---|
635 | ] |
---|
636 | print(label+" "+" ".join(data)) |
---|
637 | |
---|
638 | |
---|
639 | |
---|
640 | # =========================================================================== |
---|
641 | # |
---|
642 | NAME_OPTIONS = set([ |
---|
643 | 'plot', 'noplot', |
---|
644 | 'half', 'fast', 'single', 'double', |
---|
645 | 'single!', 'double!', 'quad!', 'sasview', |
---|
646 | 'lowq', 'midq', 'highq', 'exq', |
---|
647 | '2d', '1d', |
---|
648 | 'preset', 'random', |
---|
649 | 'poly', 'mono', |
---|
650 | 'nopars', 'pars', |
---|
651 | 'rel', 'abs', |
---|
652 | 'linear', 'log', 'q4', |
---|
653 | 'hist', 'nohist', |
---|
654 | 'edit', |
---|
655 | ]) |
---|
656 | VALUE_OPTIONS = [ |
---|
657 | # Note: random is both a name option and a value option |
---|
658 | 'cutoff', 'random', 'nq', 'res', 'accuracy', |
---|
659 | ] |
---|
660 | |
---|
661 | def columnize(L, indent="", width=79): |
---|
662 | """ |
---|
663 | Format a list of strings into columns. |
---|
664 | |
---|
665 | Returns a string with carriage returns ready for printing. |
---|
666 | """ |
---|
667 | column_width = max(len(w) for w in L) + 1 |
---|
668 | num_columns = (width - len(indent)) // column_width |
---|
669 | num_rows = len(L) // num_columns |
---|
670 | L = L + [""] * (num_rows*num_columns - len(L)) |
---|
671 | columns = [L[k*num_rows:(k+1)*num_rows] for k in range(num_columns)] |
---|
672 | lines = [" ".join("%-*s"%(column_width, entry) for entry in row) |
---|
673 | for row in zip(*columns)] |
---|
674 | output = indent + ("\n"+indent).join(lines) |
---|
675 | return output |
---|
676 | |
---|
677 | |
---|
678 | def get_demo_pars(model_info): |
---|
679 | """ |
---|
680 | Extract demo parameters from the model definition. |
---|
681 | """ |
---|
682 | # Get the default values for the parameters |
---|
683 | pars = dict((p[0], p[2]) for p in model_info['parameters']) |
---|
684 | |
---|
685 | # Fill in default values for the polydispersity parameters |
---|
686 | for p in model_info['parameters']: |
---|
687 | if p[4] in ('volume', 'orientation'): |
---|
688 | pars[p[0]+'_pd'] = 0.0 |
---|
689 | pars[p[0]+'_pd_n'] = 0 |
---|
690 | pars[p[0]+'_pd_nsigma'] = 3.0 |
---|
691 | pars[p[0]+'_pd_type'] = "gaussian" |
---|
692 | |
---|
693 | # Plug in values given in demo |
---|
694 | pars.update(model_info['demo']) |
---|
695 | return pars |
---|
696 | |
---|
697 | |
---|
698 | def parse_opts(): |
---|
699 | """ |
---|
700 | Parse command line options. |
---|
701 | """ |
---|
702 | MODELS = core.list_models() |
---|
703 | flags = [arg for arg in sys.argv[1:] |
---|
704 | if arg.startswith('-')] |
---|
705 | values = [arg for arg in sys.argv[1:] |
---|
706 | if not arg.startswith('-') and '=' in arg] |
---|
707 | args = [arg for arg in sys.argv[1:] |
---|
708 | if not arg.startswith('-') and '=' not in arg] |
---|
709 | models = "\n ".join("%-15s"%v for v in MODELS) |
---|
710 | if len(args) == 0: |
---|
711 | print(USAGE) |
---|
712 | print("\nAvailable models:") |
---|
713 | print(columnize(MODELS, indent=" ")) |
---|
714 | sys.exit(1) |
---|
715 | if len(args) > 3: |
---|
716 | print("expected parameters: model N1 N2") |
---|
717 | |
---|
718 | def _get_info(name): |
---|
719 | try: |
---|
720 | model_info = core.load_model_info(name) |
---|
721 | except ImportError, exc: |
---|
722 | print(str(exc)) |
---|
723 | print("Use one of:\n " + models) |
---|
724 | sys.exit(1) |
---|
725 | return model_info |
---|
726 | |
---|
727 | name = args[0] |
---|
728 | if '*' in name: |
---|
729 | parts = [_get_info(k) for k in name.split('*')] |
---|
730 | model_info = product.make_product_info(*parts) |
---|
731 | else: |
---|
732 | model_info = _get_info(name) |
---|
733 | |
---|
734 | invalid = [o[1:] for o in flags |
---|
735 | if o[1:] not in NAME_OPTIONS |
---|
736 | and not any(o.startswith('-%s='%t) for t in VALUE_OPTIONS)] |
---|
737 | if invalid: |
---|
738 | print("Invalid options: %s"%(", ".join(invalid))) |
---|
739 | sys.exit(1) |
---|
740 | |
---|
741 | |
---|
742 | # pylint: disable=bad-whitespace |
---|
743 | # Interpret the flags |
---|
744 | opts = { |
---|
745 | 'plot' : True, |
---|
746 | 'view' : 'log', |
---|
747 | 'is2d' : False, |
---|
748 | 'qmax' : 0.05, |
---|
749 | 'nq' : 128, |
---|
750 | 'res' : 0.0, |
---|
751 | 'accuracy' : 'Low', |
---|
752 | 'cutoff' : 1e-5, |
---|
753 | 'seed' : -1, # default to preset |
---|
754 | 'mono' : False, |
---|
755 | 'show_pars' : False, |
---|
756 | 'show_hist' : False, |
---|
757 | 'rel_err' : True, |
---|
758 | 'explore' : False, |
---|
759 | } |
---|
760 | engines = [] |
---|
761 | for arg in flags: |
---|
762 | if arg == '-noplot': opts['plot'] = False |
---|
763 | elif arg == '-plot': opts['plot'] = True |
---|
764 | elif arg == '-linear': opts['view'] = 'linear' |
---|
765 | elif arg == '-log': opts['view'] = 'log' |
---|
766 | elif arg == '-q4': opts['view'] = 'q4' |
---|
767 | elif arg == '-1d': opts['is2d'] = False |
---|
768 | elif arg == '-2d': opts['is2d'] = True |
---|
769 | elif arg == '-exq': opts['qmax'] = 10.0 |
---|
770 | elif arg == '-highq': opts['qmax'] = 1.0 |
---|
771 | elif arg == '-midq': opts['qmax'] = 0.2 |
---|
772 | elif arg == '-lowq': opts['qmax'] = 0.05 |
---|
773 | elif arg.startswith('-nq='): opts['nq'] = int(arg[4:]) |
---|
774 | elif arg.startswith('-res='): opts['res'] = float(arg[5:]) |
---|
775 | elif arg.startswith('-accuracy='): opts['accuracy'] = arg[10:] |
---|
776 | elif arg.startswith('-cutoff='): opts['cutoff'] = float(arg[8:]) |
---|
777 | elif arg.startswith('-random='): opts['seed'] = int(arg[8:]) |
---|
778 | elif arg == '-random': opts['seed'] = np.random.randint(1e6) |
---|
779 | elif arg == '-preset': opts['seed'] = -1 |
---|
780 | elif arg == '-mono': opts['mono'] = True |
---|
781 | elif arg == '-poly': opts['mono'] = False |
---|
782 | elif arg == '-pars': opts['show_pars'] = True |
---|
783 | elif arg == '-nopars': opts['show_pars'] = False |
---|
784 | elif arg == '-hist': opts['show_hist'] = True |
---|
785 | elif arg == '-nohist': opts['show_hist'] = False |
---|
786 | elif arg == '-rel': opts['rel_err'] = True |
---|
787 | elif arg == '-abs': opts['rel_err'] = False |
---|
788 | elif arg == '-half': engines.append(arg[1:]) |
---|
789 | elif arg == '-fast': engines.append(arg[1:]) |
---|
790 | elif arg == '-single': engines.append(arg[1:]) |
---|
791 | elif arg == '-double': engines.append(arg[1:]) |
---|
792 | elif arg == '-single!': engines.append(arg[1:]) |
---|
793 | elif arg == '-double!': engines.append(arg[1:]) |
---|
794 | elif arg == '-quad!': engines.append(arg[1:]) |
---|
795 | elif arg == '-sasview': engines.append(arg[1:]) |
---|
796 | elif arg == '-edit': opts['explore'] = True |
---|
797 | # pylint: enable=bad-whitespace |
---|
798 | |
---|
799 | if len(engines) == 0: |
---|
800 | engines.extend(['single', 'sasview']) |
---|
801 | elif len(engines) == 1: |
---|
802 | if engines[0][0] != 'sasview': |
---|
803 | engines.append('sasview') |
---|
804 | else: |
---|
805 | engines.append('single') |
---|
806 | elif len(engines) > 2: |
---|
807 | del engines[2:] |
---|
808 | |
---|
809 | n1 = int(args[1]) if len(args) > 1 else 1 |
---|
810 | n2 = int(args[2]) if len(args) > 2 else 1 |
---|
811 | |
---|
812 | # Get demo parameters from model definition, or use default parameters |
---|
813 | # if model does not define demo parameters |
---|
814 | pars = get_demo_pars(model_info) |
---|
815 | |
---|
816 | # Fill in parameters given on the command line |
---|
817 | presets = {} |
---|
818 | for arg in values: |
---|
819 | k, v = arg.split('=', 1) |
---|
820 | if k not in pars: |
---|
821 | # extract base name without polydispersity info |
---|
822 | s = set(p.split('_pd')[0] for p in pars) |
---|
823 | print("%r invalid; parameters are: %s"%(k, ", ".join(sorted(s)))) |
---|
824 | sys.exit(1) |
---|
825 | presets[k] = float(v) if not k.endswith('type') else v |
---|
826 | |
---|
827 | # randomize parameters |
---|
828 | #pars.update(set_pars) # set value before random to control range |
---|
829 | if opts['seed'] > -1: |
---|
830 | pars = randomize_pars(pars, seed=opts['seed']) |
---|
831 | print("Randomize using -random=%i"%opts['seed']) |
---|
832 | if opts['mono']: |
---|
833 | pars = suppress_pd(pars) |
---|
834 | pars.update(presets) # set value after random to control value |
---|
835 | constrain_pars(model_info, pars) |
---|
836 | constrain_new_to_old(model_info, pars) |
---|
837 | if opts['show_pars']: |
---|
838 | print(str(parlist(pars))) |
---|
839 | |
---|
840 | # Create the computational engines |
---|
841 | data, _ = make_data(opts) |
---|
842 | if n1: |
---|
843 | base = make_engine(model_info, data, engines[0], opts['cutoff']) |
---|
844 | else: |
---|
845 | base = None |
---|
846 | if n2: |
---|
847 | comp = make_engine(model_info, data, engines[1], opts['cutoff']) |
---|
848 | else: |
---|
849 | comp = None |
---|
850 | |
---|
851 | # pylint: disable=bad-whitespace |
---|
852 | # Remember it all |
---|
853 | opts.update({ |
---|
854 | 'name' : name, |
---|
855 | 'def' : model_info, |
---|
856 | 'n1' : n1, |
---|
857 | 'n2' : n2, |
---|
858 | 'presets' : presets, |
---|
859 | 'pars' : pars, |
---|
860 | 'data' : data, |
---|
861 | 'engines' : [base, comp], |
---|
862 | }) |
---|
863 | # pylint: enable=bad-whitespace |
---|
864 | |
---|
865 | return opts |
---|
866 | |
---|
867 | def explore(opts): |
---|
868 | """ |
---|
869 | Explore the model using the Bumps GUI. |
---|
870 | """ |
---|
871 | import wx |
---|
872 | from bumps.names import FitProblem |
---|
873 | from bumps.gui.app_frame import AppFrame |
---|
874 | |
---|
875 | problem = FitProblem(Explore(opts)) |
---|
876 | is_mac = "cocoa" in wx.version() |
---|
877 | app = wx.App() |
---|
878 | frame = AppFrame(parent=None, title="explore") |
---|
879 | if not is_mac: frame.Show() |
---|
880 | frame.panel.set_model(model=problem) |
---|
881 | frame.panel.Layout() |
---|
882 | frame.panel.aui.Split(0, wx.TOP) |
---|
883 | if is_mac: frame.Show() |
---|
884 | app.MainLoop() |
---|
885 | |
---|
886 | class Explore(object): |
---|
887 | """ |
---|
888 | Bumps wrapper for a SAS model comparison. |
---|
889 | |
---|
890 | The resulting object can be used as a Bumps fit problem so that |
---|
891 | parameters can be adjusted in the GUI, with plots updated on the fly. |
---|
892 | """ |
---|
893 | def __init__(self, opts): |
---|
894 | from bumps.cli import config_matplotlib |
---|
895 | from . import bumps_model |
---|
896 | config_matplotlib() |
---|
897 | self.opts = opts |
---|
898 | model_info = opts['def'] |
---|
899 | pars, pd_types = bumps_model.create_parameters(model_info, **opts['pars']) |
---|
900 | if not opts['is2d']: |
---|
901 | active = [base + ext |
---|
902 | for base in model_info['partype']['pd-1d'] |
---|
903 | for ext in ['', '_pd', '_pd_n', '_pd_nsigma']] |
---|
904 | active.extend(model_info['partype']['fixed-1d']) |
---|
905 | for k in active: |
---|
906 | v = pars[k] |
---|
907 | v.range(*parameter_range(k, v.value)) |
---|
908 | else: |
---|
909 | for k, v in pars.items(): |
---|
910 | v.range(*parameter_range(k, v.value)) |
---|
911 | |
---|
912 | self.pars = pars |
---|
913 | self.pd_types = pd_types |
---|
914 | self.limits = None |
---|
915 | |
---|
916 | def numpoints(self): |
---|
917 | """ |
---|
918 | Return the number of points. |
---|
919 | """ |
---|
920 | return len(self.pars) + 1 # so dof is 1 |
---|
921 | |
---|
922 | def parameters(self): |
---|
923 | """ |
---|
924 | Return a dictionary of parameters. |
---|
925 | """ |
---|
926 | return self.pars |
---|
927 | |
---|
928 | def nllf(self): |
---|
929 | """ |
---|
930 | Return cost. |
---|
931 | """ |
---|
932 | # pylint: disable=no-self-use |
---|
933 | return 0. # No nllf |
---|
934 | |
---|
935 | def plot(self, view='log'): |
---|
936 | """ |
---|
937 | Plot the data and residuals. |
---|
938 | """ |
---|
939 | pars = dict((k, v.value) for k, v in self.pars.items()) |
---|
940 | pars.update(self.pd_types) |
---|
941 | self.opts['pars'] = pars |
---|
942 | limits = compare(self.opts, limits=self.limits) |
---|
943 | if self.limits is None: |
---|
944 | vmin, vmax = limits |
---|
945 | vmax = 1.3*vmax |
---|
946 | vmin = vmax*1e-7 |
---|
947 | self.limits = vmin, vmax |
---|
948 | |
---|
949 | |
---|
950 | def main(): |
---|
951 | """ |
---|
952 | Main program. |
---|
953 | """ |
---|
954 | opts = parse_opts() |
---|
955 | if opts['explore']: |
---|
956 | explore(opts) |
---|
957 | else: |
---|
958 | compare(opts) |
---|
959 | |
---|
960 | if __name__ == "__main__": |
---|
961 | main() |
---|