-
Notifications
You must be signed in to change notification settings - Fork 2
/
codegen.py
175 lines (144 loc) · 5.75 KB
/
codegen.py
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
from sympy import *
from sympy.printing.ccode import *
from helpers import *
import math
class MyPrinter(CCodePrinter):
def __init__(self,settings={}):
CCodePrinter.__init__(self, settings)
self.known_functions = {
"Abs": [(lambda x: not x.is_integer, "fabsf")],
"gamma": "tgammaf",
"sin": "sinf",
"cos": "cosf",
"tan": "tanf",
"asin": "asinf",
"acos": "acosf",
"atan": "atanf",
"atan2": "atan2f",
"exp": "expf",
"log": "logf",
"erf": "erff",
"sinh": "sinhf",
"cosh": "coshf",
"tanh": "tanhf",
"asinh": "asinhf",
"acosh": "acoshf",
"atanh": "atanhf",
"floor": "floorf",
"ceiling": "ceilf",
}
def _print_Pow(self, expr):
if "Pow" in self.known_functions:
return self._print_Function(expr)
PREC = precedence(expr)
if expr.exp == -1:
return '1.0/%s' % (self.parenthesize(expr.base, PREC))
elif expr.exp < 0:
expr = 1/expr
if expr.exp == 0.5:
return 'sqrtf(%s)' % self._print(expr.base)
elif expr.exp.is_integer and expr.exp <= 4:
return '*'.join([self._print(expr.base) for _ in range(expr.exp)])
else:
return 'powf(%s, %s)' % (self._print(expr.base),
self._print(expr.exp))
def generateCode(jsondict, cfile):
# extract filter operations
filterOps = {}
for n,fn in jsondict.iteritems():
filterOps[n.upper()] = loadExprsFromJSON(fn)['funcs']
hashdefines = []
hashdefines.extend(getConstants(filterOps))
for k in sorted(filterOps.keys()):
hashdefines.extend(getSnippetDefines(k,filterOps[k]))
with open(cfile, 'w') as f:
f.truncate()
f.write(getHeader(hashdefines, 'EKF_'))
print('Generated code saved to %s'%(cfile,))
def getConstants(filterOps):
max_num_subx = 0
for k,v in filterOps.iteritems():
max_num_subx = max(len(v['subx']['ret']),max_num_subx)
x = filterOps['COVPRED']['cov']['params']['x']
u = filterOps['COVPRED']['cov']['params']['u']
ret = []
ret.append(('NUM_STATES', x.rows))
ret.append(('NUM_CONTROL_INPUTS', u.rows))
ret.append(('MAX_NUM_SUBX', max_num_subx))
for r in range(x.rows):
ret.append(('STATE_IDX_'+str(x[r,0]).upper(), r))
for r in range(u.rows):
ret.append(('U_IDX_'+str(u[r,0]).upper(), r))
return ret
def getSnippetDefines(opname, funcs):
ret = []
for retName,func in funcs.iteritems():
retParamName = '__RET_'+retName.upper()
paramlist = []
substitutions = []
for paramname in sorted(func['params'].keys()):
if not isinstance(func['params'][paramname], MatrixBase):
func['params'][paramname] = Matrix([[func['params'][paramname]]])
nr,nc = func['params'][paramname].shape
paramlist.append('__'+paramname.upper())
if (nr,nc) == (1,1):
substitutions += zip(func['params'][paramname], Matrix(nr,nc, [Symbol(paramlist[-1])]))
elif nc == 1:
substitutions += zip(func['params'][paramname], Matrix(nr,nc, symbols(paramlist[-1]+'[0:%u]'%(nr,))))
else:
substitutions += zip(func['params'][paramname], Matrix(nr,nc, symbols(paramlist[-1]+'[0:%u][0:%u]'%(nr,nc))))
if 'retsymbols' in func:
if not isinstance(func['retsymbols'], MatrixBase):
func['retsymbols'] = Matrix([[func['retsymbols']]])
nr,nc = func['retsymbols'].shape
if (nr,nc) == (1,1):
substitutions += zip(func['retsymbols'], Matrix(nr,nc, [Symbol(retParamName)]))
elif nc == 1:
substitutions += zip(func['retsymbols'], Matrix(nr,nc, symbols(retParamName+'[0:%u]'%(nr,))))
else:
substitutions += zip(func['retsymbols'], Matrix(nr,nc, symbols(retParamName+'[0:%u][0:%u]'%(nr,nc))))
func['ret'] = func['ret'].xreplace(dict(substitutions))
defineName = '%s_CALC_%s(%s)' % (opname,retName.upper(),','.join(paramlist+[retParamName]))
ret.append((defineName,getSnippet(retParamName,func['ret'])))
return ret
def getSnippet(retParamName, outputMatrix):
if not isinstance(outputMatrix, MatrixBase):
outputMatrix = Matrix([[outputMatrix]])
outputMatrix = outputMatrix
nr,nc = outputMatrix.shape
if (nr,nc) == (1,1):
retMatrix = Matrix(nr,nc, [Symbol(retParamName)])
elif nc == 1:
retMatrix = Matrix(nr,nc, symbols(retParamName+'[0:%u]'%(nr,)))
else:
retMatrix = Matrix(nr,nc, symbols(retParamName+'[0:%u][0:%u]'%(nr,nc)))
ret = ''
for assignee,expr in zip(retMatrix,outputMatrix):
ret += double2float(MyPrinter().doprint(expr, assignee))+' '
return str(ret)
def double2float(string):
import re
string = re.sub(r"[0-9]+\.[0-9]+", '\g<0>f', string)
return string
def wrapstring(string, linemax, delim):
strings = string.split(' ')
lines = [strings[0]]
for s in strings[1:]:
if len(lines[-1]) != 0 and len(lines[-1])+len(s) > linemax:
lines.append(s)
else:
lines[-1] += ' '+s
return delim.join(lines)
def getHeader(hashdefines, prefix=''):
ret = '/*\n'
for (key,val) in hashdefines:
if type(val) is str:
ret += prefix+key+'\n'
ret += '*/\n\n'
for (key,val) in hashdefines:
if type(val) is str:
val = wrapstring(str(val),100,' \\\n')
ret += '\n#define %s%s \\\n%s\n' % (prefix,key,val)
else:
ret += '#define %s%s %s\n' % (prefix,key,val)
return ret