source: sasmodels/sasmodels/compare.py @ 1edf610

core_shell_microgelscostrafo411magnetic_modelrelease_v0.94release_v0.95ticket-1257-vesicle-productticket_1156ticket_1265_superballticket_822_more_unit_tests
Last change on this file since 1edf610 was 1edf610, checked in by Paul Kienzle <pkienzle@…>, 8 years ago

debug checkin

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