[aa4946b] | 1 | """ |
---|
| 2 | Core model handling routines. |
---|
| 3 | """ |
---|
[6d6508e] | 4 | from __future__ import print_function |
---|
| 5 | |
---|
[98f60fc] | 6 | __all__ = [ |
---|
[6d6508e] | 7 | "list_models", "load_model", "load_model_info", |
---|
[2547694] | 8 | "build_model", "precompile_dlls", |
---|
[98f60fc] | 9 | ] |
---|
[f734e7d] | 10 | |
---|
[7bf4757] | 11 | import os |
---|
[2547694] | 12 | from os.path import basename, dirname, join as joinpath |
---|
[f734e7d] | 13 | from glob import glob |
---|
| 14 | |
---|
[7ae2b7f] | 15 | import numpy as np # type: ignore |
---|
[f734e7d] | 16 | |
---|
[aa4946b] | 17 | from . import generate |
---|
[6d6508e] | 18 | from . import modelinfo |
---|
| 19 | from . import product |
---|
[72a081d] | 20 | from . import mixture |
---|
[aa4946b] | 21 | from . import kernelpy |
---|
| 22 | from . import kerneldll |
---|
[f734e7d] | 23 | try: |
---|
[aa4946b] | 24 | from . import kernelcl |
---|
| 25 | HAVE_OPENCL = True |
---|
[ee8f734] | 26 | except Exception: |
---|
[aa4946b] | 27 | HAVE_OPENCL = False |
---|
| 28 | |
---|
[f619de7] | 29 | try: |
---|
| 30 | from typing import List, Union, Optional, Any |
---|
| 31 | from .kernel import KernelModel |
---|
[dd7fc12] | 32 | from .modelinfo import ModelInfo |
---|
[f619de7] | 33 | except ImportError: |
---|
| 34 | pass |
---|
| 35 | |
---|
[4d76711] | 36 | # TODO: refactor composite model support |
---|
| 37 | # The current load_model_info/build_model does not reuse existing model |
---|
| 38 | # definitions when loading a composite model, instead reloading and |
---|
| 39 | # rebuilding the kernel for each component model in the expression. This |
---|
| 40 | # is fine in a scripting environment where the model is built when the script |
---|
| 41 | # starts and is thrown away when the script ends, but may not be the best |
---|
| 42 | # solution in a long-lived application. This affects the following functions: |
---|
| 43 | # |
---|
| 44 | # load_model |
---|
| 45 | # load_model_info |
---|
| 46 | # build_model |
---|
[f734e7d] | 47 | |
---|
[2547694] | 48 | KINDS = ("all", "py", "c", "double", "single", "1d", "2d", |
---|
| 49 | "nonmagnetic", "magnetic") |
---|
[0b03001] | 50 | def list_models(kind=None): |
---|
[f619de7] | 51 | # type: () -> List[str] |
---|
[aa4946b] | 52 | """ |
---|
| 53 | Return the list of available models on the model path. |
---|
[40a87fa] | 54 | |
---|
| 55 | *kind* can be one of the following: |
---|
| 56 | |
---|
| 57 | * all: all models |
---|
| 58 | * py: python models only |
---|
| 59 | * c: compiled models only |
---|
| 60 | * single: models which support single precision |
---|
| 61 | * double: models which require double precision |
---|
| 62 | * 1d: models which are 1D only, or 2D using abs(q) |
---|
| 63 | * 2d: models which can be 2D |
---|
| 64 | * magnetic: models with an sld |
---|
| 65 | * nommagnetic: models without an sld |
---|
[aa4946b] | 66 | """ |
---|
[0b03001] | 67 | if kind and kind not in KINDS: |
---|
[2547694] | 68 | raise ValueError("kind not in " + ", ".join(KINDS)) |
---|
[3d9001f] | 69 | files = sorted(glob(joinpath(generate.MODEL_PATH, "[a-zA-Z]*.py"))) |
---|
[f734e7d] | 70 | available_models = [basename(f)[:-3] for f in files] |
---|
[0b03001] | 71 | selected = [name for name in available_models if _matches(name, kind)] |
---|
| 72 | |
---|
| 73 | return selected |
---|
| 74 | |
---|
| 75 | def _matches(name, kind): |
---|
[2547694] | 76 | if kind is None or kind == "all": |
---|
[0b03001] | 77 | return True |
---|
| 78 | info = load_model_info(name) |
---|
| 79 | pars = info.parameters.kernel_parameters |
---|
| 80 | if kind == "py" and callable(info.Iq): |
---|
| 81 | return True |
---|
| 82 | elif kind == "c" and not callable(info.Iq): |
---|
| 83 | return True |
---|
| 84 | elif kind == "double" and not info.single: |
---|
| 85 | return True |
---|
[d2d6100] | 86 | elif kind == "single" and info.single: |
---|
| 87 | return True |
---|
[2547694] | 88 | elif kind == "2d" and any(p.type == 'orientation' for p in pars): |
---|
[d2d6100] | 89 | return True |
---|
[40a87fa] | 90 | elif kind == "1d" and all(p.type != 'orientation' for p in pars): |
---|
[0b03001] | 91 | return True |
---|
[2547694] | 92 | elif kind == "magnetic" and any(p.type == 'sld' for p in pars): |
---|
[0b03001] | 93 | return True |
---|
[2547694] | 94 | elif kind == "nonmagnetic" and any(p.type != 'sld' for p in pars): |
---|
[d2d6100] | 95 | return True |
---|
[0b03001] | 96 | return False |
---|
[f734e7d] | 97 | |
---|
[f619de7] | 98 | def load_model(model_name, dtype=None, platform='ocl'): |
---|
[dd7fc12] | 99 | # type: (str, str, str) -> KernelModel |
---|
[b8e5e21] | 100 | """ |
---|
| 101 | Load model info and build model. |
---|
[f619de7] | 102 | |
---|
| 103 | *model_name* is the name of the model as used by :func:`load_model_info`. |
---|
| 104 | Additional keyword arguments are passed directly to :func:`build_model`. |
---|
[b8e5e21] | 105 | """ |
---|
[f619de7] | 106 | return build_model(load_model_info(model_name), |
---|
| 107 | dtype=dtype, platform=platform) |
---|
[aa4946b] | 108 | |
---|
| 109 | |
---|
[17bbadd] | 110 | def load_model_info(model_name): |
---|
[f619de7] | 111 | # type: (str) -> modelinfo.ModelInfo |
---|
[aa4946b] | 112 | """ |
---|
| 113 | Load a model definition given the model name. |
---|
[1d4017a] | 114 | |
---|
| 115 | This returns a handle to the module defining the model. This can be |
---|
| 116 | used with functions in generate to build the docs or extract model info. |
---|
[aa4946b] | 117 | """ |
---|
[72a081d] | 118 | parts = model_name.split('+') |
---|
| 119 | if len(parts) > 1: |
---|
| 120 | model_info_list = [load_model_info(p) for p in parts] |
---|
| 121 | return mixture.make_mixture_info(model_info_list) |
---|
| 122 | |
---|
| 123 | parts = model_name.split('*') |
---|
| 124 | if len(parts) > 1: |
---|
| 125 | if len(parts) > 2: |
---|
| 126 | raise ValueError("use P*S to apply structure factor S to model P") |
---|
| 127 | P_info, Q_info = [load_model_info(p) for p in parts] |
---|
| 128 | return product.make_product_info(P_info, Q_info) |
---|
| 129 | |
---|
[68e7f9d] | 130 | kernel_module = generate.load_kernel_module(model_name) |
---|
[6d6508e] | 131 | return modelinfo.make_model_info(kernel_module) |
---|
[d19962c] | 132 | |
---|
| 133 | |
---|
[17bbadd] | 134 | def build_model(model_info, dtype=None, platform="ocl"): |
---|
[dd7fc12] | 135 | # type: (modelinfo.ModelInfo, str, str) -> KernelModel |
---|
[aa4946b] | 136 | """ |
---|
| 137 | Prepare the model for the default execution platform. |
---|
| 138 | |
---|
| 139 | This will return an OpenCL model, a DLL model or a python model depending |
---|
| 140 | on the model and the computing platform. |
---|
| 141 | |
---|
[17bbadd] | 142 | *model_info* is the model definition structure returned from |
---|
| 143 | :func:`load_model_info`. |
---|
[bcd3aa3] | 144 | |
---|
[aa4946b] | 145 | *dtype* indicates whether the model should use single or double precision |
---|
[dd7fc12] | 146 | for the calculation. Choices are 'single', 'double', 'quad', 'half', |
---|
| 147 | or 'fast'. If *dtype* ends with '!', then force the use of the DLL rather |
---|
| 148 | than OpenCL for the calculation. |
---|
[aa4946b] | 149 | |
---|
| 150 | *platform* should be "dll" to force the dll to be used for C models, |
---|
| 151 | otherwise it uses the default "ocl". |
---|
| 152 | """ |
---|
[6d6508e] | 153 | composition = model_info.composition |
---|
[72a081d] | 154 | if composition is not None: |
---|
| 155 | composition_type, parts = composition |
---|
| 156 | models = [build_model(p, dtype=dtype, platform=platform) for p in parts] |
---|
| 157 | if composition_type == 'mixture': |
---|
| 158 | return mixture.MixtureModel(model_info, models) |
---|
| 159 | elif composition_type == 'product': |
---|
[e79f0a5] | 160 | P, S = models |
---|
[72a081d] | 161 | return product.ProductModel(model_info, P, S) |
---|
| 162 | else: |
---|
| 163 | raise ValueError('unknown mixture type %s'%composition_type) |
---|
[aa4946b] | 164 | |
---|
[fa5fd8d] | 165 | # If it is a python model, return it immediately |
---|
| 166 | if callable(model_info.Iq): |
---|
| 167 | return kernelpy.PyModel(model_info) |
---|
| 168 | |
---|
[def2c1b] | 169 | numpy_dtype, fast, platform = parse_dtype(model_info, dtype, platform) |
---|
[7891a2a] | 170 | |
---|
[72a081d] | 171 | source = generate.make_source(model_info) |
---|
[7891a2a] | 172 | if platform == "dll": |
---|
[f2f67a6] | 173 | #print("building dll", numpy_dtype) |
---|
[a4280bd] | 174 | return kerneldll.load_dll(source['dll'], model_info, numpy_dtype) |
---|
[aa4946b] | 175 | else: |
---|
[f2f67a6] | 176 | #print("building ocl", numpy_dtype) |
---|
[dd7fc12] | 177 | return kernelcl.GpuModel(source, model_info, numpy_dtype, fast=fast) |
---|
[aa4946b] | 178 | |
---|
[7bf4757] | 179 | def precompile_dlls(path, dtype="double"): |
---|
[7891a2a] | 180 | # type: (str, str) -> List[str] |
---|
[b8e5e21] | 181 | """ |
---|
[7bf4757] | 182 | Precompile the dlls for all builtin models, returning a list of dll paths. |
---|
[b8e5e21] | 183 | |
---|
[7bf4757] | 184 | *path* is the directory in which to save the dlls. It will be created if |
---|
| 185 | it does not already exist. |
---|
[b8e5e21] | 186 | |
---|
| 187 | This can be used when build the windows distribution of sasmodels |
---|
[7bf4757] | 188 | which may be missing the OpenCL driver and the dll compiler. |
---|
[b8e5e21] | 189 | """ |
---|
[7891a2a] | 190 | numpy_dtype = np.dtype(dtype) |
---|
[7bf4757] | 191 | if not os.path.exists(path): |
---|
| 192 | os.makedirs(path) |
---|
| 193 | compiled_dlls = [] |
---|
| 194 | for model_name in list_models(): |
---|
| 195 | model_info = load_model_info(model_name) |
---|
[a4280bd] | 196 | if not callable(model_info.Iq): |
---|
| 197 | source = generate.make_source(model_info)['dll'] |
---|
[7bf4757] | 198 | old_path = kerneldll.DLL_PATH |
---|
| 199 | try: |
---|
| 200 | kerneldll.DLL_PATH = path |
---|
[def2c1b] | 201 | dll = kerneldll.make_dll(source, model_info, dtype=numpy_dtype) |
---|
[7bf4757] | 202 | finally: |
---|
| 203 | kerneldll.DLL_PATH = old_path |
---|
| 204 | compiled_dlls.append(dll) |
---|
| 205 | return compiled_dlls |
---|
[b8e5e21] | 206 | |
---|
[7891a2a] | 207 | def parse_dtype(model_info, dtype=None, platform=None): |
---|
| 208 | # type: (ModelInfo, str, str) -> (np.dtype, bool, str) |
---|
[dd7fc12] | 209 | """ |
---|
| 210 | Interpret dtype string, returning np.dtype and fast flag. |
---|
| 211 | |
---|
| 212 | Possible types include 'half', 'single', 'double' and 'quad'. If the |
---|
| 213 | type is 'fast', then this is equivalent to dtype 'single' with the |
---|
| 214 | fast flag set to True. |
---|
| 215 | """ |
---|
[7891a2a] | 216 | # Assign default platform, overriding ocl with dll if OpenCL is unavailable |
---|
| 217 | if platform is None: |
---|
| 218 | platform = "ocl" |
---|
[2547694] | 219 | if platform == "ocl" and not HAVE_OPENCL: |
---|
[7891a2a] | 220 | platform = "dll" |
---|
| 221 | |
---|
| 222 | # Check if type indicates dll regardless of which platform is given |
---|
| 223 | if dtype is not None and dtype.endswith('!'): |
---|
| 224 | platform = "dll" |
---|
[dd7fc12] | 225 | dtype = dtype[:-1] |
---|
| 226 | |
---|
[7891a2a] | 227 | # Convert special type names "half", "fast", and "quad" |
---|
[2547694] | 228 | fast = (dtype == "fast") |
---|
[7891a2a] | 229 | if fast: |
---|
| 230 | dtype = "single" |
---|
[2547694] | 231 | elif dtype == "quad": |
---|
[7891a2a] | 232 | dtype = "longdouble" |
---|
[2547694] | 233 | elif dtype == "half": |
---|
[7891a2a] | 234 | dtype = "f16" |
---|
| 235 | |
---|
| 236 | # Convert dtype string to numpy dtype. |
---|
| 237 | if dtype is None: |
---|
[2547694] | 238 | numpy_dtype = (generate.F32 if platform == "ocl" and model_info.single |
---|
| 239 | else generate.F64) |
---|
[dd7fc12] | 240 | else: |
---|
[7891a2a] | 241 | numpy_dtype = np.dtype(dtype) |
---|
[9890053] | 242 | |
---|
[7891a2a] | 243 | # Make sure that the type is supported by opencl, otherwise use dll |
---|
[2547694] | 244 | if platform == "ocl": |
---|
[7891a2a] | 245 | env = kernelcl.environment() |
---|
| 246 | if not env.has_type(numpy_dtype): |
---|
| 247 | platform = "dll" |
---|
| 248 | if dtype is None: |
---|
| 249 | numpy_dtype = generate.F64 |
---|
[dd7fc12] | 250 | |
---|
[7891a2a] | 251 | return numpy_dtype, fast, platform |
---|
[0c24a82] | 252 | |
---|
[2547694] | 253 | def list_models_main(): |
---|
[40a87fa] | 254 | # type: () -> None |
---|
| 255 | """ |
---|
| 256 | Run list_models as a main program. See :func:`list_models` for the |
---|
| 257 | kinds of models that can be requested on the command line. |
---|
| 258 | """ |
---|
[0b03001] | 259 | import sys |
---|
| 260 | kind = sys.argv[1] if len(sys.argv) > 1 else "all" |
---|
| 261 | print("\n".join(list_models(kind))) |
---|
[2547694] | 262 | |
---|
| 263 | if __name__ == "__main__": |
---|
| 264 | list_models_main() |
---|