[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] |
---|
[f619de7] | 272 | self._Iq = self._dll[generate.kernel_name(self.info, is_2d=False)] |
---|
| 273 | self._Iqxy = self._dll[generate.kernel_name(self.info, is_2d=True)] |
---|
| 274 | self._Iq.argtypes = argtypes |
---|
| 275 | self._Iqxy.argtypes = argtypes |
---|
[ce27e21] | 276 | |
---|
| 277 | def __getstate__(self): |
---|
[f619de7] | 278 | # type: () -> Tuple[ModelInfo, str] |
---|
[eafc9fa] | 279 | return self.info, self.dllpath |
---|
[ce27e21] | 280 | |
---|
| 281 | def __setstate__(self, state): |
---|
[f619de7] | 282 | # type: (Tuple[ModelInfo, str]) -> None |
---|
[eafc9fa] | 283 | self.info, self.dllpath = state |
---|
[f619de7] | 284 | self._dll = None |
---|
[ce27e21] | 285 | |
---|
[48fbd50] | 286 | def make_kernel(self, q_vectors): |
---|
[f619de7] | 287 | # type: (List[np.ndarray]) -> DllKernel |
---|
[eafc9fa] | 288 | q_input = PyInput(q_vectors, self.dtype) |
---|
[f619de7] | 289 | # Note: pickle not supported for DllKernel |
---|
| 290 | if self._dll is None: |
---|
| 291 | self._load_dll() |
---|
| 292 | kernel = self._Iqxy if q_input.is_2d else self._Iq |
---|
[3c56da87] | 293 | return DllKernel(kernel, self.info, q_input) |
---|
[4d76711] | 294 | |
---|
[eafc9fa] | 295 | def release(self): |
---|
[f619de7] | 296 | # type: () -> None |
---|
[14de349] | 297 | """ |
---|
[eafc9fa] | 298 | Release any resources associated with the model. |
---|
[14de349] | 299 | """ |
---|
[6ad0e87] | 300 | if os.name == 'nt': |
---|
| 301 | #dll = ct.cdll.LoadLibrary(self.dllpath) |
---|
| 302 | dll = ct.CDLL(self.dllpath) |
---|
| 303 | libHandle = dll._handle |
---|
| 304 | #libHandle = ct.c_void_p(dll._handle) |
---|
[f619de7] | 305 | del dll, self._dll |
---|
| 306 | self._dll = None |
---|
[6ad0e87] | 307 | ct.windll.kernel32.FreeLibrary(libHandle) |
---|
| 308 | else: |
---|
| 309 | pass |
---|
[ff7119b] | 310 | |
---|
[14de349] | 311 | |
---|
[f619de7] | 312 | class DllKernel(Kernel): |
---|
[ff7119b] | 313 | """ |
---|
| 314 | Callable SAS kernel. |
---|
| 315 | |
---|
[b3f6bc3] | 316 | *kernel* is the c function to call. |
---|
[ff7119b] | 317 | |
---|
[17bbadd] | 318 | *model_info* is the module information |
---|
[ff7119b] | 319 | |
---|
[3c56da87] | 320 | *q_input* is the DllInput q vectors at which the kernel should be |
---|
[ff7119b] | 321 | evaluated. |
---|
| 322 | |
---|
| 323 | The resulting call method takes the *pars*, a list of values for |
---|
[823e620] | 324 | the fixed parameters to the kernel, and *pd_pars*, a list of (value, weight) |
---|
[ff7119b] | 325 | vectors for the polydisperse parameters. *cutoff* determines the |
---|
| 326 | integration limits: any points with combined weight less than *cutoff* |
---|
| 327 | will not be calculated. |
---|
| 328 | |
---|
| 329 | Call :meth:`release` when done with the kernel instance. |
---|
| 330 | """ |
---|
[17bbadd] | 331 | def __init__(self, kernel, model_info, q_input): |
---|
[f619de7] | 332 | # type: (Callable[[], np.ndarray], ModelInfo, PyInput) -> None |
---|
[48fbd50] | 333 | self.kernel = kernel |
---|
[17bbadd] | 334 | self.info = model_info |
---|
[3c56da87] | 335 | self.q_input = q_input |
---|
[39cc3be] | 336 | self.dtype = q_input.dtype |
---|
[445d1c0] | 337 | self.dim = '2d' if q_input.is_2d else '1d' |
---|
[a5b8477] | 338 | self.result = np.empty(q_input.nq+1, q_input.dtype) |
---|
| 339 | self.real = (np.float32 if self.q_input.dtype == generate.F32 |
---|
| 340 | else np.float64 if self.q_input.dtype == generate.F64 |
---|
| 341 | else np.float128) |
---|
[14de349] | 342 | |
---|
[a738209] | 343 | def __call__(self, call_details, values, cutoff): |
---|
[f619de7] | 344 | # type: (CallDetails, np.ndarray, np.ndarray, float) -> np.ndarray |
---|
[48fbd50] | 345 | |
---|
[5ff1b03] | 346 | #print("in kerneldll") |
---|
| 347 | #print("values", values) |
---|
[a738209] | 348 | start, stop = 0, call_details.pd_prod |
---|
[303d8d6] | 349 | args = [ |
---|
| 350 | self.q_input.nq, # nq |
---|
[48fbd50] | 351 | start, # pd_start |
---|
| 352 | stop, # 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 |
---|
[303d8d6] | 358 | ] |
---|
[def2c1b] | 359 | #print("calling DLL") |
---|
[f619de7] | 360 | self.kernel(*args) # type: ignore |
---|
[a5b8477] | 361 | return self.result[:-1] |
---|
[14de349] | 362 | |
---|
| 363 | def release(self): |
---|
[f619de7] | 364 | # type: () -> None |
---|
[eafc9fa] | 365 | """ |
---|
| 366 | Release any resources associated with the kernel. |
---|
| 367 | """ |
---|
[f619de7] | 368 | self.q_input.release() |
---|