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