source: sasmodels/sasmodels/compare.py @ 650c6d2

core_shell_microgelscostrafo411magnetic_modelticket-1257-vesicle-productticket_1156ticket_1265_superballticket_822_more_unit_tests
Last change on this file since 650c6d2 was 650c6d2, checked in by Paul Kienzle <pkienzle@…>, 7 years ago

use correct type info for 16-bit floats

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