[aa4946b] | 1 | """ |
---|
| 2 | Core model handling routines. |
---|
| 3 | """ |
---|
[f734e7d] | 4 | |
---|
[72a081d] | 5 | from os.path import basename, dirname, join as joinpath, splitext |
---|
[f734e7d] | 6 | from glob import glob |
---|
[72a081d] | 7 | import imp |
---|
[f734e7d] | 8 | |
---|
| 9 | import numpy as np |
---|
| 10 | |
---|
| 11 | from . import models |
---|
| 12 | from . import weights |
---|
[aa4946b] | 13 | from . import generate |
---|
[72a081d] | 14 | # TODO: remove circular references between product and core |
---|
| 15 | # product uses call_ER/call_VR, core uses make_product_info/ProductModel |
---|
| 16 | #from . import product |
---|
| 17 | from . import mixture |
---|
[aa4946b] | 18 | from . import kernelpy |
---|
| 19 | from . import kerneldll |
---|
[f734e7d] | 20 | try: |
---|
[aa4946b] | 21 | from . import kernelcl |
---|
| 22 | HAVE_OPENCL = True |
---|
[3c56da87] | 23 | except: |
---|
[aa4946b] | 24 | HAVE_OPENCL = False |
---|
| 25 | |
---|
[190fc2b] | 26 | __all__ = [ |
---|
[17bbadd] | 27 | "list_models", "load_model_info", "precompile_dll", |
---|
[48fbd50] | 28 | "build_model", "call_kernel", "call_ER_VR", |
---|
[190fc2b] | 29 | ] |
---|
[f734e7d] | 30 | |
---|
| 31 | def list_models(): |
---|
[aa4946b] | 32 | """ |
---|
| 33 | Return the list of available models on the model path. |
---|
| 34 | """ |
---|
[f734e7d] | 35 | root = dirname(__file__) |
---|
| 36 | files = sorted(glob(joinpath(root, 'models', "[a-zA-Z]*.py"))) |
---|
| 37 | available_models = [basename(f)[:-3] for f in files] |
---|
| 38 | return available_models |
---|
| 39 | |
---|
[b8e5e21] | 40 | def isstr(s): |
---|
| 41 | """ |
---|
| 42 | Return True if *s* is a string-like object. |
---|
| 43 | """ |
---|
| 44 | try: s + '' |
---|
| 45 | except: return False |
---|
| 46 | return True |
---|
| 47 | |
---|
| 48 | def load_model(model_name, **kw): |
---|
| 49 | """ |
---|
| 50 | Load model info and build model. |
---|
| 51 | """ |
---|
[72a081d] | 52 | return build_model(load_model_info(model_name), **kw) |
---|
[7b3e62c] | 53 | |
---|
[72a081d] | 54 | def load_model_info_from_path(path): |
---|
| 55 | # Pull off the last .ext if it exists; there may be others |
---|
| 56 | name = basename(splitext(path)[0]) |
---|
[7b3e62c] | 57 | |
---|
[72a081d] | 58 | # Not cleaning name since don't need to be able to reload this |
---|
| 59 | # model later |
---|
| 60 | # Should probably turf the model from sys.modules after we are done... |
---|
| 61 | |
---|
| 62 | # Placing the model in the 'sasmodels.custom' name space, even |
---|
| 63 | # though it doesn't actually exist. imp.load_source doesn't seem |
---|
| 64 | # to care. |
---|
| 65 | kernel_module = imp.load_source('sasmodels.custom.'+name, path) |
---|
| 66 | |
---|
| 67 | # Now that we have the module, we can load it as usual |
---|
| 68 | model_info = generate.make_model_info(kernel_module) |
---|
| 69 | return model_info |
---|
[aa4946b] | 70 | |
---|
[17bbadd] | 71 | def load_model_info(model_name): |
---|
[aa4946b] | 72 | """ |
---|
| 73 | Load a model definition given the model name. |
---|
[1d4017a] | 74 | |
---|
| 75 | This returns a handle to the module defining the model. This can be |
---|
| 76 | used with functions in generate to build the docs or extract model info. |
---|
[aa4946b] | 77 | """ |
---|
[72a081d] | 78 | parts = model_name.split('+') |
---|
| 79 | if len(parts) > 1: |
---|
| 80 | model_info_list = [load_model_info(p) for p in parts] |
---|
| 81 | return mixture.make_mixture_info(model_info_list) |
---|
| 82 | |
---|
| 83 | parts = model_name.split('*') |
---|
| 84 | if len(parts) > 1: |
---|
| 85 | from . import product |
---|
| 86 | # Note: currently have circular reference |
---|
| 87 | if len(parts) > 2: |
---|
| 88 | raise ValueError("use P*S to apply structure factor S to model P") |
---|
| 89 | P_info, Q_info = [load_model_info(p) for p in parts] |
---|
| 90 | return product.make_product_info(P_info, Q_info) |
---|
| 91 | |
---|
[7b3e62c] | 92 | #import sys; print "\n".join(sys.path) |
---|
[f734e7d] | 93 | __import__('sasmodels.models.'+model_name) |
---|
[17bbadd] | 94 | kernel_module = getattr(models, model_name, None) |
---|
| 95 | return generate.make_model_info(kernel_module) |
---|
[f734e7d] | 96 | |
---|
[aa4946b] | 97 | |
---|
[17bbadd] | 98 | def build_model(model_info, dtype=None, platform="ocl"): |
---|
[aa4946b] | 99 | """ |
---|
| 100 | Prepare the model for the default execution platform. |
---|
| 101 | |
---|
| 102 | This will return an OpenCL model, a DLL model or a python model depending |
---|
| 103 | on the model and the computing platform. |
---|
| 104 | |
---|
[17bbadd] | 105 | *model_info* is the model definition structure returned from |
---|
| 106 | :func:`load_model_info`. |
---|
[bcd3aa3] | 107 | |
---|
[aa4946b] | 108 | *dtype* indicates whether the model should use single or double precision |
---|
| 109 | for the calculation. Any valid numpy single or double precision identifier |
---|
| 110 | is valid, such as 'single', 'f', 'f32', or np.float32 for single, or |
---|
[d18582e] | 111 | 'double', 'd', 'f64' and np.float64 for double. If *None*, then use |
---|
| 112 | 'single' unless the model defines single=False. |
---|
[aa4946b] | 113 | |
---|
| 114 | *platform* should be "dll" to force the dll to be used for C models, |
---|
| 115 | otherwise it uses the default "ocl". |
---|
| 116 | """ |
---|
[72a081d] | 117 | composition = model_info.get('composition', None) |
---|
| 118 | if composition is not None: |
---|
| 119 | composition_type, parts = composition |
---|
| 120 | models = [build_model(p, dtype=dtype, platform=platform) for p in parts] |
---|
| 121 | if composition_type == 'mixture': |
---|
| 122 | return mixture.MixtureModel(model_info, models) |
---|
| 123 | elif composition_type == 'product': |
---|
| 124 | from . import product |
---|
[e79f0a5] | 125 | P, S = models |
---|
[72a081d] | 126 | return product.ProductModel(model_info, P, S) |
---|
| 127 | else: |
---|
| 128 | raise ValueError('unknown mixture type %s'%composition_type) |
---|
[aa4946b] | 129 | |
---|
| 130 | ## for debugging: |
---|
| 131 | ## 1. uncomment open().write so that the source will be saved next time |
---|
| 132 | ## 2. run "python -m sasmodels.direct_model $MODELNAME" to save the source |
---|
| 133 | ## 3. recomment the open.write() and uncomment open().read() |
---|
| 134 | ## 4. rerun "python -m sasmodels.direct_model $MODELNAME" |
---|
| 135 | ## 5. uncomment open().read() so that source will be regenerated from model |
---|
[17bbadd] | 136 | # open(model_info['name']+'.c','w').write(source) |
---|
| 137 | # source = open(model_info['name']+'.cl','r').read() |
---|
[72a081d] | 138 | source = generate.make_source(model_info) |
---|
| 139 | if dtype is None: |
---|
| 140 | dtype = 'single' if model_info['single'] else 'double' |
---|
| 141 | if callable(model_info.get('Iq', None)): |
---|
| 142 | return kernelpy.PyModel(model_info) |
---|
[d15a908] | 143 | if (platform == "dll" |
---|
[aa4946b] | 144 | or not HAVE_OPENCL |
---|
[5d316e9] | 145 | or not kernelcl.environment().has_type(dtype)): |
---|
[17bbadd] | 146 | return kerneldll.load_dll(source, model_info, dtype) |
---|
[aa4946b] | 147 | else: |
---|
[17bbadd] | 148 | return kernelcl.GpuModel(source, model_info, dtype) |
---|
[aa4946b] | 149 | |
---|
[b8e5e21] | 150 | def precompile_dll(model_name, dtype="double"): |
---|
| 151 | """ |
---|
| 152 | Precompile the dll for a model. |
---|
| 153 | |
---|
| 154 | Returns the path to the compiled model, or None if the model is a pure |
---|
| 155 | python model. |
---|
| 156 | |
---|
| 157 | This can be used when build the windows distribution of sasmodels |
---|
| 158 | (which may be missing the OpenCL driver and the dll compiler), or |
---|
| 159 | otherwise sharing models with windows users who do not have a compiler. |
---|
| 160 | |
---|
| 161 | See :func:`sasmodels.kerneldll.make_dll` for details on controlling the |
---|
| 162 | dll path and the allowed floating point precision. |
---|
| 163 | """ |
---|
| 164 | model_info = load_model_info(model_name) |
---|
| 165 | source = generate.make_source(model_info) |
---|
| 166 | return kerneldll.make_dll(source, model_info, dtype=dtype) if source else None |
---|
| 167 | |
---|
| 168 | |
---|
[303d8d6] | 169 | def get_weights(parameter, values): |
---|
[f734e7d] | 170 | """ |
---|
| 171 | Generate the distribution for parameter *name* given the parameter values |
---|
| 172 | in *pars*. |
---|
| 173 | |
---|
[aa4946b] | 174 | Uses "name", "name_pd", "name_pd_type", "name_pd_n", "name_pd_sigma" |
---|
| 175 | from the *pars* dictionary for parameter value and parameter dispersion. |
---|
[f734e7d] | 176 | """ |
---|
[303d8d6] | 177 | value = values.get(parameter.name, parameter.default) |
---|
| 178 | if parameter.type not in ('volume', 'orientation'): |
---|
[0880966] | 179 | return np.array([value]), np.array([1.0]) |
---|
[303d8d6] | 180 | relative = parameter.type == 'volume' |
---|
| 181 | limits = parameter.limits |
---|
| 182 | disperser = values.get(parameter.name+'_pd_type', 'gaussian') |
---|
| 183 | npts = values.get(parameter.name+'_pd_n', 0) |
---|
| 184 | width = values.get(parameter.name+'_pd', 0.0) |
---|
| 185 | nsigma = values.get(parameter.name+'_pd_nsigma', 3.0) |
---|
[d15a908] | 186 | value, weight = weights.get_weights( |
---|
[7cf2cfd] | 187 | disperser, npts, width, nsigma, value, limits, relative) |
---|
| 188 | return value, weight / np.sum(weight) |
---|
[f734e7d] | 189 | |
---|
[9890053] | 190 | def dispersion_mesh(pars): |
---|
| 191 | """ |
---|
| 192 | Create a mesh grid of dispersion parameters and weights. |
---|
| 193 | |
---|
| 194 | Returns [p1,p2,...],w where pj is a vector of values for parameter j |
---|
| 195 | and w is a vector containing the products for weights for each |
---|
| 196 | parameter set in the vector. |
---|
| 197 | """ |
---|
[3c56da87] | 198 | value, weight = zip(*pars) |
---|
[d5ba841] | 199 | value = [v.flatten() for v in np.meshgrid(*value)] |
---|
| 200 | weight = np.vstack([v.flatten() for v in np.meshgrid(*weight)]) |
---|
| 201 | weight = np.prod(weight, axis=0) |
---|
[3c56da87] | 202 | return value, weight |
---|
[9890053] | 203 | |
---|
[0880966] | 204 | def call_kernel(kernel, pars, cutoff=0, mono=False): |
---|
[aa4946b] | 205 | """ |
---|
[48fbd50] | 206 | Call *kernel* returned from *model.make_kernel* with parameters *pars*. |
---|
[aa4946b] | 207 | |
---|
| 208 | *cutoff* is the limiting value for the product of dispersion weights used |
---|
| 209 | to perform the multidimensional dispersion calculation more quickly at a |
---|
| 210 | slight cost to accuracy. The default value of *cutoff=0* integrates over |
---|
| 211 | the entire dispersion cube. Using *cutoff=1e-5* can be 50% faster, but |
---|
| 212 | with an error of about 1%, which is usually less than the measurement |
---|
| 213 | uncertainty. |
---|
[cf52f9c] | 214 | |
---|
| 215 | *mono* is True if polydispersity should be set to none on all parameters. |
---|
[aa4946b] | 216 | """ |
---|
[0880966] | 217 | if mono: |
---|
[88aa3ee] | 218 | active = lambda name: False |
---|
[445d1c0] | 219 | elif kernel.dim == '1d': |
---|
[69aa451] | 220 | pars_1d = set(p.name for p in kernel.info['parameters'].type['1d']) |
---|
| 221 | active = lambda name: name in pars_1d |
---|
[445d1c0] | 222 | elif kernel.dim == '2d': |
---|
[69aa451] | 223 | pars_2d = set(p.name for p in kernel.info['parameters'].type['2d']) |
---|
[60eab2a] | 224 | active = lambda name: name in pars_2d |
---|
[0880966] | 225 | else: |
---|
[88aa3ee] | 226 | active = lambda name: True |
---|
[0880966] | 227 | |
---|
[88aa3ee] | 228 | vw_pairs = [(get_weights(p, pars) if active(p.name) else ([p.default], [1])) |
---|
[445d1c0] | 229 | for p in kernel.info['parameters']] |
---|
| 230 | values, weights = zip(*vw_pairs) |
---|
| 231 | |
---|
[1edf610] | 232 | if max([len(w) for w in weights]) > 1: |
---|
[0880966] | 233 | details = generate.poly_details(kernel.info, weights) |
---|
[02e70ff] | 234 | else: |
---|
[0880966] | 235 | details = kernel.info['mono_details'] |
---|
| 236 | |
---|
| 237 | weights, values = [np.hstack(v) for v in (weights, values)] |
---|
| 238 | |
---|
| 239 | weights = weights.astype(dtype=kernel.dtype) |
---|
| 240 | values = values.astype(dtype=kernel.dtype) |
---|
| 241 | return kernel(details, weights, values, cutoff) |
---|
[f734e7d] | 242 | |
---|
[17bbadd] | 243 | def call_ER_VR(model_info, vol_pars): |
---|
| 244 | """ |
---|
| 245 | Return effect radius and volume ratio for the model. |
---|
| 246 | |
---|
| 247 | *info* is either *kernel.info* for *kernel=make_kernel(model,q)* |
---|
| 248 | or *model.info*. |
---|
| 249 | |
---|
| 250 | *pars* are the parameters as expected by :func:`call_kernel`. |
---|
| 251 | """ |
---|
| 252 | ER = model_info.get('ER', None) |
---|
| 253 | VR = model_info.get('VR', None) |
---|
| 254 | value, weight = dispersion_mesh(vol_pars) |
---|
| 255 | |
---|
| 256 | individual_radii = ER(*value) if ER else 1.0 |
---|
| 257 | whole, part = VR(*value) if VR else (1.0, 1.0) |
---|
| 258 | |
---|
| 259 | effect_radius = np.sum(weight*individual_radii) / np.sum(weight) |
---|
| 260 | volume_ratio = np.sum(weight*part)/np.sum(weight*whole) |
---|
| 261 | return effect_radius, volume_ratio |
---|
| 262 | |
---|
| 263 | |
---|
[303d8d6] | 264 | def call_ER(model_info, values): |
---|
[aa4946b] | 265 | """ |
---|
[303d8d6] | 266 | Call the model ER function using *values*. *model_info* is either |
---|
| 267 | *model.info* if you have a loaded model, or *kernel.info* if you |
---|
| 268 | have a model kernel prepared for evaluation. |
---|
[aa4946b] | 269 | """ |
---|
[303d8d6] | 270 | ER = model_info.get('ER', None) |
---|
[9890053] | 271 | if ER is None: |
---|
| 272 | return 1.0 |
---|
| 273 | else: |
---|
[303d8d6] | 274 | vol_pars = [get_weights(parameter, values) |
---|
| 275 | for parameter in model_info['parameters'] |
---|
| 276 | if parameter.type == 'volume'] |
---|
[3c56da87] | 277 | value, weight = dispersion_mesh(vol_pars) |
---|
| 278 | individual_radii = ER(*value) |
---|
[9404dd3] | 279 | #print(values[0].shape, weights.shape, fv.shape) |
---|
[3c56da87] | 280 | return np.sum(weight*individual_radii) / np.sum(weight) |
---|
[9890053] | 281 | |
---|
[303d8d6] | 282 | def call_VR(model_info, values): |
---|
[aa4946b] | 283 | """ |
---|
| 284 | Call the model VR function using *pars*. |
---|
| 285 | *info* is either *model.info* if you have a loaded model, or *kernel.info* |
---|
| 286 | if you have a model kernel prepared for evaluation. |
---|
| 287 | """ |
---|
[303d8d6] | 288 | VR = model_info.get('VR', None) |
---|
[9890053] | 289 | if VR is None: |
---|
| 290 | return 1.0 |
---|
| 291 | else: |
---|
[303d8d6] | 292 | vol_pars = [get_weights(parameter, values) |
---|
| 293 | for parameter in model_info['parameters'] |
---|
| 294 | if parameter.type == 'volume'] |
---|
[3c56da87] | 295 | value, weight = dispersion_mesh(vol_pars) |
---|
[d15a908] | 296 | whole, part = VR(*value) |
---|
[3c56da87] | 297 | return np.sum(weight*part)/np.sum(weight*whole) |
---|
[9890053] | 298 | |
---|
[17bbadd] | 299 | # TODO: remove call_ER, call_VR |
---|
| 300 | |
---|