source: sasmodels/sasmodels/kerneldll.py @ e9b1663d

core_shell_microgelscostrafo411magnetic_modelrelease_v0.94release_v0.95ticket-1257-vesicle-productticket_1156ticket_1265_superballticket_822_more_unit_tests
Last change on this file since e9b1663d was e9b1663d, checked in by Paul Kienzle <pkienzle@…>, 8 years ago

pull from master

  • Property mode set to 100644
File size: 10.7 KB
Line 
1r"""
2DLL driver for C kernels
3
4The global attribute *ALLOW_SINGLE_PRECISION_DLLS* should be set to *True* if
5you wish to allow single precision floating point evaluation for the compiled
6models, otherwise it defaults to *False*.
7
8The compiler command line is stored in the attribute *COMPILE*, with string
9substitutions for %(source)s and %(output)s indicating what to compile and
10where to store it.  The actual command is system dependent.
11
12On windows systems, you have a choice of compilers.  *MinGW* is the GNU
13compiler toolchain, available in packages such as anaconda and PythonXY,
14or available stand alone. This toolchain has had difficulties on some
15systems, and may or may not work for you.  In order to build DLLs, *gcc*
16must be on your path.  If the environment variable *SAS_OPENMP* is given
17then -fopenmp is added to the compiler flags.  This requires a version
18of MinGW compiled with OpenMP support.
19
20An alternative toolchain uses the Microsoft Visual C++ compiler, available
21free from microsoft:
22
23    `<http://www.microsoft.com/en-us/download/details.aspx?id=44266>`_
24
25Again, this requires that the compiler is available on your path.  This is
26done by running vcvarsall.bat in a windows terminal.  Install locations are
27system dependent, such as:
28
29    C:\Program Files (x86)\Common Files\Microsoft\Visual C++ for Python\9.0\vcvarsall.bat
30
31or maybe
32
33    C:\Users\yourname\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\9.0\vcvarsall.bat
34
35And again, the environment variable *SAS_OPENMP* controls whether OpenMP is
36used to compile the C code.  This requires the Microsoft vcomp90.dll library,
37which doesn't seem to be included with the compiler, nor does there appear
38to be a public download location.  There may be one on your machine already
39in a location such as:
40
41    C:\Windows\winsxs\x86_microsoft.vc90.openmp*\vcomp90.dll
42
43If you copy this onto your path, such as the python directory or the install
44directory for this application, then OpenMP should be supported.
45"""
46from __future__ import print_function
47
48import sys
49import os
50import tempfile
51import ctypes as ct
52from ctypes import c_void_p, c_int32, c_longdouble, c_double, c_float
53
54import numpy as np
55
56from . import generate
57from .kernelpy import PyInput, PyModel
58from .exception import annotate_exception
59
60# Compiler platform details
61if sys.platform == 'darwin':
62    #COMPILE = "gcc-mp-4.7 -shared -fPIC -std=c99 -fopenmp -O2 -Wall %s -o %s -lm -lgomp"
63    COMPILE = "gcc -shared -fPIC -std=c99 -O2 -Wall %(source)s -o %(output)s -lm"
64elif os.name == 'nt':
65    # call vcvarsall.bat before compiling to set path, headers, libs, etc.
66    if "VCINSTALLDIR" in os.environ:
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
71        # TODO: remove intermediate OBJ file created in the directory
72        # TODO: maybe don't use randomized name for the c file
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))
79    else:
80        COMPILE = "gcc -shared -fPIC -std=c99 -O2 -Wall %(source)s -o %(output)s -lm"
81        if "SAS_OPENMP" in os.environ:
82            COMPILE += " -fopenmp"
83else:
84    COMPILE = "cc -shared -fPIC -fopenmp -std=c99 -O2 -Wall %(source)s -o %(output)s -lm"
85
86DLL_PATH = tempfile.gettempdir()
87
88ALLOW_SINGLE_PRECISION_DLLS = True
89
90
91def dll_path(model_info, dtype="double"):
92    """
93    Path to the compiled model defined by *model_info*.
94    """
95    from os.path import join as joinpath, split as splitpath, splitext
96    basename = splitext(splitpath(model_info['filename'])[1])[0]
97    if np.dtype(dtype) == generate.F32:
98        basename += "32"
99    elif np.dtype(dtype) == generate.F64:
100        basename += "64"
101    else:
102        basename += "128"
103    return joinpath(DLL_PATH, basename+'.so')
104
105
106def make_dll(source, model_info, dtype="double"):
107    """
108    Load the compiled model defined by *kernel_module*.
109
110    Recompile if any files are newer than the model file.
111
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.
115
116    The DLL is not loaded until the kernel is called so models can
117    be defined without using too many resources.
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.
124    """
125    if callable(model_info.get('Iq', None)):
126        return PyModel(model_info)
127   
128    dtype = np.dtype(dtype)
129    if dtype == generate.F16:
130        raise ValueError("16 bit floats not supported")
131    if dtype == generate.F32 and not ALLOW_SINGLE_PRECISION_DLLS:
132        dtype = generate.F64  # Force 64-bit dll
133
134    if dtype == generate.F32: # 32-bit dll
135        tempfile_prefix = 'sas_' + model_info['name'] + '32_'
136    elif dtype == generate.F64:
137        tempfile_prefix = 'sas_' + model_info['name'] + '64_'
138    else:
139        tempfile_prefix = 'sas_' + model_info['name'] + '128_'
140 
141    source = generate.convert_type(source, dtype)
142    newest = generate.timestamp(model_info)
143    dll = dll_path(model_info, dtype)
144    if not os.path.exists(dll) or os.path.getmtime(dll) < newest:
145        # Replace with a proper temp file
146        fid, filename = tempfile.mkstemp(suffix=".c", prefix=tempfile_prefix)
147        os.fdopen(fid, "w").write(source)
148        command = COMPILE%{"source":filename, "output":dll}
149        print("Compile command: "+command)
150        status = os.system(command)
151        if status != 0 or not os.path.exists(dll):
152            raise RuntimeError("compile failed.  File is in %r"%filename)
153        else:
154            ## comment the following to keep the generated c file
155            os.unlink(filename)
156            #print("saving compiled file in %r"%filename)
157    return dll
158
159
160def load_dll(source, model_info, dtype="double"):
161    """
162    Create and load a dll corresponding to the source, info pair returned
163    from :func:`sasmodels.generate.make` compiled for the target precision.
164
165    See :func:`make_dll` for details on controlling the dll path and the
166    allowed floating point precision.
167    """
168    filename = make_dll(source, model_info, dtype=dtype)
169    return DllModel(filename, model_info, dtype=dtype)
170
171class DllModel(object):
172    """
173    ctypes wrapper for a single model.
174
175    *source* and *model_info* are the model source and interface as returned
176    from :func:`gen.make`.
177
178    *dtype* is the desired model precision.  Any numpy dtype for single
179    or double precision floats will do, such as 'f', 'float32' or 'single'
180    for single and 'd', 'float64' or 'double' for double.  Double precision
181    is an optional extension which may not be available on all devices.
182
183    Call :meth:`release` when done with the kernel.
184    """
185   
186    def __init__(self, dllpath, model_info, dtype=generate.F32):
187        self.info = model_info
188        self.dllpath = dllpath
189        self.dll = None
190        self.dtype = np.dtype(dtype)
191
192    def _load_dll(self):
193        #print("dll", self.dllpath)
194        try:
195            self.dll = ct.CDLL(self.dllpath)
196        except Exception as exc:
197            annotate_exception(exc, "while loading "+self.dllpath)
198            raise
199
200        fp = (c_float if self.dtype == generate.F32
201              else c_double if self.dtype == generate.F64
202              else c_longdouble)
203
204        # int, int, int, int*, double*, double*, double*, double*, double*, double
205        argtypes = [c_int32]*3 + [c_void_p]*5 + [fp]
206        self.Iq = self.dll[generate.kernel_name(self.info, False)]
207        self.Iqxy = self.dll[generate.kernel_name(self.info, True)]
208        self.Iq.argtypes = argtypes
209        self.Iqxy.argtypes = argtypes
210
211    def __getstate__(self):
212        return self.info, self.dllpath
213
214    def __setstate__(self, state):
215        self.info, self.dllpath = state
216        self.dll = None
217
218    def make_kernel(self, q_vectors):
219        q_input = PyInput(q_vectors, self.dtype)
220        if self.dll is None: self._load_dll()
221        kernel = self.Iqxy if q_input.is_2d else self.Iq
222        return DllKernel(kernel, self.info, q_input)
223   
224    def release(self):
225        """
226        Release any resources associated with the model.
227        """
228        if os.name == 'nt':
229            #dll = ct.cdll.LoadLibrary(self.dllpath)
230            dll = ct.CDLL(self.dllpath)
231            libHandle = dll._handle
232            #libHandle = ct.c_void_p(dll._handle)
233            del dll, self.dll
234            self.dll = None
235            #_ctypes.FreeLibrary(libHandle)
236            ct.windll.kernel32.FreeLibrary(libHandle)
237        else:   
238            pass 
239
240
241class DllKernel(object):
242    """
243    Callable SAS kernel.
244
245    *kernel* is the c function to call.
246
247    *model_info* is the module information
248
249    *q_input* is the DllInput q vectors at which the kernel should be
250    evaluated.
251
252    The resulting call method takes the *pars*, a list of values for
253    the fixed parameters to the kernel, and *pd_pars*, a list of (value, weight)
254    vectors for the polydisperse parameters.  *cutoff* determines the
255    integration limits: any points with combined weight less than *cutoff*
256    will not be calculated.
257
258    Call :meth:`release` when done with the kernel instance.
259    """
260    def __init__(self, kernel, model_info, q_input):
261        self.kernel = kernel
262        self.info = model_info
263        self.q_input = q_input
264        self.dtype = q_input.dtype
265        self.dim = '2d' if q_input.is_2d else '1d'
266        self.result = np.empty(q_input.nq+3, q_input.dtype)
267
268    def __call__(self, details, weights, values, cutoff):
269        real = (np.float32 if self.q_input.dtype == generate.F32
270                else np.float64 if self.q_input.dtype == generate.F64
271                else np.float128)
272        assert details.dtype == np.int32
273        assert weights.dtype == real and values.dtype == real
274
275        max_pd = self.info['max_pd']
276        start, stop = 0, details[4*max_pd-1]
277        print(details)
278        args = [
279            self.q_input.nq, # nq
280            start, # pd_start
281            stop, # pd_stop pd_stride[MAX_PD]
282            details.ctypes.data, # problem
283            weights.ctypes.data,  # weights
284            values.ctypes.data,  #pars
285            self.q_input.q.ctypes.data, #q
286            self.result.ctypes.data,   # results
287            real(cutoff), # cutoff
288            ]
289        self.kernel(*args)
290        return self.result[:-3]
291
292    def release(self):
293        """
294        Release any resources associated with the kernel.
295        """
296        pass
Note: See TracBrowser for help on using the repository browser.