[14de349] | 1 | """ |
---|
| 2 | C types wrapper for sasview models. |
---|
[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*. |
---|
[14de349] | 7 | """ |
---|
[750ffa5] | 8 | |
---|
[5d4777d] | 9 | import sys |
---|
| 10 | import os |
---|
[df4dc86] | 11 | import tempfile |
---|
[14de349] | 12 | import ctypes as ct |
---|
[750ffa5] | 13 | from ctypes import c_void_p, c_int, c_double, c_float |
---|
[14de349] | 14 | |
---|
| 15 | import numpy as np |
---|
| 16 | |
---|
[cb6ecf4] | 17 | from . import generate |
---|
[f734e7d] | 18 | from .kernelpy import PyInput, PyModel |
---|
[2c801fe] | 19 | from .exception import annotate_exception |
---|
[14de349] | 20 | |
---|
[5d4777d] | 21 | # Compiler platform details |
---|
| 22 | if sys.platform == 'darwin': |
---|
[216a9e1] | 23 | #COMPILE = "gcc-mp-4.7 -shared -fPIC -std=c99 -fopenmp -O2 -Wall %s -o %s -lm -lgomp" |
---|
[df4dc86] | 24 | COMPILE = "gcc -shared -fPIC -std=c99 -O2 -Wall %(source)s -o %(output)s -lm" |
---|
[5d4777d] | 25 | elif os.name == 'nt': |
---|
[3c56da87] | 26 | # call vcvarsall.bat before compiling to set path, headers, libs, etc. |
---|
[68d3c1b] | 27 | if "VCINSTALLDIR" in os.environ: |
---|
[a30cdd5] | 28 | # MSVC compiler is available, so use it. OpenMP requires a copy of |
---|
| 29 | # vcomp90.dll on the path. One may be found here: |
---|
| 30 | # C:/Windows/winsxs/x86_microsoft.vc90.openmp*/vcomp90.dll |
---|
| 31 | # Copy this to the python directory and uncomment the OpenMP COMPILE |
---|
[f734e7d] | 32 | # TODO: remove intermediate OBJ file created in the directory |
---|
| 33 | # TODO: maybe don't use randomized name for the c file |
---|
[a30cdd5] | 34 | CC = "cl /nologo /Ox /MD /W3 /GS- /DNDEBUG /Tp%(source)s " |
---|
| 35 | LN = "/link /DLL /INCREMENTAL:NO /MANIFEST /OUT:%(output)s" |
---|
| 36 | if "SAS_OPENMP" in os.environ: |
---|
| 37 | COMPILE = " ".join((CC, "/openmp", LN)) |
---|
| 38 | else: |
---|
| 39 | COMPILE = " ".join((CC, LN)) |
---|
[68d3c1b] | 40 | else: |
---|
| 41 | COMPILE = "gcc -shared -fPIC -std=c99 -O2 -Wall %(source)s -o %(output)s -lm" |
---|
[a30cdd5] | 42 | if "SAS_OPENMP" in os.environ: |
---|
| 43 | COMPILE = COMPILE + " -fopenmp" |
---|
[5d4777d] | 44 | else: |
---|
[a30cdd5] | 45 | COMPILE = "cc -shared -fPIC -fopenmp -std=c99 -O2 -Wall %(source)s -o %(output)s -lm" |
---|
[df4dc86] | 46 | |
---|
| 47 | DLL_PATH = tempfile.gettempdir() |
---|
[5d4777d] | 48 | |
---|
[750ffa5] | 49 | ALLOW_SINGLE_PRECISION_DLLS = False |
---|
[5d4777d] | 50 | |
---|
[750ffa5] | 51 | |
---|
| 52 | def dll_path(info, dtype="double"): |
---|
[5d4777d] | 53 | """ |
---|
| 54 | Path to the compiled model defined by *info*. |
---|
| 55 | """ |
---|
| 56 | from os.path import join as joinpath, split as splitpath, splitext |
---|
| 57 | basename = splitext(splitpath(info['filename'])[1])[0] |
---|
[750ffa5] | 58 | if np.dtype(dtype) == generate.F32: |
---|
| 59 | basename += "32" |
---|
[5d4777d] | 60 | return joinpath(DLL_PATH, basename+'.so') |
---|
| 61 | |
---|
| 62 | |
---|
[aa4946b] | 63 | def make_dll(source, info, dtype="double"): |
---|
[5d4777d] | 64 | """ |
---|
| 65 | Load the compiled model defined by *kernel_module*. |
---|
| 66 | |
---|
| 67 | Recompile if any files are newer than the model file. |
---|
| 68 | |
---|
[aa4946b] | 69 | *dtype* is a numpy floating point precision specifier indicating whether |
---|
| 70 | the model should be single or double precision. The default is double |
---|
| 71 | precision. |
---|
[5d4777d] | 72 | |
---|
[aa4946b] | 73 | The DLL is not loaded until the kernel is called so models can |
---|
[5d4777d] | 74 | be defined without using too many resources. |
---|
[aa4946b] | 75 | |
---|
| 76 | Set *sasmodels.kerneldll.DLL_PATH* to the compiled dll output path. |
---|
| 77 | The default is the system temporary directory. |
---|
| 78 | |
---|
| 79 | Set *sasmodels.ALLOW_SINGLE_PRECISION_DLLS* to True if single precision |
---|
| 80 | models are allowed as DLLs. |
---|
[5d4777d] | 81 | """ |
---|
[750ffa5] | 82 | if not ALLOW_SINGLE_PRECISION_DLLS: dtype = "double" # Force 64-bit dll |
---|
| 83 | dtype = np.dtype(dtype) |
---|
| 84 | |
---|
[f734e7d] | 85 | if callable(info.get('Iq',None)): |
---|
| 86 | return PyModel(info) |
---|
[750ffa5] | 87 | |
---|
| 88 | if dtype == generate.F32: # 32-bit dll |
---|
| 89 | source = generate.use_single(source) |
---|
| 90 | tempfile_prefix = 'sas_'+info['name']+'32_' |
---|
| 91 | else: |
---|
| 92 | tempfile_prefix = 'sas_'+info['name']+'_' |
---|
| 93 | |
---|
[cb6ecf4] | 94 | source_files = generate.sources(info) + [info['filename']] |
---|
[aa4946b] | 95 | dll= dll_path(info, dtype) |
---|
[5d4777d] | 96 | newest = max(os.path.getmtime(f) for f in source_files) |
---|
[aa4946b] | 97 | if not os.path.exists(dll) or os.path.getmtime(dll)<newest: |
---|
[5d4777d] | 98 | # Replace with a proper temp file |
---|
[750ffa5] | 99 | fid, filename = tempfile.mkstemp(suffix=".c",prefix=tempfile_prefix) |
---|
[5d4777d] | 100 | os.fdopen(fid,"w").write(source) |
---|
[aa4946b] | 101 | command = COMPILE%{"source":filename, "output":dll} |
---|
[df4dc86] | 102 | print "Compile command:",command |
---|
| 103 | status = os.system(command) |
---|
[aa4946b] | 104 | if status != 0 or not os.path.exists(dll): |
---|
[f734e7d] | 105 | raise RuntimeError("compile failed. File is in %r"%filename) |
---|
[5d4777d] | 106 | else: |
---|
| 107 | ## uncomment the following to keep the generated c file |
---|
[aa4946b] | 108 | os.unlink(filename); print "saving compiled file in %r"%filename |
---|
| 109 | return dll |
---|
| 110 | |
---|
| 111 | |
---|
| 112 | def load_dll(source, info, dtype="double"): |
---|
| 113 | """ |
---|
| 114 | Create and load a dll corresponding to the source,info pair returned |
---|
| 115 | from :func:`sasmodels.generate.make` compiled for the target precision. |
---|
| 116 | |
---|
| 117 | See :func:`make_dll` for details on controlling the dll path and the |
---|
| 118 | allowed floating point precision. |
---|
| 119 | """ |
---|
| 120 | filename = make_dll(source, info, dtype=dtype) |
---|
| 121 | return DllModel(filename, info, dtype=dtype) |
---|
[5d4777d] | 122 | |
---|
[14de349] | 123 | |
---|
[f734e7d] | 124 | IQ_ARGS = [c_void_p, c_void_p, c_int] |
---|
| 125 | IQXY_ARGS = [c_void_p, c_void_p, c_void_p, c_int] |
---|
[14de349] | 126 | |
---|
| 127 | class DllModel(object): |
---|
| 128 | """ |
---|
| 129 | ctypes wrapper for a single model. |
---|
| 130 | |
---|
[ce27e21] | 131 | *source* and *info* are the model source and interface as returned |
---|
[14de349] | 132 | from :func:`gen.make`. |
---|
| 133 | |
---|
| 134 | *dtype* is the desired model precision. Any numpy dtype for single |
---|
| 135 | or double precision floats will do, such as 'f', 'float32' or 'single' |
---|
| 136 | for single and 'd', 'float64' or 'double' for double. Double precision |
---|
| 137 | is an optional extension which may not be available on all devices. |
---|
[ff7119b] | 138 | |
---|
| 139 | Call :meth:`release` when done with the kernel. |
---|
[14de349] | 140 | """ |
---|
[750ffa5] | 141 | def __init__(self, dllpath, info, dtype=generate.F32): |
---|
[ce27e21] | 142 | self.info = info |
---|
| 143 | self.dllpath = dllpath |
---|
| 144 | self.dll = None |
---|
[750ffa5] | 145 | self.dtype = np.dtype(dtype) |
---|
[14de349] | 146 | |
---|
[ce27e21] | 147 | def _load_dll(self): |
---|
| 148 | Nfixed1d = len(self.info['partype']['fixed-1d']) |
---|
| 149 | Nfixed2d = len(self.info['partype']['fixed-2d']) |
---|
| 150 | Npd1d = len(self.info['partype']['pd-1d']) |
---|
| 151 | Npd2d = len(self.info['partype']['pd-2d']) |
---|
[14de349] | 152 | |
---|
[df4dc86] | 153 | #print "dll",self.dllpath |
---|
[2c801fe] | 154 | try: |
---|
| 155 | self.dll = ct.CDLL(self.dllpath) |
---|
| 156 | except Exception, exc: |
---|
[f3f46cd] | 157 | annotate_exception(exc, "while loading "+self.dllpath) |
---|
[2c801fe] | 158 | raise |
---|
[14de349] | 159 | |
---|
[750ffa5] | 160 | fp = c_float if self.dtype == generate.F32 else c_double |
---|
| 161 | pd_args_1d = [c_void_p, fp] + [c_int]*Npd1d if Npd1d else [] |
---|
| 162 | pd_args_2d= [c_void_p, fp] + [c_int]*Npd2d if Npd2d else [] |
---|
[cb6ecf4] | 163 | self.Iq = self.dll[generate.kernel_name(self.info, False)] |
---|
[750ffa5] | 164 | self.Iq.argtypes = IQ_ARGS + pd_args_1d + [fp]*Nfixed1d |
---|
[ce27e21] | 165 | |
---|
[cb6ecf4] | 166 | self.Iqxy = self.dll[generate.kernel_name(self.info, True)] |
---|
[750ffa5] | 167 | self.Iqxy.argtypes = IQXY_ARGS + pd_args_2d + [fp]*Nfixed2d |
---|
[ce27e21] | 168 | |
---|
| 169 | def __getstate__(self): |
---|
| 170 | return {'info': self.info, 'dllpath': self.dllpath, 'dll': None} |
---|
| 171 | |
---|
| 172 | def __setstate__(self, state): |
---|
| 173 | self.__dict__ = state |
---|
| 174 | |
---|
[3c56da87] | 175 | def __call__(self, q_input): |
---|
[750ffa5] | 176 | if self.dtype != q_input.dtype: |
---|
| 177 | raise TypeError("data is %s kernel is %s" % (q_input.dtype, self.dtype)) |
---|
[b3f6bc3] | 178 | if self.dll is None: self._load_dll() |
---|
[3c56da87] | 179 | kernel = self.Iqxy if q_input.is_2D else self.Iq |
---|
| 180 | return DllKernel(kernel, self.info, q_input) |
---|
[14de349] | 181 | |
---|
[3c56da87] | 182 | # pylint: disable=no-self-use |
---|
[14de349] | 183 | def make_input(self, q_vectors): |
---|
| 184 | """ |
---|
| 185 | Make q input vectors available to the model. |
---|
| 186 | |
---|
[b3f6bc3] | 187 | Note that each model needs its own q vector even if the case of |
---|
| 188 | mixture models because some models may be OpenCL, some may be |
---|
| 189 | ctypes and some may be pure python. |
---|
[14de349] | 190 | """ |
---|
[750ffa5] | 191 | return PyInput(q_vectors, dtype=self.dtype) |
---|
[14de349] | 192 | |
---|
[ff7119b] | 193 | def release(self): |
---|
| 194 | pass # TODO: should release the dll |
---|
| 195 | |
---|
[14de349] | 196 | |
---|
| 197 | class DllKernel(object): |
---|
[ff7119b] | 198 | """ |
---|
| 199 | Callable SAS kernel. |
---|
| 200 | |
---|
[b3f6bc3] | 201 | *kernel* is the c function to call. |
---|
[ff7119b] | 202 | |
---|
| 203 | *info* is the module information |
---|
| 204 | |
---|
[3c56da87] | 205 | *q_input* is the DllInput q vectors at which the kernel should be |
---|
[ff7119b] | 206 | evaluated. |
---|
| 207 | |
---|
| 208 | The resulting call method takes the *pars*, a list of values for |
---|
| 209 | the fixed parameters to the kernel, and *pd_pars*, a list of (value,weight) |
---|
| 210 | vectors for the polydisperse parameters. *cutoff* determines the |
---|
| 211 | integration limits: any points with combined weight less than *cutoff* |
---|
| 212 | will not be calculated. |
---|
| 213 | |
---|
| 214 | Call :meth:`release` when done with the kernel instance. |
---|
| 215 | """ |
---|
[3c56da87] | 216 | def __init__(self, kernel, info, q_input): |
---|
[5d4777d] | 217 | self.info = info |
---|
[3c56da87] | 218 | self.q_input = q_input |
---|
[14de349] | 219 | self.kernel = kernel |
---|
[3c56da87] | 220 | self.res = np.empty(q_input.nq, q_input.dtype) |
---|
| 221 | dim = '2d' if q_input.is_2D else '1d' |
---|
[ce27e21] | 222 | self.fixed_pars = info['partype']['fixed-'+dim] |
---|
| 223 | self.pd_pars = info['partype']['pd-'+dim] |
---|
[14de349] | 224 | |
---|
[ce27e21] | 225 | # In dll kernel, but not in opencl kernel |
---|
| 226 | self.p_res = self.res.ctypes.data |
---|
[14de349] | 227 | |
---|
[f734e7d] | 228 | def __call__(self, fixed_pars, pd_pars, cutoff): |
---|
[63b32bb] | 229 | real = np.float32 if self.q_input.dtype == generate.F32 else np.float64 |
---|
[14de349] | 230 | |
---|
[3c56da87] | 231 | nq = c_int(self.q_input.nq) |
---|
[f734e7d] | 232 | if pd_pars: |
---|
| 233 | cutoff = real(cutoff) |
---|
| 234 | loops_N = [np.uint32(len(p[0])) for p in pd_pars] |
---|
| 235 | loops = np.hstack(pd_pars) |
---|
[3c56da87] | 236 | loops = np.ascontiguousarray(loops.T, self.q_input.dtype).flatten() |
---|
[f734e7d] | 237 | p_loops = loops.ctypes.data |
---|
| 238 | dispersed = [p_loops, cutoff] + loops_N |
---|
| 239 | else: |
---|
| 240 | dispersed = [] |
---|
| 241 | fixed = [real(p) for p in fixed_pars] |
---|
[3c56da87] | 242 | args = self.q_input.q_pointers + [self.p_res, nq] + dispersed + fixed |
---|
[14de349] | 243 | #print pars |
---|
[ce27e21] | 244 | self.kernel(*args) |
---|
[14de349] | 245 | |
---|
| 246 | return self.res |
---|
| 247 | |
---|
| 248 | def release(self): |
---|
| 249 | pass |
---|