[92da231] | 1 | r""" |
---|
[eafc9fa] | 2 | DLL driver for C kernels |
---|
[750ffa5] | 3 | |
---|
[3764ec1] | 4 | If the environment variable *SAS_OPENMP* is set, then sasmodels |
---|
| 5 | will attempt to compile with OpenMP flags so that the model can use all |
---|
| 6 | available kernels. This may or may not be available on your compiler |
---|
| 7 | toolchain. Depending on operating system and environment. |
---|
[92da231] | 8 | |
---|
[3764ec1] | 9 | Windows does not have provide a compiler with the operating system. |
---|
| 10 | Instead, we assume that TinyCC is installed and available. This can |
---|
| 11 | be done with a simple pip command if it is not already available:: |
---|
[92da231] | 12 | |
---|
[3764ec1] | 13 | pip install tinycc |
---|
[92da231] | 14 | |
---|
[3764ec1] | 15 | If Microsoft Visual C++ is available (because VCINSTALLDIR is |
---|
| 16 | defined in the environment), then that will be used instead. |
---|
| 17 | Microsoft Visual C++ for Python is available from Microsoft: |
---|
[92da231] | 18 | |
---|
[d138d43] | 19 | `<http://www.microsoft.com/en-us/download/details.aspx?id=44266>`_ |
---|
[92da231] | 20 | |
---|
[3764ec1] | 21 | If neither compiler is available, sasmodels will check for *MinGW*, |
---|
| 22 | the GNU compiler toolchain. This available in packages such as Anaconda |
---|
| 23 | and PythonXY, or available stand alone. This toolchain has had |
---|
| 24 | difficulties on some systems, and may or may not work for you. |
---|
| 25 | |
---|
| 26 | You can control which compiler to use by setting SAS_COMPILER in the |
---|
| 27 | environment: |
---|
| 28 | |
---|
| 29 | - tinycc (Windows): use the TinyCC compiler shipped with SasView |
---|
| 30 | - msvc (Windows): use the Microsoft Visual C++ compiler |
---|
| 31 | - mingw (Windows): use the MinGW GNU cc compiler |
---|
| 32 | - unix (Linux): use the system cc compiler. |
---|
| 33 | - unix (Mac): use the clang compiler. You will need XCode installed, and |
---|
| 34 | the XCode command line tools. Mac comes with OpenCL drivers, so generally |
---|
| 35 | this will not be needed. |
---|
| 36 | |
---|
| 37 | Both *msvc* and *mingw* require that the compiler is available on your path. |
---|
| 38 | For *msvc*, this can done by running vcvarsall.bat in a windows terminal. |
---|
| 39 | Install locations are system dependent, such as: |
---|
[92da231] | 40 | |
---|
[2d81cfe] | 41 | C:\Program Files (x86)\Common Files\Microsoft\Visual |
---|
| 42 | C++ for Python\9.0\vcvarsall.bat |
---|
[92da231] | 43 | |
---|
| 44 | or maybe |
---|
| 45 | |
---|
[2d81cfe] | 46 | C:\Users\yourname\AppData\Local\Programs\Common\Microsoft\Visual |
---|
| 47 | C++ for Python\9.0\vcvarsall.bat |
---|
[92da231] | 48 | |
---|
[3764ec1] | 49 | OpenMP for *msvc* requires the Microsoft vcomp90.dll library, which doesn't |
---|
| 50 | seem to be included with the compiler, nor does there appear to be a public |
---|
| 51 | download location. There may be one on your machine already in a location |
---|
| 52 | such as: |
---|
[92da231] | 53 | |
---|
| 54 | C:\Windows\winsxs\x86_microsoft.vc90.openmp*\vcomp90.dll |
---|
| 55 | |
---|
[3764ec1] | 56 | If you copy this to somewhere on your path, such as the python directory or |
---|
| 57 | the install directory for this application, then OpenMP should be supported. |
---|
| 58 | |
---|
| 59 | For full control of the compiler, define a function |
---|
| 60 | *compile_command(source,output)* which takes the name of the source file |
---|
| 61 | and the name of the output file and returns a compile command that can be |
---|
| 62 | evaluated in the shell. For even more control, replace the entire |
---|
| 63 | *compile(source,output)* function. |
---|
| 64 | |
---|
| 65 | The global attribute *ALLOW_SINGLE_PRECISION_DLLS* should be set to *False* if |
---|
| 66 | you wish to prevent single precision floating point evaluation for the compiled |
---|
| 67 | models, otherwise set it defaults to *True*. |
---|
[14de349] | 68 | """ |
---|
[eafc9fa] | 69 | from __future__ import print_function |
---|
[750ffa5] | 70 | |
---|
[5d4777d] | 71 | import sys |
---|
| 72 | import os |
---|
[40a87fa] | 73 | from os.path import join as joinpath, splitext |
---|
[7e16db7] | 74 | import subprocess |
---|
[df4dc86] | 75 | import tempfile |
---|
[7ae2b7f] | 76 | import ctypes as ct # type: ignore |
---|
[886fa25] | 77 | import _ctypes as _ct |
---|
[821a9c6] | 78 | import logging |
---|
[14de349] | 79 | |
---|
[7ae2b7f] | 80 | import numpy as np # type: ignore |
---|
[14de349] | 81 | |
---|
[739aad4] | 82 | try: |
---|
| 83 | import tinycc |
---|
| 84 | except ImportError: |
---|
| 85 | tinycc = None |
---|
| 86 | |
---|
[cb6ecf4] | 87 | from . import generate |
---|
[f619de7] | 88 | from .kernel import KernelModel, Kernel |
---|
| 89 | from .kernelpy import PyInput |
---|
[2c801fe] | 90 | from .exception import annotate_exception |
---|
[f619de7] | 91 | from .generate import F16, F32, F64 |
---|
| 92 | |
---|
[2d81cfe] | 93 | # pylint: disable=unused-import |
---|
[f619de7] | 94 | try: |
---|
| 95 | from typing import Tuple, Callable, Any |
---|
| 96 | from .modelinfo import ModelInfo |
---|
| 97 | from .details import CallDetails |
---|
| 98 | except ImportError: |
---|
| 99 | pass |
---|
[2d81cfe] | 100 | # pylint: enable=unused-import |
---|
[14de349] | 101 | |
---|
[739aad4] | 102 | if "SAS_COMPILER" in os.environ: |
---|
[b2f1d2f] | 103 | COMPILER = os.environ["SAS_COMPILER"] |
---|
[739aad4] | 104 | elif os.name == 'nt': |
---|
[b2f1d2f] | 105 | if tinycc is not None: |
---|
| 106 | COMPILER = "tinycc" |
---|
| 107 | elif "VCINSTALLDIR" in os.environ: |
---|
| 108 | # If vcvarsall.bat has been called, then VCINSTALLDIR is in the environment |
---|
| 109 | # and we can use the MSVC compiler. Otherwise, if tinycc is available |
---|
| 110 | # the use it. Otherwise, hope that mingw is available. |
---|
| 111 | COMPILER = "msvc" |
---|
[fb69211] | 112 | else: |
---|
[b2f1d2f] | 113 | COMPILER = "mingw" |
---|
[5d4777d] | 114 | else: |
---|
[b2f1d2f] | 115 | COMPILER = "unix" |
---|
[739aad4] | 116 | |
---|
[886fa25] | 117 | ARCH = "" if ct.sizeof(ct.c_void_p) > 4 else "x86" # 4 byte pointers on x86 |
---|
[b2f1d2f] | 118 | if COMPILER == "unix": |
---|
[5efe850] | 119 | # Generic unix compile |
---|
| 120 | # On mac users will need the X code command line tools installed |
---|
[7e16db7] | 121 | #COMPILE = "gcc-mp-4.7 -shared -fPIC -std=c99 -fopenmp -O2 -Wall %s -o %s -lm -lgomp" |
---|
[aa343d6] | 122 | CC = "cc -shared -fPIC -std=c99 -O2 -Wall".split() |
---|
[5efe850] | 123 | # add openmp support if not running on a mac |
---|
[7e16db7] | 124 | if sys.platform != "darwin": |
---|
[33969b6] | 125 | # OpenMP seems to be broken on gcc 5.4.0 (ubuntu 16.04.9) |
---|
| 126 | # Shut it off for all unix until we can investigate. |
---|
| 127 | #CC.append("-fopenmp") |
---|
| 128 | pass |
---|
[7e16db7] | 129 | def compile_command(source, output): |
---|
[40a87fa] | 130 | """unix compiler command""" |
---|
[15e74ad] | 131 | return CC + [source, "-o", output, "-lm"] |
---|
[b2f1d2f] | 132 | elif COMPILER == "msvc": |
---|
[739aad4] | 133 | # Call vcvarsall.bat before compiling to set path, headers, libs, etc. |
---|
| 134 | # MSVC compiler is available, so use it. OpenMP requires a copy of |
---|
| 135 | # vcomp90.dll on the path. One may be found here: |
---|
| 136 | # C:/Windows/winsxs/x86_microsoft.vc90.openmp*/vcomp90.dll |
---|
| 137 | # Copy this to the python directory and uncomment the OpenMP COMPILE |
---|
| 138 | # TODO: remove intermediate OBJ file created in the directory |
---|
| 139 | # TODO: maybe don't use randomized name for the c file |
---|
| 140 | # TODO: maybe ask distutils to find MSVC |
---|
| 141 | CC = "cl /nologo /Ox /MD /W3 /GS- /DNDEBUG".split() |
---|
| 142 | if "SAS_OPENMP" in os.environ: |
---|
| 143 | CC.append("/openmp") |
---|
| 144 | LN = "/link /DLL /INCREMENTAL:NO /MANIFEST".split() |
---|
| 145 | def compile_command(source, output): |
---|
[40a87fa] | 146 | """MSVC compiler command""" |
---|
[739aad4] | 147 | return CC + ["/Tp%s"%source] + LN + ["/OUT:%s"%output] |
---|
[b2f1d2f] | 148 | elif COMPILER == "tinycc": |
---|
[739aad4] | 149 | # TinyCC compiler. |
---|
| 150 | CC = [tinycc.TCC] + "-shared -rdynamic -Wall".split() |
---|
| 151 | def compile_command(source, output): |
---|
[40a87fa] | 152 | """tinycc compiler command""" |
---|
[739aad4] | 153 | return CC + [source, "-o", output] |
---|
[b2f1d2f] | 154 | elif COMPILER == "mingw": |
---|
[739aad4] | 155 | # MinGW compiler. |
---|
| 156 | CC = "gcc -shared -std=c99 -O2 -Wall".split() |
---|
| 157 | if "SAS_OPENMP" in os.environ: |
---|
| 158 | CC.append("-fopenmp") |
---|
| 159 | def compile_command(source, output): |
---|
[40a87fa] | 160 | """mingw compiler command""" |
---|
[739aad4] | 161 | return CC + [source, "-o", output, "-lm"] |
---|
[df4dc86] | 162 | |
---|
[bf94e6e] | 163 | # Assume the default location of module DLLs is in .sasmodels/compiled_models. |
---|
| 164 | DLL_PATH = os.path.join(os.path.expanduser("~"), ".sasmodels", "compiled_models") |
---|
[5d4777d] | 165 | |
---|
[5d316e9] | 166 | ALLOW_SINGLE_PRECISION_DLLS = True |
---|
[5d4777d] | 167 | |
---|
[7e16db7] | 168 | def compile(source, output): |
---|
[40a87fa] | 169 | # type: (str, str) -> None |
---|
| 170 | """ |
---|
| 171 | Compile *source* producing *output*. |
---|
| 172 | |
---|
| 173 | Raises RuntimeError if the compile failed or the output wasn't produced. |
---|
| 174 | """ |
---|
[7e16db7] | 175 | command = compile_command(source=source, output=output) |
---|
| 176 | command_str = " ".join('"%s"'%p if ' ' in p else p for p in command) |
---|
| 177 | logging.info(command_str) |
---|
| 178 | try: |
---|
[15e74ad] | 179 | # need shell=True on windows to keep console box from popping up |
---|
| 180 | shell = (os.name == 'nt') |
---|
[aa343d6] | 181 | subprocess.check_output(command, shell=shell, stderr=subprocess.STDOUT) |
---|
[7e16db7] | 182 | except subprocess.CalledProcessError as exc: |
---|
| 183 | raise RuntimeError("compile failed.\n%s\n%s"%(command_str, exc.output)) |
---|
| 184 | if not os.path.exists(output): |
---|
| 185 | raise RuntimeError("compile failed. File is in %r"%source) |
---|
[750ffa5] | 186 | |
---|
[151f3bc] | 187 | def dll_name(model_info, dtype): |
---|
[f619de7] | 188 | # type: (ModelInfo, np.dtype) -> str |
---|
[5d4777d] | 189 | """ |
---|
[151f3bc] | 190 | Name of the dll containing the model. This is the base file name without |
---|
| 191 | any path or extension, with a form such as 'sas_sphere32'. |
---|
[5d4777d] | 192 | """ |
---|
[151f3bc] | 193 | bits = 8*dtype.itemsize |
---|
[56b2687] | 194 | basename = "sas%d_%s"%(bits, model_info.id) |
---|
[c7118f4] | 195 | basename += ARCH + ".so" |
---|
[01b8659] | 196 | |
---|
| 197 | # Hack to find precompiled dlls |
---|
[c7118f4] | 198 | path = joinpath(generate.DATA_PATH, '..', 'compiled_models', basename) |
---|
[01b8659] | 199 | if os.path.exists(path): |
---|
| 200 | return path |
---|
| 201 | |
---|
[c7118f4] | 202 | return joinpath(DLL_PATH, basename) |
---|
[5d4777d] | 203 | |
---|
[f619de7] | 204 | |
---|
[151f3bc] | 205 | def dll_path(model_info, dtype): |
---|
[f619de7] | 206 | # type: (ModelInfo, np.dtype) -> str |
---|
[151f3bc] | 207 | """ |
---|
| 208 | Complete path to the dll for the model. Note that the dll may not |
---|
| 209 | exist yet if it hasn't been compiled. |
---|
| 210 | """ |
---|
[a738209] | 211 | return os.path.join(DLL_PATH, dll_name(model_info, dtype)) |
---|
[5d4777d] | 212 | |
---|
[f619de7] | 213 | |
---|
| 214 | def make_dll(source, model_info, dtype=F64): |
---|
| 215 | # type: (str, ModelInfo, np.dtype) -> str |
---|
[5d4777d] | 216 | """ |
---|
[f619de7] | 217 | Returns the path to the compiled model defined by *kernel_module*. |
---|
[5d4777d] | 218 | |
---|
[f619de7] | 219 | If the model has not been compiled, or if the source file(s) are newer |
---|
| 220 | than the dll, then *make_dll* will compile the model before returning. |
---|
| 221 | This routine does not load the resulting dll. |
---|
[5d4777d] | 222 | |
---|
[aa4946b] | 223 | *dtype* is a numpy floating point precision specifier indicating whether |
---|
[f619de7] | 224 | the model should be single, double or long double precision. The default |
---|
| 225 | is double precision, *np.dtype('d')*. |
---|
[5d4777d] | 226 | |
---|
[f619de7] | 227 | Set *sasmodels.ALLOW_SINGLE_PRECISION_DLLS* to False if single precision |
---|
| 228 | models are not allowed as DLLs. |
---|
[aa4946b] | 229 | |
---|
| 230 | Set *sasmodels.kerneldll.DLL_PATH* to the compiled dll output path. |
---|
[bf94e6e] | 231 | The default is in ~/.sasmodels/compiled_models. |
---|
[5d4777d] | 232 | """ |
---|
[f619de7] | 233 | if dtype == F16: |
---|
[5d316e9] | 234 | raise ValueError("16 bit floats not supported") |
---|
[f619de7] | 235 | if dtype == F32 and not ALLOW_SINGLE_PRECISION_DLLS: |
---|
| 236 | dtype = F64 # Force 64-bit dll |
---|
| 237 | # Note: dtype may be F128 for long double precision |
---|
[750ffa5] | 238 | |
---|
[17bbadd] | 239 | dll = dll_path(model_info, dtype) |
---|
[e1454ab] | 240 | |
---|
| 241 | if not os.path.exists(dll): |
---|
[5a91c6b] | 242 | need_recompile = True |
---|
| 243 | else: |
---|
| 244 | dll_time = os.path.getmtime(dll) |
---|
[0dc34c3] | 245 | newest_source = generate.dll_timestamp(model_info) |
---|
[5a91c6b] | 246 | need_recompile = dll_time < newest_source |
---|
| 247 | if need_recompile: |
---|
[bf94e6e] | 248 | # Make sure the DLL path exists |
---|
| 249 | if not os.path.exists(DLL_PATH): |
---|
| 250 | os.makedirs(DLL_PATH) |
---|
[40a87fa] | 251 | basename = splitext(os.path.basename(dll))[0] + "_" |
---|
| 252 | system_fd, filename = tempfile.mkstemp(suffix=".c", prefix=basename) |
---|
[f619de7] | 253 | source = generate.convert_type(source, dtype) |
---|
[40a87fa] | 254 | with os.fdopen(system_fd, "w") as file_handle: |
---|
| 255 | file_handle.write(source) |
---|
[7e16db7] | 256 | compile(source=filename, output=dll) |
---|
| 257 | # comment the following to keep the generated c file |
---|
| 258 | # Note: if there is a syntax error then compile raises an error |
---|
| 259 | # and the source file will not be deleted. |
---|
[c036ddb] | 260 | os.unlink(filename) |
---|
| 261 | #print("saving compiled file in %r"%filename) |
---|
[aa4946b] | 262 | return dll |
---|
| 263 | |
---|
| 264 | |
---|
[f619de7] | 265 | def load_dll(source, model_info, dtype=F64): |
---|
| 266 | # type: (str, ModelInfo, np.dtype) -> "DllModel" |
---|
[aa4946b] | 267 | """ |
---|
[823e620] | 268 | Create and load a dll corresponding to the source, info pair returned |
---|
[aa4946b] | 269 | from :func:`sasmodels.generate.make` compiled for the target precision. |
---|
| 270 | |
---|
| 271 | See :func:`make_dll` for details on controlling the dll path and the |
---|
| 272 | allowed floating point precision. |
---|
| 273 | """ |
---|
[17bbadd] | 274 | filename = make_dll(source, model_info, dtype=dtype) |
---|
| 275 | return DllModel(filename, model_info, dtype=dtype) |
---|
[5d4777d] | 276 | |
---|
[f619de7] | 277 | |
---|
| 278 | class DllModel(KernelModel): |
---|
[14de349] | 279 | """ |
---|
| 280 | ctypes wrapper for a single model. |
---|
| 281 | |
---|
[17bbadd] | 282 | *source* and *model_info* are the model source and interface as returned |
---|
[14de349] | 283 | from :func:`gen.make`. |
---|
| 284 | |
---|
| 285 | *dtype* is the desired model precision. Any numpy dtype for single |
---|
| 286 | or double precision floats will do, such as 'f', 'float32' or 'single' |
---|
| 287 | for single and 'd', 'float64' or 'double' for double. Double precision |
---|
| 288 | is an optional extension which may not be available on all devices. |
---|
[ff7119b] | 289 | |
---|
| 290 | Call :meth:`release` when done with the kernel. |
---|
[14de349] | 291 | """ |
---|
[17bbadd] | 292 | def __init__(self, dllpath, model_info, dtype=generate.F32): |
---|
[f619de7] | 293 | # type: (str, ModelInfo, np.dtype) -> None |
---|
[17bbadd] | 294 | self.info = model_info |
---|
[ce27e21] | 295 | self.dllpath = dllpath |
---|
[f619de7] | 296 | self._dll = None # type: ct.CDLL |
---|
[40a87fa] | 297 | self._kernels = None # type: List[Callable, Callable] |
---|
[750ffa5] | 298 | self.dtype = np.dtype(dtype) |
---|
[14de349] | 299 | |
---|
[ce27e21] | 300 | def _load_dll(self): |
---|
[f619de7] | 301 | # type: () -> None |
---|
[2c801fe] | 302 | try: |
---|
[f619de7] | 303 | self._dll = ct.CDLL(self.dllpath) |
---|
[4d76711] | 304 | except: |
---|
| 305 | annotate_exception("while loading "+self.dllpath) |
---|
[2c801fe] | 306 | raise |
---|
[14de349] | 307 | |
---|
[886fa25] | 308 | float_type = (ct.c_float if self.dtype == generate.F32 |
---|
| 309 | else ct.c_double if self.dtype == generate.F64 |
---|
| 310 | else ct.c_longdouble) |
---|
[ce27e21] | 311 | |
---|
[a738209] | 312 | # int, int, int, int*, double*, double*, double*, double*, double |
---|
[886fa25] | 313 | argtypes = [ct.c_int32]*3 + [ct.c_void_p]*4 + [float_type] |
---|
[9eb3632] | 314 | names = [generate.kernel_name(self.info, variant) |
---|
| 315 | for variant in ("Iq", "Iqxy", "Imagnetic")] |
---|
| 316 | self._kernels = [self._dll[name] for name in names] |
---|
| 317 | for k in self._kernels: |
---|
| 318 | k.argtypes = argtypes |
---|
[ce27e21] | 319 | |
---|
| 320 | def __getstate__(self): |
---|
[f619de7] | 321 | # type: () -> Tuple[ModelInfo, str] |
---|
[eafc9fa] | 322 | return self.info, self.dllpath |
---|
[ce27e21] | 323 | |
---|
| 324 | def __setstate__(self, state): |
---|
[f619de7] | 325 | # type: (Tuple[ModelInfo, str]) -> None |
---|
[eafc9fa] | 326 | self.info, self.dllpath = state |
---|
[f619de7] | 327 | self._dll = None |
---|
[ce27e21] | 328 | |
---|
[48fbd50] | 329 | def make_kernel(self, q_vectors): |
---|
[f619de7] | 330 | # type: (List[np.ndarray]) -> DllKernel |
---|
[eafc9fa] | 331 | q_input = PyInput(q_vectors, self.dtype) |
---|
[f619de7] | 332 | # Note: pickle not supported for DllKernel |
---|
| 333 | if self._dll is None: |
---|
| 334 | self._load_dll() |
---|
[9eb3632] | 335 | is_2d = len(q_vectors) == 2 |
---|
| 336 | kernel = self._kernels[1:3] if is_2d else [self._kernels[0]]*2 |
---|
[3c56da87] | 337 | return DllKernel(kernel, self.info, q_input) |
---|
[4d76711] | 338 | |
---|
[eafc9fa] | 339 | def release(self): |
---|
[f619de7] | 340 | # type: () -> None |
---|
[14de349] | 341 | """ |
---|
[eafc9fa] | 342 | Release any resources associated with the model. |
---|
[14de349] | 343 | """ |
---|
[886fa25] | 344 | dll_handle = self._dll._handle |
---|
[6ad0e87] | 345 | if os.name == 'nt': |
---|
[40a87fa] | 346 | ct.windll.kernel32.FreeLibrary(dll_handle) |
---|
| 347 | else: |
---|
[886fa25] | 348 | _ct.dlclose(dll_handle) |
---|
| 349 | del self._dll |
---|
| 350 | self._dll = None |
---|
[14de349] | 351 | |
---|
[f619de7] | 352 | class DllKernel(Kernel): |
---|
[ff7119b] | 353 | """ |
---|
| 354 | Callable SAS kernel. |
---|
| 355 | |
---|
[b3f6bc3] | 356 | *kernel* is the c function to call. |
---|
[ff7119b] | 357 | |
---|
[17bbadd] | 358 | *model_info* is the module information |
---|
[ff7119b] | 359 | |
---|
[3c56da87] | 360 | *q_input* is the DllInput q vectors at which the kernel should be |
---|
[ff7119b] | 361 | evaluated. |
---|
| 362 | |
---|
| 363 | The resulting call method takes the *pars*, a list of values for |
---|
[823e620] | 364 | the fixed parameters to the kernel, and *pd_pars*, a list of (value, weight) |
---|
[ff7119b] | 365 | vectors for the polydisperse parameters. *cutoff* determines the |
---|
| 366 | integration limits: any points with combined weight less than *cutoff* |
---|
| 367 | will not be calculated. |
---|
| 368 | |
---|
| 369 | Call :meth:`release` when done with the kernel instance. |
---|
| 370 | """ |
---|
[17bbadd] | 371 | def __init__(self, kernel, model_info, q_input): |
---|
[f619de7] | 372 | # type: (Callable[[], np.ndarray], ModelInfo, PyInput) -> None |
---|
[01c8d9e] | 373 | #,model_info,q_input) |
---|
[48fbd50] | 374 | self.kernel = kernel |
---|
[17bbadd] | 375 | self.info = model_info |
---|
[3c56da87] | 376 | self.q_input = q_input |
---|
[39cc3be] | 377 | self.dtype = q_input.dtype |
---|
[445d1c0] | 378 | self.dim = '2d' if q_input.is_2d else '1d' |
---|
[c036ddb] | 379 | # leave room for f1/f2 results in case we need to compute beta for 1d models |
---|
| 380 | num_returns = 1 if self.dim == '2d' else 2 # |
---|
| 381 | # plus 1 for the normalization value |
---|
| 382 | self.result = np.empty((q_input.nq+1)*num_returns, self.dtype) |
---|
[a5b8477] | 383 | self.real = (np.float32 if self.q_input.dtype == generate.F32 |
---|
| 384 | else np.float64 if self.q_input.dtype == generate.F64 |
---|
| 385 | else np.float128) |
---|
[14de349] | 386 | |
---|
[01c8d9e] | 387 | def Iq(self, call_details, values, cutoff, magnetic): |
---|
[32e3c9b] | 388 | # type: (CallDetails, np.ndarray, np.ndarray, float, bool) -> np.ndarray |
---|
[01c8d9e] | 389 | self._call_kernel(call_details, values, cutoff, magnetic) |
---|
| 390 | #print("returned",self.q_input.q, self.result) |
---|
| 391 | pd_norm = self.result[self.q_input.nq] |
---|
| 392 | scale = values[0]/(pd_norm if pd_norm != 0.0 else 1.0) |
---|
| 393 | background = values[1] |
---|
| 394 | #print("scale",scale,background) |
---|
| 395 | return scale*self.result[:self.q_input.nq] + background |
---|
| 396 | __call__ = Iq |
---|
[48fbd50] | 397 | |
---|
[01c8d9e] | 398 | def beta(self, call_details, values, cutoff, magnetic): |
---|
| 399 | # type: (CallDetails, np.ndarray, np.ndarray, float, bool) -> np.ndarray |
---|
| 400 | self._call_kernel(call_details, values, cutoff, magnetic) |
---|
| 401 | w_norm = self.result[2*self.q_input.nq + 1] |
---|
| 402 | pd_norm = self.result[self.q_input.nq] |
---|
| 403 | if w_norm == 0.: |
---|
| 404 | w_norm = 1. |
---|
| 405 | F2 = self.result[:self.q_input.nq]/w_norm |
---|
| 406 | F1 = self.result[self.q_input.nq+1:2*self.q_input.nq+1]/w_norm |
---|
| 407 | volume_avg = pd_norm/w_norm |
---|
| 408 | return F1, F2, volume_avg |
---|
| 409 | |
---|
| 410 | def _call_kernel(self, call_details, values, cutoff, magnetic): |
---|
[9eb3632] | 411 | kernel = self.kernel[1 if magnetic else 0] |
---|
[303d8d6] | 412 | args = [ |
---|
| 413 | self.q_input.nq, # nq |
---|
[9eb3632] | 414 | None, # pd_start |
---|
| 415 | None, # pd_stop pd_stride[MAX_PD] |
---|
[8d62008] | 416 | call_details.buffer.ctypes.data, # problem |
---|
[01c8d9e] | 417 | values.ctypes.data, # pars |
---|
| 418 | self.q_input.q.ctypes.data, # q |
---|
[48fbd50] | 419 | self.result.ctypes.data, # results |
---|
[a5b8477] | 420 | self.real(cutoff), # cutoff |
---|
[9eb3632] | 421 | ] |
---|
[c036ddb] | 422 | #print("Calling DLL") |
---|
[bde38b5] | 423 | #call_details.show(values) |
---|
[9eb3632] | 424 | step = 100 |
---|
[bde38b5] | 425 | for start in range(0, call_details.num_eval, step): |
---|
| 426 | stop = min(start + step, call_details.num_eval) |
---|
[9eb3632] | 427 | args[1:3] = [start, stop] |
---|
| 428 | kernel(*args) # type: ignore |
---|
| 429 | |
---|
[14de349] | 430 | def release(self): |
---|
[f619de7] | 431 | # type: () -> None |
---|
[eafc9fa] | 432 | """ |
---|
| 433 | Release any resources associated with the kernel. |
---|
| 434 | """ |
---|
[f619de7] | 435 | self.q_input.release() |
---|