[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 |
---|
[df4dc86] | 50 | import tempfile |
---|
[14de349] | 51 | import ctypes as ct |
---|
[7ff3cf3] | 52 | from ctypes import c_void_p, c_int32, c_longdouble, c_double, c_float |
---|
[14de349] | 53 | |
---|
| 54 | import numpy as np |
---|
| 55 | |
---|
[cb6ecf4] | 56 | from . import generate |
---|
[f734e7d] | 57 | from .kernelpy import PyInput, PyModel |
---|
[2c801fe] | 58 | from .exception import annotate_exception |
---|
[14de349] | 59 | |
---|
[5d4777d] | 60 | # Compiler platform details |
---|
| 61 | if sys.platform == 'darwin': |
---|
[216a9e1] | 62 | #COMPILE = "gcc-mp-4.7 -shared -fPIC -std=c99 -fopenmp -O2 -Wall %s -o %s -lm -lgomp" |
---|
[4a72d1a] | 63 | COMPILE = "gcc -shared -fPIC -std=c99 -O2 -Wall %(source)s -o %(output)s -lm" |
---|
[5d4777d] | 64 | elif os.name == 'nt': |
---|
[3c56da87] | 65 | # call vcvarsall.bat before compiling to set path, headers, libs, etc. |
---|
[68d3c1b] | 66 | if "VCINSTALLDIR" in os.environ: |
---|
[a30cdd5] | 67 | # MSVC compiler is available, so use it. OpenMP requires a copy of |
---|
| 68 | # vcomp90.dll on the path. One may be found here: |
---|
| 69 | # C:/Windows/winsxs/x86_microsoft.vc90.openmp*/vcomp90.dll |
---|
| 70 | # Copy this to the python directory and uncomment the OpenMP COMPILE |
---|
[f734e7d] | 71 | # TODO: remove intermediate OBJ file created in the directory |
---|
| 72 | # TODO: maybe don't use randomized name for the c file |
---|
[a30cdd5] | 73 | CC = "cl /nologo /Ox /MD /W3 /GS- /DNDEBUG /Tp%(source)s " |
---|
| 74 | LN = "/link /DLL /INCREMENTAL:NO /MANIFEST /OUT:%(output)s" |
---|
| 75 | if "SAS_OPENMP" in os.environ: |
---|
| 76 | COMPILE = " ".join((CC, "/openmp", LN)) |
---|
| 77 | else: |
---|
| 78 | COMPILE = " ".join((CC, LN)) |
---|
[68d3c1b] | 79 | else: |
---|
| 80 | COMPILE = "gcc -shared -fPIC -std=c99 -O2 -Wall %(source)s -o %(output)s -lm" |
---|
[a30cdd5] | 81 | if "SAS_OPENMP" in os.environ: |
---|
[03cac08] | 82 | COMPILE += " -fopenmp" |
---|
[5d4777d] | 83 | else: |
---|
[a30cdd5] | 84 | COMPILE = "cc -shared -fPIC -fopenmp -std=c99 -O2 -Wall %(source)s -o %(output)s -lm" |
---|
[df4dc86] | 85 | |
---|
| 86 | DLL_PATH = tempfile.gettempdir() |
---|
[5d4777d] | 87 | |
---|
[5d316e9] | 88 | ALLOW_SINGLE_PRECISION_DLLS = True |
---|
[5d4777d] | 89 | |
---|
[750ffa5] | 90 | |
---|
[17bbadd] | 91 | def dll_path(model_info, dtype="double"): |
---|
[5d4777d] | 92 | """ |
---|
[17bbadd] | 93 | Path to the compiled model defined by *model_info*. |
---|
[5d4777d] | 94 | """ |
---|
| 95 | from os.path import join as joinpath, split as splitpath, splitext |
---|
[17bbadd] | 96 | basename = splitext(splitpath(model_info['filename'])[1])[0] |
---|
[750ffa5] | 97 | if np.dtype(dtype) == generate.F32: |
---|
| 98 | basename += "32" |
---|
[5edfe12] | 99 | elif np.dtype(dtype) == generate.F64: |
---|
| 100 | basename += "64" |
---|
| 101 | else: |
---|
| 102 | basename += "128" |
---|
[5d4777d] | 103 | return joinpath(DLL_PATH, basename+'.so') |
---|
| 104 | |
---|
| 105 | |
---|
[17bbadd] | 106 | def make_dll(source, model_info, dtype="double"): |
---|
[5d4777d] | 107 | """ |
---|
| 108 | Load the compiled model defined by *kernel_module*. |
---|
| 109 | |
---|
| 110 | Recompile if any files are newer than the model file. |
---|
| 111 | |
---|
[aa4946b] | 112 | *dtype* is a numpy floating point precision specifier indicating whether |
---|
| 113 | the model should be single or double precision. The default is double |
---|
| 114 | precision. |
---|
[5d4777d] | 115 | |
---|
[aa4946b] | 116 | The DLL is not loaded until the kernel is called so models can |
---|
[5d4777d] | 117 | be defined without using too many resources. |
---|
[aa4946b] | 118 | |
---|
| 119 | Set *sasmodels.kerneldll.DLL_PATH* to the compiled dll output path. |
---|
| 120 | The default is the system temporary directory. |
---|
| 121 | |
---|
| 122 | Set *sasmodels.ALLOW_SINGLE_PRECISION_DLLS* to True if single precision |
---|
| 123 | models are allowed as DLLs. |
---|
[5d4777d] | 124 | """ |
---|
[17bbadd] | 125 | if callable(model_info.get('Iq', None)): |
---|
| 126 | return PyModel(model_info) |
---|
[5d316e9] | 127 | |
---|
[750ffa5] | 128 | dtype = np.dtype(dtype) |
---|
[5d316e9] | 129 | if dtype == generate.F16: |
---|
| 130 | raise ValueError("16 bit floats not supported") |
---|
[5edfe12] | 131 | if dtype == generate.F32 and not ALLOW_SINGLE_PRECISION_DLLS: |
---|
| 132 | dtype = generate.F64 # Force 64-bit dll |
---|
[750ffa5] | 133 | |
---|
| 134 | if dtype == generate.F32: # 32-bit dll |
---|
[17bbadd] | 135 | tempfile_prefix = 'sas_' + model_info['name'] + '32_' |
---|
[5edfe12] | 136 | elif dtype == generate.F64: |
---|
[17bbadd] | 137 | tempfile_prefix = 'sas_' + model_info['name'] + '64_' |
---|
[750ffa5] | 138 | else: |
---|
[17bbadd] | 139 | tempfile_prefix = 'sas_' + model_info['name'] + '128_' |
---|
[750ffa5] | 140 | |
---|
[5d316e9] | 141 | source = generate.convert_type(source, dtype) |
---|
[303d8d6] | 142 | source_files = (generate.model_sources(model_info) |
---|
| 143 | + [model_info['filename']] |
---|
| 144 | + generate.model_templates()) |
---|
[17bbadd] | 145 | dll = dll_path(model_info, dtype) |
---|
[5d4777d] | 146 | newest = max(os.path.getmtime(f) for f in source_files) |
---|
[823e620] | 147 | if not os.path.exists(dll) or os.path.getmtime(dll) < newest: |
---|
[5d4777d] | 148 | # Replace with a proper temp file |
---|
[823e620] | 149 | fid, filename = tempfile.mkstemp(suffix=".c", prefix=tempfile_prefix) |
---|
| 150 | os.fdopen(fid, "w").write(source) |
---|
[aa4946b] | 151 | command = COMPILE%{"source":filename, "output":dll} |
---|
[9404dd3] | 152 | print("Compile command: "+command) |
---|
[df4dc86] | 153 | status = os.system(command) |
---|
[aa4946b] | 154 | if status != 0 or not os.path.exists(dll): |
---|
[f734e7d] | 155 | raise RuntimeError("compile failed. File is in %r"%filename) |
---|
[5d4777d] | 156 | else: |
---|
[74667d3] | 157 | ## comment the following to keep the generated c file |
---|
| 158 | os.unlink(filename) |
---|
| 159 | #print("saving compiled file in %r"%filename) |
---|
[aa4946b] | 160 | return dll |
---|
| 161 | |
---|
| 162 | |
---|
[17bbadd] | 163 | def load_dll(source, model_info, dtype="double"): |
---|
[aa4946b] | 164 | """ |
---|
[823e620] | 165 | Create and load a dll corresponding to the source, info pair returned |
---|
[aa4946b] | 166 | from :func:`sasmodels.generate.make` compiled for the target precision. |
---|
| 167 | |
---|
| 168 | See :func:`make_dll` for details on controlling the dll path and the |
---|
| 169 | allowed floating point precision. |
---|
| 170 | """ |
---|
[17bbadd] | 171 | filename = make_dll(source, model_info, dtype=dtype) |
---|
| 172 | return DllModel(filename, model_info, dtype=dtype) |
---|
[5d4777d] | 173 | |
---|
[14de349] | 174 | class DllModel(object): |
---|
| 175 | """ |
---|
| 176 | ctypes wrapper for a single model. |
---|
| 177 | |
---|
[17bbadd] | 178 | *source* and *model_info* are the model source and interface as returned |
---|
[14de349] | 179 | from :func:`gen.make`. |
---|
| 180 | |
---|
| 181 | *dtype* is the desired model precision. Any numpy dtype for single |
---|
| 182 | or double precision floats will do, such as 'f', 'float32' or 'single' |
---|
| 183 | for single and 'd', 'float64' or 'double' for double. Double precision |
---|
| 184 | is an optional extension which may not be available on all devices. |
---|
[ff7119b] | 185 | |
---|
| 186 | Call :meth:`release` when done with the kernel. |
---|
[14de349] | 187 | """ |
---|
[17bbadd] | 188 | def __init__(self, dllpath, model_info, dtype=generate.F32): |
---|
| 189 | self.info = model_info |
---|
[ce27e21] | 190 | self.dllpath = dllpath |
---|
| 191 | self.dll = None |
---|
[750ffa5] | 192 | self.dtype = np.dtype(dtype) |
---|
[14de349] | 193 | |
---|
[ce27e21] | 194 | def _load_dll(self): |
---|
[823e620] | 195 | #print("dll", self.dllpath) |
---|
[2c801fe] | 196 | try: |
---|
| 197 | self.dll = ct.CDLL(self.dllpath) |
---|
[9404dd3] | 198 | except Exception as exc: |
---|
[f3f46cd] | 199 | annotate_exception(exc, "while loading "+self.dllpath) |
---|
[2c801fe] | 200 | raise |
---|
[14de349] | 201 | |
---|
[5edfe12] | 202 | fp = (c_float if self.dtype == generate.F32 |
---|
| 203 | else c_double if self.dtype == generate.F64 |
---|
| 204 | else c_longdouble) |
---|
[ce27e21] | 205 | |
---|
[303d8d6] | 206 | # int, int, int, int*, double*, double*, double*, double*, double*, double |
---|
[7ff3cf3] | 207 | argtypes = [c_int32]*3 + [c_void_p]*5 + [fp] |
---|
[303d8d6] | 208 | self.Iq = self.dll[generate.kernel_name(self.info, False)] |
---|
[cb6ecf4] | 209 | self.Iqxy = self.dll[generate.kernel_name(self.info, True)] |
---|
[303d8d6] | 210 | self.Iq.argtypes = argtypes |
---|
| 211 | self.Iqxy.argtypes = argtypes |
---|
[ce27e21] | 212 | |
---|
| 213 | def __getstate__(self): |
---|
[eafc9fa] | 214 | return self.info, self.dllpath |
---|
[ce27e21] | 215 | |
---|
| 216 | def __setstate__(self, state): |
---|
[eafc9fa] | 217 | self.info, self.dllpath = state |
---|
| 218 | self.dll = None |
---|
[ce27e21] | 219 | |
---|
[48fbd50] | 220 | def make_kernel(self, q_vectors): |
---|
[eafc9fa] | 221 | q_input = PyInput(q_vectors, self.dtype) |
---|
[b3f6bc3] | 222 | if self.dll is None: self._load_dll() |
---|
[eafc9fa] | 223 | kernel = self.Iqxy if q_input.is_2d else self.Iq |
---|
[3c56da87] | 224 | return DllKernel(kernel, self.info, q_input) |
---|
[14de349] | 225 | |
---|
[eafc9fa] | 226 | def release(self): |
---|
[14de349] | 227 | """ |
---|
[eafc9fa] | 228 | Release any resources associated with the model. |
---|
[14de349] | 229 | """ |
---|
[ff7119b] | 230 | pass # TODO: should release the dll |
---|
| 231 | |
---|
[14de349] | 232 | |
---|
| 233 | class DllKernel(object): |
---|
[ff7119b] | 234 | """ |
---|
| 235 | Callable SAS kernel. |
---|
| 236 | |
---|
[b3f6bc3] | 237 | *kernel* is the c function to call. |
---|
[ff7119b] | 238 | |
---|
[17bbadd] | 239 | *model_info* is the module information |
---|
[ff7119b] | 240 | |
---|
[3c56da87] | 241 | *q_input* is the DllInput q vectors at which the kernel should be |
---|
[ff7119b] | 242 | evaluated. |
---|
| 243 | |
---|
| 244 | The resulting call method takes the *pars*, a list of values for |
---|
[823e620] | 245 | the fixed parameters to the kernel, and *pd_pars*, a list of (value, weight) |
---|
[ff7119b] | 246 | vectors for the polydisperse parameters. *cutoff* determines the |
---|
| 247 | integration limits: any points with combined weight less than *cutoff* |
---|
| 248 | will not be calculated. |
---|
| 249 | |
---|
| 250 | Call :meth:`release` when done with the kernel instance. |
---|
| 251 | """ |
---|
[17bbadd] | 252 | def __init__(self, kernel, model_info, q_input): |
---|
[48fbd50] | 253 | self.kernel = kernel |
---|
[17bbadd] | 254 | self.info = model_info |
---|
[3c56da87] | 255 | self.q_input = q_input |
---|
[39cc3be] | 256 | self.dtype = q_input.dtype |
---|
[445d1c0] | 257 | self.dim = '2d' if q_input.is_2d else '1d' |
---|
[48fbd50] | 258 | self.result = np.empty(q_input.nq+3, q_input.dtype) |
---|
[14de349] | 259 | |
---|
[39cc3be] | 260 | def __call__(self, details, weights, values, cutoff): |
---|
[5edfe12] | 261 | real = (np.float32 if self.q_input.dtype == generate.F32 |
---|
| 262 | else np.float64 if self.q_input.dtype == generate.F64 |
---|
| 263 | else np.float128) |
---|
[48fbd50] | 264 | assert details.dtype == np.int32 |
---|
| 265 | assert weights.dtype == real and values.dtype == real |
---|
| 266 | |
---|
| 267 | max_pd = self.info['max_pd'] |
---|
| 268 | start, stop = 0, details[4*max_pd-1] |
---|
[fec69dd] | 269 | print(details) |
---|
[303d8d6] | 270 | args = [ |
---|
| 271 | self.q_input.nq, # nq |
---|
[48fbd50] | 272 | start, # pd_start |
---|
| 273 | stop, # pd_stop pd_stride[MAX_PD] |
---|
[303d8d6] | 274 | details.ctypes.data, # problem |
---|
| 275 | weights.ctypes.data, # weights |
---|
| 276 | values.ctypes.data, #pars |
---|
[48fbd50] | 277 | self.q_input.q.ctypes.data, #q |
---|
| 278 | self.result.ctypes.data, # results |
---|
[303d8d6] | 279 | real(cutoff), # cutoff |
---|
| 280 | ] |
---|
[ce27e21] | 281 | self.kernel(*args) |
---|
[48fbd50] | 282 | return self.result[:-3] |
---|
[14de349] | 283 | |
---|
| 284 | def release(self): |
---|
[eafc9fa] | 285 | """ |
---|
| 286 | Release any resources associated with the kernel. |
---|
| 287 | """ |
---|
[14de349] | 288 | pass |
---|