Created
March 14, 2013 12:58
-
-
Save jgillis/5161094 to your computer and use it in GitHub Desktop.
Parse m-functions in casadi
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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