File: ext_tools.py

package info (click to toggle)
python-scipy 0.18.1-2
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 75,464 kB
  • ctags: 79,406
  • sloc: python: 143,495; cpp: 89,357; fortran: 81,650; ansic: 79,778; makefile: 364; sh: 265
file content (482 lines) | stat: -rw-r--r-- 17,820 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
from __future__ import absolute_import, print_function

import os
import sys
import re

from . import catalog
from . import build_tools
from . import converters
from . import base_spec


class ext_function_from_specs(object):
    def __init__(self,name,code_block,arg_specs):
        self.name = name
        self.arg_specs = base_spec.arg_spec_list(arg_specs)
        self.code_block = code_block
        self.compiler = ''
        self.customize = base_info.custom_info()

    def header_code(self):
        pass

    def function_declaration_code(self):
        code = 'static PyObject* %s(PyObject*self, PyObject* args,' \
                ' PyObject* kywds)\n{\n'
        return code % self.name

    def template_declaration_code(self):
        code = 'template<class T>\n' \
               'static PyObject* %s(PyObject*self, PyObject* args,' \
               ' PyObject* kywds)\n{\n'
        return code % self.name

    #def cpp_function_declaration_code(self):
    #    pass
    #def cpp_function_call_code(self):
    #s    pass

    def parse_tuple_code(self):
        """ Create code block for PyArg_ParseTuple.  Variable declarations
            for all PyObjects are done also.

            This code got a lot uglier when I added local_dict...
        """

        declare_return = 'py::object return_val;\n' \
                         'int exception_occurred = 0;\n' \
                         'PyObject *py_local_dict = NULL;\n'
        arg_string_list = self.arg_specs.variable_as_strings() + ['"local_dict"']
        arg_strings = ','.join(arg_string_list)
        if arg_strings:
            arg_strings += ','
        declare_kwlist = 'static const char *kwlist[] = {%s NULL};\n' % \
                         arg_strings

        py_objects = ', '.join(self.arg_specs.py_pointers())
        init_flags = ', '.join(self.arg_specs.init_flags())
        init_flags_init = '= '.join(self.arg_specs.init_flags())
        py_vars = ' = '.join(self.arg_specs.py_variables())
        if py_objects:
            declare_py_objects = 'PyObject ' + py_objects + ';\n'
            declare_py_objects += 'int ' + init_flags + ';\n'
            init_values = py_vars + ' = NULL;\n'
            init_values += init_flags_init + ' = 0;\n\n'
        else:
            declare_py_objects = ''
            init_values = ''

        #Each variable is in charge of its own cleanup now.
        #cnt = len(arg_list)
        #declare_cleanup = "blitz::TinyVector<PyObject*,%d> clean_up(0);\n" % cnt

        ref_string = ', '.join(self.arg_specs.py_references())
        if ref_string:
            ref_string += ', &py_local_dict'
        else:
            ref_string = '&py_local_dict'

        format = "O" * len(self.arg_specs) + "|O" + ':' + self.name
        parse_tuple = 'if(!PyArg_ParseTupleAndKeywords(args,' \
                             'kywds,"%s",const_cast<char**>(kwlist),%s))\n' % \
                             (format,ref_string)
        parse_tuple += '   return NULL;\n'

        return declare_return + declare_kwlist + declare_py_objects  \
               + init_values + parse_tuple

    def arg_declaration_code(self):
        arg_strings = []
        for arg in self.arg_specs:
            arg_strings.append(arg.declaration_code())
            arg_strings.append(arg.init_flag() + " = 1;\n")
        code = "".join(arg_strings)
        return code

    def arg_cleanup_code(self):
        arg_strings = []
        have_cleanup = filter(lambda x:x.cleanup_code(),self.arg_specs)
        for arg in have_cleanup:
            code = "if(%s)\n" % arg.init_flag()
            code += "{\n"
            code += indent(arg.cleanup_code(),4)
            code += "}\n"
            arg_strings.append(code)
        code = "".join(arg_strings)
        return code

    def arg_local_dict_code(self):
        arg_strings = []
        for arg in self.arg_specs:
            arg_strings.append(arg.local_dict_code())
        code = "".join(arg_strings)
        return code

    def function_code(self):
        decl_code = indent(self.arg_declaration_code(),4)
        cleanup_code = indent(self.arg_cleanup_code(),4)
        function_code = indent(self.code_block,4)
        local_dict_code = indent(self.arg_local_dict_code(),4)

        dict_code = "if(py_local_dict)                                  \n"   \
                    "{                                                  \n"   \
                    "    py::dict local_dict = py::dict(py_local_dict); \n" + \
                         local_dict_code + \
                    "}                                                  \n"

        try_code = "try                              \n"   \
                      "{                                \n" + \
                           decl_code + \
                      "    /*<function call here>*/     \n" + \
                           function_code + \
                           indent(dict_code,4) + \
                      "\n}                                \n"
        catch_code = "catch(...)                       \n"   \
                      "{                                \n" + \
                      "    return_val =  py::object();      \n"   \
                      "    exception_occurred = 1;       \n"   \
                      "}                                \n"

        return_code = "    /*cleanup code*/                     \n" + \
                           cleanup_code + \
                      '    if(!(PyObject*)return_val && !exception_occurred)\n'   \
                      '    {\n                                  \n'   \
                      '        return_val = Py_None;            \n'   \
                      '    }\n                                  \n'   \
                      '    return return_val.disown();           \n'           \
                      '}                                \n'

        all_code = self.function_declaration_code() + \
                       indent(self.parse_tuple_code(),4) + \
                       indent(try_code,4) + \
                       indent(catch_code,4) + \
                       return_code

        return all_code

    def python_function_definition_code(self):
        args = (self.name, self.name)
        function_decls = '{"%s",(PyCFunction)%s , METH_VARARGS|' \
                          'METH_KEYWORDS},\n' % args
        return function_decls

    def set_compiler(self,compiler):
        self.compiler = compiler
        for arg in self.arg_specs:
            arg.set_compiler(compiler)


class ext_function(ext_function_from_specs):
    def __init__(self,name,code_block, args, local_dict=None, global_dict=None,
                 auto_downcast=1, type_converters=None):

        call_frame = sys._getframe().f_back
        if local_dict is None:
            local_dict = call_frame.f_locals
        if global_dict is None:
            global_dict = call_frame.f_globals
        if type_converters is None:
            type_converters = converters.default
        arg_specs = assign_variable_types(args,local_dict, global_dict,
                                          auto_downcast, type_converters)
        ext_function_from_specs.__init__(self,name,code_block,arg_specs)


from . import base_info


class ext_module(object):
    def __init__(self,name,compiler=''):
        standard_info = converters.standard_info
        self.name = name
        self.functions = []
        self.compiler = compiler
        self.customize = base_info.custom_info()
        self._build_information = base_info.info_list(standard_info)

    def add_function(self,func):
        self.functions.append(func)

    def module_code(self):
        code = '\n'.join([
            """\
#ifdef __CPLUSPLUS__
extern "C" {
#endif
""",
            self.warning_code(),
            self.header_code(),
            self.support_code(),
            self.function_code(),
            self.python_function_definition_code(),
            self.module_init_code(),
            """\
#ifdef __CPLUSCPLUS__
}
#endif
"""
            ])
        return code

    def arg_specs(self):
        all_arg_specs = base_spec.arg_spec_list()
        for func in self.functions:
            all_arg_specs += func.arg_specs
        return all_arg_specs

    def build_information(self):
        info = self._build_information + [self.customize] + \
               self.arg_specs().build_information()
        for func in self.functions:
            info.append(func.customize)
        #redundant, but easiest place to make sure compiler is set
        for i in info:
            i.set_compiler(self.compiler)
        return info

    def get_headers(self):
        all_headers = self.build_information().headers()

        # blitz/array.h always needs to go before most other headers, so we
        # hack that here, but we need to ensure that Python.h is the very
        # first header included.  As indicated in

        # http://docs.python.org/api/includes.html

        # "Warning:  Since Python may define some pre-processor definitions which
        # affect the standard headers on some systems, you must include Python.h
        # before any standard headers are included. "

        # Since blitz/array.h pulls in system headers, we must massage this
        # list a bit so that the order is Python.h, blitz/array.h, ...

        if '"blitz/array.h"' in all_headers:
            all_headers.remove('"blitz/array.h"')
            # Insert blitz AFTER Python.h, which must remain the first header
            all_headers.insert(1,'"blitz/array.h"')
        return all_headers

    def warning_code(self):
        all_warnings = self.build_information().warnings()
        w = map(lambda x: "#pragma warning(%s)\n" % x,all_warnings)
        return '#ifndef __GNUC__\n' + ''.join(w) + '\n#endif'

    def header_code(self):
        h = self.get_headers()
        h = map(lambda x: '#include ' + x + '\n',h)
        return ''.join(h) + '\n'

    def support_code(self):
        code = self.build_information().support_code()
        return ''.join(code) + '\n'

    def function_code(self):
        all_function_code = ""
        for func in self.functions:
            all_function_code += func.function_code()
        return ''.join(all_function_code) + '\n'

    def python_function_definition_code(self):
        all_definition_code = ""
        for func in self.functions:
            all_definition_code += func.python_function_definition_code()
        all_definition_code = indent(''.join(all_definition_code),4)
        code = 'static PyMethodDef compiled_methods[] = \n' \
               '{\n' \
               '%s' \
               '    {NULL,      NULL}        /* Sentinel */\n' \
               '};\n'
        return code % (all_definition_code)

    def module_init_code(self):
        init_code_list = self.build_information().module_init_code()
        init_code = indent(''.join(init_code_list),4)
        code = 'PyMODINIT_FUNC init%s(void)\n' \
               '{\n' \
               '%s' \
               '    (void) Py_InitModule("%s", compiled_methods);\n' \
               '}\n' % (self.name,init_code,self.name)
        return code

    def generate_file(self,file_name="",location='.'):
        code = self.module_code()
        if not file_name:
            file_name = self.name + '.cpp'
        name = generate_file_name(file_name,location)
        #return name
        return generate_module(code,name)

    def set_compiler(self,compiler):
        # This is not used anymore -- I think we should ditch it.
        #for i in self.arg_specs()
        #    i.set_compiler(compiler)
        for i in self.build_information():
            i.set_compiler(compiler)
        for i in self.functions:
            i.set_compiler(compiler)
        self.compiler = compiler

    def build_kw_and_file(self,location,kw):
        arg_specs = self.arg_specs()
        info = self.build_information()
        _source_files = info.sources()
        # remove duplicates
        source_files = {}
        for i in _source_files:
            source_files[i] = None
        source_files = source_files.keys()

        # add internally specified macros, includes, etc. to the key words
        # values of the same names so that distutils will use them.
        kw['define_macros'] = kw.get('define_macros',[]) + \
                              info.define_macros()
        kw['include_dirs'] = kw.get('include_dirs',[]) + info.include_dirs()
        kw['libraries'] = kw.get('libraries',[]) + info.libraries()
        kw['library_dirs'] = kw.get('library_dirs',[]) + info.library_dirs()
        kw['extra_compile_args'] = kw.get('extra_compile_args',[]) + \
                                   info.extra_compile_args()
        kw['extra_link_args'] = kw.get('extra_link_args',[]) + \
                                   info.extra_link_args()
        kw['sources'] = kw.get('sources',[]) + source_files
        file = self.generate_file(location=location)
        return kw,file

    def setup_extension(self,location='.',**kw):
        kw,file = self.build_kw_and_file(location,kw)
        return build_tools.create_extension(file, **kw)

    def compile(self,location='.',compiler=None, verbose=0, **kw):

        if compiler is not None:
            self.compiler = compiler

        # !! removed -- we don't have any compiler dependent code
        # currently in spec or info classes
        # hmm.  Is there a cleaner way to do this?  Seems like
        # choosing the compiler spagettis around a little.
        #compiler = build_tools.choose_compiler(self.compiler)
        #self.set_compiler(compiler)

        kw,file = self.build_kw_and_file(location,kw)

        # This is needed so that files build correctly even when different
        # versions of Python are running around.
        # Imported at beginning of file now to help with test paths.
        # import catalog
        #temp = catalog.default_temp_dir()
        # for speed, build in the machines temp directory
        temp = catalog.intermediate_dir()

        success = build_tools.build_extension(file, temp_dir=temp,
                                              compiler_name=compiler,
                                              verbose=verbose, **kw)
        if not success:
            raise SystemError('Compilation failed')


def generate_file_name(module_name,module_location):
    module_file = os.path.join(module_location,module_name)
    return os.path.abspath(module_file)


def generate_module(module_string, module_file):
    """ generate the source code file.  Only overwrite
        the existing file if the actual source has changed.
    """
    file_changed = 1
    if os.path.exists(module_file):
        f = open(module_file,'r')
        old_string = f.read()
        f.close()
        if old_string == module_string:
            file_changed = 0
    if file_changed:
        f = open(module_file,'w')
        f.write(module_string)
        f.close()
    return module_file


def assign_variable_types(variables,local_dict={}, global_dict={},
                          auto_downcast=1,
                          type_converters=converters.default):
    incoming_vars = {}
    incoming_vars.update(global_dict)
    incoming_vars.update(local_dict)
    variable_specs = []
    errors = {}
    for var in variables:
        try:
            example_type = incoming_vars[var]

            # look through possible type specs to find which one
            # should be used to for example_type
            spec = None
            for factory in type_converters:
                if factory.type_match(example_type):
                    spec = factory.type_spec(var,example_type)
                    break
            if not spec:
                # should really define our own type.
                raise IndexError
            else:
                variable_specs.append(spec)
        except KeyError:
            errors[var] = ("The type and dimensionality specifications" +
                           "for variable '" + var + "' are missing.")
        except IndexError:
            errors[var] = ("Unable to convert variable '" + var +
                           "' to a C++ type.")
    if errors:
        raise TypeError(format_error_msg(errors))

    if auto_downcast:
        variable_specs = downcast(variable_specs)
    return variable_specs


def downcast(var_specs):
    """ Cast python scalars down to most common type of
         arrays used.

         Right now, focus on complex and float types. Ignore int types.
         Require all arrays to have same type before forcing downcasts.

         Note: var_specs are currently altered in place (horrors...!)
    """
    numeric_types = []

    #grab all the numeric types associated with a variables.
    for var in var_specs:
        if hasattr(var,'numeric_type'):
            numeric_types.append(var.numeric_type)

    # if arrays are present, but none of them are double precision,
    # make all numeric types float or complex(float)
    if (('f' in numeric_types or 'F' in numeric_types) and not (
            'd' in numeric_types or 'D' in numeric_types)):
        for var in var_specs:
            if hasattr(var,'numeric_type'):
                if issubclass(var.numeric_type, complex):
                    var.numeric_type = 'F'
                elif issubclass(var.numeric_type, float):
                    var.numeric_type = 'f'
    return var_specs


def indent(st,spaces):
    indention = ' '*spaces
    indented = indention + st.replace('\n','\n'+indention)
    # trim off any trailing spaces
    indented = re.sub(r' +$',r'',indented)
    return indented


def format_error_msg(errors):
    #minimum effort right now...
    import pprint
    import cStringIO
    msg = cStringIO.StringIO()
    pprint.pprint(errors,msg)
    return msg.getvalue()