[8a20be5] | 1 | #!/usr/bin/env python |
---|
| 2 | # -*- coding: utf-8 -*- |
---|
[caeb06d] | 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 |
---|
[9cfcac8] | 11 | tag the model as double precision only. |
---|
[caeb06d] | 12 | |
---|
[9cfcac8] | 13 | Run using ./compare.sh (Linux, Mac) or compare.bat (Windows) in the |
---|
[caeb06d] | 14 | sasmodels root to see the command line options. |
---|
| 15 | |
---|
[9cfcac8] | 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 |
---|
[caeb06d] | 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 | |
---|
[190fc2b] | 31 | import sys |
---|
[a769b54] | 32 | import os |
---|
[190fc2b] | 33 | import math |
---|
| 34 | import datetime |
---|
| 35 | import traceback |
---|
[ff1fff5] | 36 | import re |
---|
[190fc2b] | 37 | |
---|
[7ae2b7f] | 38 | import numpy as np # type: ignore |
---|
[190fc2b] | 39 | |
---|
| 40 | from . import core |
---|
| 41 | from . import kerneldll |
---|
[6831fa0] | 42 | from . import exception |
---|
[a769b54] | 43 | from .data import plot_theory, empty_data1D, empty_data2D, load_data |
---|
[190fc2b] | 44 | from .direct_model import DirectModel |
---|
[f247314] | 45 | from .convert import revert_name, revert_pars, constrain_new_to_old |
---|
[ff1fff5] | 46 | from .generate import FLOAT_RE |
---|
[190fc2b] | 47 | |
---|
[dd7fc12] | 48 | try: |
---|
| 49 | from typing import Optional, Dict, Any, Callable, Tuple |
---|
[6831fa0] | 50 | except Exception: |
---|
[dd7fc12] | 51 | pass |
---|
| 52 | else: |
---|
| 53 | from .modelinfo import ModelInfo, Parameter, ParameterSet |
---|
| 54 | from .data import Data |
---|
[8d62008] | 55 | Calculator = Callable[[float], np.ndarray] |
---|
[dd7fc12] | 56 | |
---|
[caeb06d] | 57 | USAGE = """ |
---|
| 58 | usage: compare.py model N1 N2 [options...] [key=val] |
---|
| 59 | |
---|
| 60 | Compare the speed and value for a model between the SasView original and the |
---|
| 61 | sasmodels rewrite. |
---|
| 62 | |
---|
[8c65a33] | 63 | model or model1,model2 are the names of the models to compare (see below). |
---|
[caeb06d] | 64 | N1 is the number of times to run sasmodels (default=1). |
---|
| 65 | N2 is the number times to run sasview (default=1). |
---|
| 66 | |
---|
| 67 | Options (* for default): |
---|
| 68 | |
---|
| 69 | -plot*/-noplot plots or suppress the plot of the model |
---|
| 70 | -lowq*/-midq/-highq/-exq use q values up to 0.05, 0.2, 1.0, 10.0 |
---|
| 71 | -nq=128 sets the number of Q points in the data set |
---|
[e78edc4] | 72 | -zero indicates that q=0 should be included |
---|
[caeb06d] | 73 | -1d*/-2d computes 1d or 2d data |
---|
| 74 | -preset*/-random[=seed] preset or random parameters |
---|
[630156b] | 75 | -mono*/-poly force monodisperse or allow polydisperse demo parameters |
---|
[0b040de] | 76 | -magnetic/-nonmagnetic* suppress magnetism |
---|
[caeb06d] | 77 | -cutoff=1e-5* cutoff value for including a point in polydispersity |
---|
| 78 | -pars/-nopars* prints the parameter set or not |
---|
| 79 | -abs/-rel* plot relative or absolute error |
---|
| 80 | -linear/-log*/-q4 intensity scaling |
---|
| 81 | -hist/-nohist* plot histogram of relative error |
---|
| 82 | -res=0 sets the resolution width dQ/Q if calculating with resolution |
---|
| 83 | -accuracy=Low accuracy of the resolution calculation Low, Mid, High, Xhigh |
---|
| 84 | -edit starts the parameter explorer |
---|
[98d6cfc] | 85 | -default/-demo* use demo vs default parameters |
---|
[630156b] | 86 | -help/-html shows the model docs instead of running the model |
---|
[9068f4c] | 87 | -title="note" adds note to the plot title, after the model name |
---|
[a769b54] | 88 | -data="path" uses q, dq from the data file |
---|
[caeb06d] | 89 | |
---|
| 90 | Any two calculation engines can be selected for comparison: |
---|
| 91 | |
---|
| 92 | -single/-double/-half/-fast sets an OpenCL calculation engine |
---|
| 93 | -single!/-double!/-quad! sets an OpenMP calculation engine |
---|
| 94 | -sasview sets the sasview calculation engine |
---|
| 95 | |
---|
[8c65a33] | 96 | The default is -single -double. Note that the interpretation of quad |
---|
[caeb06d] | 97 | precision depends on architecture, and may vary from 64-bit to 128-bit, |
---|
| 98 | with 80-bit floats being common (1e-19 precision). |
---|
| 99 | |
---|
| 100 | Key=value pairs allow you to set specific values for the model parameters. |
---|
[8c65a33] | 101 | Key=value1,value2 to compare different values of the same parameter. |
---|
| 102 | value can be an expression including other parameters |
---|
[caeb06d] | 103 | """ |
---|
| 104 | |
---|
| 105 | # Update docs with command line usage string. This is separate from the usual |
---|
| 106 | # doc string so that we can display it at run time if there is an error. |
---|
| 107 | # lin |
---|
[d15a908] | 108 | __doc__ = (__doc__ # pylint: disable=redefined-builtin |
---|
| 109 | + """ |
---|
[caeb06d] | 110 | Program description |
---|
| 111 | ------------------- |
---|
| 112 | |
---|
[d15a908] | 113 | """ |
---|
| 114 | + USAGE) |
---|
[caeb06d] | 115 | |
---|
[750ffa5] | 116 | kerneldll.ALLOW_SINGLE_PRECISION_DLLS = True |
---|
[87985ca] | 117 | |
---|
[248561a] | 118 | # list of math functions for use in evaluating parameters |
---|
| 119 | MATH = dict((k,getattr(math, k)) for k in dir(math) if not k.startswith('_')) |
---|
| 120 | |
---|
[7cf2cfd] | 121 | # CRUFT python 2.6 |
---|
| 122 | if not hasattr(datetime.timedelta, 'total_seconds'): |
---|
| 123 | def delay(dt): |
---|
| 124 | """Return number date-time delta as number seconds""" |
---|
| 125 | return dt.days * 86400 + dt.seconds + 1e-6 * dt.microseconds |
---|
| 126 | else: |
---|
| 127 | def delay(dt): |
---|
| 128 | """Return number date-time delta as number seconds""" |
---|
| 129 | return dt.total_seconds() |
---|
| 130 | |
---|
| 131 | |
---|
[4f2478e] | 132 | class push_seed(object): |
---|
| 133 | """ |
---|
| 134 | Set the seed value for the random number generator. |
---|
| 135 | |
---|
| 136 | When used in a with statement, the random number generator state is |
---|
| 137 | restored after the with statement is complete. |
---|
| 138 | |
---|
| 139 | :Parameters: |
---|
| 140 | |
---|
| 141 | *seed* : int or array_like, optional |
---|
| 142 | Seed for RandomState |
---|
| 143 | |
---|
| 144 | :Example: |
---|
| 145 | |
---|
| 146 | Seed can be used directly to set the seed:: |
---|
| 147 | |
---|
| 148 | >>> from numpy.random import randint |
---|
| 149 | >>> push_seed(24) |
---|
| 150 | <...push_seed object at...> |
---|
| 151 | >>> print(randint(0,1000000,3)) |
---|
| 152 | [242082 899 211136] |
---|
| 153 | |
---|
| 154 | Seed can also be used in a with statement, which sets the random |
---|
| 155 | number generator state for the enclosed computations and restores |
---|
| 156 | it to the previous state on completion:: |
---|
| 157 | |
---|
| 158 | >>> with push_seed(24): |
---|
| 159 | ... print(randint(0,1000000,3)) |
---|
| 160 | [242082 899 211136] |
---|
| 161 | |
---|
| 162 | Using nested contexts, we can demonstrate that state is indeed |
---|
| 163 | restored after the block completes:: |
---|
| 164 | |
---|
| 165 | >>> with push_seed(24): |
---|
| 166 | ... print(randint(0,1000000)) |
---|
| 167 | ... with push_seed(24): |
---|
| 168 | ... print(randint(0,1000000,3)) |
---|
| 169 | ... print(randint(0,1000000)) |
---|
| 170 | 242082 |
---|
| 171 | [242082 899 211136] |
---|
| 172 | 899 |
---|
| 173 | |
---|
| 174 | The restore step is protected against exceptions in the block:: |
---|
| 175 | |
---|
| 176 | >>> with push_seed(24): |
---|
| 177 | ... print(randint(0,1000000)) |
---|
| 178 | ... try: |
---|
| 179 | ... with push_seed(24): |
---|
| 180 | ... print(randint(0,1000000,3)) |
---|
| 181 | ... raise Exception() |
---|
[dd7fc12] | 182 | ... except Exception: |
---|
[4f2478e] | 183 | ... print("Exception raised") |
---|
| 184 | ... print(randint(0,1000000)) |
---|
| 185 | 242082 |
---|
| 186 | [242082 899 211136] |
---|
| 187 | Exception raised |
---|
| 188 | 899 |
---|
| 189 | """ |
---|
| 190 | def __init__(self, seed=None): |
---|
[dd7fc12] | 191 | # type: (Optional[int]) -> None |
---|
[4f2478e] | 192 | self._state = np.random.get_state() |
---|
| 193 | np.random.seed(seed) |
---|
| 194 | |
---|
| 195 | def __enter__(self): |
---|
[dd7fc12] | 196 | # type: () -> None |
---|
| 197 | pass |
---|
[4f2478e] | 198 | |
---|
[b32dafd] | 199 | def __exit__(self, exc_type, exc_value, traceback): |
---|
[dd7fc12] | 200 | # type: (Any, BaseException, Any) -> None |
---|
| 201 | # TODO: better typing for __exit__ method |
---|
[4f2478e] | 202 | np.random.set_state(self._state) |
---|
| 203 | |
---|
[7cf2cfd] | 204 | def tic(): |
---|
[dd7fc12] | 205 | # type: () -> Callable[[], float] |
---|
[7cf2cfd] | 206 | """ |
---|
| 207 | Timer function. |
---|
| 208 | |
---|
| 209 | Use "toc=tic()" to start the clock and "toc()" to measure |
---|
| 210 | a time interval. |
---|
| 211 | """ |
---|
| 212 | then = datetime.datetime.now() |
---|
| 213 | return lambda: delay(datetime.datetime.now() - then) |
---|
| 214 | |
---|
| 215 | |
---|
| 216 | def set_beam_stop(data, radius, outer=None): |
---|
[dd7fc12] | 217 | # type: (Data, float, float) -> None |
---|
[7cf2cfd] | 218 | """ |
---|
| 219 | Add a beam stop of the given *radius*. If *outer*, make an annulus. |
---|
| 220 | |
---|
[dd7fc12] | 221 | Note: this function does not require sasview |
---|
[7cf2cfd] | 222 | """ |
---|
| 223 | if hasattr(data, 'qx_data'): |
---|
| 224 | q = np.sqrt(data.qx_data**2 + data.qy_data**2) |
---|
| 225 | data.mask = (q < radius) |
---|
| 226 | if outer is not None: |
---|
| 227 | data.mask |= (q >= outer) |
---|
| 228 | else: |
---|
| 229 | data.mask = (data.x < radius) |
---|
| 230 | if outer is not None: |
---|
| 231 | data.mask |= (data.x >= outer) |
---|
| 232 | |
---|
[8a20be5] | 233 | |
---|
[ec7e360] | 234 | def parameter_range(p, v): |
---|
[dd7fc12] | 235 | # type: (str, float) -> Tuple[float, float] |
---|
[87985ca] | 236 | """ |
---|
[ec7e360] | 237 | Choose a parameter range based on parameter name and initial value. |
---|
[87985ca] | 238 | """ |
---|
[8bd7b77] | 239 | # process the polydispersity options |
---|
[ec7e360] | 240 | if p.endswith('_pd_n'): |
---|
[dd7fc12] | 241 | return 0., 100. |
---|
[ec7e360] | 242 | elif p.endswith('_pd_nsigma'): |
---|
[dd7fc12] | 243 | return 0., 5. |
---|
[ec7e360] | 244 | elif p.endswith('_pd_type'): |
---|
[dd7fc12] | 245 | raise ValueError("Cannot return a range for a string value") |
---|
[caeb06d] | 246 | elif any(s in p for s in ('theta', 'phi', 'psi')): |
---|
[87985ca] | 247 | # orientation in [-180,180], orientation pd in [0,45] |
---|
| 248 | if p.endswith('_pd'): |
---|
[dd7fc12] | 249 | return 0., 45. |
---|
[87985ca] | 250 | else: |
---|
[dd7fc12] | 251 | return -180., 180. |
---|
[87985ca] | 252 | elif p.endswith('_pd'): |
---|
[dd7fc12] | 253 | return 0., 1. |
---|
[8bd7b77] | 254 | elif 'sld' in p: |
---|
[dd7fc12] | 255 | return -0.5, 10. |
---|
[eb46451] | 256 | elif p == 'background': |
---|
[dd7fc12] | 257 | return 0., 10. |
---|
[eb46451] | 258 | elif p == 'scale': |
---|
[dd7fc12] | 259 | return 0., 1.e3 |
---|
| 260 | elif v < 0.: |
---|
| 261 | return 2.*v, -2.*v |
---|
[87985ca] | 262 | else: |
---|
[dd7fc12] | 263 | return 0., (2.*v if v > 0. else 1.) |
---|
[87985ca] | 264 | |
---|
[4f2478e] | 265 | |
---|
[0bdddc2] | 266 | def _randomize_one(model_info, name, value): |
---|
[dd7fc12] | 267 | # type: (ModelInfo, str, float) -> float |
---|
| 268 | # type: (ModelInfo, str, str) -> str |
---|
[ec7e360] | 269 | """ |
---|
[caeb06d] | 270 | Randomize a single parameter. |
---|
[ec7e360] | 271 | """ |
---|
[31df0c9] | 272 | # Set the amount of polydispersity/angular dispersion, but by default pd_n |
---|
| 273 | # is zero so there is no polydispersity. This allows us to turn on/off |
---|
| 274 | # pd by setting pd_n, and still have randomly generated values |
---|
[0bdddc2] | 275 | if name.endswith('_pd'): |
---|
| 276 | par = model_info.parameters[name[:-3]] |
---|
| 277 | if par.type == 'orientation': |
---|
| 278 | # Let oriention variation peak around 13 degrees; 95% < 42 degrees |
---|
| 279 | return 180*np.random.beta(2.5, 20) |
---|
| 280 | else: |
---|
| 281 | # Let polydispersity peak around 15%; 95% < 0.4; max=100% |
---|
| 282 | return np.random.beta(1.5, 7) |
---|
[8bd7b77] | 283 | |
---|
[31df0c9] | 284 | # pd is selected globally rather than per parameter, so set to 0 for no pd |
---|
| 285 | # In particular, when multiple pd dimensions, want to decrease the number |
---|
| 286 | # of points per dimension for faster computation |
---|
[0bdddc2] | 287 | if name.endswith('_pd_n'): |
---|
| 288 | return 0 |
---|
| 289 | |
---|
[31df0c9] | 290 | # Don't mess with distribution type for now |
---|
[0bdddc2] | 291 | if name.endswith('_pd_type'): |
---|
| 292 | return 'gaussian' |
---|
| 293 | |
---|
[31df0c9] | 294 | # type-dependent value of number of sigmas; for gaussian use 3. |
---|
[0bdddc2] | 295 | if name.endswith('_pd_nsigma'): |
---|
| 296 | return 3. |
---|
[8bd7b77] | 297 | |
---|
[31df0c9] | 298 | # background in the range [0.01, 1] |
---|
[0bdddc2] | 299 | if name == 'background': |
---|
[31df0c9] | 300 | return 10**np.random.uniform(-2, 0) |
---|
[0bdddc2] | 301 | |
---|
[31df0c9] | 302 | # scale defaults to 0.1% to 30% volume fraction |
---|
[0bdddc2] | 303 | if name == 'scale': |
---|
[31df0c9] | 304 | return 10**np.random.uniform(-3, -0.5) |
---|
[0bdddc2] | 305 | |
---|
[31df0c9] | 306 | # If it is a list of choices, pick one at random with equal probability |
---|
| 307 | # In practice, the model specific random generator will override. |
---|
[0bdddc2] | 308 | par = model_info.parameters[name] |
---|
[8bd7b77] | 309 | if len(par.limits) > 2: # choice list |
---|
| 310 | return np.random.randint(len(par.limits)) |
---|
| 311 | |
---|
[31df0c9] | 312 | # If it is a fixed range, pick from it with equal probability. |
---|
| 313 | # For logarithmic ranges, the model will have to override. |
---|
[0bdddc2] | 314 | if np.isfinite(par.limits).all(): |
---|
| 315 | return np.random.uniform(*par.limits) |
---|
| 316 | |
---|
[31df0c9] | 317 | # If the paramter is marked as an sld use the range of neutron slds |
---|
| 318 | # Should be doing something with randomly selected contrast matching |
---|
| 319 | # but for now use random contrasts. Since real data is contrast-matched, |
---|
| 320 | # this will favour selection of hollow models when they exist. |
---|
[0bdddc2] | 321 | if par.type == 'sld': |
---|
| 322 | # Range of neutron SLDs |
---|
| 323 | return np.random.uniform(-0.5, 12) |
---|
[8bd7b77] | 324 | |
---|
[31df0c9] | 325 | # Guess at the random length/radius/thickness. In practice, all models |
---|
| 326 | # are going to set their own reasonable ranges. |
---|
[0bdddc2] | 327 | if par.type == 'volume': |
---|
| 328 | if ('length' in par.name or |
---|
| 329 | 'radius' in par.name or |
---|
| 330 | 'thick' in par.name): |
---|
[31df0c9] | 331 | return 10**np.random.uniform(2, 4) |
---|
[0bdddc2] | 332 | |
---|
[31df0c9] | 333 | # In the absence of any other info, select a value in [0, 2v], or |
---|
| 334 | # [-2|v|, 2|v|] if v is negative, or [0, 1] if v is zero. Mostly the |
---|
| 335 | # model random parameter generators will override this default. |
---|
[0bdddc2] | 336 | low, high = parameter_range(par.name, value) |
---|
| 337 | limits = (max(par.limits[0], low), min(par.limits[1], high)) |
---|
[8bd7b77] | 338 | return np.random.uniform(*limits) |
---|
[cd3dba0] | 339 | |
---|
[109d963] | 340 | def _random_pd(model_info, pars): |
---|
| 341 | pd = [p for p in model_info.parameters.kernel_parameters if p.polydisperse] |
---|
| 342 | pd_volume = [] |
---|
| 343 | pd_oriented = [] |
---|
| 344 | for p in pd: |
---|
| 345 | if p.type == 'orientation': |
---|
| 346 | pd_oriented.append(p.name) |
---|
| 347 | elif p.length_control is not None: |
---|
| 348 | n = pars.get(p.length_control, 1) |
---|
| 349 | pd_volume.extend(p.name+str(k+1) for k in range(n)) |
---|
| 350 | elif p.length > 1: |
---|
| 351 | pd_volume.extend(p.name+str(k+1) for k in range(p.length)) |
---|
| 352 | else: |
---|
| 353 | pd_volume.append(p.name) |
---|
| 354 | u = np.random.rand() |
---|
| 355 | n = len(pd_volume) |
---|
| 356 | if u < 0.01 or n < 1: |
---|
| 357 | pass # 1% chance of no polydispersity |
---|
| 358 | elif u < 0.86 or n < 2: |
---|
| 359 | pars[np.random.choice(pd_volume)+"_pd_n"] = 35 |
---|
| 360 | elif u < 0.99 or n < 3: |
---|
| 361 | choices = np.random.choice(len(pd_volume), size=2) |
---|
| 362 | pars[pd_volume[choices[0]]+"_pd_n"] = 25 |
---|
| 363 | pars[pd_volume[choices[1]]+"_pd_n"] = 10 |
---|
| 364 | else: |
---|
| 365 | choices = np.random.choice(len(pd_volume), size=3) |
---|
| 366 | pars[pd_volume[choices[0]]+"_pd_n"] = 25 |
---|
| 367 | pars[pd_volume[choices[1]]+"_pd_n"] = 10 |
---|
| 368 | pars[pd_volume[choices[2]]+"_pd_n"] = 5 |
---|
| 369 | if pd_oriented: |
---|
| 370 | pars['theta_pd_n'] = 20 |
---|
| 371 | if np.random.rand() < 0.1: |
---|
| 372 | pars['phi_pd_n'] = 5 |
---|
| 373 | if np.random.rand() < 0.1: |
---|
| 374 | pars['psi_pd_n'] = 5 |
---|
| 375 | |
---|
| 376 | ## Show selected polydispersity |
---|
| 377 | #for name, value in pars.items(): |
---|
| 378 | # if name.endswith('_pd_n') and value > 0: |
---|
| 379 | # print(name, value, pars.get(name[:-5], 0), pars.get(name[:-2], 0)) |
---|
| 380 | |
---|
| 381 | |
---|
| 382 | def randomize_pars(model_info, pars): |
---|
| 383 | # type: (ModelInfo, ParameterSet) -> ParameterSet |
---|
[caeb06d] | 384 | """ |
---|
| 385 | Generate random values for all of the parameters. |
---|
| 386 | |
---|
| 387 | Valid ranges for the random number generator are guessed from the name of |
---|
| 388 | the parameter; this will not account for constraints such as cap radius |
---|
| 389 | greater than cylinder radius in the capped_cylinder model, so |
---|
| 390 | :func:`constrain_pars` needs to be called afterward.. |
---|
| 391 | """ |
---|
[0bdddc2] | 392 | # Note: the sort guarantees order of calls to random number generator |
---|
| 393 | random_pars = dict((p, _randomize_one(model_info, p, v)) |
---|
| 394 | for p, v in sorted(pars.items())) |
---|
| 395 | if model_info.random is not None: |
---|
| 396 | random_pars.update(model_info.random()) |
---|
[109d963] | 397 | _random_pd(model_info, random_pars) |
---|
[dd7fc12] | 398 | return random_pars |
---|
[cd3dba0] | 399 | |
---|
[109d963] | 400 | |
---|
[17bbadd] | 401 | def constrain_pars(model_info, pars): |
---|
[dd7fc12] | 402 | # type: (ModelInfo, ParameterSet) -> None |
---|
[9a66e65] | 403 | """ |
---|
| 404 | Restrict parameters to valid values. |
---|
[caeb06d] | 405 | |
---|
| 406 | This includes model specific code for models such as capped_cylinder |
---|
| 407 | which need to support within model constraints (cap radius more than |
---|
| 408 | cylinder radius in this case). |
---|
[dd7fc12] | 409 | |
---|
| 410 | Warning: this updates the *pars* dictionary in place. |
---|
[9a66e65] | 411 | """ |
---|
[109d963] | 412 | # TODO: move the model specific code to the individual models |
---|
[6d6508e] | 413 | name = model_info.id |
---|
[17bbadd] | 414 | # if it is a product model, then just look at the form factor since |
---|
| 415 | # none of the structure factors need any constraints. |
---|
| 416 | if '*' in name: |
---|
| 417 | name = name.split('*')[0] |
---|
| 418 | |
---|
[f72d70a] | 419 | # Suppress magnetism for python models (not yet implemented) |
---|
| 420 | if callable(model_info.Iq): |
---|
| 421 | pars.update(suppress_magnetism(pars)) |
---|
| 422 | |
---|
[158cee4] | 423 | if name == 'barbell': |
---|
| 424 | if pars['radius_bell'] < pars['radius']: |
---|
| 425 | pars['radius'], pars['radius_bell'] = pars['radius_bell'], pars['radius'] |
---|
[b514adf] | 426 | |
---|
[158cee4] | 427 | elif name == 'capped_cylinder': |
---|
| 428 | if pars['radius_cap'] < pars['radius']: |
---|
| 429 | pars['radius'], pars['radius_cap'] = pars['radius_cap'], pars['radius'] |
---|
| 430 | |
---|
| 431 | elif name == 'guinier': |
---|
| 432 | # Limit guinier to an Rg such that Iq > 1e-30 (single precision cutoff) |
---|
[48462b0] | 433 | # I(q) = A e^-(Rg^2 q^2/3) > e^-(30 ln 10) |
---|
| 434 | # => ln A - (Rg^2 q^2/3) > -30 ln 10 |
---|
| 435 | # => Rg^2 q^2/3 < 30 ln 10 + ln A |
---|
| 436 | # => Rg < sqrt(90 ln 10 + 3 ln A)/q |
---|
[b514adf] | 437 | #q_max = 0.2 # mid q maximum |
---|
| 438 | q_max = 1.0 # high q maximum |
---|
| 439 | rg_max = np.sqrt(90*np.log(10) + 3*np.log(pars['scale']))/q_max |
---|
[caeb06d] | 440 | pars['rg'] = min(pars['rg'], rg_max) |
---|
[cd3dba0] | 441 | |
---|
[3e8ea5d] | 442 | elif name == 'pearl_necklace': |
---|
| 443 | if pars['radius'] < pars['thick_string']: |
---|
| 444 | pars['radius'], pars['thick_string'] = pars['thick_string'], pars['radius'] |
---|
| 445 | pass |
---|
| 446 | |
---|
[158cee4] | 447 | elif name == 'rpa': |
---|
[82c299f] | 448 | # Make sure phi sums to 1.0 |
---|
| 449 | if pars['case_num'] < 2: |
---|
[8bd7b77] | 450 | pars['Phi1'] = 0. |
---|
| 451 | pars['Phi2'] = 0. |
---|
[82c299f] | 452 | elif pars['case_num'] < 5: |
---|
[8bd7b77] | 453 | pars['Phi1'] = 0. |
---|
| 454 | total = sum(pars['Phi'+c] for c in '1234') |
---|
| 455 | for c in '1234': |
---|
[82c299f] | 456 | pars['Phi'+c] /= total |
---|
| 457 | |
---|
[d6850fa] | 458 | def parlist(model_info, pars, is2d): |
---|
[dd7fc12] | 459 | # type: (ModelInfo, ParameterSet, bool) -> str |
---|
[caeb06d] | 460 | """ |
---|
| 461 | Format the parameter list for printing. |
---|
| 462 | """ |
---|
[a4a7308] | 463 | lines = [] |
---|
[6d6508e] | 464 | parameters = model_info.parameters |
---|
[0b040de] | 465 | magnetic = False |
---|
[d19962c] | 466 | for p in parameters.user_parameters(pars, is2d): |
---|
[0b040de] | 467 | if any(p.id.startswith(x) for x in ('M0:', 'mtheta:', 'mphi:')): |
---|
| 468 | continue |
---|
| 469 | if p.id.startswith('up:') and not magnetic: |
---|
| 470 | continue |
---|
[d19962c] | 471 | fields = dict( |
---|
| 472 | value=pars.get(p.id, p.default), |
---|
| 473 | pd=pars.get(p.id+"_pd", 0.), |
---|
| 474 | n=int(pars.get(p.id+"_pd_n", 0)), |
---|
| 475 | nsigma=pars.get(p.id+"_pd_nsgima", 3.), |
---|
[dd7fc12] | 476 | pdtype=pars.get(p.id+"_pd_type", 'gaussian'), |
---|
[bd49c79] | 477 | relative_pd=p.relative_pd, |
---|
[0b040de] | 478 | M0=pars.get('M0:'+p.id, 0.), |
---|
| 479 | mphi=pars.get('mphi:'+p.id, 0.), |
---|
| 480 | mtheta=pars.get('mtheta:'+p.id, 0.), |
---|
[dd7fc12] | 481 | ) |
---|
[d19962c] | 482 | lines.append(_format_par(p.name, **fields)) |
---|
[0b040de] | 483 | magnetic = magnetic or fields['M0'] != 0. |
---|
[a4a7308] | 484 | return "\n".join(lines) |
---|
| 485 | |
---|
| 486 | #return "\n".join("%s: %s"%(p, v) for p, v in sorted(pars.items())) |
---|
| 487 | |
---|
[bd49c79] | 488 | def _format_par(name, value=0., pd=0., n=0, nsigma=3., pdtype='gaussian', |
---|
[0b040de] | 489 | relative_pd=False, M0=0., mphi=0., mtheta=0.): |
---|
[dd7fc12] | 490 | # type: (str, float, float, int, float, str) -> str |
---|
[a4a7308] | 491 | line = "%s: %g"%(name, value) |
---|
| 492 | if pd != 0. and n != 0: |
---|
[bd49c79] | 493 | if relative_pd: |
---|
| 494 | pd *= value |
---|
[a4a7308] | 495 | line += " +/- %g (%d points in [-%g,%g] sigma %s)"\ |
---|
[dd7fc12] | 496 | % (pd, n, nsigma, nsigma, pdtype) |
---|
[0b040de] | 497 | if M0 != 0.: |
---|
| 498 | line += " M0:%.3f mphi:%.1f mtheta:%.1f" % (M0, mphi, mtheta) |
---|
[a4a7308] | 499 | return line |
---|
[87985ca] | 500 | |
---|
| 501 | def suppress_pd(pars): |
---|
[dd7fc12] | 502 | # type: (ParameterSet) -> ParameterSet |
---|
[87985ca] | 503 | """ |
---|
| 504 | Suppress theta_pd for now until the normalization is resolved. |
---|
| 505 | |
---|
| 506 | May also suppress complete polydispersity of the model to test |
---|
| 507 | models more quickly. |
---|
| 508 | """ |
---|
[f4f3919] | 509 | pars = pars.copy() |
---|
[87985ca] | 510 | for p in pars: |
---|
[109d963] | 511 | if p.endswith("_pd_n"): |
---|
| 512 | pars[p] = 0 |
---|
[f4f3919] | 513 | return pars |
---|
[87985ca] | 514 | |
---|
[0b040de] | 515 | def suppress_magnetism(pars): |
---|
| 516 | # type: (ParameterSet) -> ParameterSet |
---|
| 517 | """ |
---|
| 518 | Suppress theta_pd for now until the normalization is resolved. |
---|
| 519 | |
---|
| 520 | May also suppress complete polydispersity of the model to test |
---|
| 521 | models more quickly. |
---|
| 522 | """ |
---|
| 523 | pars = pars.copy() |
---|
| 524 | for p in pars: |
---|
| 525 | if p.startswith("M0:"): pars[p] = 0 |
---|
| 526 | return pars |
---|
| 527 | |
---|
[17bbadd] | 528 | def eval_sasview(model_info, data): |
---|
[dd7fc12] | 529 | # type: (Modelinfo, Data) -> Calculator |
---|
[caeb06d] | 530 | """ |
---|
[f247314] | 531 | Return a model calculator using the pre-4.0 SasView models. |
---|
[caeb06d] | 532 | """ |
---|
[dc056b9] | 533 | # importing sas here so that the error message will be that sas failed to |
---|
| 534 | # import rather than the more obscure smear_selection not imported error |
---|
[2bebe2b] | 535 | import sas |
---|
[dd7fc12] | 536 | import sas.models |
---|
[8d62008] | 537 | from sas.models.qsmearing import smear_selection |
---|
| 538 | from sas.models.MultiplicationModel import MultiplicationModel |
---|
[050c2c8] | 539 | from sas.models.dispersion_models import models as dispersers |
---|
[ec7e360] | 540 | |
---|
[256dfe1] | 541 | def get_model_class(name): |
---|
[dd7fc12] | 542 | # type: (str) -> "sas.models.BaseComponent" |
---|
[17bbadd] | 543 | #print("new",sorted(_pars.items())) |
---|
[dd7fc12] | 544 | __import__('sas.models.' + name) |
---|
[17bbadd] | 545 | ModelClass = getattr(getattr(sas.models, name, None), name, None) |
---|
| 546 | if ModelClass is None: |
---|
| 547 | raise ValueError("could not find model %r in sas.models"%name) |
---|
[256dfe1] | 548 | return ModelClass |
---|
| 549 | |
---|
| 550 | # WARNING: ugly hack when handling model! |
---|
| 551 | # Sasview models with multiplicity need to be created with the target |
---|
| 552 | # multiplicity, so we cannot create the target model ahead of time for |
---|
| 553 | # for multiplicity models. Instead we store the model in a list and |
---|
| 554 | # update the first element of that list with the new multiplicity model |
---|
| 555 | # every time we evaluate. |
---|
[17bbadd] | 556 | |
---|
| 557 | # grab the sasview model, or create it if it is a product model |
---|
[6d6508e] | 558 | if model_info.composition: |
---|
| 559 | composition_type, parts = model_info.composition |
---|
[17bbadd] | 560 | if composition_type == 'product': |
---|
[51ec7e8] | 561 | P, S = [get_model_class(revert_name(p))() for p in parts] |
---|
[256dfe1] | 562 | model = [MultiplicationModel(P, S)] |
---|
[17bbadd] | 563 | else: |
---|
[72a081d] | 564 | raise ValueError("sasview mixture models not supported by compare") |
---|
[17bbadd] | 565 | else: |
---|
[f3bd37f] | 566 | old_name = revert_name(model_info) |
---|
| 567 | if old_name is None: |
---|
| 568 | raise ValueError("model %r does not exist in old sasview" |
---|
| 569 | % model_info.id) |
---|
[256dfe1] | 570 | ModelClass = get_model_class(old_name) |
---|
| 571 | model = [ModelClass()] |
---|
[050c2c8] | 572 | model[0].disperser_handles = {} |
---|
[216a9e1] | 573 | |
---|
[17bbadd] | 574 | # build a smearer with which to call the model, if necessary |
---|
| 575 | smearer = smear_selection(data, model=model) |
---|
[ec7e360] | 576 | if hasattr(data, 'qx_data'): |
---|
| 577 | q = np.sqrt(data.qx_data**2 + data.qy_data**2) |
---|
| 578 | index = ((~data.mask) & (~np.isnan(data.data)) |
---|
| 579 | & (q >= data.qmin) & (q <= data.qmax)) |
---|
| 580 | if smearer is not None: |
---|
| 581 | smearer.model = model # because smear_selection has a bug |
---|
| 582 | smearer.accuracy = data.accuracy |
---|
| 583 | smearer.set_index(index) |
---|
[256dfe1] | 584 | def _call_smearer(): |
---|
| 585 | smearer.model = model[0] |
---|
| 586 | return smearer.get_value() |
---|
[b32dafd] | 587 | theory = _call_smearer |
---|
[ec7e360] | 588 | else: |
---|
[256dfe1] | 589 | theory = lambda: model[0].evalDistribution([data.qx_data[index], |
---|
| 590 | data.qy_data[index]]) |
---|
[ec7e360] | 591 | elif smearer is not None: |
---|
[256dfe1] | 592 | theory = lambda: smearer(model[0].evalDistribution(data.x)) |
---|
[ec7e360] | 593 | else: |
---|
[256dfe1] | 594 | theory = lambda: model[0].evalDistribution(data.x) |
---|
[ec7e360] | 595 | |
---|
| 596 | def calculator(**pars): |
---|
[dd7fc12] | 597 | # type: (float, ...) -> np.ndarray |
---|
[caeb06d] | 598 | """ |
---|
| 599 | Sasview calculator for model. |
---|
| 600 | """ |
---|
[256dfe1] | 601 | oldpars = revert_pars(model_info, pars) |
---|
[bd49c79] | 602 | # For multiplicity models, create a model with the correct multiplicity |
---|
| 603 | control = oldpars.pop("CONTROL", None) |
---|
| 604 | if control is not None: |
---|
| 605 | # sphericalSLD has one fewer multiplicity. This update should |
---|
| 606 | # happen in revert_pars, but it hasn't been called yet. |
---|
| 607 | model[0] = ModelClass(control) |
---|
| 608 | # paying for parameter conversion each time to keep life simple, if not fast |
---|
[050c2c8] | 609 | for k, v in oldpars.items(): |
---|
| 610 | if k.endswith('.type'): |
---|
| 611 | par = k[:-5] |
---|
[6831fa0] | 612 | if v == 'gaussian': continue |
---|
[050c2c8] | 613 | cls = dispersers[v if v != 'rectangle' else 'rectangula'] |
---|
| 614 | handle = cls() |
---|
| 615 | model[0].disperser_handles[par] = handle |
---|
[6831fa0] | 616 | try: |
---|
| 617 | model[0].set_dispersion(par, handle) |
---|
| 618 | except Exception: |
---|
| 619 | exception.annotate_exception("while setting %s to %r" |
---|
| 620 | %(par, v)) |
---|
| 621 | raise |
---|
| 622 | |
---|
[050c2c8] | 623 | |
---|
[f67f26c] | 624 | #print("sasview pars",oldpars) |
---|
[256dfe1] | 625 | for k, v in oldpars.items(): |
---|
[dd7fc12] | 626 | name_attr = k.split('.') # polydispersity components |
---|
| 627 | if len(name_attr) == 2: |
---|
[050c2c8] | 628 | par, disp_par = name_attr |
---|
| 629 | model[0].dispersion[par][disp_par] = v |
---|
[ec7e360] | 630 | else: |
---|
[256dfe1] | 631 | model[0].setParam(k, v) |
---|
[ec7e360] | 632 | return theory() |
---|
| 633 | |
---|
| 634 | calculator.engine = "sasview" |
---|
| 635 | return calculator |
---|
| 636 | |
---|
| 637 | DTYPE_MAP = { |
---|
| 638 | 'half': '16', |
---|
| 639 | 'fast': 'fast', |
---|
| 640 | 'single': '32', |
---|
| 641 | 'double': '64', |
---|
| 642 | 'quad': '128', |
---|
| 643 | 'f16': '16', |
---|
| 644 | 'f32': '32', |
---|
| 645 | 'f64': '64', |
---|
[650c6d2] | 646 | 'float16': '16', |
---|
| 647 | 'float32': '32', |
---|
| 648 | 'float64': '64', |
---|
| 649 | 'float128': '128', |
---|
[ec7e360] | 650 | 'longdouble': '128', |
---|
| 651 | } |
---|
[17bbadd] | 652 | def eval_opencl(model_info, data, dtype='single', cutoff=0.): |
---|
[dd7fc12] | 653 | # type: (ModelInfo, Data, str, float) -> Calculator |
---|
[caeb06d] | 654 | """ |
---|
| 655 | Return a model calculator using the OpenCL calculation engine. |
---|
| 656 | """ |
---|
[a738209] | 657 | if not core.HAVE_OPENCL: |
---|
| 658 | raise RuntimeError("OpenCL not available") |
---|
| 659 | model = core.build_model(model_info, dtype=dtype, platform="ocl") |
---|
[7cf2cfd] | 660 | calculator = DirectModel(data, model, cutoff=cutoff) |
---|
[ec7e360] | 661 | calculator.engine = "OCL%s"%DTYPE_MAP[dtype] |
---|
| 662 | return calculator |
---|
[216a9e1] | 663 | |
---|
[17bbadd] | 664 | def eval_ctypes(model_info, data, dtype='double', cutoff=0.): |
---|
[dd7fc12] | 665 | # type: (ModelInfo, Data, str, float) -> Calculator |
---|
[9cfcac8] | 666 | """ |
---|
| 667 | Return a model calculator using the DLL calculation engine. |
---|
| 668 | """ |
---|
[72a081d] | 669 | model = core.build_model(model_info, dtype=dtype, platform="dll") |
---|
[7cf2cfd] | 670 | calculator = DirectModel(data, model, cutoff=cutoff) |
---|
[ec7e360] | 671 | calculator.engine = "OMP%s"%DTYPE_MAP[dtype] |
---|
| 672 | return calculator |
---|
| 673 | |
---|
[b32dafd] | 674 | def time_calculation(calculator, pars, evals=1): |
---|
[dd7fc12] | 675 | # type: (Calculator, ParameterSet, int) -> Tuple[np.ndarray, float] |
---|
[caeb06d] | 676 | """ |
---|
| 677 | Compute the average calculation time over N evaluations. |
---|
| 678 | |
---|
| 679 | An additional call is generated without polydispersity in order to |
---|
| 680 | initialize the calculation engine, and make the average more stable. |
---|
| 681 | """ |
---|
[ec7e360] | 682 | # initialize the code so time is more accurate |
---|
[b32dafd] | 683 | if evals > 1: |
---|
[dd7fc12] | 684 | calculator(**suppress_pd(pars)) |
---|
[216a9e1] | 685 | toc = tic() |
---|
[dd7fc12] | 686 | # make sure there is at least one eval |
---|
| 687 | value = calculator(**pars) |
---|
[b32dafd] | 688 | for _ in range(evals-1): |
---|
[7cf2cfd] | 689 | value = calculator(**pars) |
---|
[b32dafd] | 690 | average_time = toc()*1000. / evals |
---|
[f2f67a6] | 691 | #print("I(q)",value) |
---|
[216a9e1] | 692 | return value, average_time |
---|
| 693 | |
---|
[ec7e360] | 694 | def make_data(opts): |
---|
[dd7fc12] | 695 | # type: (Dict[str, Any]) -> Tuple[Data, np.ndarray] |
---|
[caeb06d] | 696 | """ |
---|
| 697 | Generate an empty dataset, used with the model to set Q points |
---|
| 698 | and resolution. |
---|
| 699 | |
---|
| 700 | *opts* contains the options, with 'qmax', 'nq', 'res', |
---|
| 701 | 'accuracy', 'is2d' and 'view' parsed from the command line. |
---|
| 702 | """ |
---|
[ec7e360] | 703 | qmax, nq, res = opts['qmax'], opts['nq'], opts['res'] |
---|
| 704 | if opts['is2d']: |
---|
[dd7fc12] | 705 | q = np.linspace(-qmax, qmax, nq) # type: np.ndarray |
---|
| 706 | data = empty_data2D(q, resolution=res) |
---|
[ec7e360] | 707 | data.accuracy = opts['accuracy'] |
---|
[ea75043] | 708 | set_beam_stop(data, 0.0004) |
---|
[87985ca] | 709 | index = ~data.mask |
---|
[216a9e1] | 710 | else: |
---|
[e78edc4] | 711 | if opts['view'] == 'log' and not opts['zero']: |
---|
[b89f519] | 712 | qmax = math.log10(qmax) |
---|
[ec7e360] | 713 | q = np.logspace(qmax-3, qmax, nq) |
---|
[b89f519] | 714 | else: |
---|
[ec7e360] | 715 | q = np.linspace(0.001*qmax, qmax, nq) |
---|
[e78edc4] | 716 | if opts['zero']: |
---|
| 717 | q = np.hstack((0, q)) |
---|
[ec7e360] | 718 | data = empty_data1D(q, resolution=res) |
---|
[216a9e1] | 719 | index = slice(None, None) |
---|
| 720 | return data, index |
---|
| 721 | |
---|
[17bbadd] | 722 | def make_engine(model_info, data, dtype, cutoff): |
---|
[dd7fc12] | 723 | # type: (ModelInfo, Data, str, float) -> Calculator |
---|
[caeb06d] | 724 | """ |
---|
| 725 | Generate the appropriate calculation engine for the given datatype. |
---|
| 726 | |
---|
| 727 | Datatypes with '!' appended are evaluated using external C DLLs rather |
---|
| 728 | than OpenCL. |
---|
| 729 | """ |
---|
[ec7e360] | 730 | if dtype == 'sasview': |
---|
[17bbadd] | 731 | return eval_sasview(model_info, data) |
---|
[ec7e360] | 732 | elif dtype.endswith('!'): |
---|
[17bbadd] | 733 | return eval_ctypes(model_info, data, dtype=dtype[:-1], cutoff=cutoff) |
---|
[ec7e360] | 734 | else: |
---|
[17bbadd] | 735 | return eval_opencl(model_info, data, dtype=dtype, cutoff=cutoff) |
---|
[87985ca] | 736 | |
---|
[e78edc4] | 737 | def _show_invalid(data, theory): |
---|
[dd7fc12] | 738 | # type: (Data, np.ma.ndarray) -> None |
---|
| 739 | """ |
---|
| 740 | Display a list of the non-finite values in theory. |
---|
| 741 | """ |
---|
[e78edc4] | 742 | if not theory.mask.any(): |
---|
| 743 | return |
---|
| 744 | |
---|
| 745 | if hasattr(data, 'x'): |
---|
| 746 | bad = zip(data.x[theory.mask], theory[theory.mask]) |
---|
[dd7fc12] | 747 | print(" *** ", ", ".join("I(%g)=%g"%(x, y) for x, y in bad)) |
---|
[e78edc4] | 748 | |
---|
| 749 | |
---|
[013adb7] | 750 | def compare(opts, limits=None): |
---|
[dd7fc12] | 751 | # type: (Dict[str, Any], Optional[Tuple[float, float]]) -> Tuple[float, float] |
---|
[caeb06d] | 752 | """ |
---|
| 753 | Preform a comparison using options from the command line. |
---|
| 754 | |
---|
| 755 | *limits* are the limits on the values to use, either to set the y-axis |
---|
| 756 | for 1D or to set the colormap scale for 2D. If None, then they are |
---|
| 757 | inferred from the data and returned. When exploring using Bumps, |
---|
| 758 | the limits are set when the model is initially called, and maintained |
---|
| 759 | as the values are adjusted, making it easier to see the effects of the |
---|
| 760 | parameters. |
---|
| 761 | """ |
---|
[0bdddc2] | 762 | limits = np.Inf, -np.Inf |
---|
| 763 | for k in range(opts['sets']): |
---|
| 764 | opts['pars'] = parse_pars(opts) |
---|
[8f04da4] | 765 | if opts['pars'] is None: |
---|
| 766 | return |
---|
[0bdddc2] | 767 | result = run_models(opts, verbose=True) |
---|
| 768 | if opts['plot']: |
---|
| 769 | limits = plot_models(opts, result, limits=limits, setnum=k) |
---|
| 770 | if opts['plot']: |
---|
| 771 | import matplotlib.pyplot as plt |
---|
| 772 | plt.show() |
---|
[ca9e54e] | 773 | |
---|
| 774 | def run_models(opts, verbose=False): |
---|
| 775 | # type: (Dict[str, Any]) -> Dict[str, Any] |
---|
| 776 | |
---|
[ff1fff5] | 777 | n_base, n_comp = opts['count'] |
---|
| 778 | pars, pars2 = opts['pars'] |
---|
[ec7e360] | 779 | data = opts['data'] |
---|
[87985ca] | 780 | |
---|
[dd7fc12] | 781 | # silence the linter |
---|
[b32dafd] | 782 | base = opts['engines'][0] if n_base else None |
---|
| 783 | comp = opts['engines'][1] if n_comp else None |
---|
[ca9e54e] | 784 | |
---|
[dd7fc12] | 785 | base_time = comp_time = None |
---|
| 786 | base_value = comp_value = resid = relerr = None |
---|
| 787 | |
---|
[4b41184] | 788 | # Base calculation |
---|
[b32dafd] | 789 | if n_base > 0: |
---|
[319ab14] | 790 | try: |
---|
[b32dafd] | 791 | base_raw, base_time = time_calculation(base, pars, n_base) |
---|
[dd7fc12] | 792 | base_value = np.ma.masked_invalid(base_raw) |
---|
[ca9e54e] | 793 | if verbose: |
---|
| 794 | print("%s t=%.2f ms, intensity=%.0f" |
---|
| 795 | % (base.engine, base_time, base_value.sum())) |
---|
[e78edc4] | 796 | _show_invalid(data, base_value) |
---|
[319ab14] | 797 | except ImportError: |
---|
| 798 | traceback.print_exc() |
---|
[b32dafd] | 799 | n_base = 0 |
---|
[4b41184] | 800 | |
---|
| 801 | # Comparison calculation |
---|
[b32dafd] | 802 | if n_comp > 0: |
---|
[7cf2cfd] | 803 | try: |
---|
[ff1fff5] | 804 | comp_raw, comp_time = time_calculation(comp, pars2, n_comp) |
---|
[dd7fc12] | 805 | comp_value = np.ma.masked_invalid(comp_raw) |
---|
[ca9e54e] | 806 | if verbose: |
---|
| 807 | print("%s t=%.2f ms, intensity=%.0f" |
---|
| 808 | % (comp.engine, comp_time, comp_value.sum())) |
---|
[e78edc4] | 809 | _show_invalid(data, comp_value) |
---|
[7cf2cfd] | 810 | except ImportError: |
---|
[5753e4e] | 811 | traceback.print_exc() |
---|
[b32dafd] | 812 | n_comp = 0 |
---|
[87985ca] | 813 | |
---|
| 814 | # Compare, but only if computing both forms |
---|
[b32dafd] | 815 | if n_base > 0 and n_comp > 0: |
---|
[ec7e360] | 816 | resid = (base_value - comp_value) |
---|
[b32dafd] | 817 | relerr = resid/np.where(comp_value != 0., abs(comp_value), 1.0) |
---|
[ca9e54e] | 818 | if verbose: |
---|
| 819 | _print_stats("|%s-%s|" |
---|
| 820 | % (base.engine, comp.engine) + (" "*(3+len(comp.engine))), |
---|
| 821 | resid) |
---|
| 822 | _print_stats("|(%s-%s)/%s|" |
---|
| 823 | % (base.engine, comp.engine, comp.engine), |
---|
| 824 | relerr) |
---|
| 825 | |
---|
| 826 | return dict(base_value=base_value, comp_value=comp_value, |
---|
| 827 | base_time=base_time, comp_time=comp_time, |
---|
| 828 | resid=resid, relerr=relerr) |
---|
| 829 | |
---|
| 830 | |
---|
| 831 | def _print_stats(label, err): |
---|
| 832 | # type: (str, np.ma.ndarray) -> None |
---|
| 833 | # work with trimmed data, not the full set |
---|
| 834 | sorted_err = np.sort(abs(err.compressed())) |
---|
| 835 | if len(sorted_err) == 0.: |
---|
| 836 | print(label + " no valid values") |
---|
| 837 | return |
---|
| 838 | |
---|
| 839 | p50 = int((len(sorted_err)-1)*0.50) |
---|
| 840 | p98 = int((len(sorted_err)-1)*0.98) |
---|
| 841 | data = [ |
---|
| 842 | "max:%.3e"%sorted_err[-1], |
---|
| 843 | "median:%.3e"%sorted_err[p50], |
---|
| 844 | "98%%:%.3e"%sorted_err[p98], |
---|
| 845 | "rms:%.3e"%np.sqrt(np.mean(sorted_err**2)), |
---|
| 846 | "zero-offset:%+.3e"%np.mean(sorted_err), |
---|
| 847 | ] |
---|
| 848 | print(label+" "+" ".join(data)) |
---|
| 849 | |
---|
| 850 | |
---|
[0bdddc2] | 851 | def plot_models(opts, result, limits=(np.Inf, -np.Inf), setnum=0): |
---|
[ca9e54e] | 852 | # type: (Dict[str, Any], Dict[str, Any], Optional[Tuple[float, float]]) -> Tuple[float, float] |
---|
| 853 | base_value, comp_value= result['base_value'], result['comp_value'] |
---|
| 854 | base_time, comp_time = result['base_time'], result['comp_time'] |
---|
| 855 | resid, relerr = result['resid'], result['relerr'] |
---|
| 856 | |
---|
| 857 | have_base, have_comp = (base_value is not None), (comp_value is not None) |
---|
| 858 | base = opts['engines'][0] if have_base else None |
---|
| 859 | comp = opts['engines'][1] if have_comp else None |
---|
| 860 | data = opts['data'] |
---|
[630156b] | 861 | use_data = (opts['datafile'] is not None) and (have_base ^ have_comp) |
---|
[87985ca] | 862 | |
---|
| 863 | # Plot if requested |
---|
[ec7e360] | 864 | view = opts['view'] |
---|
[1726b21] | 865 | import matplotlib.pyplot as plt |
---|
[0bdddc2] | 866 | vmin, vmax = limits |
---|
| 867 | if have_base: |
---|
| 868 | vmin = min(vmin, base_value.min()) |
---|
| 869 | vmax = max(vmax, base_value.max()) |
---|
| 870 | if have_comp: |
---|
| 871 | vmin = min(vmin, comp_value.min()) |
---|
| 872 | vmax = max(vmax, comp_value.max()) |
---|
| 873 | limits = vmin, vmax |
---|
[013adb7] | 874 | |
---|
[ca9e54e] | 875 | if have_base: |
---|
| 876 | if have_comp: plt.subplot(131) |
---|
[a769b54] | 877 | plot_theory(data, base_value, view=view, use_data=use_data, limits=limits) |
---|
[af92b73] | 878 | plt.title("%s t=%.2f ms"%(base.engine, base_time)) |
---|
[ec7e360] | 879 | #cbar_title = "log I" |
---|
[ca9e54e] | 880 | if have_comp: |
---|
| 881 | if have_base: plt.subplot(132) |
---|
| 882 | if not opts['is2d'] and have_base: |
---|
[a769b54] | 883 | plot_theory(data, base_value, view=view, use_data=use_data, limits=limits) |
---|
| 884 | plot_theory(data, comp_value, view=view, use_data=use_data, limits=limits) |
---|
[af92b73] | 885 | plt.title("%s t=%.2f ms"%(comp.engine, comp_time)) |
---|
[7cf2cfd] | 886 | #cbar_title = "log I" |
---|
[ca9e54e] | 887 | if have_base and have_comp: |
---|
[87985ca] | 888 | plt.subplot(133) |
---|
[d5e650d] | 889 | if not opts['rel_err']: |
---|
[caeb06d] | 890 | err, errstr, errview = resid, "abs err", "linear" |
---|
[29f5536] | 891 | else: |
---|
[caeb06d] | 892 | err, errstr, errview = abs(relerr), "rel err", "log" |
---|
[158cee4] | 893 | if 0: # 95% cutoff |
---|
| 894 | sorted = np.sort(err.flatten()) |
---|
| 895 | cutoff = sorted[int(sorted.size*0.95)] |
---|
| 896 | err[err>cutoff] = cutoff |
---|
[4b41184] | 897 | #err,errstr = base/comp,"ratio" |
---|
[a769b54] | 898 | plot_theory(data, None, resid=err, view=errview, use_data=use_data) |
---|
[d5e650d] | 899 | if view == 'linear': |
---|
| 900 | plt.xscale('linear') |
---|
[e78edc4] | 901 | plt.title("max %s = %.3g"%(errstr, abs(err).max())) |
---|
[7cf2cfd] | 902 | #cbar_title = errstr if errview=="linear" else "log "+errstr |
---|
| 903 | #if is2D: |
---|
| 904 | # h = plt.colorbar() |
---|
| 905 | # h.ax.set_title(cbar_title) |
---|
[0c24a82] | 906 | fig = plt.gcf() |
---|
[a0d75ce] | 907 | extra_title = ' '+opts['title'] if opts['title'] else '' |
---|
[ff1fff5] | 908 | fig.suptitle(":".join(opts['name']) + extra_title) |
---|
[ba69383] | 909 | |
---|
[ca9e54e] | 910 | if have_base and have_comp and opts['show_hist']: |
---|
[ba69383] | 911 | plt.figure() |
---|
[346bc88] | 912 | v = relerr |
---|
[caeb06d] | 913 | v[v == 0] = 0.5*np.min(np.abs(v[v != 0])) |
---|
| 914 | plt.hist(np.log10(np.abs(v)), normed=1, bins=50) |
---|
| 915 | plt.xlabel('log10(err), err = |(%s - %s) / %s|' |
---|
| 916 | % (base.engine, comp.engine, comp.engine)) |
---|
[ba69383] | 917 | plt.ylabel('P(err)') |
---|
[ec7e360] | 918 | plt.title('Distribution of relative error between calculation engines') |
---|
[ba69383] | 919 | |
---|
[013adb7] | 920 | return limits |
---|
| 921 | |
---|
[0763009] | 922 | |
---|
[87985ca] | 923 | # =========================================================================== |
---|
| 924 | # |
---|
[216a9e1] | 925 | NAME_OPTIONS = set([ |
---|
[5d316e9] | 926 | 'plot', 'noplot', |
---|
[ec7e360] | 927 | 'half', 'fast', 'single', 'double', |
---|
| 928 | 'single!', 'double!', 'quad!', 'sasview', |
---|
[e78edc4] | 929 | 'lowq', 'midq', 'highq', 'exq', 'zero', |
---|
[5d316e9] | 930 | '2d', '1d', |
---|
| 931 | 'preset', 'random', |
---|
| 932 | 'poly', 'mono', |
---|
[0b040de] | 933 | 'magnetic', 'nonmagnetic', |
---|
[5d316e9] | 934 | 'nopars', 'pars', |
---|
| 935 | 'rel', 'abs', |
---|
[b89f519] | 936 | 'linear', 'log', 'q4', |
---|
[5d316e9] | 937 | 'hist', 'nohist', |
---|
[630156b] | 938 | 'edit', 'html', 'help', |
---|
[98d6cfc] | 939 | 'demo', 'default', |
---|
[216a9e1] | 940 | ]) |
---|
| 941 | VALUE_OPTIONS = [ |
---|
| 942 | # Note: random is both a name option and a value option |
---|
[0bdddc2] | 943 | 'cutoff', 'random', 'nq', 'res', 'accuracy', 'title', 'data', 'sets' |
---|
[87985ca] | 944 | ] |
---|
| 945 | |
---|
[b32dafd] | 946 | def columnize(items, indent="", width=79): |
---|
[dd7fc12] | 947 | # type: (List[str], str, int) -> str |
---|
[caeb06d] | 948 | """ |
---|
[1d4017a] | 949 | Format a list of strings into columns. |
---|
| 950 | |
---|
| 951 | Returns a string with carriage returns ready for printing. |
---|
[caeb06d] | 952 | """ |
---|
[b32dafd] | 953 | column_width = max(len(w) for w in items) + 1 |
---|
[7cf2cfd] | 954 | num_columns = (width - len(indent)) // column_width |
---|
[b32dafd] | 955 | num_rows = len(items) // num_columns |
---|
| 956 | items = items + [""] * (num_rows * num_columns - len(items)) |
---|
| 957 | columns = [items[k*num_rows:(k+1)*num_rows] for k in range(num_columns)] |
---|
[7cf2cfd] | 958 | lines = [" ".join("%-*s"%(column_width, entry) for entry in row) |
---|
| 959 | for row in zip(*columns)] |
---|
| 960 | output = indent + ("\n"+indent).join(lines) |
---|
| 961 | return output |
---|
| 962 | |
---|
| 963 | |
---|
[98d6cfc] | 964 | def get_pars(model_info, use_demo=False): |
---|
[dd7fc12] | 965 | # type: (ModelInfo, bool) -> ParameterSet |
---|
[caeb06d] | 966 | """ |
---|
| 967 | Extract demo parameters from the model definition. |
---|
| 968 | """ |
---|
[ec7e360] | 969 | # Get the default values for the parameters |
---|
[c499331] | 970 | pars = {} |
---|
[6d6508e] | 971 | for p in model_info.parameters.call_parameters: |
---|
[c499331] | 972 | parts = [('', p.default)] |
---|
| 973 | if p.polydisperse: |
---|
| 974 | parts.append(('_pd', 0.0)) |
---|
| 975 | parts.append(('_pd_n', 0)) |
---|
| 976 | parts.append(('_pd_nsigma', 3.0)) |
---|
| 977 | parts.append(('_pd_type', "gaussian")) |
---|
| 978 | for ext, val in parts: |
---|
| 979 | if p.length > 1: |
---|
[b32dafd] | 980 | dict(("%s%d%s" % (p.id, k, ext), val) |
---|
| 981 | for k in range(1, p.length+1)) |
---|
[c499331] | 982 | else: |
---|
[b32dafd] | 983 | pars[p.id + ext] = val |
---|
[ec7e360] | 984 | |
---|
| 985 | # Plug in values given in demo |
---|
[98d6cfc] | 986 | if use_demo: |
---|
[6d6508e] | 987 | pars.update(model_info.demo) |
---|
[373d1b6] | 988 | return pars |
---|
| 989 | |
---|
[ff1fff5] | 990 | INTEGER_RE = re.compile("^[+-]?[1-9][0-9]*$") |
---|
| 991 | def isnumber(str): |
---|
| 992 | match = FLOAT_RE.match(str) |
---|
| 993 | isfloat = (match and not str[match.end():]) |
---|
| 994 | return isfloat or INTEGER_RE.match(str) |
---|
[17bbadd] | 995 | |
---|
[8c65a33] | 996 | # For distinguishing pairs of models for comparison |
---|
| 997 | # key-value pair separator = |
---|
| 998 | # shell characters | & ; <> $ % ' " \ # ` |
---|
| 999 | # model and parameter names _ |
---|
| 1000 | # parameter expressions - + * / . ( ) |
---|
| 1001 | # path characters including tilde expansion and windows drive ~ / : |
---|
| 1002 | # not sure about brackets [] {} |
---|
| 1003 | # maybe one of the following @ ? ^ ! , |
---|
| 1004 | MODEL_SPLIT = ',' |
---|
[424fe00] | 1005 | def parse_opts(argv): |
---|
| 1006 | # type: (List[str]) -> Dict[str, Any] |
---|
[caeb06d] | 1007 | """ |
---|
| 1008 | Parse command line options. |
---|
| 1009 | """ |
---|
[fc0fcd0] | 1010 | MODELS = core.list_models() |
---|
[424fe00] | 1011 | flags = [arg for arg in argv |
---|
[caeb06d] | 1012 | if arg.startswith('-')] |
---|
[424fe00] | 1013 | values = [arg for arg in argv |
---|
[caeb06d] | 1014 | if not arg.startswith('-') and '=' in arg] |
---|
[424fe00] | 1015 | positional_args = [arg for arg in argv |
---|
[0bdddc2] | 1016 | if not arg.startswith('-') and '=' not in arg] |
---|
[d547f16] | 1017 | models = "\n ".join("%-15s"%v for v in MODELS) |
---|
[424fe00] | 1018 | if len(positional_args) == 0: |
---|
[7cf2cfd] | 1019 | print(USAGE) |
---|
[caeb06d] | 1020 | print("\nAvailable models:") |
---|
[7cf2cfd] | 1021 | print(columnize(MODELS, indent=" ")) |
---|
[424fe00] | 1022 | return None |
---|
| 1023 | if len(positional_args) > 3: |
---|
[9cfcac8] | 1024 | print("expected parameters: model N1 N2") |
---|
[87985ca] | 1025 | |
---|
[ec7e360] | 1026 | invalid = [o[1:] for o in flags |
---|
[216a9e1] | 1027 | if o[1:] not in NAME_OPTIONS |
---|
[d15a908] | 1028 | and not any(o.startswith('-%s='%t) for t in VALUE_OPTIONS)] |
---|
[87985ca] | 1029 | if invalid: |
---|
[9404dd3] | 1030 | print("Invalid options: %s"%(", ".join(invalid))) |
---|
[424fe00] | 1031 | return None |
---|
[87985ca] | 1032 | |
---|
[ff1fff5] | 1033 | name = positional_args[0] |
---|
| 1034 | n1 = int(positional_args[1]) if len(positional_args) > 1 else 1 |
---|
| 1035 | n2 = int(positional_args[2]) if len(positional_args) > 2 else 1 |
---|
[ec7e360] | 1036 | |
---|
[d15a908] | 1037 | # pylint: disable=bad-whitespace |
---|
[ec7e360] | 1038 | # Interpret the flags |
---|
| 1039 | opts = { |
---|
| 1040 | 'plot' : True, |
---|
| 1041 | 'view' : 'log', |
---|
| 1042 | 'is2d' : False, |
---|
| 1043 | 'qmax' : 0.05, |
---|
| 1044 | 'nq' : 128, |
---|
| 1045 | 'res' : 0.0, |
---|
| 1046 | 'accuracy' : 'Low', |
---|
[72a081d] | 1047 | 'cutoff' : 0.0, |
---|
[ec7e360] | 1048 | 'seed' : -1, # default to preset |
---|
[630156b] | 1049 | 'mono' : True, |
---|
[0b040de] | 1050 | # Default to magnetic a magnetic moment is set on the command line |
---|
[b6f10d8] | 1051 | 'magnetic' : False, |
---|
[ec7e360] | 1052 | 'show_pars' : False, |
---|
| 1053 | 'show_hist' : False, |
---|
| 1054 | 'rel_err' : True, |
---|
| 1055 | 'explore' : False, |
---|
[98d6cfc] | 1056 | 'use_demo' : True, |
---|
[dd7fc12] | 1057 | 'zero' : False, |
---|
[234c532] | 1058 | 'html' : False, |
---|
[a0d75ce] | 1059 | 'title' : None, |
---|
[630156b] | 1060 | 'datafile' : None, |
---|
[0bdddc2] | 1061 | 'sets' : 1, |
---|
[ec7e360] | 1062 | } |
---|
| 1063 | engines = [] |
---|
| 1064 | for arg in flags: |
---|
| 1065 | if arg == '-noplot': opts['plot'] = False |
---|
| 1066 | elif arg == '-plot': opts['plot'] = True |
---|
| 1067 | elif arg == '-linear': opts['view'] = 'linear' |
---|
| 1068 | elif arg == '-log': opts['view'] = 'log' |
---|
| 1069 | elif arg == '-q4': opts['view'] = 'q4' |
---|
| 1070 | elif arg == '-1d': opts['is2d'] = False |
---|
| 1071 | elif arg == '-2d': opts['is2d'] = True |
---|
| 1072 | elif arg == '-exq': opts['qmax'] = 10.0 |
---|
| 1073 | elif arg == '-highq': opts['qmax'] = 1.0 |
---|
| 1074 | elif arg == '-midq': opts['qmax'] = 0.2 |
---|
[ce0b154] | 1075 | elif arg == '-lowq': opts['qmax'] = 0.05 |
---|
[e78edc4] | 1076 | elif arg == '-zero': opts['zero'] = True |
---|
[ec7e360] | 1077 | elif arg.startswith('-nq='): opts['nq'] = int(arg[4:]) |
---|
| 1078 | elif arg.startswith('-res='): opts['res'] = float(arg[5:]) |
---|
[0bdddc2] | 1079 | elif arg.startswith('-sets='): opts['sets'] = int(arg[6:]) |
---|
[ec7e360] | 1080 | elif arg.startswith('-accuracy='): opts['accuracy'] = arg[10:] |
---|
| 1081 | elif arg.startswith('-cutoff='): opts['cutoff'] = float(arg[8:]) |
---|
| 1082 | elif arg.startswith('-random='): opts['seed'] = int(arg[8:]) |
---|
[a769b54] | 1083 | elif arg.startswith('-title='): opts['title'] = arg[7:] |
---|
[630156b] | 1084 | elif arg.startswith('-data='): opts['datafile'] = arg[6:] |
---|
[dd7fc12] | 1085 | elif arg == '-random': opts['seed'] = np.random.randint(1000000) |
---|
[ec7e360] | 1086 | elif arg == '-preset': opts['seed'] = -1 |
---|
| 1087 | elif arg == '-mono': opts['mono'] = True |
---|
| 1088 | elif arg == '-poly': opts['mono'] = False |
---|
[0b040de] | 1089 | elif arg == '-magnetic': opts['magnetic'] = True |
---|
| 1090 | elif arg == '-nonmagnetic': opts['magnetic'] = False |
---|
[ec7e360] | 1091 | elif arg == '-pars': opts['show_pars'] = True |
---|
| 1092 | elif arg == '-nopars': opts['show_pars'] = False |
---|
| 1093 | elif arg == '-hist': opts['show_hist'] = True |
---|
| 1094 | elif arg == '-nohist': opts['show_hist'] = False |
---|
| 1095 | elif arg == '-rel': opts['rel_err'] = True |
---|
| 1096 | elif arg == '-abs': opts['rel_err'] = False |
---|
| 1097 | elif arg == '-half': engines.append(arg[1:]) |
---|
| 1098 | elif arg == '-fast': engines.append(arg[1:]) |
---|
| 1099 | elif arg == '-single': engines.append(arg[1:]) |
---|
| 1100 | elif arg == '-double': engines.append(arg[1:]) |
---|
| 1101 | elif arg == '-single!': engines.append(arg[1:]) |
---|
| 1102 | elif arg == '-double!': engines.append(arg[1:]) |
---|
| 1103 | elif arg == '-quad!': engines.append(arg[1:]) |
---|
| 1104 | elif arg == '-sasview': engines.append(arg[1:]) |
---|
| 1105 | elif arg == '-edit': opts['explore'] = True |
---|
[98d6cfc] | 1106 | elif arg == '-demo': opts['use_demo'] = True |
---|
| 1107 | elif arg == '-default': opts['use_demo'] = False |
---|
[234c532] | 1108 | elif arg == '-html': opts['html'] = True |
---|
[630156b] | 1109 | elif arg == '-help': opts['html'] = True |
---|
[d15a908] | 1110 | # pylint: enable=bad-whitespace |
---|
[ec7e360] | 1111 | |
---|
[0bdddc2] | 1112 | # Force random if more than one set |
---|
| 1113 | if opts['sets'] > 1 and opts['seed'] < 0: |
---|
| 1114 | opts['seed'] = np.random.randint(1000000) |
---|
| 1115 | |
---|
[8c65a33] | 1116 | if MODEL_SPLIT in name: |
---|
| 1117 | name, name2 = name.split(MODEL_SPLIT, 2) |
---|
[ff1fff5] | 1118 | else: |
---|
| 1119 | name2 = name |
---|
| 1120 | try: |
---|
| 1121 | model_info = core.load_model_info(name) |
---|
| 1122 | model_info2 = core.load_model_info(name2) if name2 != name else model_info |
---|
| 1123 | except ImportError as exc: |
---|
| 1124 | print(str(exc)) |
---|
| 1125 | print("Could not find model; use one of:\n " + models) |
---|
| 1126 | return None |
---|
[87985ca] | 1127 | |
---|
[0bdddc2] | 1128 | # TODO: check if presets are different when deciding if models are same |
---|
| 1129 | same_model = name == name2 |
---|
| 1130 | if len(engines) == 0: |
---|
| 1131 | if same_model: |
---|
| 1132 | engines.extend(['single', 'double']) |
---|
| 1133 | else: |
---|
| 1134 | engines.extend(['single', 'single']) |
---|
| 1135 | elif len(engines) == 1: |
---|
| 1136 | if not same_model: |
---|
| 1137 | engines.append(engines[0]) |
---|
| 1138 | elif engines[0] == 'double': |
---|
| 1139 | engines.append('single') |
---|
| 1140 | else: |
---|
| 1141 | engines.append('double') |
---|
| 1142 | elif len(engines) > 2: |
---|
| 1143 | del engines[2:] |
---|
| 1144 | |
---|
| 1145 | # Create the computational engines |
---|
| 1146 | if opts['datafile'] is not None: |
---|
| 1147 | data = load_data(os.path.expanduser(opts['datafile'])) |
---|
| 1148 | else: |
---|
| 1149 | data, _ = make_data(opts) |
---|
| 1150 | if n1: |
---|
| 1151 | base = make_engine(model_info, data, engines[0], opts['cutoff']) |
---|
| 1152 | else: |
---|
| 1153 | base = None |
---|
| 1154 | if n2: |
---|
| 1155 | comp = make_engine(model_info2, data, engines[1], opts['cutoff']) |
---|
| 1156 | else: |
---|
| 1157 | comp = None |
---|
| 1158 | |
---|
| 1159 | # pylint: disable=bad-whitespace |
---|
| 1160 | # Remember it all |
---|
| 1161 | opts.update({ |
---|
| 1162 | 'data' : data, |
---|
| 1163 | 'name' : [name, name2], |
---|
| 1164 | 'def' : [model_info, model_info2], |
---|
| 1165 | 'count' : [n1, n2], |
---|
| 1166 | 'engines' : [base, comp], |
---|
| 1167 | 'values' : values, |
---|
| 1168 | }) |
---|
| 1169 | # pylint: enable=bad-whitespace |
---|
| 1170 | |
---|
| 1171 | return opts |
---|
| 1172 | |
---|
| 1173 | def parse_pars(opts): |
---|
| 1174 | model_info, model_info2 = opts['def'] |
---|
| 1175 | |
---|
[ec7e360] | 1176 | # Get demo parameters from model definition, or use default parameters |
---|
| 1177 | # if model does not define demo parameters |
---|
[98d6cfc] | 1178 | pars = get_pars(model_info, opts['use_demo']) |
---|
[ff1fff5] | 1179 | pars2 = get_pars(model_info2, opts['use_demo']) |
---|
[248561a] | 1180 | pars2.update((k, v) for k, v in pars.items() if k in pars2) |
---|
[ff1fff5] | 1181 | # randomize parameters |
---|
| 1182 | #pars.update(set_pars) # set value before random to control range |
---|
| 1183 | if opts['seed'] > -1: |
---|
[0bdddc2] | 1184 | pars = randomize_pars(model_info, pars) |
---|
[ff1fff5] | 1185 | if model_info != model_info2: |
---|
[0bdddc2] | 1186 | pars2 = randomize_pars(model_info2, pars2) |
---|
[158cee4] | 1187 | # Share values for parameters with the same name |
---|
| 1188 | for k, v in pars.items(): |
---|
| 1189 | if k in pars2: |
---|
| 1190 | pars2[k] = v |
---|
[ff1fff5] | 1191 | else: |
---|
| 1192 | pars2 = pars.copy() |
---|
[158cee4] | 1193 | constrain_pars(model_info, pars) |
---|
| 1194 | constrain_pars(model_info2, pars2) |
---|
[ff1fff5] | 1195 | if opts['mono']: |
---|
| 1196 | pars = suppress_pd(pars) |
---|
| 1197 | pars2 = suppress_pd(pars2) |
---|
[b6f10d8] | 1198 | if not opts['magnetic']: |
---|
| 1199 | pars = suppress_magnetism(pars) |
---|
| 1200 | pars2 = suppress_magnetism(pars2) |
---|
[87985ca] | 1201 | |
---|
| 1202 | # Fill in parameters given on the command line |
---|
[ec7e360] | 1203 | presets = {} |
---|
[ff1fff5] | 1204 | presets2 = {} |
---|
[0bdddc2] | 1205 | for arg in opts['values']: |
---|
[d15a908] | 1206 | k, v = arg.split('=', 1) |
---|
[ff1fff5] | 1207 | if k not in pars and k not in pars2: |
---|
[ec7e360] | 1208 | # extract base name without polydispersity info |
---|
[87985ca] | 1209 | s = set(p.split('_pd')[0] for p in pars) |
---|
[d15a908] | 1210 | print("%r invalid; parameters are: %s"%(k, ", ".join(sorted(s)))) |
---|
[424fe00] | 1211 | return None |
---|
[8c65a33] | 1212 | v1, v2 = v.split(MODEL_SPLIT, 2) if MODEL_SPLIT in v else (v,v) |
---|
[ff1fff5] | 1213 | if v1 and k in pars: |
---|
| 1214 | presets[k] = float(v1) if isnumber(v1) else v1 |
---|
| 1215 | if v2 and k in pars2: |
---|
| 1216 | presets2[k] = float(v2) if isnumber(v2) else v2 |
---|
| 1217 | |
---|
[b6f10d8] | 1218 | # If pd given on the command line, default pd_n to 35 |
---|
| 1219 | for k, v in list(presets.items()): |
---|
| 1220 | if k.endswith('_pd'): |
---|
| 1221 | presets.setdefault(k+'_n', 35.) |
---|
| 1222 | for k, v in list(presets2.items()): |
---|
| 1223 | if k.endswith('_pd'): |
---|
| 1224 | presets2.setdefault(k+'_n', 35.) |
---|
| 1225 | |
---|
[ff1fff5] | 1226 | # Evaluate preset parameter expressions |
---|
[248561a] | 1227 | context = MATH.copy() |
---|
[fe25eda] | 1228 | context['np'] = np |
---|
[248561a] | 1229 | context.update(pars) |
---|
[0bdddc2] | 1230 | context.update((k, v) for k, v in presets.items() if isinstance(v, float)) |
---|
[ff1fff5] | 1231 | for k, v in presets.items(): |
---|
| 1232 | if not isinstance(v, float) and not k.endswith('_type'): |
---|
| 1233 | presets[k] = eval(v, context) |
---|
| 1234 | context.update(presets) |
---|
[0bdddc2] | 1235 | context.update((k, v) for k, v in presets2.items() if isinstance(v, float)) |
---|
[ff1fff5] | 1236 | for k, v in presets2.items(): |
---|
| 1237 | if not isinstance(v, float) and not k.endswith('_type'): |
---|
| 1238 | presets2[k] = eval(v, context) |
---|
| 1239 | |
---|
| 1240 | # update parameters with presets |
---|
[ec7e360] | 1241 | pars.update(presets) # set value after random to control value |
---|
[ff1fff5] | 1242 | pars2.update(presets2) # set value after random to control value |
---|
[fcd7bbd] | 1243 | #import pprint; pprint.pprint(model_info) |
---|
[ff1fff5] | 1244 | |
---|
[ec7e360] | 1245 | if opts['show_pars']: |
---|
[0bdddc2] | 1246 | if model_info.name != model_info2.name or pars != pars2: |
---|
[248561a] | 1247 | print("==== %s ====="%model_info.name) |
---|
| 1248 | print(str(parlist(model_info, pars, opts['is2d']))) |
---|
| 1249 | print("==== %s ====="%model_info2.name) |
---|
| 1250 | print(str(parlist(model_info2, pars2, opts['is2d']))) |
---|
| 1251 | else: |
---|
| 1252 | print(str(parlist(model_info, pars, opts['is2d']))) |
---|
[ec7e360] | 1253 | |
---|
[0bdddc2] | 1254 | return pars, pars2 |
---|
[ec7e360] | 1255 | |
---|
[234c532] | 1256 | def show_docs(opts): |
---|
| 1257 | # type: (Dict[str, Any]) -> None |
---|
| 1258 | """ |
---|
| 1259 | show html docs for the model |
---|
| 1260 | """ |
---|
[c4e3215] | 1261 | import os |
---|
| 1262 | from .generate import make_html |
---|
| 1263 | from . import rst2html |
---|
| 1264 | |
---|
| 1265 | info = opts['def'][0] |
---|
| 1266 | html = make_html(info) |
---|
| 1267 | path = os.path.dirname(info.filename) |
---|
| 1268 | url = "file://"+path.replace("\\","/")[2:]+"/" |
---|
| 1269 | rst2html.view_html_qtapp(html, url) |
---|
[234c532] | 1270 | |
---|
[ec7e360] | 1271 | def explore(opts): |
---|
[dd7fc12] | 1272 | # type: (Dict[str, Any]) -> None |
---|
[d15a908] | 1273 | """ |
---|
[234c532] | 1274 | explore the model using the bumps gui. |
---|
[d15a908] | 1275 | """ |
---|
[7ae2b7f] | 1276 | import wx # type: ignore |
---|
| 1277 | from bumps.names import FitProblem # type: ignore |
---|
| 1278 | from bumps.gui.app_frame import AppFrame # type: ignore |
---|
[ca9e54e] | 1279 | from bumps.gui import signal |
---|
[ec7e360] | 1280 | |
---|
[d15a908] | 1281 | is_mac = "cocoa" in wx.version() |
---|
[80013a6] | 1282 | # Create an app if not running embedded |
---|
| 1283 | app = wx.App() if wx.GetApp() is None else None |
---|
[ca9e54e] | 1284 | model = Explore(opts) |
---|
| 1285 | problem = FitProblem(model) |
---|
[0bdddc2] | 1286 | frame = AppFrame(parent=None, title="explore", size=(1000, 700)) |
---|
| 1287 | if not is_mac: |
---|
| 1288 | frame.Show() |
---|
[ec7e360] | 1289 | frame.panel.set_model(model=problem) |
---|
| 1290 | frame.panel.Layout() |
---|
| 1291 | frame.panel.aui.Split(0, wx.TOP) |
---|
[ca9e54e] | 1292 | def reset_parameters(event): |
---|
| 1293 | model.revert_values() |
---|
| 1294 | signal.update_parameters(problem) |
---|
| 1295 | frame.Bind(wx.EVT_TOOL, reset_parameters, frame.ToolBar.GetToolByPos(1)) |
---|
[d15a908] | 1296 | if is_mac: frame.Show() |
---|
[80013a6] | 1297 | # If running withing an app, start the main loop |
---|
[0bdddc2] | 1298 | if app: |
---|
| 1299 | app.MainLoop() |
---|
[ec7e360] | 1300 | |
---|
| 1301 | class Explore(object): |
---|
| 1302 | """ |
---|
[d15a908] | 1303 | Bumps wrapper for a SAS model comparison. |
---|
| 1304 | |
---|
| 1305 | The resulting object can be used as a Bumps fit problem so that |
---|
| 1306 | parameters can be adjusted in the GUI, with plots updated on the fly. |
---|
[ec7e360] | 1307 | """ |
---|
| 1308 | def __init__(self, opts): |
---|
[dd7fc12] | 1309 | # type: (Dict[str, Any]) -> None |
---|
[7ae2b7f] | 1310 | from bumps.cli import config_matplotlib # type: ignore |
---|
[608e31e] | 1311 | from . import bumps_model |
---|
[ec7e360] | 1312 | config_matplotlib() |
---|
| 1313 | self.opts = opts |
---|
[0bdddc2] | 1314 | opts['pars'] = list(opts['pars']) |
---|
[ca9e54e] | 1315 | p1, p2 = opts['pars'] |
---|
| 1316 | m1, m2 = opts['def'] |
---|
| 1317 | self.fix_p2 = m1 != m2 or p1 != p2 |
---|
| 1318 | model_info = m1 |
---|
| 1319 | pars, pd_types = bumps_model.create_parameters(model_info, **p1) |
---|
[21b116f] | 1320 | # Initialize parameter ranges, fixing the 2D parameters for 1D data. |
---|
[ec7e360] | 1321 | if not opts['is2d']: |
---|
[85fe7f8] | 1322 | for p in model_info.parameters.user_parameters({}, is2d=False): |
---|
[303d8d6] | 1323 | for ext in ['', '_pd', '_pd_n', '_pd_nsigma']: |
---|
[69aa451] | 1324 | k = p.name+ext |
---|
[303d8d6] | 1325 | v = pars.get(k, None) |
---|
| 1326 | if v is not None: |
---|
| 1327 | v.range(*parameter_range(k, v.value)) |
---|
[ec7e360] | 1328 | else: |
---|
[013adb7] | 1329 | for k, v in pars.items(): |
---|
[ec7e360] | 1330 | v.range(*parameter_range(k, v.value)) |
---|
| 1331 | |
---|
| 1332 | self.pars = pars |
---|
[ca9e54e] | 1333 | self.starting_values = dict((k, v.value) for k, v in pars.items()) |
---|
[ec7e360] | 1334 | self.pd_types = pd_types |
---|
[0bdddc2] | 1335 | self.limits = np.Inf, -np.Inf |
---|
[ec7e360] | 1336 | |
---|
[ca9e54e] | 1337 | def revert_values(self): |
---|
| 1338 | for k, v in self.starting_values.items(): |
---|
| 1339 | self.pars[k].value = v |
---|
| 1340 | |
---|
| 1341 | def model_update(self): |
---|
| 1342 | pass |
---|
| 1343 | |
---|
[ec7e360] | 1344 | def numpoints(self): |
---|
[dd7fc12] | 1345 | # type: () -> int |
---|
[ec7e360] | 1346 | """ |
---|
[608e31e] | 1347 | Return the number of points. |
---|
[ec7e360] | 1348 | """ |
---|
| 1349 | return len(self.pars) + 1 # so dof is 1 |
---|
| 1350 | |
---|
| 1351 | def parameters(self): |
---|
[dd7fc12] | 1352 | # type: () -> Any # Dict/List hierarchy of parameters |
---|
[ec7e360] | 1353 | """ |
---|
[608e31e] | 1354 | Return a dictionary of parameters. |
---|
[ec7e360] | 1355 | """ |
---|
| 1356 | return self.pars |
---|
| 1357 | |
---|
| 1358 | def nllf(self): |
---|
[dd7fc12] | 1359 | # type: () -> float |
---|
[608e31e] | 1360 | """ |
---|
| 1361 | Return cost. |
---|
| 1362 | """ |
---|
[d15a908] | 1363 | # pylint: disable=no-self-use |
---|
[ec7e360] | 1364 | return 0. # No nllf |
---|
| 1365 | |
---|
| 1366 | def plot(self, view='log'): |
---|
[dd7fc12] | 1367 | # type: (str) -> None |
---|
[ec7e360] | 1368 | """ |
---|
| 1369 | Plot the data and residuals. |
---|
| 1370 | """ |
---|
[608e31e] | 1371 | pars = dict((k, v.value) for k, v in self.pars.items()) |
---|
[ec7e360] | 1372 | pars.update(self.pd_types) |
---|
[ff1fff5] | 1373 | self.opts['pars'][0] = pars |
---|
[ca9e54e] | 1374 | if not self.fix_p2: |
---|
| 1375 | self.opts['pars'][1] = pars |
---|
| 1376 | result = run_models(self.opts) |
---|
| 1377 | limits = plot_models(self.opts, result, limits=self.limits) |
---|
[013adb7] | 1378 | if self.limits is None: |
---|
| 1379 | vmin, vmax = limits |
---|
[dd7fc12] | 1380 | self.limits = vmax*1e-7, 1.3*vmax |
---|
[ca9e54e] | 1381 | import pylab; pylab.clf() |
---|
| 1382 | plot_models(self.opts, result, limits=self.limits) |
---|
[87985ca] | 1383 | |
---|
| 1384 | |
---|
[424fe00] | 1385 | def main(*argv): |
---|
| 1386 | # type: (*str) -> None |
---|
[d15a908] | 1387 | """ |
---|
| 1388 | Main program. |
---|
| 1389 | """ |
---|
[424fe00] | 1390 | opts = parse_opts(argv) |
---|
| 1391 | if opts is not None: |
---|
[48462b0] | 1392 | if opts['seed'] > -1: |
---|
| 1393 | print("Randomize using -random=%i"%opts['seed']) |
---|
| 1394 | np.random.seed(opts['seed']) |
---|
[234c532] | 1395 | if opts['html']: |
---|
| 1396 | show_docs(opts) |
---|
| 1397 | elif opts['explore']: |
---|
[0bdddc2] | 1398 | opts['pars'] = parse_pars(opts) |
---|
[8f04da4] | 1399 | if opts['pars'] is None: |
---|
| 1400 | return |
---|
[424fe00] | 1401 | explore(opts) |
---|
| 1402 | else: |
---|
| 1403 | compare(opts) |
---|
[d15a908] | 1404 | |
---|
[8a20be5] | 1405 | if __name__ == "__main__": |
---|
[424fe00] | 1406 | main(*sys.argv[1:]) |
---|