Skip to content

Instantly share code, notes, and snippets.

@jgillis
Created March 14, 2013 12:58
Show Gist options
  • Save jgillis/5161094 to your computer and use it in GitHub Desktop.
Save jgillis/5161094 to your computer and use it in GitHub Desktop.
Parse m-functions in casadi
import casadi
import re
class MFunctionParser:
def parse(self,filename):
f = open(filename,"r")
signature = f.readline()
m = re.search("function \[?([\w,]+)\]? = \w+\((.*)\)",signature)
if not m:
raise Exception("Parse error %s" %signature)
outputs = m.group(1).split(",")
inputs = m.group(2)
inputSX = casadi.ssym("["+inputs+"]")
evaldict = dict(zip(inputs.split(","),inputSX))
for l in f.readlines():
m = re.search("(\w+) = (.*);",l)
if m:
tvar = m.group(1)
expr = m.group(2)
expr = re.sub("\.[*]","*",expr)
expr = re.sub("\.\^","**",expr)
expr = re.sub("\./","/",expr)
expr = re.sub(";",",",expr)
evaldict[tvar] = eval(expr,casadi.__dict__,evaldict)
f = casadi.SXFunction([inputSX],[casadi.vertcat(evaldict[o]) for o in outputs])
f.init()
return f
if __name__ == "__main__":
p = MFunctionParser()
f = p.parse("matcode_NATURAL.m")
print f
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment