1 | """ |
---|
2 | Automatically translate python models to C |
---|
3 | """ |
---|
4 | from __future__ import print_function |
---|
5 | |
---|
6 | import ast |
---|
7 | import inspect |
---|
8 | from functools import reduce |
---|
9 | |
---|
10 | import numpy as np |
---|
11 | |
---|
12 | from . import codegen |
---|
13 | from . import special |
---|
14 | |
---|
15 | # pylint: disable=unused-import |
---|
16 | try: |
---|
17 | from types import ModuleType |
---|
18 | #from .modelinfo import ModelInfo # circular import |
---|
19 | except ImportError: |
---|
20 | pass |
---|
21 | # pylint: enable=unused-import |
---|
22 | |
---|
23 | DEPENDENCY = { |
---|
24 | 'core_shell_kernel': ['lib/core_shell.c'], |
---|
25 | 'fractal_sq': ['lib/fractal_sq.c'], |
---|
26 | 'gfn4': ['lib/gfn.c'], |
---|
27 | 'polevl': ['lib/polevl.c'], |
---|
28 | 'p1evl': ['lib/polevl.c'], |
---|
29 | 'sas_2J1x_x': ['lib/polevl.c', 'lib/sas_J1.c'], |
---|
30 | 'sas_3j1x_x': ['lib/sas_3j1x_x.c'], |
---|
31 | 'sas_erf': ['lib/polevl.c', 'lib/sas_erf.c'], |
---|
32 | 'sas_erfc': ['lib/polevl.c', 'lib/sas_erf.c'], |
---|
33 | 'sas_gamma': ['lib/sas_gamma.c'], |
---|
34 | 'sas_J0': ['lib/polevl.c', 'lib/sas_J0.c'], |
---|
35 | 'sas_J1': ['lib/polevl.c', 'lib/sas_J1.c'], |
---|
36 | 'sas_JN': ['lib/polevl.c', 'lib/sas_J0.c', 'lib/sas_J1.c', 'lib/sas_JN.c'], |
---|
37 | 'sas_Si': ['lib/Si.c'], |
---|
38 | } |
---|
39 | |
---|
40 | DEFINES = frozenset("M_PI M_PI_2 M_PI_4 M_SQRT1_2 M_E NAN INFINITY M_PI_180 M_4PI_3".split()) |
---|
41 | |
---|
42 | def convert(info, module): |
---|
43 | # type: ("ModelInfo", ModuleType) -> bool |
---|
44 | """ |
---|
45 | convert Iq, Iqxy and form_volume to c |
---|
46 | """ |
---|
47 | # Check if there is already C code |
---|
48 | if info.source or info.c_code is not None: |
---|
49 | return |
---|
50 | |
---|
51 | public_methods = "Iq", "Iqxy", "form_volume" |
---|
52 | |
---|
53 | tagged = [] # type: List[str] |
---|
54 | translate = [] # type: List[Callable] |
---|
55 | for function_name in public_methods: |
---|
56 | function = getattr(info, function_name) |
---|
57 | if callable(function): |
---|
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 | code = {} # type: Dict[str, str] |
---|
66 | depends = {} # type: Dict[str, List[str]] |
---|
67 | while translate: |
---|
68 | function_name, function = translate.pop(0) |
---|
69 | filename = function.__code__.co_filename |
---|
70 | offset = function.__code__.co_firstlineno |
---|
71 | refs = function.__code__.co_names |
---|
72 | depends[function_name] = set(refs) |
---|
73 | source = inspect.getsource(function) |
---|
74 | for name in refs: |
---|
75 | if name in tagged or name in DEFINES: |
---|
76 | continue |
---|
77 | tagged.append(name) |
---|
78 | obj = getattr(module, name, None) |
---|
79 | if obj is None: |
---|
80 | pass # ignore unbound variables for now |
---|
81 | #raise ValueError("global %s is not defined" % name) |
---|
82 | elif callable(obj): |
---|
83 | if getattr(special, name, None): |
---|
84 | # special symbol: look up depenencies |
---|
85 | libs.extend(DEPENDENCY.get(name, [])) |
---|
86 | else: |
---|
87 | # not special: add function to translate stack |
---|
88 | translate.append((name, obj)) |
---|
89 | elif isinstance(obj, float): |
---|
90 | code[name] = "const double %s = %.15g\n"%(name, obj) |
---|
91 | elif isinstance(obj, int): |
---|
92 | code[name] = "const int %s = %d\n"%(name, obj) |
---|
93 | elif isinstance(obj, (list, tuple, np.ndarray)): |
---|
94 | vals = ", ".join("%.15g"%v for v in obj) |
---|
95 | code[name] = "const double %s[] = {%s};\n" %(name, vals) |
---|
96 | elif isinstance(obj, special.Gauss): |
---|
97 | libs.append('lib/gauss%d.c'%obj.n) |
---|
98 | source = (source.replace(name+'.n', 'GAUSS_N') |
---|
99 | .replace(name+'.z', 'GAUSS_Z') |
---|
100 | .replace(name+'.w', 'GAUSS_W')) |
---|
101 | else: |
---|
102 | raise TypeError("Could not convert global %s of type %s" |
---|
103 | % (name, str(type(obj)))) |
---|
104 | |
---|
105 | tree = ast.parse(source) |
---|
106 | snippet = codegen.to_source(tree) #, filename, offset) |
---|
107 | code[function_name] = snippet |
---|
108 | |
---|
109 | # remove duplicates from the dependecy list |
---|
110 | unique_libs = [] |
---|
111 | for filename in libs: |
---|
112 | if filename not in unique_libs: |
---|
113 | unique_libs.append(filename) |
---|
114 | |
---|
115 | info.source = unique_libs |
---|
116 | info.c_code = "\n".join(code[k] for k in ordered_dag(depends) if k in code) |
---|
117 | |
---|
118 | info.Iq = info.Iqxy = info.form_volume = None |
---|
119 | |
---|
120 | print("source", info.source) |
---|
121 | print(info.c_code) |
---|
122 | |
---|
123 | raise RuntimeError("not yet converted...") |
---|
124 | |
---|
125 | |
---|
126 | # Modified from the following: |
---|
127 | # |
---|
128 | # http://code.activestate.com/recipes/578272-topological-sort/ |
---|
129 | # Copyright (C) 2012 Sam Denton |
---|
130 | # License: MIT |
---|
131 | def ordered_dag(dag): |
---|
132 | # type: (Dict[T, Set[T]]) -> Iterator[T] |
---|
133 | dag = dag.copy() |
---|
134 | |
---|
135 | # make leaves depend on the empty set |
---|
136 | leaves = reduce(set.union, dag.values()) - set(dag.keys()) |
---|
137 | dag.update({node: set() for node in leaves}) |
---|
138 | while True: |
---|
139 | leaves = set(node for node, links in dag.items() if not links) |
---|
140 | if not leaves: |
---|
141 | break |
---|
142 | for node in leaves: |
---|
143 | yield node |
---|
144 | dag = {node: (links-leaves) |
---|
145 | for node, links in dag.items() if node not in leaves} |
---|
146 | if dag: |
---|
147 | raise ValueError("Cyclic dependes exists amongst these items:\n%s" |
---|
148 | % ", ".join(str(node) for node in dag.keys())) |
---|