source: sasmodels/sasmodels/core.py @ d5ba841

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

product model now works with sphere

  • Property mode set to 100644
File size: 8.5 KB
Line 
1"""
2Core model handling routines.
3"""
4
5from os.path import basename, dirname, join as joinpath
6from glob import glob
7
8import numpy as np
9
10from . import models
11from . import weights
12from . import generate
13
14from . import kernelpy
15from . import kerneldll
16try:
17    from . import kernelcl
18    HAVE_OPENCL = True
19except:
20    HAVE_OPENCL = False
21
22__all__ = [
23    "list_models", "load_model_info", "precompile_dll",
24    "build_model", "make_kernel", "call_kernel", "call_ER_VR",
25]
26
27def list_models():
28    """
29    Return the list of available models on the model path.
30    """
31    root = dirname(__file__)
32    files = sorted(glob(joinpath(root, 'models', "[a-zA-Z]*.py")))
33    available_models = [basename(f)[:-3] for f in files]
34    return available_models
35
36def isstr(s):
37    """
38    Return True if *s* is a string-like object.
39    """
40    try: s + ''
41    except: return False
42    return True
43
44def load_model(model_name, **kw):
45    """
46    Load model info and build model.
47    """
48    parts = model_name.split('+')
49    if len(parts) > 1:
50        from .mixture import MixtureModel
51        models = [load_model(p, **kw) for p in parts]
52        return MixtureModel(models)
53
54    parts = model_name.split('*')
55    if len(parts) > 1:
56        # Note: currently have circular reference
57        from .product import ProductModel
58        if len(parts) > 2:
59            raise ValueError("use P*S to apply structure factor S to model P")
60        P, Q = [load_model(p, **kw) for p in parts]
61        return ProductModel(P, Q)
62
63    return build_model(load_model_info(model_name), **kw)
64
65def load_model_info(model_name):
66    """
67    Load a model definition given the model name.
68
69    This returns a handle to the module defining the model.  This can be
70    used with functions in generate to build the docs or extract model info.
71    """
72    #import sys; print "\n".join(sys.path)
73    __import__('sasmodels.models.'+model_name)
74    kernel_module = getattr(models, model_name, None)
75    return generate.make_model_info(kernel_module)
76
77
78def build_model(model_info, dtype=None, platform="ocl"):
79    """
80    Prepare the model for the default execution platform.
81
82    This will return an OpenCL model, a DLL model or a python model depending
83    on the model and the computing platform.
84
85    *model_info* is the model definition structure returned from
86    :func:`load_model_info`.
87
88    *dtype* indicates whether the model should use single or double precision
89    for the calculation. Any valid numpy single or double precision identifier
90    is valid, such as 'single', 'f', 'f32', or np.float32 for single, or
91    'double', 'd', 'f64'  and np.float64 for double.  If *None*, then use
92    'single' unless the model defines single=False.
93
94    *platform* should be "dll" to force the dll to be used for C models,
95    otherwise it uses the default "ocl".
96    """
97    source = generate.make_source(model_info)
98    if dtype is None:
99        dtype = 'single' if model_info['single'] else 'double'
100    if callable(model_info.get('Iq', None)):
101        return kernelpy.PyModel(model_info)
102
103    ## for debugging:
104    ##  1. uncomment open().write so that the source will be saved next time
105    ##  2. run "python -m sasmodels.direct_model $MODELNAME" to save the source
106    ##  3. recomment the open.write() and uncomment open().read()
107    ##  4. rerun "python -m sasmodels.direct_model $MODELNAME"
108    ##  5. uncomment open().read() so that source will be regenerated from model
109    # open(model_info['name']+'.c','w').write(source)
110    # source = open(model_info['name']+'.cl','r').read()
111
112    if (platform == "dll"
113            or not HAVE_OPENCL
114            or not kernelcl.environment().has_type(dtype)):
115        return kerneldll.load_dll(source, model_info, dtype)
116    else:
117        return kernelcl.GpuModel(source, model_info, dtype)
118
119def precompile_dll(model_name, dtype="double"):
120    """
121    Precompile the dll for a model.
122
123    Returns the path to the compiled model, or None if the model is a pure
124    python model.
125
126    This can be used when build the windows distribution of sasmodels
127    (which may be missing the OpenCL driver and the dll compiler), or
128    otherwise sharing models with windows users who do not have a compiler.
129
130    See :func:`sasmodels.kerneldll.make_dll` for details on controlling the
131    dll path and the allowed floating point precision.
132    """
133    model_info = load_model_info(model_name)
134    source = generate.make_source(model_info)
135    return kerneldll.make_dll(source, model_info, dtype=dtype) if source else None
136
137
138def make_kernel(model, q_vectors):
139    """
140    Return a computation kernel from the model definition and the q input.
141    """
142    return model(q_vectors)
143
144def get_weights(model_info, pars, name):
145    """
146    Generate the distribution for parameter *name* given the parameter values
147    in *pars*.
148
149    Uses "name", "name_pd", "name_pd_type", "name_pd_n", "name_pd_sigma"
150    from the *pars* dictionary for parameter value and parameter dispersion.
151    """
152    relative = name in model_info['partype']['pd-rel']
153    limits = model_info['limits'][name]
154    disperser = pars.get(name+'_pd_type', 'gaussian')
155    value = pars.get(name, model_info['defaults'][name])
156    npts = pars.get(name+'_pd_n', 0)
157    width = pars.get(name+'_pd', 0.0)
158    nsigma = pars.get(name+'_pd_nsigma', 3.0)
159    value, weight = weights.get_weights(
160        disperser, npts, width, nsigma, value, limits, relative)
161    return value, weight / np.sum(weight)
162
163def dispersion_mesh(pars):
164    """
165    Create a mesh grid of dispersion parameters and weights.
166
167    Returns [p1,p2,...],w where pj is a vector of values for parameter j
168    and w is a vector containing the products for weights for each
169    parameter set in the vector.
170    """
171    value, weight = zip(*pars)
172    value = [v.flatten() for v in np.meshgrid(*value)]
173    weight = np.vstack([v.flatten() for v in np.meshgrid(*weight)])
174    weight = np.prod(weight, axis=0)
175    return value, weight
176
177def call_kernel(kernel, pars, cutoff=0, mono=False):
178    """
179    Call *kernel* returned from :func:`make_kernel` with parameters *pars*.
180
181    *cutoff* is the limiting value for the product of dispersion weights used
182    to perform the multidimensional dispersion calculation more quickly at a
183    slight cost to accuracy. The default value of *cutoff=0* integrates over
184    the entire dispersion cube.  Using *cutoff=1e-5* can be 50% faster, but
185    with an error of about 1%, which is usually less than the measurement
186    uncertainty.
187    """
188    fixed_pars = [pars.get(name, kernel.info['defaults'][name])
189                  for name in kernel.fixed_pars]
190    if mono:
191        pd_pars = [( np.array([pars[name]]), np.array([1.0]) )
192                   for name in kernel.pd_pars]
193    else:
194        pd_pars = [get_weights(kernel.info, pars, name) for name in kernel.pd_pars]
195    return kernel(fixed_pars, pd_pars, cutoff=cutoff)
196
197def call_ER_VR(model_info, vol_pars):
198    """
199    Return effect radius and volume ratio for the model.
200
201    *info* is either *kernel.info* for *kernel=make_kernel(model,q)*
202    or *model.info*.
203
204    *pars* are the parameters as expected by :func:`call_kernel`.
205    """
206    ER = model_info.get('ER', None)
207    VR = model_info.get('VR', None)
208    value, weight = dispersion_mesh(vol_pars)
209
210    individual_radii = ER(*value) if ER else 1.0
211    whole, part = VR(*value) if VR else (1.0, 1.0)
212
213    effect_radius = np.sum(weight*individual_radii) / np.sum(weight)
214    volume_ratio = np.sum(weight*part)/np.sum(weight*whole)
215    return effect_radius, volume_ratio
216
217
218def call_ER(info, pars):
219    """
220    Call the model ER function using *pars*.
221    *info* is either *model.info* if you have a loaded model, or *kernel.info*
222    if you have a model kernel prepared for evaluation.
223    """
224    ER = info.get('ER', None)
225    if ER is None:
226        return 1.0
227    else:
228        vol_pars = [get_weights(info, pars, name)
229                    for name in info['partype']['volume']]
230        value, weight = dispersion_mesh(vol_pars)
231        individual_radii = ER(*value)
232        #print(values[0].shape, weights.shape, fv.shape)
233        return np.sum(weight*individual_radii) / np.sum(weight)
234
235def call_VR(info, pars):
236    """
237    Call the model VR function using *pars*.
238    *info* is either *model.info* if you have a loaded model, or *kernel.info*
239    if you have a model kernel prepared for evaluation.
240    """
241    VR = info.get('VR', None)
242    if VR is None:
243        return 1.0
244    else:
245        vol_pars = [get_weights(info, pars, name)
246                    for name in info['partype']['volume']]
247        value, weight = dispersion_mesh(vol_pars)
248        whole, part = VR(*value)
249        return np.sum(weight*part)/np.sum(weight*whole)
250
251# TODO: remove call_ER, call_VR
252
Note: See TracBrowser for help on using the repository browser.