source: sasmodels/sasmodels/autoc.py @ 765d025

Last change on this file since 765d025 was 765d025, checked in by Paul Kienzle <pkienzle@…>, 5 years ago

Merge remote-tracking branch 'upstream/beta_approx'

  • Property mode set to 100644
File size: 5.0 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_gammaln': ['lib/sas_gammainc.c'],
33    'sas_gammainc': ['lib/sas_gammainc.c'],
34    'sas_gammaincc': ['lib/sas_gammainc.c'],
35    'sas_J0': ['lib/polevl.c', 'lib/sas_J0.c'],
36    'sas_J1': ['lib/polevl.c', 'lib/sas_J1.c'],
37    'sas_JN': ['lib/polevl.c', 'lib/sas_J0.c', 'lib/sas_J1.c', 'lib/sas_JN.c'],
38    'sas_Si': ['lib/Si.c'],
39}
40
41DEFINES = frozenset("M_PI M_PI_2 M_PI_4 M_SQRT1_2 M_E NAN INFINITY M_PI_180 M_4PI_3".split())
42
43def convert(info, module):
44    # type: ("ModelInfo", ModuleType) -> bool
45    """
46    Convert Iq, Iqxy, form_volume, etc. to c
47
48    Returns list of warnings
49    """
50    # Check if there is already C code
51    if info.source or info.c_code is not None:
52        return
53
54    public_methods = ("Iq", "Iqac", "Iqabc", "Iqxy", 
55            "form_volume", "shell_volume", "effective_radius")
56
57    tagged = [] # type: List[str]
58    translate = [] # type: List[Callable]
59    for function_name in public_methods:
60        function = getattr(info, function_name)
61        if callable(function):
62            if getattr(function, 'vectorized', None):
63                return  # Don't try to translate vectorized code
64            tagged.append(function_name)
65            translate.append((function_name, function))
66    if not translate:
67        # nothing to translate---maybe Iq, etc. are already C snippets?
68        return
69
70    libs = []  # type: List[str]
71    snippets = []  # type: List[str]
72    constants = {} # type: Dict[str, Any]
73    code = {}  # type: Dict[str, str]
74    depends = {}  # type: Dict[str, List[str]]
75    while translate:
76        function_name, function = translate.pop(0)
77        filename = function.__code__.co_filename
78        escaped_filename = filename.replace('\\', '\\\\')
79        offset = function.__code__.co_firstlineno
80        refs = function.__code__.co_names
81        depends[function_name] = set(refs)
82        source = inspect.getsource(function)
83        for name in refs:
84            if name in tagged or name in DEFINES:
85                continue
86            tagged.append(name)
87            obj = getattr(module, name, None)
88            if obj is None:
89                pass # ignore unbound variables for now
90                #raise ValueError("global %s is not defined" % name)
91            elif callable(obj):
92                if getattr(special, name, None):
93                    # special symbol: look up depenencies
94                    libs.extend(DEPENDENCY.get(name, []))
95                else:
96                    # not special: add function to translate stack
97                    translate.append((name, obj))
98            elif isinstance(obj, (int, float, list, tuple, np.ndarray)):
99                constants[name] = obj
100                # Claim all constants are declared on line 1
101                snippets.append('#line 1 "%s"\n'%escaped_filename)
102                snippets.append(py2c.define_constant(name, obj))
103            elif isinstance(obj, special.Gauss):
104                for var, value in zip(("N", "Z", "W"), (obj.n, obj.z, obj.w)):
105                    var = "GAUSS_"+var
106                    constants[var] = value
107                    snippets.append('#line 1 "%s"\n'%escaped_filename)
108                    snippets.append(py2c.define_constant(var, value))
109                #libs.append('lib/gauss%d.c'%obj.n)
110                source = (source.replace(name+'.n', 'GAUSS_N')
111                          .replace(name+'.z', 'GAUSS_Z')
112                          .replace(name+'.w', 'GAUSS_W'))
113            else:
114                raise TypeError("Could not convert global %s of type %s"
115                                % (name, str(type(obj))))
116
117        # add (possibly modified) source to set of functions to compile
118        code[function_name] = (source, filename, offset)
119
120    # remove duplicates from the dependecy list
121    unique_libs = []
122    for filename in libs:
123        if filename not in unique_libs:
124            unique_libs.append(filename)
125
126    # translate source
127    ordered_code = [code[name] for name in py2c.ordered_dag(depends) if name in code]
128    functions, warnings = py2c.translate(ordered_code, constants)
129    snippets.extend(functions)
130
131    # update model info
132    info.source = unique_libs
133    info.c_code = "".join(snippets)
134    info.Iq = info.Iqac = info.Iqabc = info.Iqxy = info.form_volume = None
135
136    return warnings
137
Note: See TracBrowser for help on using the repository browser.