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