[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 |
---|
[14de349] | 53 | import ctypes as ct |
---|
[5edfe12] | 54 | from ctypes import c_void_p, c_int, c_longdouble, c_double, c_float |
---|
[821a9c6] | 55 | import logging |
---|
[14de349] | 56 | |
---|
| 57 | import numpy as np |
---|
| 58 | |
---|
[cb6ecf4] | 59 | from . import generate |
---|
[f734e7d] | 60 | from .kernelpy import PyInput, PyModel |
---|
[2c801fe] | 61 | from .exception import annotate_exception |
---|
[14de349] | 62 | |
---|
[5efe850] | 63 | if os.name == 'nt': |
---|
| 64 | # Windows compiler; check if TinyCC is available |
---|
| 65 | try: |
---|
[7e16db7] | 66 | import tinycc |
---|
[5efe850] | 67 | except ImportError: |
---|
[7e16db7] | 68 | tinycc = None |
---|
[3c56da87] | 69 | # call vcvarsall.bat before compiling to set path, headers, libs, etc. |
---|
[68d3c1b] | 70 | if "VCINSTALLDIR" in os.environ: |
---|
[a30cdd5] | 71 | # MSVC compiler is available, so use it. OpenMP requires a copy of |
---|
| 72 | # vcomp90.dll on the path. One may be found here: |
---|
| 73 | # C:/Windows/winsxs/x86_microsoft.vc90.openmp*/vcomp90.dll |
---|
| 74 | # Copy this to the python directory and uncomment the OpenMP COMPILE |
---|
[f734e7d] | 75 | # TODO: remove intermediate OBJ file created in the directory |
---|
| 76 | # TODO: maybe don't use randomized name for the c file |
---|
[5efe850] | 77 | # TODO: maybe ask distutils to find MSVC |
---|
[7e16db7] | 78 | CC = "cl /nologo /Ox /MD /W3 /GS- /DNDEBUG".split() |
---|
[a30cdd5] | 79 | if "SAS_OPENMP" in os.environ: |
---|
[7e16db7] | 80 | CC.append("/openmp") |
---|
| 81 | LN = "/link /DLL /INCREMENTAL:NO /MANIFEST".split() |
---|
| 82 | def compile_command(source, output): |
---|
| 83 | return CC + ["/Tp%s"%source] + LN + ["/OUT:%s"%output] |
---|
| 84 | elif tinycc: |
---|
[5efe850] | 85 | # TinyCC compiler. |
---|
[7e16db7] | 86 | CC = [tinycc.find_tcc_path()] + "-shared -rdynamic -Wall".split() |
---|
| 87 | def compile_command(source, output): |
---|
| 88 | return CC + ["%s"%source, "-o", "%s"%output] |
---|
[5efe850] | 89 | else: |
---|
| 90 | # MinGW compiler. |
---|
[7e16db7] | 91 | CC = "gcc -shared -std=c99 -O2 -Wall".split() |
---|
[a30cdd5] | 92 | if "SAS_OPENMP" in os.environ: |
---|
[7e16db7] | 93 | CC.append("-fopenmp") |
---|
| 94 | def compile_command(source, output): |
---|
| 95 | return CC + ["%s"%source, "-o", "%s"%output, "-lm"] |
---|
[5d4777d] | 96 | else: |
---|
[5efe850] | 97 | # Generic unix compile |
---|
| 98 | # On mac users will need the X code command line tools installed |
---|
[7e16db7] | 99 | #COMPILE = "gcc-mp-4.7 -shared -fPIC -std=c99 -fopenmp -O2 -Wall %s -o %s -lm -lgomp" |
---|
| 100 | CC = "gcc -shared -fPIC -std=c99 -O2 -Wall".split() |
---|
[5efe850] | 101 | # add openmp support if not running on a mac |
---|
[7e16db7] | 102 | if sys.platform != "darwin": |
---|
| 103 | CC.append("-fopenmp") |
---|
| 104 | def compile_command(source, output): |
---|
| 105 | return CC + ["%s"%source, "-o", "%s"%output, "-lm"] |
---|
[df4dc86] | 106 | |
---|
[ff97458] | 107 | # Windows-specific solution |
---|
| 108 | if os.name == 'nt': |
---|
[3ecf034] | 109 | # Assume the default location of module DLLs is in .sasmodels/compiled_models. |
---|
| 110 | DLL_PATH = os.path.join(os.path.expanduser("~"), ".sasmodels", "compiled_models") |
---|
| 111 | if not os.path.exists(DLL_PATH): |
---|
| 112 | os.makedirs(DLL_PATH) |
---|
[ff97458] | 113 | else: |
---|
| 114 | # Set up the default path for compiled modules. |
---|
| 115 | DLL_PATH = tempfile.gettempdir() |
---|
[5d4777d] | 116 | |
---|
[5d316e9] | 117 | ALLOW_SINGLE_PRECISION_DLLS = True |
---|
[5d4777d] | 118 | |
---|
[7e16db7] | 119 | def compile(source, output): |
---|
| 120 | command = compile_command(source=source, output=output) |
---|
| 121 | command_str = " ".join('"%s"'%p if ' ' in p else p for p in command) |
---|
| 122 | logging.info(command_str) |
---|
| 123 | try: |
---|
| 124 | subprocess.check_output(command, shell=True, stderr=subprocess.STDOUT) |
---|
| 125 | except subprocess.CalledProcessError as exc: |
---|
| 126 | raise RuntimeError("compile failed.\n%s\n%s"%(command_str, exc.output)) |
---|
| 127 | if not os.path.exists(output): |
---|
| 128 | raise RuntimeError("compile failed. File is in %r"%source) |
---|
[750ffa5] | 129 | |
---|
[17bbadd] | 130 | def dll_path(model_info, dtype="double"): |
---|
[5d4777d] | 131 | """ |
---|
[17bbadd] | 132 | Path to the compiled model defined by *model_info*. |
---|
[5d4777d] | 133 | """ |
---|
[17bbadd] | 134 | basename = splitext(splitpath(model_info['filename'])[1])[0] |
---|
[750ffa5] | 135 | if np.dtype(dtype) == generate.F32: |
---|
| 136 | basename += "32" |
---|
[5edfe12] | 137 | elif np.dtype(dtype) == generate.F64: |
---|
| 138 | basename += "64" |
---|
| 139 | else: |
---|
| 140 | basename += "128" |
---|
[01b8659] | 141 | |
---|
| 142 | # Hack to find precompiled dlls |
---|
| 143 | path = joinpath(generate.DATA_PATH, '..', 'compiled_models', basename+'.so') |
---|
| 144 | if os.path.exists(path): |
---|
| 145 | return path |
---|
| 146 | |
---|
[5d4777d] | 147 | return joinpath(DLL_PATH, basename+'.so') |
---|
| 148 | |
---|
[17bbadd] | 149 | def make_dll(source, model_info, dtype="double"): |
---|
[5d4777d] | 150 | """ |
---|
| 151 | Load the compiled model defined by *kernel_module*. |
---|
| 152 | |
---|
| 153 | Recompile if any files are newer than the model file. |
---|
| 154 | |
---|
[aa4946b] | 155 | *dtype* is a numpy floating point precision specifier indicating whether |
---|
| 156 | the model should be single or double precision. The default is double |
---|
| 157 | precision. |
---|
[5d4777d] | 158 | |
---|
[aa4946b] | 159 | The DLL is not loaded until the kernel is called so models can |
---|
[5d4777d] | 160 | be defined without using too many resources. |
---|
[aa4946b] | 161 | |
---|
| 162 | Set *sasmodels.kerneldll.DLL_PATH* to the compiled dll output path. |
---|
| 163 | The default is the system temporary directory. |
---|
| 164 | |
---|
| 165 | Set *sasmodels.ALLOW_SINGLE_PRECISION_DLLS* to True if single precision |
---|
| 166 | models are allowed as DLLs. |
---|
[5d4777d] | 167 | """ |
---|
[17bbadd] | 168 | if callable(model_info.get('Iq', None)): |
---|
| 169 | return PyModel(model_info) |
---|
[6ad0e87] | 170 | |
---|
[750ffa5] | 171 | dtype = np.dtype(dtype) |
---|
[5d316e9] | 172 | if dtype == generate.F16: |
---|
| 173 | raise ValueError("16 bit floats not supported") |
---|
[5edfe12] | 174 | if dtype == generate.F32 and not ALLOW_SINGLE_PRECISION_DLLS: |
---|
| 175 | dtype = generate.F64 # Force 64-bit dll |
---|
[750ffa5] | 176 | |
---|
| 177 | if dtype == generate.F32: # 32-bit dll |
---|
[17bbadd] | 178 | tempfile_prefix = 'sas_' + model_info['name'] + '32_' |
---|
[5edfe12] | 179 | elif dtype == generate.F64: |
---|
[17bbadd] | 180 | tempfile_prefix = 'sas_' + model_info['name'] + '64_' |
---|
[750ffa5] | 181 | else: |
---|
[17bbadd] | 182 | tempfile_prefix = 'sas_' + model_info['name'] + '128_' |
---|
[01b8659] | 183 | |
---|
[17bbadd] | 184 | dll = dll_path(model_info, dtype) |
---|
[e1454ab] | 185 | |
---|
| 186 | if not os.path.exists(dll): |
---|
[5a91c6b] | 187 | need_recompile = True |
---|
[31bc9bf] | 188 | elif getattr(sys, 'frozen', None) is not None: |
---|
[5a91c6b] | 189 | # TODO: don't suppress time stamp |
---|
| 190 | # Currently suppressing recompile when running in a frozen environment |
---|
| 191 | need_recompile = False |
---|
| 192 | else: |
---|
| 193 | dll_time = os.path.getmtime(dll) |
---|
| 194 | source_files = generate.model_sources(model_info) + [model_info['filename']] |
---|
| 195 | newest_source = max(os.path.getmtime(f) for f in source_files) |
---|
| 196 | need_recompile = dll_time < newest_source |
---|
| 197 | if need_recompile: |
---|
| 198 | source = generate.convert_type(source, dtype) |
---|
[7e16db7] | 199 | fd, filename = tempfile.mkstemp(suffix=".c", prefix=tempfile_prefix) |
---|
[9b71c30] | 200 | with open(filename, "w") as file: |
---|
[7e16db7] | 201 | file.write(source) |
---|
[9b71c30] | 202 | os.close(fd) |
---|
[7e16db7] | 203 | compile(source=filename, output=dll) |
---|
| 204 | # comment the following to keep the generated c file |
---|
| 205 | # Note: if there is a syntax error then compile raises an error |
---|
| 206 | # and the source file will not be deleted. |
---|
| 207 | os.unlink(filename) |
---|
| 208 | #print("saving compiled file in %r"%filename) |
---|
[aa4946b] | 209 | return dll |
---|
| 210 | |
---|
| 211 | |
---|
[17bbadd] | 212 | def load_dll(source, model_info, dtype="double"): |
---|
[aa4946b] | 213 | """ |
---|
[823e620] | 214 | Create and load a dll corresponding to the source, info pair returned |
---|
[aa4946b] | 215 | from :func:`sasmodels.generate.make` compiled for the target precision. |
---|
| 216 | |
---|
| 217 | See :func:`make_dll` for details on controlling the dll path and the |
---|
| 218 | allowed floating point precision. |
---|
| 219 | """ |
---|
[17bbadd] | 220 | filename = make_dll(source, model_info, dtype=dtype) |
---|
| 221 | return DllModel(filename, model_info, dtype=dtype) |
---|
[5d4777d] | 222 | |
---|
[14de349] | 223 | |
---|
[f734e7d] | 224 | IQ_ARGS = [c_void_p, c_void_p, c_int] |
---|
| 225 | IQXY_ARGS = [c_void_p, c_void_p, c_void_p, c_int] |
---|
[14de349] | 226 | |
---|
| 227 | class DllModel(object): |
---|
| 228 | """ |
---|
| 229 | ctypes wrapper for a single model. |
---|
| 230 | |
---|
[17bbadd] | 231 | *source* and *model_info* are the model source and interface as returned |
---|
[14de349] | 232 | from :func:`gen.make`. |
---|
| 233 | |
---|
| 234 | *dtype* is the desired model precision. Any numpy dtype for single |
---|
| 235 | or double precision floats will do, such as 'f', 'float32' or 'single' |
---|
| 236 | for single and 'd', 'float64' or 'double' for double. Double precision |
---|
| 237 | is an optional extension which may not be available on all devices. |
---|
[ff7119b] | 238 | |
---|
| 239 | Call :meth:`release` when done with the kernel. |
---|
[14de349] | 240 | """ |
---|
[6ad0e87] | 241 | |
---|
[17bbadd] | 242 | def __init__(self, dllpath, model_info, dtype=generate.F32): |
---|
| 243 | self.info = model_info |
---|
[ce27e21] | 244 | self.dllpath = dllpath |
---|
| 245 | self.dll = None |
---|
[750ffa5] | 246 | self.dtype = np.dtype(dtype) |
---|
[14de349] | 247 | |
---|
[ce27e21] | 248 | def _load_dll(self): |
---|
| 249 | Nfixed1d = len(self.info['partype']['fixed-1d']) |
---|
| 250 | Nfixed2d = len(self.info['partype']['fixed-2d']) |
---|
| 251 | Npd1d = len(self.info['partype']['pd-1d']) |
---|
| 252 | Npd2d = len(self.info['partype']['pd-2d']) |
---|
[14de349] | 253 | |
---|
[823e620] | 254 | #print("dll", self.dllpath) |
---|
[2c801fe] | 255 | try: |
---|
| 256 | self.dll = ct.CDLL(self.dllpath) |
---|
[4d76711] | 257 | except: |
---|
| 258 | annotate_exception("while loading "+self.dllpath) |
---|
[2c801fe] | 259 | raise |
---|
[14de349] | 260 | |
---|
[5edfe12] | 261 | fp = (c_float if self.dtype == generate.F32 |
---|
| 262 | else c_double if self.dtype == generate.F64 |
---|
| 263 | else c_longdouble) |
---|
[750ffa5] | 264 | pd_args_1d = [c_void_p, fp] + [c_int]*Npd1d if Npd1d else [] |
---|
[823e620] | 265 | pd_args_2d = [c_void_p, fp] + [c_int]*Npd2d if Npd2d else [] |
---|
[cb6ecf4] | 266 | self.Iq = self.dll[generate.kernel_name(self.info, False)] |
---|
[750ffa5] | 267 | self.Iq.argtypes = IQ_ARGS + pd_args_1d + [fp]*Nfixed1d |
---|
[ce27e21] | 268 | |
---|
[cb6ecf4] | 269 | self.Iqxy = self.dll[generate.kernel_name(self.info, True)] |
---|
[750ffa5] | 270 | self.Iqxy.argtypes = IQXY_ARGS + pd_args_2d + [fp]*Nfixed2d |
---|
[6ad0e87] | 271 | |
---|
| 272 | self.release() |
---|
[ce27e21] | 273 | |
---|
| 274 | def __getstate__(self): |
---|
[eafc9fa] | 275 | return self.info, self.dllpath |
---|
[ce27e21] | 276 | |
---|
| 277 | def __setstate__(self, state): |
---|
[eafc9fa] | 278 | self.info, self.dllpath = state |
---|
| 279 | self.dll = None |
---|
[ce27e21] | 280 | |
---|
[4d76711] | 281 | def make_kernel(self, q_vectors): |
---|
[eafc9fa] | 282 | q_input = PyInput(q_vectors, self.dtype) |
---|
[b3f6bc3] | 283 | if self.dll is None: self._load_dll() |
---|
[eafc9fa] | 284 | kernel = self.Iqxy if q_input.is_2d else self.Iq |
---|
[3c56da87] | 285 | return DllKernel(kernel, self.info, q_input) |
---|
[4d76711] | 286 | |
---|
[eafc9fa] | 287 | def release(self): |
---|
[14de349] | 288 | """ |
---|
[eafc9fa] | 289 | Release any resources associated with the model. |
---|
[14de349] | 290 | """ |
---|
[6ad0e87] | 291 | if os.name == 'nt': |
---|
| 292 | #dll = ct.cdll.LoadLibrary(self.dllpath) |
---|
| 293 | dll = ct.CDLL(self.dllpath) |
---|
| 294 | libHandle = dll._handle |
---|
| 295 | #libHandle = ct.c_void_p(dll._handle) |
---|
| 296 | del dll, self.dll |
---|
| 297 | self.dll = None |
---|
| 298 | ct.windll.kernel32.FreeLibrary(libHandle) |
---|
| 299 | else: |
---|
| 300 | pass |
---|
[ff7119b] | 301 | |
---|
[14de349] | 302 | |
---|
| 303 | class DllKernel(object): |
---|
[ff7119b] | 304 | """ |
---|
| 305 | Callable SAS kernel. |
---|
| 306 | |
---|
[b3f6bc3] | 307 | *kernel* is the c function to call. |
---|
[ff7119b] | 308 | |
---|
[17bbadd] | 309 | *model_info* is the module information |
---|
[ff7119b] | 310 | |
---|
[3c56da87] | 311 | *q_input* is the DllInput q vectors at which the kernel should be |
---|
[ff7119b] | 312 | evaluated. |
---|
| 313 | |
---|
| 314 | The resulting call method takes the *pars*, a list of values for |
---|
[823e620] | 315 | the fixed parameters to the kernel, and *pd_pars*, a list of (value, weight) |
---|
[ff7119b] | 316 | vectors for the polydisperse parameters. *cutoff* determines the |
---|
| 317 | integration limits: any points with combined weight less than *cutoff* |
---|
| 318 | will not be calculated. |
---|
| 319 | |
---|
| 320 | Call :meth:`release` when done with the kernel instance. |
---|
| 321 | """ |
---|
[17bbadd] | 322 | def __init__(self, kernel, model_info, q_input): |
---|
| 323 | self.info = model_info |
---|
[3c56da87] | 324 | self.q_input = q_input |
---|
[14de349] | 325 | self.kernel = kernel |
---|
[3c56da87] | 326 | self.res = np.empty(q_input.nq, q_input.dtype) |
---|
[eafc9fa] | 327 | dim = '2d' if q_input.is_2d else '1d' |
---|
[17bbadd] | 328 | self.fixed_pars = model_info['partype']['fixed-' + dim] |
---|
| 329 | self.pd_pars = model_info['partype']['pd-' + dim] |
---|
[14de349] | 330 | |
---|
[ce27e21] | 331 | # In dll kernel, but not in opencl kernel |
---|
| 332 | self.p_res = self.res.ctypes.data |
---|
[14de349] | 333 | |
---|
[f734e7d] | 334 | def __call__(self, fixed_pars, pd_pars, cutoff): |
---|
[5edfe12] | 335 | real = (np.float32 if self.q_input.dtype == generate.F32 |
---|
| 336 | else np.float64 if self.q_input.dtype == generate.F64 |
---|
| 337 | else np.float128) |
---|
[14de349] | 338 | |
---|
[3c56da87] | 339 | nq = c_int(self.q_input.nq) |
---|
[f734e7d] | 340 | if pd_pars: |
---|
| 341 | cutoff = real(cutoff) |
---|
| 342 | loops_N = [np.uint32(len(p[0])) for p in pd_pars] |
---|
| 343 | loops = np.hstack(pd_pars) |
---|
[3c56da87] | 344 | loops = np.ascontiguousarray(loops.T, self.q_input.dtype).flatten() |
---|
[f734e7d] | 345 | p_loops = loops.ctypes.data |
---|
| 346 | dispersed = [p_loops, cutoff] + loops_N |
---|
| 347 | else: |
---|
| 348 | dispersed = [] |
---|
| 349 | fixed = [real(p) for p in fixed_pars] |
---|
[3c56da87] | 350 | args = self.q_input.q_pointers + [self.p_res, nq] + dispersed + fixed |
---|
[9404dd3] | 351 | #print(pars) |
---|
[ce27e21] | 352 | self.kernel(*args) |
---|
[14de349] | 353 | |
---|
| 354 | return self.res |
---|
| 355 | |
---|
| 356 | def release(self): |
---|
[eafc9fa] | 357 | """ |
---|
| 358 | Release any resources associated with the kernel. |
---|
| 359 | """ |
---|
[14de349] | 360 | pass |
---|