source: sasmodels/sasmodels/autoc.py @ 15be191

Last change on this file since 15be191 was 15be191, checked in by Paul Kienzle <pkienzle@…>, 6 years ago

Fix line breaks so there is only one space between lines

  • Property mode set to 100644
File size: 4.7 KB
Line 
1"""
2Automatically translate python models to C
3"""
4from __future__ import print_function
5
6import inspect
7
8import numpy as np
9
10from . import py2c
11from . import special
12
13# pylint: disable=unused-import
14try:
15    from types import ModuleType
16    #from .modelinfo import ModelInfo  # circular import
17except ImportError:
18    pass
19# pylint: enable=unused-import
20
21DEPENDENCY = {
22    'core_shell_kernel': ['lib/core_shell.c'],
23    'fractal_sq': ['lib/fractal_sq.c'],
24    'gfn4': ['lib/gfn.c'],
25    'polevl': ['lib/polevl.c'],
26    'p1evl': ['lib/polevl.c'],
27    'sas_2J1x_x': ['lib/polevl.c', 'lib/sas_J1.c'],
28    'sas_3j1x_x': ['lib/sas_3j1x_x.c'],
29    'sas_erf': ['lib/polevl.c', 'lib/sas_erf.c'],
30    'sas_erfc': ['lib/polevl.c', 'lib/sas_erf.c'],
31    'sas_gamma': ['lib/sas_gamma.c'],
32    'sas_J0': ['lib/polevl.c', 'lib/sas_J0.c'],
33    'sas_J1': ['lib/polevl.c', 'lib/sas_J1.c'],
34    'sas_JN': ['lib/polevl.c', 'lib/sas_J0.c', 'lib/sas_J1.c', 'lib/sas_JN.c'],
35    'sas_Si': ['lib/Si.c'],
36}
37
38DEFINES = frozenset("M_PI M_PI_2 M_PI_4 M_SQRT1_2 M_E NAN INFINITY M_PI_180 M_4PI_3".split())
39
40def convert(info, module):
41    # type: ("ModelInfo", ModuleType) -> bool
42    """
43    convert Iq, Iqxy and form_volume to c
44    """
45    # Check if there is already C code
46    if info.source or info.c_code is not None:
47        return
48
49    public_methods = "Iq", "Iqac", "Iqabc", "Iqxy", "form_volume"
50
51    tagged = [] # type: List[str]
52    translate = [] # type: List[Callable]
53    for function_name in public_methods:
54        function = getattr(info, function_name)
55        if callable(function):
56            if getattr(function, 'vectorized', None):
57                return  # Don't try to translate vectorized code
58            tagged.append(function_name)
59            translate.append((function_name, function))
60    if not translate:
61        # nothing to translate---maybe Iq, etc. are already C snippets?
62        return
63
64    libs = []  # type: List[str]
65    snippets = []  # type: List[str]
66    constants = {} # type: Dict[str, Any]
67    code = {}  # type: Dict[str, str]
68    depends = {}  # type: Dict[str, List[str]]
69    while translate:
70        function_name, function = translate.pop(0)
71        filename = function.__code__.co_filename
72        escaped_filename = filename.replace('\\', '\\\\')
73        offset = function.__code__.co_firstlineno
74        refs = function.__code__.co_names
75        depends[function_name] = set(refs)
76        source = inspect.getsource(function)
77        for name in refs:
78            if name in tagged or name in DEFINES:
79                continue
80            tagged.append(name)
81            obj = getattr(module, name, None)
82            if obj is None:
83                pass # ignore unbound variables for now
84                #raise ValueError("global %s is not defined" % name)
85            elif callable(obj):
86                if getattr(special, name, None):
87                    # special symbol: look up depenencies
88                    libs.extend(DEPENDENCY.get(name, []))
89                else:
90                    # not special: add function to translate stack
91                    translate.append((name, obj))
92            elif isinstance(obj, (int, float, list, tuple, np.ndarray)):
93                constants[name] = obj
94                # Claim all constants are declared on line 1
95                snippets.append('#line 1 "%s"\n'%escaped_filename)
96                snippets.append(py2c.define_constant(name, obj))
97            elif isinstance(obj, special.Gauss):
98                for var, value in zip(("N", "Z", "W"), (obj.n, obj.z, obj.w)):
99                    var = "GAUSS_"+var
100                    constants[var] = value
101                    snippets.append('#line 1 "%s"\n'%escaped_filename)
102                    snippets.append(py2c.define_constant(var, value))
103                #libs.append('lib/gauss%d.c'%obj.n)
104                source = (source.replace(name+'.n', 'GAUSS_N')
105                          .replace(name+'.z', 'GAUSS_Z')
106                          .replace(name+'.w', 'GAUSS_W'))
107            else:
108                raise TypeError("Could not convert global %s of type %s"
109                                % (name, str(type(obj))))
110
111        # add (possibly modified) source to set of functions to compile
112        code[function_name] = (source, filename, offset)
113
114    # remove duplicates from the dependecy list
115    unique_libs = []
116    for filename in libs:
117        if filename not in unique_libs:
118            unique_libs.append(filename)
119
120    # translate source
121    ordered_code = [code[name] for name in py2c.ordered_dag(depends) if name in code]
122    functions = py2c.translate(ordered_code, constants)
123    snippets.extend(functions)
124
125    # update model info
126    info.source = unique_libs
127    info.c_code = "".join(snippets)
128    info.Iq = info.Iqac = info.Iqabc = info.Iqxy = info.form_volume = None
Note: See TracBrowser for help on using the repository browser.