Changeset 7be65ea in sasmodels


Ignore:
Timestamp:
Nov 24, 2015 9:57:53 AM (8 years ago)
Author:
Paul Kienzle <pkienzle@…>
Branches:
master, core_shell_microgels, costrafo411, magnetic_model, release_v0.94, release_v0.95, ticket-1257-vesicle-product, ticket_1156, ticket_1265_superball, ticket_822_more_unit_tests
Children:
a30cdd5
Parents:
34375ea (diff), cd3dba0 (diff)
Note: this is a merge changeset, the changes displayed below correspond to the merge itself.
Use the (diff) links above to see all the changes relative to each parent.
Message:

Merge branch 'master' of github.com:sasview/sasmodels

Files:
8 edited

Legend:

Unmodified
Added
Removed
  • sasmodels/compare.py

    r73a3e22 rcd3dba0  
    1616from . import core 
    1717from . import kerneldll 
    18 from . import models 
     18from . import generate 
    1919from .data import plot_theory, empty_data1D, empty_data2D 
    2020from .direct_model import DirectModel 
     
    116116        return 2*np.random.rand()*(v if v != 0 else 1) 
    117117 
    118 def randomize_model(name, pars, seed=None): 
     118def randomize_model(pars, seed=None): 
    119119    if seed is None: 
    120120        seed = np.random.randint(1e9) 
     
    122122    # Note: the sort guarantees order of calls to random number generator 
    123123    pars = dict((p,randomize(p,v)) for p,v in sorted(pars.items())) 
    124     # The capped cylinder model has a constraint on its parameters 
     124 
     125    return pars, seed 
     126 
     127def constrain_pars(model_definition, pars): 
     128    name = model_definition.name 
    125129    if name == 'capped_cylinder' and pars['cap_radius'] < pars['radius']: 
    126130        pars['radius'],pars['cap_radius'] = pars['cap_radius'],pars['radius'] 
    127     return pars, seed 
     131 
     132    # These constraints are only needed for comparison to sasview 
     133    if name in ('teubner_strey','broad_peak'): 
     134        del pars['scale'] 
     135    if name in ('guinier',): 
     136        del pars['background'] 
     137    if getattr(model_definition, 'category', None) == 'structure-factor': 
     138        del pars['scale'], pars['background'] 
     139 
    128140 
    129141def parlist(pars): 
     
    209221 
    210222def compare(name, pars, Ncpu, Nocl, opts, set_pars): 
     223    model_definition = core.load_model_definition(name) 
     224 
    211225    view = 'linear' if '-linear' in opts else 'log' if '-log' in opts else 'q4' if '-q4' in opts else 'log' 
    212226 
     
    231245    if '-random' in opts or '-random' in opt_values: 
    232246        seed = int(opt_values['-random']) if '-random' in opt_values else None 
    233         pars, seed = randomize_model(name, pars, seed=seed) 
     247        pars, seed = randomize_model(pars, seed=seed) 
     248        constrain_pars(model_definition, pars) 
    234249        print "Randomize using -random=%i"%seed 
    235250    pars.update(set_pars)  # set value after random to control value 
     
    241256        print "pars",parlist(pars) 
    242257 
    243     model_definition = core.load_model_definition(name) 
    244258    # OpenCl calculation 
    245259    if Nocl > 0: 
     
    247261                                    dtype=dtype, cutoff=cutoff, Nevals=Nocl) 
    248262        print "opencl t=%.1f ms, intensity=%.0f"%(ocl_time, sum(ocl)) 
     263        #print "ocl", ocl 
    249264        #print max(ocl), min(ocl) 
    250265 
     
    261276            #print "ocl/sasview", (ocl-pars['background'])/(cpu-pars['background']) 
    262277            print "sasview t=%.1f ms, intensity=%.0f"%(cpu_time, sum(cpu)) 
     278            #print "sasview",cpu 
    263279        except ImportError: 
    264280            Ncpu = 0 
     
    396412 
    397413 
    398 def get_demo_pars(name): 
    399     __import__('sasmodels.models.'+name) 
    400     model = getattr(models, name) 
    401     pars = getattr(model, 'demo', None) 
    402     if pars is None: pars = dict((p[0],p[2]) for p in model.parameters) 
     414def get_demo_pars(model_definition): 
     415    info = generate.make_info(model_definition) 
     416    pars = dict((p[0],p[2]) for p in info['parameters']) 
     417    pars.update(info['demo']) 
    403418    return pars 
    404419 
     
    425440    # if model does not define demo parameters 
    426441    name = args[0] 
    427     pars = get_demo_pars(name) 
     442    model_definition = core.load_model_definition(name) 
     443    pars = get_demo_pars(model_definition) 
    428444 
    429445    Nopencl = int(args[1]) if len(args) > 1 else 5 
  • sasmodels/compare_many.py

    re922c5d rcd3dba0  
    99from .compare import (MODELS, randomize_model, suppress_pd, eval_sasview, 
    1010                      eval_opencl, eval_ctypes, make_data, get_demo_pars, 
    11                       columnize) 
     11                      columnize, constrain_pars) 
    1212 
    1313def get_stats(target, value, index): 
     
    3636def compare_instance(name, data, index, N=1, mono=True, cutoff=1e-5): 
    3737    model_definition = core.load_model_definition(name) 
    38     pars = get_demo_pars(name) 
     38    pars = get_demo_pars(model_definition) 
    3939    header = '\n"Model","%s","Count","%d"'%(name, N) 
    4040    if not mono: header += ',"Cutoff",%g'%(cutoff,) 
    4141    print(header) 
    4242 
    43     # Stuff the failure flag into a mutable object so we can update it from 
    44     # within the nested function.  Note that the nested function uses "pars" 
    45     # which is dynamically scoped, not lexically scoped in this context.  That 
    46     # is, pars is replaced each time in the loop, so don't assume that it is 
    47     # the default values defined above. 
    4843    def trymodel(fn, *args, **kw): 
    4944        try: 
    50             result, _ = fn(model_definition, pars, data, *args, **kw) 
     45            result, _ = fn(model_definition, pars_i, data, *args, **kw) 
     46        except KeyboardInterrupt: 
     47            raise 
    5148        except: 
    52             result = np.NaN 
    53             traceback.print_exc() 
     49            print >>sys.stderr, traceback.format_exc() 
     50            print >>sys.stderr, "when comparing",name,"for seed",seed 
     51            if hasattr(data, 'qx_data'): 
     52                result = np.NaN*data.data 
     53            else: 
     54                result = np.NaN*data.x 
    5455        return result 
    5556 
    5657    num_good = 0 
    5758    first = True 
    58     for _ in range(N): 
    59         pars, seed = randomize_model(name, pars) 
    60         if mono: suppress_pd(pars) 
    61  
    62         # Force parameter constraints on a per-model basis. 
    63         if name in ('teubner_strey','broad_peak'): 
    64             pars['scale'] = 1.0 
    65         #if name == 'parallelepiped': 
    66         #    pars['a_side'],pars['b_side'],pars['c_side'] = \ 
    67         #        sorted([pars['a_side'],pars['b_side'],pars['c_side']]) 
    68  
     59    for k in range(N): 
     60        print >>sys.stderr, name, k 
     61        pars_i, seed = randomize_model(pars) 
     62        constrain_pars(model_definition, pars_i) 
     63        if mono: suppress_pd(pars_i) 
    6964 
    7065        good = True 
     
    9792            good = good and (stats[0] < 1e-14) 
    9893 
    99         columns += [v for _,v in sorted(pars.items())] 
     94        columns += [v for _,v in sorted(pars_i.items())] 
    10095        if first: 
    101             print_column_headers(pars, labels) 
     96            print_column_headers(pars_i, labels) 
    10297            first = False 
    10398        if good: 
  • sasmodels/generate.py

    r4eac427 rcd3dba0  
    9999The kernel module must set variables defining the kernel meta data: 
    100100 
    101     *name* is the model name 
     101    *id* is an implicit variable formed from the filename.  It will be 
     102    a valid python identifier, and will be used as the reference into 
     103    the html documentation, with '_' replaced by '-'. 
     104 
     105    *name* is the model name as displayed to the user.  If it is missing, 
     106    it will be constructed from the id. 
    102107 
    103108    *title* is a short description of the model, suitable for a tool tip, 
     
    114119    the kernel functions. 
    115120 
     121    *category* is the default category for the model.  Models in the 
     122    *structure-factor* category do not have *scale* and *background* 
     123    added. 
     124 
    116125    *source* is the list of C-99 source files that must be joined to 
    117126    create the OpenCL kernel functions.  The files defining the functions 
     
    134143    this step is significant. 
    135144 
    136 An *info* dictionary is constructed from the kernel meta data and 
    137 returned to the caller. 
    138  
    139 Additional fields can be defined in the kernel definition file that 
    140 are not needed for sas modelling. 
    141  
    142145    *demo* is a dictionary of parameter=value defining a set of 
    143     parameters to use by default when *compare* is called. 
     146    parameters to use by default when *compare* is called.  Any 
     147    parameter not set in *demo* gets the initial value from the 
     148    parameter list.  *demo* is mostly needed to set the default 
     149    polydispersity values for tests. 
    144150 
    145151    *oldname* is the name of the model in sasview before sasmodels 
     
    149155    of the new model against the values of the old model before 
    150156    you are ready to add the new model to sasmodels. 
     157 
     158 
     159An *info* dictionary is constructed from the kernel meta data and 
     160returned to the caller. 
    151161 
    152162The model evaluator, function call sequence consists of q inputs and the return vector, 
     
    190200 
    191201import sys 
    192 from os.path import abspath, dirname, join as joinpath, exists 
     202from os.path import abspath, dirname, join as joinpath, exists, basename 
    193203import re 
    194204 
     
    233243# description and its parameter table.  The remainder of the doc comes 
    234244# from the module docstring. 
    235 DOC_HEADER = """.. _%(name)s: 
    236  
    237 %(label)s 
     245DOC_HEADER = """.. _%(id)s: 
     246 
     247%(name)s 
    238248======================================================= 
    239249 
     
    254264    Generate the parameter table to include in the sphinx documentation. 
    255265    """ 
    256     pars = COMMON_PARAMETERS + pars 
    257266    column_widths = [ 
    258267        max(len(p[0]) for p in pars), 
     
    523532        } 
    524533 
    525 def make(kernel_module): 
    526     """ 
    527     Build an OpenCL/ctypes function from the definition in *kernel_module*. 
    528  
    529     The module can be loaded with a normal python import statement if you 
    530     know which module you need, or with __import__('sasmodels.model.'+name) 
    531     if the name is in a string. 
    532     """ 
    533     # TODO: allow Iq and Iqxy to be defined in python 
     534def make_info(kernel_module): 
     535    """ 
     536    Interpret the model definition file, categorizing the parameters. 
     537    """ 
    534538    #print kernelfile 
     539    category = getattr(kernel_module, 'category', None) 
     540    parameters = COMMON_PARAMETERS + kernel_module.parameters 
     541    # Default the demo parameters to the starting values for the individual 
     542    # parameters if an explicit demo parameter set has not been specified. 
     543    demo_parameters = getattr(kernel_module, 'demo', None) 
     544    if demo_parameters is None: 
     545        demo_parameters = dict((p[0],p[2]) for p in parameters) 
     546    filename = abspath(kernel_module.__file__) 
     547    kernel_id = basename(filename)[:-3] 
     548    name = getattr(kernel_module, 'name', None) 
     549    if name is None: 
     550        name = " ".join(w.capitalize() for w in kernel_id.split('_')) 
    535551    info = dict( 
     552        id = kernel_id,  # string used to load the kernel 
    536553        filename=abspath(kernel_module.__file__), 
    537         name=kernel_module.name, 
     554        name=name, 
    538555        title=kernel_module.title, 
    539556        description=kernel_module.description, 
    540         parameters=COMMON_PARAMETERS + kernel_module.parameters, 
     557        category=category, 
     558        parameters=parameters, 
     559        demo=demo_parameters, 
    541560        source=getattr(kernel_module, 'source', []), 
    542561        oldname=kernel_module.oldname, 
     
    550569    info['partype'] = categorize_parameters(info['parameters']) 
    551570    info['defaults'] = dict((p[0], p[2]) for p in info['parameters']) 
    552  
     571    return info 
     572 
     573def make(kernel_module): 
     574    """ 
     575    Build an OpenCL/ctypes function from the definition in *kernel_module*. 
     576 
     577    The module can be loaded with a normal python import statement if you 
     578    know which module you need, or with __import__('sasmodels.model.'+name) 
     579    if the name is in a string. 
     580    """ 
     581    info = make_info(kernel_module) 
    553582    # Assume if one part of the kernel is python then all parts are. 
    554583    source = make_model(info) if not callable(info['Iq']) else None 
     
    559588    Return the documentation for the model. 
    560589    """ 
    561     subst = dict(name=kernel_module.name.replace('_', '-'), 
    562                  label=" ".join(kernel_module.name.split('_')).capitalize(), 
    563                  title=kernel_module.title, 
    564                  parameters=make_partable(kernel_module.parameters), 
     590    info = make_info(kernel_module) 
     591    subst = dict(id=info['id'].replace('_', '-'), 
     592                 name=info['name'], 
     593                 title=info['title'], 
     594                 parameters=make_partable(info['parameters']), 
    565595                 docs=kernel_module.__doc__) 
    566596    return DOC_HEADER % subst 
  • sasmodels/models/HayterMSAsq.py

    r63b32bb rcd3dba0  
    7575               "dielectric constant of solvent (default water), for Debye length"], 
    7676             ] 
     77category = "structure-factor" 
    7778 
    7879# No volume normalization despite having a volume parameter 
  • sasmodels/models/bcc.py

    r485aee2 rcd3dba0  
    134134    radius=40, 
    135135    theta=60, phi=60, psi=60, 
    136     radius_pd=.2, radius_pd_n=0.2, 
     136    radius_pd=.2, radius_pd_n=2, 
    137137    theta_pd=15, theta_pd_n=0, 
    138138    phi_pd=15, phi_pd_n=0, 
  • sasmodels/models/parallelepiped.py

    r9fd094c rcd3dba0  
    158158            a_side_pd=0.1, a_side_pd_n=10, 
    159159            b_side_pd=0.1, b_side_pd_n=1, 
    160             c_side_pd=0.1, c_side_pd_n=10, 
     160            c_side_pd=0.1, c_side_pd_n=1, 
    161161            theta_pd=10, theta_pd_n=1, 
    162162            phi_pd=10, phi_pd_n=1, 
  • doc/Makefile

    r23259b9 r34375ea  
    4747model/img/%: ../sasmodels/models/img/% 
    4848ifdef ComSpec 
    49         $(COPY) $(subst /,\\,$<) $(subst /,\\,$@) 
     49        $(COPY) $(subst /,\,$<) $(subst /,\,$@) 
    5050else 
    5151        $(COPY) $< $@ 
  • sasmodels/models/spherepy.py

    rade352a r34375ea  
    6161from numpy import pi, inf, sin, cos, sqrt, log 
    6262 
    63 name = "sphere" 
     63name = "sphere (python)" 
    6464title = "Spheres with uniform scattering length density" 
    6565description = """\ 
Note: See TracChangeset for help on using the changeset viewer.