source: sasmodels/sasmodels/compare.py @ 31df0c9

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

tuned random model generation for more models

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