[go: up one dir, main page]

Menu

[r1]: / libermate.py  Maximize  Restore  History

Download this file

393 lines (357 with data), 12.0 kB

  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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
#
# LiberMate
#
# Copyright (C) 2009 Eric C. Schug
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
__author__ = "Eric C. Schug (schugschug@gmail.com)"
__version__ = "0.1"
__copyright__ = "Copyright (c) 2009 Eric C. Schug"
__license__ = "GNU General Public License"
__revision__ = "$Id$"
# Standard Python
import sys
import re
from copy import copy
import glob
import os
import stat
### class "calcLexer extends Lexer" will generate python
### module "calcLexer" with class "Lexer".
import MatlabLexer
import MatlabParser
import Mat2Py
import antlr
import CommandLine
import pprint
def ASTtoTree(ast):
a=ast
b=[]
while a:
c=ASTtoTree(a.getFirstChild())
if(c):
b.append(((MatlabParse._tokenNames[a.getType()],a.getText()),c))
else:
b.append(((MatlabParse._tokenNames[a.getType()],a.getText()),None))
a=a.getNextSibling()
return b
python_priority = {
"": -3,
"=": -3,
",": -1,
"lambda": 0,
"or": 1,
"and": 2,
"not": 3,
">": 6,
"<": 6,
"<=": 6,
">=": 6,
"==": 6,
"!=": 6,
"|": 7,
"^": 8,
"&": 9,
"+": 11,
"-": 11,
"*": 12,
"/": 12,
" +": 13,
" -": 13,
"~": 14,
"**": 15,
".": 16,
":": 0,
}
# n = numel(A) returns the number of elements, n, in array A.
class MatParse(MatlabParser.Parser):
'Higher level logic for parser'
def __init__(self, *args, **kwargs):
MatlabParse.Parser.__init__(self, *args, **kwargs)
self.vars=set()
self.funcs=set()
self.is_dot=False
self.inside_args=False
def new_scope(self):
self.vars=set()
self.funcs=set()
def get_scope(self):
ast=self.astFactory.create(MatlabParse.SCOPE,", ".join(self.vars)+"\n #Functions "+", ".join(self.funcs))
print 'The following appear to be variables:'
print ' ',", ".join(self.vars)
print 'The following appear to be functions:'
print ' ',", ".join(self.funcs)
return ast
def as_global(self,vartoken):
vartoken.setType(MatlabParse.VAR)
self.vars.add(vartoken.getText())
def as_var(self,vartoken):
vartoken.setType(MatlabParse.VAR)
self.vars.add(vartoken.getText())
def as_func(self,functoken):
self.funcs.add(functoken.getText())
def var_lookup(self,vartoken):
#print("Checking var",vartoken.getText())
if(self.is_dot or (vartoken.getText() in self.vars)):
vartoken.setType(MatlabParse.VAR)
else:
self.as_func(vartoken)
def var_names(self):
return list(self.vars)
def print_tree(self,tree):
pprint.pprint(ASTtoTree(tree))
sys.stdout.flush()
import keyword
class Mat2PyTrans(Mat2Py.Walker):
'Higher level logic for translator'
def __init__(self):
Mat2PyWalker.Walker.__init__(self)
self.nl="\n"
self.in_var=False
self.indcnt=0
self.indent=""
self.is_simple_rhs=False
self.is_lhs=False
self.token_stack=[]
self.mapping={'size':'shape.Error',
'ndims':'Error.ndim',
'eps':'finfo(float).eps',
'i':'1j',
'find':'nonzero',
'rand':'random.rand',
'meshgrid':'mgridError',
'repmat':'tileError',
'max':'maximumError',
'norm':'linalg.norm',
'bitand':'&Error',
'bitor':'|Error',
'inv':'linalg.inv',
'pinv':'linalg.pinv',
'chol':'linalg.cholesky',
'eig':'linalg.eig',
'qr':'scipy.linalg.qr',
'lu':'scipy.linalg.lu',
'conjgrad':'scipy.linalg.cg',
'regress':'linalg.lstsqError',
'decimate':'scipy.signal.resampleError',
'assert':'assertError',
}
def incr(self):
self.indcnt+=1
self.indent=" "*(self.indcnt*4)
self.nl="\n"+self.indent
#print 'increment "'+self.indent+'"'
def decr(self):
self.indcnt-=1
self.indent=" "*(self.indcnt*4)
self.nl="\n"+self.indent
#print 'decrement "'+self.indent+'"'
def Lookup(self,name):
if(name in self.mapping):
return self.mapping[name]
if(keyword.iskeyword(name)):
if(name!='assert'):
name=name+'_rename'
return name
def bop(self,op,a,b):
if(not a):
a='Error'
if(not b):
b='Error'
k=a+op+b
if(python_priority[self.ptoken]<python_priority[op.strip()]):
return '('+k+')'
else:
return k
def preop(self,op,a):
if(not a):
a='Error'
k=op+a
#print 'preop', self.ptoken
if(python_priority[self.ptoken]<python_priority[op.strip()]):
return '('+k+')'
else:
return k
def multiop(self,op,c):
k=op.join(c)
if(python_priority[self.ptoken]<python_priority[op.strip()]):
return '('+k+')'
else:
return k
def colonop(self,a,b,c):
if( self.in_var):
if(not a and not b):
sstr=":"
else:
if(a.replace('.','').isdigit()):
a=str(int(float(a))-1)
else:
a="("+a+")-1"
if(c):
if(c=='xend'):
c=''
sstr=a+":"+c+":"+b
else:
if(b=='xend'):
b=''
sstr=a+":"+b
else:
if(not a and not b):
sstr="Error:Error"
else:
if(c):
if(c.replace('.','').isdigit()):
c=str(float(c)-1)
else:
c="("+c+")+1"
sstr="arange("+a+", "+c+", "+b+")"
else:
if(b.replace('.','').isdigit()):
b=str(float(b)-1)
else:
b="("+b+")+1"
sstr="arange("+a+", "+b+")"
return sstr
def join_args(self,cc,braces=False,ptoken=None):
def mapper(ii):
if(":" in ii):
return ii
elif(ii.isdigit()):
return str(int(ii)-1)
else:
return '('+ii+')-1'
if(self.in_var or self.is_lhs or ptoken=="VAR"):
if(braces):
sstr=".cell["
else:
sstr="["
cc=[mapper(ii) for ii in cc]
k=",".join(cc)
if(k==':' and not self.is_lhs and not braces):
return '.flatten(1)'
else:
sstr+=k
if(braces):
sstr+="]"
else:
sstr+="]"
else:
if(braces):
sstr=".cell_getattr("+", ".join(cc)+")"
else:
sstr="("+", ".join(cc)+")"
return sstr
class MainApp(CommandLine.App):
usage_str='[options] [matfile]...'
about_str='Translates MATLAB files matfile (.m) to Python (.py)'
def __init__(self):
# Specify configuration options build an array of options defined as
# [Name, shortkey, description, type, default]
#type can be 'str','dir','file','bool','num', or a list of strings (enumeration)
self.config_options=[
['help','h','display help and quit','bool',False],
#TODO ['output','o','log output to file ARG','file','workit.log'],
#TODO ['quite','','run silently hush all but prompts','bool',False],
]
args=self.command_line()
self.files=[]
for ifile in args:
#files=glob.glob(ifile)
files=[ifile]
self.files.extend(files)
for filename in self.files:
try:
stat_info=os.stat(filename)
except OSError, desc:
print 'Error: could not open file %s' % filename
sys.exit(2)
if(stat.S_ISDIR(stat_info[stat.ST_MODE])):
print 'Error: %s is a directory but should be a file' % filename
sys.exit(2)
if filename.replace('.m','.py') == filename:
print "Error: file %s must have a .m suffix" % filename
sys.exit(2)
print self.files
#self.main()
def main(self):
for filename in files:
f = file(filename, "r")
lexer = MatlabLexer.Lexer(f) ### create a lexer for calculator
print 'Starting Parser'
p = MatParse(lexer)
p.script()
print 'Parser Complete'
a=p.getAST()
b=ASTtoTree(a)
#pprint.pprint( b)
#c=ASTtoXML(a)
walk=TestWalker()
print "Starting Translator"
s=walk.script(a)
#Simple conversions
s=re.sub(r'pi\(\)','pi',s)
s=re.sub(r'Inf\(\)','inf',s)
s=re.sub(r'nan\(\)','nan',s)
s=re.sub(r'matdiv\((.+?),\ (\d+)\)',r'(\1)/\2',s)
s=re.sub(r'matdiv\((\d+),\ ',r'\1/(',s)
s=re.sub(r'dot\((.+?),\ (\d+)\)',r'(\1)*\2',s)
s=re.sub(r'dot\((\d+),\ ',r'\1*(',s)
s=re.sub(r'shape\.Error\(([\w\.]+),\ ([\w\.]+)\)',r'\1.shape[\2-1]',s)
s=re.sub(r'shape\.Error\((\w+)\)',r'\1.shape',s)
s=re.sub(r'\.flatten\(1\)\.conj\(\)\.T',r'.flatten(0).conj()',s)
s=re.sub(r'\.flatten\(1\)\.T',r'.flatten(0)',s)
print 'Translation Complete'
#print p.var_names()
outfile=filename.replace('.m','.py')
print 'writing to file',outfile
f=open(outfile,'w')
f.write( """
from numpy import *
import scipy
""")
f.write(s)
f.close()
def testLexer(files):
'do quick scan of selected files'
#files=glob.glob('/home/eric/Downloads/mpi-ikl-simplemkl-1.0/*.m')
quick_scan(files)
def testLexer(filename):
'test parsing of specified file'
f = file(filename, "r")
lexer = MatlabLexer.Lexer(f) ### create a lexer for calculator
pcount=0
for token in lexer:
## do something with token
print token.getText(),
if token.getType() in [MatlabParse.END,MatlabParse.ARRAY_END,MatlabParse.STRING,MatlabParse.TRANS]:
print "\\"+str(pcount)+MatlabParse._tokenNames[token.getType()]+'/',
if(token.getType() in [MatlabParse.LPAREN,MatlabParse.LBRACE,MatlabParse.ATPAREN]):
pcount+=1
print '\\'+str(pcount)+'/',
if(token.getType() in [MatlabParse.RPAREN,MatlabParse.RBRACE]):
pcount-=1
print '\\'+str(pcount)+'/',
def testParser(files):
'Test parsing of specified files'
for filename in files:
f = file(filename, "r")
lexer = MatlabLexer.Lexer(f) ### create a lexer for calculator
p = MatParse(lexer)
p.script()
a=p.getAST()
b=ASTtoTree(a)
def main():
app=MainApp()
if __name__ == "__main__":
main()