Changeset 24212


Ignore:
Timestamp:
10/11/19 00:24:15 (5 years ago)
Author:
bdef
Message:

CHG: syntax cahnge to meet most of Pep8 requirement

Location:
issm/trunk-jpl/scripts
Files:
6 edited

Legend:

Unmodified
Added
Removed
  • issm/trunk-jpl/scripts/BinRead.py

    r24201 r24212  
    1 #! /usr/bin/env python
    2 
    3 import os
     1#! / usr / bin / env python
     2import numpy as np
     3from os import environ, path
    44import sys
    5 import numpy
    6 import math
    75import struct
    8 import argparse
    9 
    10 def BinRead(filin,filout='',verbose=0): #{{{
    11 
    12         print "reading binary file."
    13         f=open(filin,'rb')
    14 
    15         if filout:
    16                 sys.stdout=open(filout,'w')
    17 
    18         while True:
    19                 try:
    20                         #Step 1: read size of record name
    21                         recordnamesize=struct.unpack('i',f.read(struct.calcsize('i')))[0]
    22                 except struct.error as e:
    23                         print "probable EOF: %s" % e
    24                         break
    25 
    26                 print "============================================================================"
    27                 if verbose>2:
    28                         print "\nrecordnamesize = \"%d\"" % (recordnamesize)
    29                 recordname=struct.unpack('%ds' % recordnamesize,f.read(recordnamesize))[0]
    30                 print "field: %s" % recordname
    31 
    32                 #Step 2: read the data itself.
    33                 #first read length of record
    34                 reclen=struct.unpack('q',f.read(struct.calcsize('q')))[0]
    35                 if verbose>1:
    36                         print "reclen = %d" % reclen
    37 
    38                 #read data code:
    39                 code=struct.unpack('i',f.read(struct.calcsize('i')))[0]
    40                 #print "code = %d (%s)" % (code,CodeToFormat(code))
    41                 print "Format = %s" % CodeToFormat(code)
    42 
    43                 if   code == FormatToCode('Boolean'):
    44 #                       bval=struct.unpack('b',f.read(reclen-struct.calcsize('i')))[0]
    45                         bval=struct.unpack('i',f.read(reclen-struct.calcsize('i')))[0]
    46                         print "value = %d" % bval
    47 
    48                 elif code == FormatToCode('Integer'):
    49                         ival=struct.unpack('i',f.read(reclen-struct.calcsize('i')))[0]
    50                         print "value = %d" % ival
    51 
    52                 elif code == FormatToCode('Double'):
    53                         dval=struct.unpack('d',f.read(reclen-struct.calcsize('i')))[0]
    54                         print "value = %f" % dval
    55 
    56                 elif code == FormatToCode('String'):
    57                         strlen=struct.unpack('i',f.read(struct.calcsize('i')))[0]
    58                         if verbose>1:
    59                                 print "strlen = %d" % strlen
    60                         sval=struct.unpack('%ds' % strlen,f.read(strlen))[0]
    61                         print "value = '%s'" % sval
    62 
    63                 elif code == FormatToCode('BooleanMat'):
    64                         #read matrix type:
    65                         mattype=struct.unpack('i',f.read(struct.calcsize('i')))[0]
    66                         print "mattype = %d" % mattype
    67 
    68                         #now read matrix
    69                         s=[0,0]
    70                         s[0]=struct.unpack('i',f.read(struct.calcsize('i')))[0]
    71                         s[1]=struct.unpack('i',f.read(struct.calcsize('i')))[0]
    72                         print "size = [%dx%d]" % (s[0],s[1])
    73                         data=numpy.zeros((s[0],s[1]))
    74                         for i in xrange(s[0]):
    75                                 for j in xrange(s[1]):
    76                                         data[i][j]=struct.unpack('d',f.read(struct.calcsize('d')))[0]    #get to the "c" convention, hence the transpose
    77                                         if verbose>2: print "data[%d,%d] = %f" % (i,j,data[i][j])
    78 
    79                 elif code == FormatToCode('IntMat'):
    80                         #read matrix type:
    81                         mattype=struct.unpack('i',f.read(struct.calcsize('i')))[0]
    82                         print "mattype = %d" % mattype
    83 
    84                         #now read matrix
    85                         s=[0,0]
    86                         s[0]=struct.unpack('i',f.read(struct.calcsize('i')))[0]
    87                         s[1]=struct.unpack('i',f.read(struct.calcsize('i')))[0]
    88                         print "size = [%dx%d]" % (s[0],s[1])
    89                         data=numpy.zeros((s[0],s[1]))
    90                         for i in xrange(s[0]):
    91                                 for j in xrange(s[1]):
    92                                         data[i][j]=struct.unpack('d',f.read(struct.calcsize('d')))[0]    #get to the "c" convention, hence the transpose
    93                                         if verbose>2: print "data[%d,%d] = %f" % (i,j,data[i][j])
    94 
    95                 elif code == FormatToCode('DoubleMat'):
    96                         #read matrix type:
    97                         mattype=struct.unpack('i',f.read(struct.calcsize('i')))[0]
    98                         print "mattype = %d" % mattype
    99 
    100                         #now read matrix
    101                         s=[0,0]
    102                         s[0]=struct.unpack('i',f.read(struct.calcsize('i')))[0]
    103                         s[1]=struct.unpack('i',f.read(struct.calcsize('i')))[0]
    104                         print "size = [%dx%d]" % (s[0],s[1])
    105                         data=numpy.zeros((s[0],s[1]))
    106                         for i in xrange(s[0]):
    107                                 for j in xrange(s[1]):
    108                                         data[i][j]=struct.unpack('d',f.read(struct.calcsize('d')))[0]    #get to the "c" convention, hence the transpose
    109                                         if verbose>2: print "data[%d,%d] = %f" % (i,j,data[i][j])
    110 
    111                 elif code == FormatToCode('MatArray'):
    112                         f.seek(reclen-4,1)
    113                         print "skipping %d bytes for code %d." % (reclen-4, code)
    114 
    115                 elif code == FormatToCode('StringArray'):
    116                         f.seek(reclen-4,1)
    117                         print "skipping %d bytes for code %d." % (reclen-4, code)
    118 
    119                 elif code == FormatToCode('CompressedMat'):
    120                         print "still need to implement reading for code %d." % code
    121 
    122                 else:
    123                         raise TypeError('BinRead error message: data type: %d not supported yet! (%s)' % (code, recordname))
    124 
    125         f.close()
     6from argparse import ArgumentParser
     7
     8
     9def BinRead(filin, filout='', verbose=0):  #{{{
     10
     11    print("reading binary file.")
     12    f = open(filin, 'rb')
     13
     14    if filout:
     15        sys.stdout = open(filout, 'w')
     16
     17    while True:
     18        try:
     19            #Step 1: read size of record name
     20            recordnamesize = struct.unpack('i', f.read(struct.calcsize('i')))[0]
     21        except struct.error as e:
     22            print("probable EOF: {}".format(e))
     23            break
     24
     25        print("============================================================================ ")
     26        if verbose > 2:
     27            print("\n recordnamesize = {}".format(recordnamesize))
     28        recordname = struct.unpack('{}s'.format(recordnamesize), f.read(recordnamesize))[0]
     29        print("field: {}".format(recordname))
     30
     31        #Step 2: read the data itself.
     32        #first read length of record
     33        #reclen = struct.unpack('i', f.read(struct.calcsize('i')))[0]
     34        reclen = struct.unpack('q', f.read(struct.calcsize('q')))[0]
     35        if verbose > 1:
     36            print("reclen = {}".format(reclen))
     37
     38        #read data code:
     39        code = struct.unpack('i', f.read(struct.calcsize('i')))[0]
     40        print("Format = {} (code {})".format(CodeToFormat(code), code))
     41
     42        if code == FormatToCode('Boolean'):
     43            bval = struct.unpack('i', f.read(reclen - struct.calcsize('i')))[0]
     44            print("value = {}".format(bval))
     45
     46        elif code == FormatToCode('Integer'):
     47            ival = struct.unpack('i', f.read(reclen - struct.calcsize('i')))[0]
     48            print("value = {}".format(ival))
     49
     50        elif code == FormatToCode('Double'):
     51            dval = struct.unpack('d', f.read(reclen - struct.calcsize('i')))[0]
     52            print("value = {}".format(dval))
     53
     54        elif code == FormatToCode('String'):
     55            strlen = struct.unpack('i', f.read(struct.calcsize('i')))[0]
     56            if verbose > 1:
     57                print("strlen = {}".format(strlen))
     58            sval = struct.unpack('{}s'.format(strlen), f.read(strlen))[0]
     59            print("value = '{}'".format(sval))
     60
     61        elif code == FormatToCode('BooleanMat'):
     62            #read matrix type:
     63            mattype = struct.unpack('i', f.read(struct.calcsize('i')))[0]
     64            print("mattype = {}".format(mattype))
     65
     66            #now read matrix
     67            s = [0, 0]
     68            s[0] = struct.unpack('i', f.read(struct.calcsize('i')))[0]
     69            s[1] = struct.unpack('i', f.read(struct.calcsize('i')))[0]
     70            print("size = [{}x{}]".format(s[0], s[1]))
     71            data = np.zeros((s[0], s[1]))
     72            for i in range(s[0]):
     73                for j in range(s[1]):
     74                    data[i][j] = struct.unpack('d', f.read(struct.calcsize('d')))[0]    #get to the "c" convention, hence the transpose
     75                    if verbose > 2:
     76                        print("data[{}, {}] = {}".format(i, j, data[i][j]))
     77
     78        elif code == FormatToCode('IntMat'):
     79            #read matrix type:
     80            mattype = struct.unpack('i', f.read(struct.calcsize('i')))[0]
     81            print("mattype = {}".format(mattype))
     82
     83            #now read matrix
     84            s = [0, 0]
     85            s[0] = struct.unpack('i', f.read(struct.calcsize('i')))[0]
     86            s[1] = struct.unpack('i', f.read(struct.calcsize('i')))[0]
     87            print("size = [{}x{}]".format(s[0], s[1]))
     88            data = np.zeros((s[0], s[1]))
     89            for i in range(s[0]):
     90                for j in range(s[1]):
     91                    data[i][j] = struct.unpack('d', f.read(struct.calcsize('d')))[0]    #get to the "c" convention, hence the transpose
     92                    if verbose > 2:
     93                        print("data[{}, {}] = {}".format(i, j, data[i][j]))
     94
     95        elif code == FormatToCode('DoubleMat'):
     96            #read matrix type:
     97            mattype = struct.unpack('i', f.read(struct.calcsize('i')))[0]
     98            print("mattype = {}".format(mattype))
     99
     100            #now read matrix
     101            s = [0, 0]
     102            s[0] = struct.unpack('i', f.read(struct.calcsize('i')))[0]
     103            s[1] = struct.unpack('i', f.read(struct.calcsize('i')))[0]
     104            print("size = [{}x{}]".format(s[0], s[1]))
     105            data = np.zeros((s[0], s[1]))
     106            for i in range(s[0]):
     107                for j in range(s[1]):
     108                    data[i][j] = struct.unpack('d', f.read(struct.calcsize('d')))[0]    #get to the "c" convention, hence the transpose
     109                    if verbose > 2:
     110                        print("data[{}, {}] = {}".format(i, j, data[i][j]))
     111
     112        elif code == FormatToCode('MatArray'):
     113            f.seek(reclen - 4, 1)
     114            print("skipping {} bytes for code {}.".format(code, reclen - 4))
     115        elif code == FormatToCode('StringArray'):
     116            f.seek(reclen - 4, 1)
     117            print("skipping {} bytes for code {}.".format(code, reclen - 4))
     118
     119        else:
     120            raise TypeError('BinRead error message: data type: {} not supported yet! ({})'.format(code, recordname))
     121
     122    f.close()
    126123#}}}
    127 def FormatToCode(format): # {{{
    128         """
    129         This routine takes the format string, and hardcodes it into an integer, which
    130         is passed along the record, in order to identify the nature of the dataset being
    131         sent.
    132         """
    133         if format=='Boolean':
    134                 code=1
    135         elif format=='Integer':
    136                 code=2
    137         elif format=='Double':
    138                 code=3
    139         elif format=='String':
    140                 code=4
    141         elif format=='BooleanMat':
    142                 code=5
    143         elif format=='IntMat':
    144                 code=6
    145         elif format=='DoubleMat':
    146                 code=7
    147         elif format=='MatArray':
    148                 code=8
    149         elif format=='StringArray':
    150                 code=9
    151         elif format=='CompressedMat':
    152                 code=10
    153         else:
    154                 raise InputError('FormatToCode error message: data type %s not supported yet!' % format)
    155 
    156         return code
     124
     125
     126def FormatToCode(format):  # {{{
     127    """
     128    This routine takes the format string, and hardcodes it into an integer, which
     129    is passed along the record, in order to identify the nature of the dataset being
     130    sent.
     131    """
     132
     133    if format == 'Boolean':
     134        code = 1
     135    elif format == 'Integer':
     136        code = 2
     137    elif format == 'Double':
     138        code = 3
     139    elif format == 'String':
     140        code = 4
     141    elif format == 'BooleanMat':
     142        code = 5
     143    elif format == 'IntMat':
     144        code = 6
     145    elif format == 'DoubleMat':
     146        code = 7
     147    elif format == 'MatArray':
     148        code = 8
     149    elif format == 'StringArray':
     150        code = 9
     151    else:
     152        raise IOError('FormatToCode error message: data type not supported yet!')
     153
     154    return code
    157155# }}}
    158 def CodeToFormat(code): # {{{
    159         """
    160         This routine takes the format string, and hardcodes it into an integer, which
    161         is passed along the record, in order to identify the nature of the dataset being
    162         sent.
    163         """
    164         if code==1:
    165                 format='Boolean'
    166         elif code==2:
    167                 format='Integer'
    168         elif code==3:
    169                 format='Double'
    170         elif code==4:
    171                 format='String'
    172         elif code==5:
    173                 format='BooleanMat'
    174         elif code==6:
    175                 format='IntMat'
    176         elif code==7:
    177                 format='DoubleMat'
    178         elif code==8:
    179                 format='MatArray'
    180         elif code==9:
    181                 format='StringArray'
    182         elif code==10:
    183                 format='CompressedMat'
    184         else:
    185                 raise TypeError('CodeToFormat error message: code %d not supported yet!' % code)
    186 
    187         return format
     156
     157
     158def CodeToFormat(code):  # {{{
     159    """
     160    This routine takes the format string, and hardcodes it into an integer, which
     161    is passed along the record, in order to identify the nature of the dataset being
     162    sent.
     163    """
     164
     165    if code == 1:
     166        format = 'Boolean'
     167    elif code == 2:
     168        format = 'Integer'
     169    elif code == 3:
     170        format = 'Double'
     171    elif code == 4:
     172        format = 'String'
     173    elif code == 5:
     174        format = 'BooleanMat'
     175    elif code == 6:
     176        format = 'IntMat'
     177    elif code == 7:
     178        format = 'DoubleMat'
     179    elif code == 8:
     180        format = 'MatArray'
     181    elif code == 9:
     182        format = 'StringArray'
     183    else:
     184        raise TypeError('FormatToCode error message: code {} not supported yet!'.format(code))
     185
     186    return format
    188187# }}}
    189188
    190 if __name__ == '__main__': #{{{
    191         if 'PYTHONSTARTUP' in os.environ:
    192                 PYTHONSTARTUP=os.environ['PYTHONSTARTUP']
    193                 print 'PYTHONSTARTUP =',PYTHONSTARTUP
    194                 if os.path.exists(PYTHONSTARTUP):
    195                         try:
    196                                 execfile(PYTHONSTARTUP)
    197                         except Exception as e:
    198                                 print "PYTHONSTARTUP error: ",e
    199                 else:
    200                         print "PYTHONSTARTUP file '%s' does not exist." % PYTHONSTARTUP
    201 
    202         parser = argparse.ArgumentParser(description='BinRead - function to read binary input file.')
    203         parser.add_argument('-f','--filin', help='name of binary input file', default='')
    204         parser.add_argument('-o','--filout', help='optional name of text output file', default='')
    205         parser.add_argument('-v','--verbose', help='optional level of output', default=0)
    206         args = parser.parse_args()
    207 
    208         BinRead(args.filin, args.filout,args.verbose)
     189
     190if __name__ == '__main__':  #{{{
     191    if 'PYTHONSTARTUP' in environ:
     192        PYTHONSTARTUP = environ['PYTHONSTARTUP']
     193        print('PYTHONSTARTUP = {}'.format(PYTHONSTARTUP))
     194        if path.exists(PYTHONSTARTUP):
     195            try:
     196                exec(compile(open(PYTHONSTARTUP).read(), PYTHONSTARTUP, 'exec'), globals())
     197
     198            except Exception as e:
     199                print("PYTHONSTARTUP error: ", e)
     200        else:
     201            print("PYTHONSTARTUP file '{}' does not exist.".format(PYTHONSTARTUP))
     202
     203    parser = ArgumentParser(description='BinRead - function to read binary input file.')
     204    parser.add_argument(' -f', ' --filin', help='name of binary input file', default='')
     205    parser.add_argument(' -o', ' --filout', help='optional name of text output file', default='')
     206    parser.add_argument(' -v', ' --verbose', help='optional level of output', default=0)
     207    args = parser.parse_args()
     208
     209    BinRead(args.filin, args.filout, args.verbose)
    209210#}}}
  • issm/trunk-jpl/scripts/DownloadExternalPackage.py

    r23393 r24212  
    1 #!/usr/bin/env python
    2 # -*- coding: ISO-8859-1 -*-
     1#! / usr / bin / env python
     2# - * - coding: ISO - 8859 - 1 - * -
    33
    4 import os,sys
     4import os
     5import sys
    56import urllib
    67
    78#Check inputs
    8 if(len(sys.argv)!=3): raise NameError('usage: ./DownloadExternalPackage.py URL localfile')
     9if(len(sys.argv) != 3):
     10    raise NameError('usage: . / DownloadExternalPackage.py URL localfile')
    911
    10 url=sys.argv[1];
    11 localFile=sys.argv[2]
     12url = sys.argv[1]
     13localFile = sys.argv[2]
    1214
    1315#Remove file if it already exists
    1416if os.path.exists(localFile):
    15         print "File "+ localFile +" already exists and will not be downloaded..."
    16         sys.exit()
     17    print("File " + localFile + " already exists and will not be downloaded...")
     18    sys.exit()
    1719
    1820#Try to download from url
    19 httpfail=-1
     21httpfail = -1
    2022try:
    21         print "Fetching %s" % localFile
    22         urllib.urlretrieve(url,localFile)
    23         httpfail=0
    24 except Exception, e:
    25         httpfail=1
    26 
    27 #Error message in case it failed
    28 if (httpfail):
    29         failureMessage = '''
    30 ===========================================================================
    31 Unable to download package %s from: %s
    32 * If URL specified manually - perhaps there is a typo?
    33 * If your network is disconnected - please reconnect
    34 * Alternatively, you can download the above URL manually
    35 ===========================================================================
    36 ''' % (localFile,url)
    37         raise RuntimeError(failureMessage)
     23    print("Fetching %s" % localFile)
     24    urllib.request(url, localFile)
     25    httpfail = 0
     26except urllib.error.URLError as e:
     27    failureMessage = '''
     28   ===========================================================================
     29    Unable to download package {} from: {} due to {}
     30    * If URL specified manually - perhaps there is a typo?
     31    * If your network is disconnected - please reconnect
     32    * Alternatively, you can download the above URL manually
     33   ===========================================================================
     34    '''.format(localFile, url, e)
     35    print(failureMessage)
  • issm/trunk-jpl/scripts/cloc2html.py

    r17912 r24212  
    1 #!/usr/bin/env python
    2 # -*- coding: ISO-8859-1 -*-
    3 #inspired from http://qwiki.stanford.edu/images/d/df/Latex2qwiki.txt
    4 import sys, re, os
     1#! / usr / bin / env python
     2# - * - coding: ISO - 8859 - 1 - * -
     3#inspired from http: / / qwiki.stanford.edu / images / d / df / Latex2qwiki.txt
     4import re
     5import os
    56
    6 ISSM_DIR=os.getenv('ISSM_DIR');
    7 if(not ISSM_DIR): raise NameError('ISSM_DIR undefined')
     7ISSM_DIR = os.getenv('ISSM_DIR')
     8if(not ISSM_DIR):
     9    raise NameError('ISSM_DIR undefined')
    810
    9 infile  = open('temp','r')
    10 outfile = open('temp.html','w')
    11 file_text  = infile.readlines()
     11infile = open('temp', 'r')
     12outfile = open('temp.html', 'w')
     13file_text = infile.readlines()
    1214
    1315#write header
    14 outfile.write('<table width="600px" rules=none border=0 bordercolor="#000000" cellpadding="3" align="center" style="border-collapse:collapse;">\n')
    15 style_r='style="text-align:right;"'
    16 style_c='style="text-align:center;"'
    17 style_l='style="text-align:left;"'
    18 color = ' bgcolor=#7AA9DD ' #dark blue
    19 color1 = ' bgcolor=#C6E2FF ' #light blue
    20 color2 = ' bgcolor=#FFFFFF ' #white
     16outfile.write(' < table width = "600px" rules = none border = 0 bordercolor = "#000000" cellpadding = "3" align = "center" style = "border - collapse:collapse;" > \n')
     17style_r = 'style="text - align:right;"'
     18style_c = 'style="text - align:center;"'
     19style_l = 'style="text - align:left;"'
     20color = ' bgcolor=#7AA9DD '  #dark blue
     21color1 = ' bgcolor=#C6E2FF '  #light blue
     22color2 = ' bgcolor=#FFFFFF '  #white
    2123
    22 count = 0 
     24count = 0
    2325toggle = 0
    2426for i in range(len(file_text)):
    2527
    26         #Get current lines except if first line
    27         if(i==0): continue
    28         line = file_text[i]
     28    #Get current lines except if first line
     29    if(i == 0):
     30        continue
     31    line = file_text[i]
    2932
    30         pattern=r"----------------"
    31         if (re.search(pattern,line)):
    32                 count+=1
    33                 continue
     33    pattern = r"----------------"
     34    if (re.search(pattern, line)):
     35        count += 1
     36        continue
    3437
    35         if(count==1):
    36                 mystr = '<tr>\n'
    37                 column = 1
    38                 for i in line.split():
    39                         if(column==1): mystr += '<th '+color+style_l+'>'+i+'</th>'; column+=1
    40                         else:          mystr += '<th '+color+style_r+'>'+i+'</th>'
    41                 mystr += '<th '+color+style_r+'>Total</th>\n</th>\n'
    42         elif(count==2):
    43                 total  = 0
    44                 column = 1
    45                 if(toggle): mystr = '<tr>\n<th '+color1+style_l+'>'
    46                 else:       mystr = '<tr>\n<th '+color2+style_l+'>'
    47                 for i in line.split():
    48                         if(not i.isdigit() or (i.isdigit and int(i)==77)):
    49                                 mystr += ' '+i+' '
    50                         else:
    51                                 if(column==1): mystr += '</th>'
    52                                 if(column>=2): total += int(i)
    53                                 if(toggle): mystr += '<td '+color1+style_r+'>'+i+'</td>'
    54                                 else:       mystr += '<td '+color2+style_r+'>'+i+'</td>'
    55                                 column += 1
    56                 if(toggle): mystr += '<td '+color1+style_r+'>'+str(total)+'</td>\n</tr>\n'
    57                 else:       mystr += '<td '+color2+style_r+'>'+str(total)+'</td>\n</tr>\n'
    58                 toggle = 1 - toggle
    59         elif(count==3):
    60                 total  = 0
    61                 column = 1
    62                 if(toggle): mystr = '<tr>\n<th '+color1+style_l+'>'
    63                 else:       mystr = '<tr>\n<th '+color2+style_l+'>'
    64                 for i in line.split():
    65                         if(not i.isdigit()):
    66                                 mystr += ' '+i+' '
    67                         else:
    68                                 if(column==1): mystr += '</th>'
    69                                 if(column>=2): total += int(i)
    70                                 if(toggle): mystr += '<td '+color1+style_r+'>'+i+'</td>'
    71                                 else:       mystr += '<td '+color2+style_r+'>'+i+'</td>'
    72                                 column += 1
    73                 if(toggle): mystr += '<td '+color1+style_r+'>'+str(total)+'</td>\n</tr>\n'
    74                 else:       mystr += '<td '+color2+style_r+'>'+str(total)+'</td>\n</tr>\n'
    75         else:
    76                 continue
     38    if(count == 1):
     39        mystr = ' < tr > \n'
     40        column = 1
     41        for i in line.split():
     42            if(column == 1):
     43                mystr += '<th ' + color + style_l + '>' + i + '</th>'
     44                column += 1
     45            else:
     46                mystr += '<th ' + color + style_r + '>' + i + '</th>'
     47        mystr += '<th ' + color + style_r + '>Total</th>\n</th>\n'
     48    elif(count == 2):
     49        total = 0
     50        column = 1
     51        if(toggle):
     52            mystr = '<tr>\n<th ' + color1 + style_l + '>'
     53        else:
     54            mystr = '<tr>\n<th ' + color2 + style_l + '>'
     55        for i in line.split():
     56            if(not i.isdigit() or (i.isdigit and int(i) == 77)):
     57                mystr += ' ' + i + ' '
     58            else:
     59                if(column == 1):
     60                    mystr += '</th>'
     61                if(column >= 2):
     62                    total += int(i)
     63                if(toggle):
     64                    mystr += '<td ' + color1 + style_r + '>' + i + '</td>'
     65                else:
     66                    mystr += '<td ' + color2 + style_r + '>' + i + '</td>'
     67                column += 1
     68        if(toggle):
     69            mystr += '<td ' + color1 + style_r + '>' + str(total) + '</td>\n</tr>\n'
     70        else:
     71            mystr += '<td ' + color2 + style_r + '>' + str(total) + '</td>\n</tr>\n'
     72        toggle = 1 - toggle
     73    elif(count == 3):
     74        total = 0
     75        column = 1
     76        if(toggle):
     77            mystr = '<tr>\n<th ' + color1 + style_l + '>'
     78        else:
     79            mystr = '<tr>\n<th ' + color2 + style_l + '>'
     80        for i in line.split():
     81            if(not i.isdigit()):
     82                mystr += ' ' + i + ' '
     83            else:
     84                if(column == 1):
     85                    mystr += '</th>'
     86                if(column >= 2):
     87                    total += int(i)
     88                if(toggle):
     89                    mystr += '<td ' + color1 + style_r + '>' + i + '</td>'
     90                else:
     91                    mystr += '<td ' + color2 + style_r + '>' + i + '</td>'
     92                column += 1
     93        if(toggle):
     94            mystr += '<td ' + color1 + style_r + '>' + str(total) + '</td>\n</tr>\n'
     95        else:
     96            mystr += '<td ' + color2 + style_r + '>' + str(total) + '</td>\n</tr>\n'
     97    else:
     98        continue
    7799
    78         outfile.write(mystr)
     100    outfile.write(mystr)
    79101
    80102#write header
    81 outfile.write('</table>\n')
     103outfile.write(' </table>\n')
    82104
    83105#close all files
  • issm/trunk-jpl/scripts/convertmatlabclasses.py

    r12159 r24212  
    1 #!/usr/bin/env python
    2 # -*- coding: ISO-8859-1 -*-
    3 import sys, re, os, shutil
     1#! / usr / bin / env python
     2# - * - coding: ISO - 8859 - 1 - * -
     3import sys
     4import re
     5import os
     6import shutil
    47
    58#get names of all directories to process
    6 ISSM_DIR=os.getenv('ISSM_DIR');
    7 if(not ISSM_DIR): raise NameError('ISSM_DIR undefined')
     9ISSM_DIR = os.getenv('ISSM_DIR')
     10if(not ISSM_DIR):
     11    raise NameError('ISSM_DIR undefined')
    812newclassesdir = ISSM_DIR + '/src/m/classes/'
    913oldclassesdir = ISSM_DIR + '/src/m/oldclasses/'
    1014
    1115#make new directory
    12 if(os.path.exists(oldclassesdir)):shutil.rmtree(oldclassesdir)
     16if(os.path.exists(oldclassesdir)):
     17    shutil.rmtree(oldclassesdir)
    1318os.mkdir(oldclassesdir)
    1419
     
    1621#{{{
    1722subsasgntext = r'''
    18 function obj = subsasgn(obj,index,val)
    19 obj=builtin('subsasgn',obj,index,val);
     23function obj = subsasgn(obj, index, val)
     24obj = builtin('subsasgn', obj, index, val)
    2025'''
    2126subsreftext = r'''
    22 function obj = subsref(obj,index)
    23 obj=builtin('subsref',obj,index);
     27function obj = subsref(obj, index)
     28obj = builtin('subsref', obj, index)
    2429'''
    2530#}}}
     
    2833files = os.listdir(newclassesdir)
    2934for filename in files:
    30         newpath = newclassesdir + filename
    31         oldpath = oldclassesdir + filename
    32         if(filename==".svn"):         continue
    33         if(filename.endswith(".m")):  shutil.copy(newpath,oldpath)
    34         if(filename.startswith("@")): shutil.copytree(newpath,oldpath)
    35         if(filename=="clusters"):
    36                 files2 = os.listdir(newpath)
    37                 for filename2 in files2:
    38                         if(filename2==".svn"): continue
    39                         newpath = newclassesdir + filename +'/'+ filename2
    40                         oldpath = oldclassesdir + filename2
    41                         shutil.copy(newpath,oldpath)
    42         if(filename=="model"):
    43                 shutil.copy(newpath+'/model.m'     ,oldclassesdir+'model.m');
    44         if(filename=="qmu"):
    45                 shutil.copytree(newpath+'/@dakota_method',oldclassesdir+'/@dakota_method')
    46                 files2 = os.listdir(newpath)
    47                 for filename2 in files2:
    48                         if(filename2==".svn"): continue
    49                         if(filename2=="@dakota_method"): continue
    50                         newpath = newclassesdir + filename +'/'+ filename2
    51                         oldpath = oldclassesdir + filename2
    52                         shutil.copy(newpath,oldpath)
     35    newpath = newclassesdir + filename
     36    oldpath = oldclassesdir + filename
     37    if(filename == ".svn"):
     38        continue
     39    if(filename.endswith(".m")):
     40        shutil.copy(newpath, oldpath)
     41    if(filename.startswith("@")):
     42        shutil.copytree(newpath, oldpath)
     43    if(filename == "clusters"):
     44        files2 = os.listdir(newpath)
     45        for filename2 in files2:
     46            if(filename2 == ".svn"):
     47                continue
     48            newpath = newclassesdir + filename + '/' + filename2
     49            oldpath = oldclassesdir + filename2
     50            shutil.copy(newpath, oldpath)
     51    if(filename == "model"):
     52        shutil.copy(newpath + '/model.m', oldclassesdir + 'model.m')
     53    if(filename == "qmu"):
     54        shutil.copytree(newpath + '/@dakota_method', oldclassesdir + '/@dakota_method')
     55        files2 = os.listdir(newpath)
     56        for filename2 in files2:
     57            if(filename2 == ".svn"):
     58                continue
     59            if(filename2 == "@dakota_method"):
     60                continue
     61            newpath = newclassesdir + filename + '/' + filename2
     62            oldpath = oldclassesdir + filename2
     63            shutil.copy(newpath, oldpath)
    5364
    5465files = os.listdir(oldclassesdir)
    5566#prepare properties
    5667#{{{
    57 propertiesfile = open(oldclassesdir+'/properties.m','w')
    58 propertiesfile.write("function out=properties(classname)\n");
     68propertiesfile = open(oldclassesdir + '/properties.m', 'w')
     69propertiesfile.write("function out = properties(classname)\n")
    5970#}}}
    6071for file in files:
    61         if(not file.endswith(".m")): continue;
    62         print "converting " + file + " from new to old Matlab class definition..."
    63         infile     = open(oldclassesdir+file,'r')
    64         classname  = (re.compile(r"\.m")).sub("",file)
    65         dirname    = oldclassesdir+'/@'+classname
    66         step       = 0
    67         properties = ""
     72    if(not file.endswith(".m")):
     73        continue
     74    print("converting " + file + " from new to old Matlab class definition...")
     75    infile = open(oldclassesdir + file, 'r')
     76    classname = (re.compile(r"\.m")).sub("", file)
     77    dirname = oldclassesdir + '/@' + classname
     78    step = 0
     79    properties = ""
    6880
    69         #create directory
    70         if(not os.path.exists(dirname)):
    71                 #print "Directory " + dirname + " does not exist, creating...";
    72                 os.mkdir(dirname)
     81    #create directory
     82    if(not os.path.exists(dirname)):
     83        #print "Directory " + dirname + " does not exist, creating..."
     84        os.mkdir(dirname)
    7385
    74         #Process file
    75         file_text = infile.readlines()
    76         for i in range(len(file_text)-2):
    77                 mystr  = file_text[i];
     86    #Process file
     87    file_text = infile.readlines()
     88    for i in range(len(file_text) - 2):
     89        mystr = file_text[i]
    7890
    79                 if("properties" in mystr and step==0): step  = 1; continue
    80                 if("methods"    in mystr and step==1): step  = 2; continue
    81                 if("function "   in mystr and step==2): step += 1;
     91        if("properties" in mystr and step == 0):
     92            step = 1
     93            continue
     94        if("methods" in mystr and step == 1):
     95            step = 2
     96            continue
     97        if("function " in mystr and step == 2):
     98            step += 1
    8299
    83                 if(step==1):
    84                         if("end" in mystr): continue
    85                         property = mystr.lstrip();
    86                         property = re.sub(r"%.*$","",property);
    87                         property = re.sub(r"\n","",property);
    88                         if(len(property)):
    89                                 properties = properties + 'OBJ' + property + ";\n"
     100        if(step == 1):
     101            if("end" in mystr):
     102                continue
     103            property = mystr.lstrip()
     104            property = re.sub(r"%. * $", "", property)
     105            property = re.sub(r"\n", "", property)
     106            if(len(property)):
     107                properties = properties + 'OBJ' + property + ";\n"
    90108
    91                 if("function " in mystr):
     109        if("function " in mystr):
    92110
    93                         #close previous file
    94                         if(step>3): outfile.close()
     111            #close previous file
     112            if(step > 3):
     113                outfile.close()
    95114
    96                         #get function name
    97                         mystr2 = (re.compile("=")).sub(" ",mystr); #replaces equal signs by blank space
    98                         mystr2 = (re.compile("\(")).sub(" ( ",mystr2); #add blank spaces before and after (
    99                         list=mystr2.split();
    100                         for j in range(len(list)):
    101                                 word=list[j];
    102                                 if(word=='('): break
    103                         objectname   = list[1]
    104                         functionname = list[j-1]
    105                         objectname = re.sub("\[","",objectname);
    106                         objectname = re.sub("\]","",objectname);
    107                         if(functionname == "disp"): functionname = "display"
    108                         outfile = open(dirname + '/' + functionname + '.m','w')
     115            #get function name
     116            mystr2 = (re.compile("=")).sub(" ", mystr)  #replaces equal signs by blank space
     117            mystr2 = (re.compile(r"\(")).sub(" (", mystr2)  #add blank spaces before and after (
     118            list = mystr2.split()
     119            for j in range(len(list)):
     120                word = list[j]
     121                if(word == '('):
     122                    break
     123            objectname = list[1]
     124            functionname = list[j - 1]
     125            objectname = re.sub(r"\[", "", objectname)
     126            objectname = re.sub(r"\]", "", objectname)
     127            if(functionname == "disp"):
     128                functionname = "display"
     129            outfile = open(dirname + '/' + functionname + '.m', 'w')
    109130
    110                         #deal with constructor
    111                         if(functionname==classname):
     131            #deal with constructor
     132            if(functionname == classname):
    112133
    113                                 properties2 = re.sub("OBJ",objectname + '.',properties);
    114                                 #write function declaration
    115                                 outfile.write(mystr)
    116                                 #write properties
    117                                 outfile.write(properties2)
    118                                 #write set class
    119                                 outfile.write(objectname + "=class(" + objectname + ",'" + classname + "');\n")
     134                properties2 = re.sub("OBJ", objectname + '.', properties)
     135                #write function declaration
     136                outfile.write(mystr)
     137                #write properties
     138                outfile.write(properties2)
     139                #write set class
     140                outfile.write(objectname + "=class(" + objectname + ", '" + classname + "');\n")
    120141
    121                                 #update properties list
    122                                 properties2=properties2.split('\n')
    123                                 propertiesfile2 = open(dirname + '/properties.m','w')
    124                                 propertiesfile2.write("function out=properties(obj),\n")
    125                                 propertiesfile2.write('\tout=cell('+str(len(properties2)-1)+',1);\n')
    126                                 propertiesfile.write("if strcmp(classname,'"+ classname +"'),\n")
    127                                 propertiesfile.write('\tout=cell('+str(len(properties2)-1)+',1);\n')
    128                                 for j in range(len(properties2)-1):
    129                                         property = re.sub(r"=.*$","",properties2[j]);
    130                                         property = property.strip()
    131                                         property = re.sub(objectname+'.',"",property);
    132                                         propertiesfile.write('\tout{' + str(j+1) + "}='" + property + "';\n")
    133                                         propertiesfile2.write('\tout{' + str(j+1) + "}='" + property + "';\n")
    134                                 propertiesfile.write('end\n')
    135                                 continue
     142                #update properties list
     143                properties2 = properties2.split('\n')
     144                propertiesfile2 = open(dirname + '/properties.m', 'w')
     145                propertiesfile2.write("function out = properties(obj), \n")
     146                propertiesfile2.write('\tout = cell(' + str(len(properties2) - 1) + ', 1);\n')
     147                propertiesfile.write("if strcmp(classname, '" + classname + "'), \n")
     148                propertiesfile.write('\tout = cell(' + str(len(properties2) - 1) + ', 1);\n')
     149                for j in range(len(properties2) - 1):
     150                    property = re.sub(r"=. * $", "", properties2[j])
     151                    property = property.strip()
     152                    property = re.sub(objectname + '.', "", property)
     153                    propertiesfile.write('\tout{' + str(j + 1) + "} = '" + property + "';\n")
     154                    propertiesfile2.write('\tout{' + str(j + 1) + "} = '" + property + "';\n")
     155                propertiesfile.write('end\n')
     156                continue
    136157
    137                 #write file
    138                 if(step>2): outfile.write(mystr)
     158        #write file
     159        if(step > 2):
     160            outfile.write(mystr)
    139161
    140         #close all files and delete m file
    141         if(step>3):outfile.close()
    142         infile.close()
    143         os.remove(oldclassesdir+file)
     162    #close all files and delete m file
     163    if(step > 3):
     164        outfile.close()
     165    infile.close()
     166    os.remove(oldclassesdir + file)
    144167
    145         #Add subsref and subsasgn
    146         outfile = open(dirname+'/subsasgn.m','w')
    147         outfile.write(subsasgntext)
    148         outfile.close()
    149         outfile = open(dirname+'/subsref.m','w')
    150         outfile.write(subsreftext)
    151         outfile.close()
     168    #Add subsref and subsasgn
     169    outfile = open(dirname + '/subsasgn.m', 'w')
     170    outfile.write(subsasgntext)
     171    outfile.close()
     172    outfile = open(dirname + '/subsref.m', 'w')
     173    outfile.write(subsreftext)
     174    outfile.close()
    152175
    153176
  • issm/trunk-jpl/scripts/mToPy.py

    r13455 r24212  
    1 #!/usr/bin/env python
     1#! / usr / bin / env python
     2import sys
     3import os
     4import shutil
     5import translateToPy
     6import mToPy  # touch mToPy to assertain location of installation
    27#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    38#
    4 program =               'mToPy.py'
    5 version =               '1.0'
    6 versionReleaseDate =    '09/24/12'
    7 origAuthor =            'Mike Pellegrin'
     9program = 'mToPy.py'
     10version = '1.0'
     11versionReleaseDate = '09/24/12'
     12origAuthor = 'Mike Pellegrin'
    813desc = '\nMain control unit for converting an matlab script file to python'
    914#
    1015#   Note: Output will be put in the same (absolute) location as the input.
    1116#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    12 #                               History
    13 #       Date            Developer           Modification
     17#                History
     18#    Date        Developer           Modification
    1419#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    15 #       09/24/12        Michael Pellegrin       Initial Release         V1.0
     20#    09 / 24 / 12    Michael Pellegrin    Initial Release         V1.0
    1621#
    1722#
    1823#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    1924
    20 import sys, os, shutil
    21 import translateToPy
    22 import mToPy   # touch mToPy to assertain location of installation
    2325
    24 def convert ( inputFile ):
     26def convert(inputFile):
    2527    try:
    26       if os.path.exists( inputFile + '.m') and os.path.isfile( inputFile + '.m'):
    27         checkBackupOutputFile( inputFile )
    28         convertMToPy( inputFile )
    29       else:
    30         print 'Specified input file: ' + inputFile + '.m doesn\'t appear to exist'
     28        if os.path.exists(inputFile + '.m') and os.path.isfile(inputFile + '.m'):
     29            checkBackupOutputFile(inputFile)
     30            convertMToPy(inputFile)
     31        else:
     32            print('Specified input file: ' + inputFile + '.m doesn\'t appear to exist')
    3133    finally:
    32       print ''
     34        print('')
    3335
    34 def convertMToPy ( inputFileName ):
    35     translateToPy.convertToPython ( inputFileName + '.m', inputFileName + '.py' )
    3636
    37 def checkBackupOutputFile ( inputFile ):
     37def convertMToPy(inputFileName):
     38    translateToPy.convertToPython(inputFileName + '.m', inputFileName + '.py')
     39
     40
     41def checkBackupOutputFile(inputFile):
    3842    mFile = inputFile + '.m'
    3943    pyFile = inputFile + '.py'
    40     if os.path.exists( pyFile ):
    41         i=1
     44    if os.path.exists(pyFile):
     45        i = 1
    4246        bkupName = pyFile + str(i)
    43         while os.path.exists( bkupName ):
    44             i+=1
     47        while os.path.exists(bkupName):
     48            i += 1
    4549            bkupName = pyFile + str(i)
    46         os.rename( pyFile, bkupName )
     50        os.rename(pyFile, bkupName)
    4751
    4852    shutil.copyfile(mFile, pyFile)
    4953
     54
    5055if __name__ == "__main__":
    51     convert( sys.argv[1])
    52 
     56    convert(sys.argv[1])
  • issm/trunk-jpl/scripts/translateToPy.py

    r13491 r24212  
     1
     2import codecs
     3import unicodedata
     4import sys
     5import datetime
     6import os
    17
    28#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    39#
    4 program =               'translateToPy.py'
    5 version =               '1.0'
    6 versionReleaseDate =    '09/24/12'
    7 origAuthor =            'Mike Pellegrin'
     10program = 'translateToPy.py'
     11version = '1.0'
     12versionReleaseDate = '09/24/12'
     13origAuthor = 'Mike Pellegrin'
    814desc = '\nMatlab script conversion into python'
    915#
    1016#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    11 #                               History
    12 #       Date            Developer           Modification
    13 #+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    14 #       09/24/12 Michael Pellegrin      Initial Release     V1.0
     17#                History
     18#    Date        Developer           Modification
     19#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
     20#    09 / 24 / 12 Michael Pellegrin    Initial Release     V1.0
    1521#
    1622#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    17 
    18 import codecs, unicodedata
    19 import sys, re, datetime, os
    20 import decimal, operator
    2123
    2224
     
    2830
    2931
    30 def setupOutputLocation ( outFile ):
     32def setupOutputLocation(outFile):
    3133    if outFile != sys.stdout:
    32                 globals()['outputLocation'] = open( outFile, 'w' ) # clobber
    33 
    34 def translateFile ( inputFile ):
    35         f = codecs.open( inputFile, encoding='utf-8' )
    36         try:
    37                 for line in f:
    38                         # print "in: " +line
    39 
    40                         asciiLine = unicodedata.normalize('NFKD', line).encode('ascii','ignore')
    41                         line = asciiLine
    42 
    43                         translateLine( line )
    44 
    45         finally:
    46                 f.close()
    47 
    48 def translateLine ( line ):
    49 
    50         if len(line) == 1:      # blank line
    51                 output( line )
    52 
    53         elif line.split()[0][0] == '%':         # comment line
    54                 output("# " + line.replace('%','') )
    55 
    56         else:           # needs cleanup.  this is a real-quick-n-dirty implimentation
    57                 #print line
    58                 res = line.replace('{','[')
    59                 res = res.replace('}',']')
    60                 res = res.replace('model','model()')
    61                 res = res.replace('SolutionEnum','SolutionEnum()')
    62                 res = res.replace('StressTensorEnum','StressTensorEnum()')
    63                 res = res.replace('.par','.py')
    64                 res = res.replace('=extrude(md,','.extrude(')
    65 
    66                 res = res.replace('thickness(pos)','thickness[pos]')
    67                 res = res.replace('find(md.','numpy.nonzero(md.')
    68 
    69                 res = res.replace('\n','')
    70 
    71                 # handle inline comments
    72                 res = res.replace('%','#')
    73 
    74                 res = res.replace('...','\\')
    75 
    76                 # determine if the m file has mult. line cmd (real quick solution)
    77                 multCmds = res.split(';')
    78                 numLines = len( multCmds ) - 2
    79                 allParts = ''
    80                 for part in multCmds:
    81                         allParts += part
    82                         #allParts += re.sub('^\s+','',part)
    83                         #allParts += part.strip()
    84                         if numLines > 0:
    85                                 allParts += '\n'
    86                                 numLines -= 1
    87                 res = allParts 
    88 
    89                 res = res.replace(';','')
    90 
    91 
    92                 res = convertFieldValues( res )
    93                 #print 'resulting line:' + str(res) + '\n'
    94                 output(res)
    95 
    96 def convertFieldValues ( currentLine ):
    97         # before utilizing regex's {starting w/ eg. \([0-9]\) } for special case: ...(#)...
    98         # i noticed what i'm looking for is only TransientSolution(*). So, ...
    99 
    100         res = currentLine
    101         if 'md.results' in currentLine:
    102                 res = res.replace('(md.results.','md.results[\'')
    103 
    104                 if 'TransientSolution(' in currentLine:         # got a TransientSolution([0-9..]) case
    105                         res = res.replace('TransientSolution(','TransientSolution\'][')
    106                         parts = res.split(')')
    107                         res = parts[0] + '][\'' + parts[1].replace('.','') + '\']' + parts[2]
    108 
    109                 else:                           # handle the other cases for md.results
    110                        
    111                         res = res.replace('Solution.Vx)','Solution\'][1][\'Vx\']')
    112                         res = res.replace('Solution.Vy)','Solution\'][1][\'Vy\']')
    113                         res = res.replace('Solution.Vz)','Solution\'][1][\'Vz\']')
    114                         res = res.replace('Solution.Vel)','Solution\'][1][\'Vel\']')
    115 
    116                         res = res.replace('Solution.Pressure)','Solution\'][1][\'Pressure\']')
    117 
    118                         res = res.replace('Solution.StressTensorxx)','Solution\'][1][\'StressTensorxx\']')
    119                         res = res.replace('Solution.StressTensorxy)','Solution\'][1][\'StressTensorxy\']')
    120                         res = res.replace('Solution.StressTensoryy)','Solution\'][1][\'StressTensoryy\']')
    121                         res = res.replace('Solution.StressTensorzz)','Solution\'][1][\'StressTensorzz\']')
    122                         res = res.replace('Solution.StressTensorxz)','Solution\'][1][\'StressTensorxz\']')
    123                         res = res.replace('Solution.StressTensoryz)','Solution\'][1][\'StressTensoryz\']')
    124 
    125                         res = res.replace('Solution.FrictionCoefficient)','Solution\'][1][\'FrictionCoefficient\']')
    126                         res = res.replace('Solution.SurfaceforcingsMasBalance)','Solution\'][1][\'SurfaceforcingsMasBalance\']')
    127                         res = res.replace('Solution.MaskElementonfloatingice)','Solution\'][1][\'MaskElementonfloatingice\']')
    128                         res = res.replace('Solution.J)','Solution\'][1][\'J\']')
    129                         res = res.replace('Solution.BalancethicknessThickeningRate)','Solution\'][1][\'BalancethicknessThickeningRate\']')
    130 
    131                         res = res.replace('Solution.Gradient1)','Solution\'][1][\'Gradient1\']')
    132                         res = res.replace('Solution.Gradient2)','Solution\'][1][\'Gradient2\']')
    133 
    134                         res = res.replace('Solution.MaterialsRheologyZbar)','Solution\'][1][\'MaterialsRheologyZbar\']')
    135                         res = res.replace('Solution.MaterialsRheologyBbar)','Solution\'][1][\'MaterialsRheologyBbar\']')
    136                         res = res.replace('Solution.MaterialsRheologyB)','Solution\'][1][\'MaterialsRheologyB\']')
    137 
    138                         res = res.replace('Solution.Thickness)','Solution\'][1][\'Thickness\']')
    139 
    140                         res = res.replace('Solution.Temperature)','Solution\'][1][\'Temperature\']')
    141 
    142                         res = res.replace('Solution.BasalforcingsMeltingRate)','Solution\'][1][\'BasalforcingsMeltingRate\']')
    143 
    144                         res = res.replace('Solution.SurfaceSlopeX)','Solution\'][1][\'SurfaceSlopeX\']')
    145                         res = res.replace('Solution.SurfaceSlopeY)','Solution\'][1][\'SurfaceSlopeY\']')
    146                         res = res.replace('Solution.SurfaceSlopeZ)','Solution\'][1][\'SurfaceSlopeZ\']')
    147 
    148                         res = res.replace('Solution.BedSlopeX)','Solution\'][1][\'BedSlopeX\']')
    149                         res = res.replace('Solution.BedSlopeY)','Solution\'][1][\'BedSlopeY\']')
    150                         res = res.replace('Solution.BedSlopeZ)','Solution\'][1][\'BedSlopeZ\']')
    151 
    152                         res = res.replace('Solution.Enthalpy)','Solution\'][1][\'Enthalpy\']')
    153                         res = res.replace('Solution.Waterfraction)','Solution\'][1][\'Waterfraction\']')
    154                         res = res.replace('Solution.Temperature)','Solution\'][1][\'Temperature\']')
    155 
    156                         # special case
    157                         res = res.replace('.DiagnosticSolution.J','[\'DiagnosticSolution\'][1][\'J\']')
    158 
    159         return res
    160 
    161 def output ( line ):
    162         numTabs = indentLevel
    163         while numTabs:
    164                 numTabs -= 1
    165                 print >> outputLocation, '\t',
    166         print >> outputLocation, line
    167 
    168 def outputTopOfSript( inputFile ):
    169 
    170         global indentLevel
    171 
    172         output("\"\"\"")
    173         output("== == == == == == == == == == == == == == == == == == ==")
    174         output("Auto generated python script for ISSM:   %s" % (inputFile) )
    175         output("Created on %s via %s Ver %s by %s" % ( datetime.date.today(), program, version, os.getlogin()))
    176         output("== == == == == == == == == == == == == == == == == == ==")
    177         #output("")
    178         output(desc)
    179         output("%s Author: Michael Pellegrin" % (program))
    180         output("%s Date: %s" % (program, versionReleaseDate))
    181         output("== == == == == == == == == == == == == == == == == == ==")
    182         output("\"\"\"")
    183         output("")
     34        globals()['outputLocation'] = open(outFile, 'w')  # clobber
     35
     36
     37def translateFile(inputFile):
     38    f = codecs.open(inputFile, encoding='utf-8')
     39    try:
     40        for line in f:
     41            # print "in: " + line
     42
     43            asciiLine = unicodedata.normalize('NFKD', line).encode('ascii', 'ignore')
     44            line = asciiLine
     45            translateLine(line)
     46
     47    finally:
     48        f.close()
     49
     50
     51def translateLine(line):
     52
     53    if len(line) == 1:    # blank line
     54        output(line)
     55
     56    elif line.split()[0][0] == '%':        # comment line
     57        output("# " + line.replace('%', ''))
     58
     59    else:        # needs cleanup.  this is a real - quick - n - dirty implimentation
     60        #print line
     61        res = line.replace('{', '[')
     62        res = res.replace('}', ']')
     63        res = res.replace('model', 'model()')
     64        res = res.replace('SolutionEnum', 'SolutionEnum()')
     65        res = res.replace('StressTensorEnum', 'StressTensorEnum()')
     66        res = res.replace('.par', '.py')
     67        res = res.replace('=extrude(md, ', '.extrude(')
     68
     69        res = res.replace('thickness(pos)', 'thickness[pos]')
     70        res = res.replace('find(md.', 'numpy.nonzero(md.')
     71
     72        res = res.replace('\n', '')
     73
     74        # handle inline comments
     75        res = res.replace('%', '#')
     76
     77        res = res.replace('...', '\\')
     78
     79        # determine if the m file has mult. line cmd (real quick solution)
     80        multCmds = res.split(';')
     81        numLines = len(multCmds) - 2
     82        allParts = ''
     83        for part in multCmds:
     84            allParts += part
     85            #allParts += re.sub('^\s + ', '', part)
     86            #allParts += part.strip()
     87            if numLines > 0:
     88                allParts += '\n'
     89                numLines -= 1
     90
     91        res = allParts
     92        res = res.replace(';', '')
     93        res = convertFieldValues(res)
     94        #print 'resulting line:' + str(res) + '\n'
     95        output(res)
     96
     97
     98def convertFieldValues(currentLine):
     99    # before utilizing regex's {starting w / eg. \([0 - 9]\) } for special case: ...(#)...
     100    # i noticed what i'm looking for is only TransientSolution(* ). So, ...
     101
     102    res = currentLine
     103    if 'md.results' in currentLine:
     104        res = res.replace('(md.results.', 'md.results[\'')
     105
     106        if 'TransientSolution(' in currentLine:        # got a TransientSolution([0 - 9..]) case
     107            res = res.replace('TransientSolution(', 'TransientSolution\'][')
     108            parts = res.split(')')
     109            res = parts[0] + '][\'' + parts[1].replace('.', '') + '\']' + parts[2]
     110
     111        else:                # handle the other cases for md.results
     112
     113            res = res.replace('Solution.Vx)', 'Solution\'][1][\'Vx\']')
     114            res = res.replace('Solution.Vy)', 'Solution\'][1][\'Vy\']')
     115            res = res.replace('Solution.Vz)', 'Solution\'][1][\'Vz\']')
     116            res = res.replace('Solution.Vel)', 'Solution\'][1][\'Vel\']')
     117
     118            res = res.replace('Solution.Pressure)', 'Solution\'][1][\'Pressure\']')
     119
     120            res = res.replace('Solution.StressTensorxx)', 'Solution\'][1][\'StressTensorxx\']')
     121            res = res.replace('Solution.StressTensorxy)', 'Solution\'][1][\'StressTensorxy\']')
     122            res = res.replace('Solution.StressTensoryy)', 'Solution\'][1][\'StressTensoryy\']')
     123            res = res.replace('Solution.StressTensorzz)', 'Solution\'][1][\'StressTensorzz\']')
     124            res = res.replace('Solution.StressTensorxz)', 'Solution\'][1][\'StressTensorxz\']')
     125            res = res.replace('Solution.StressTensoryz)', 'Solution\'][1][\'StressTensoryz\']')
     126
     127            res = res.replace('Solution.FrictionCoefficient)', 'Solution\'][1][\'FrictionCoefficient\']')
     128            res = res.replace('Solution.SurfaceforcingsMasBalance)', 'Solution\'][1][\'SurfaceforcingsMasBalance\']')
     129            res = res.replace('Solution.MaskElementonfloatingice)', 'Solution\'][1][\'MaskElementonfloatingice\']')
     130            res = res.replace('Solution.J)', 'Solution\'][1][\'J\']')
     131            res = res.replace('Solution.BalancethicknessThickeningRate)', 'Solution\'][1][\'BalancethicknessThickeningRate\']')
     132
     133            res = res.replace('Solution.Gradient1)', 'Solution\'][1][\'Gradient1\']')
     134            res = res.replace('Solution.Gradient2)', 'Solution\'][1][\'Gradient2\']')
     135
     136            res = res.replace('Solution.MaterialsRheologyZbar)', 'Solution\'][1][\'MaterialsRheologyZbar\']')
     137            res = res.replace('Solution.MaterialsRheologyBbar)', 'Solution\'][1][\'MaterialsRheologyBbar\']')
     138            res = res.replace('Solution.MaterialsRheologyB)', 'Solution\'][1][\'MaterialsRheologyB\']')
     139
     140            res = res.replace('Solution.Thickness)', 'Solution\'][1][\'Thickness\']')
     141
     142            res = res.replace('Solution.Temperature)', 'Solution\'][1][\'Temperature\']')
     143
     144            res = res.replace('Solution.BasalforcingsMeltingRate)', 'Solution\'][1][\'BasalforcingsMeltingRate\']')
     145
     146            res = res.replace('Solution.SurfaceSlopeX)', 'Solution\'][1][\'SurfaceSlopeX\']')
     147            res = res.replace('Solution.SurfaceSlopeY)', 'Solution\'][1][\'SurfaceSlopeY\']')
     148            res = res.replace('Solution.SurfaceSlopeZ)', 'Solution\'][1][\'SurfaceSlopeZ\']')
     149
     150            res = res.replace('Solution.BedSlopeX)', 'Solution\'][1][\'BedSlopeX\']')
     151            res = res.replace('Solution.BedSlopeY)', 'Solution\'][1][\'BedSlopeY\']')
     152            res = res.replace('Solution.BedSlopeZ)', 'Solution\'][1][\'BedSlopeZ\']')
     153
     154            res = res.replace('Solution.Enthalpy)', 'Solution\'][1][\'Enthalpy\']')
     155            res = res.replace('Solution.Waterfraction)', 'Solution\'][1][\'Waterfraction\']')
     156            res = res.replace('Solution.Temperature)', 'Solution\'][1][\'Temperature\']')
     157
     158            # special case
     159            res = res.replace('.DiagnosticSolution.J', '[\'DiagnosticSolution\'][1][\'J\']')
     160
     161    return res
     162
     163
     164def output(line):
     165    numTabs = indentLevel
     166    while numTabs:
     167        numTabs -= 1
     168        print('\t', end="", file=outputLocation)
     169
     170    print(line, end="", file=outputLocation)
     171
     172
     173def outputTopOfSript(inputFile):
     174
     175    global indentLevel
     176
     177    output("\"\"\"")
     178    output("====================================== ")
     179    output("Auto generated python script for ISSM: {}".format(inputFile))
     180    output("Created on {} via {} Ver {} by {}".format(datetime.date.today(), program, version, os.getlogin()))
     181    output("====================================== ")
     182    #output("")
     183    output(desc)
     184    output("%s Author: Michael Pellegrin" % (program))
     185    output("%s Date: %s" % (program, versionReleaseDate))
     186    output("====================================== ")
     187    output("\"\"\"")
     188    output("")
     189
    184190
    185191def outputBottomOfScript():
    186192
    187         global indentLevel
    188 
    189         output("")
    190        
    191 def genericImports ():
    192         output("from MatlabFuncs import *")
    193         output("from model import *")
    194         output("from EnumDefinitions import *")
    195         output("from numpy import *")
    196 
    197 def createImports ( inputFile ):
    198         genericImports()
    199 
    200         # cycle through eachline to assertain import needs
    201         f = codecs.open( inputFile, encoding='utf-8' )
    202         try:
    203                 for line in f:
    204                         # print "in: " +line
    205 
    206                         # toss blank lines
    207                         if len(line) == 1:
    208                                 continue
    209 
    210                         asciiLine = unicodedata.normalize('NFKD', line).encode('ascii','ignore')
    211                         line = asciiLine
    212 
    213                         for il in importList:
    214                                 if line.find(il) != -1:
    215                                         output( "from %s import *" % (il) )
    216                                         importList.remove(il)   # already got it
    217 
    218         finally:
    219                 output("")
    220                 f.close()
    221 
    222 
    223 def initImportList ():
    224         global importList
    225        
    226         importList = [ \
    227                 'triangle'      ,\
    228                 'setmask'       ,\
    229                 'parameterize'  ,\
    230                 'setflowequation'       ,\
    231                 'meshconvert'   ,\
    232                 'solve' ,\
    233                 #'zeros'                                        # -> numpy
    234                 ]
    235        
    236 
    237 
    238 def convertToPython ( inFile, outFile = sys.stdout ):
    239     #print ' in cnvrt to python w/ file:' + inFile
     193    global indentLevel
     194
     195    output("")
     196
     197
     198def genericImports():
     199    output("from MatlabFuncs import * ")
     200    output("from model import * ")
     201    output("from EnumDefinitions import * ")
     202    output("from numpy import * ")
     203
     204
     205def createImports(inputFile):
     206    genericImports()
     207
     208    # cycle through eachline to assertain import needs
     209    f = codecs.open(inputFile, encoding='utf-8')
     210    try:
     211        for line in f:
     212            # print "in: " + line
     213
     214            # toss blank lines
     215            if len(line) == 1:
     216                continue
     217
     218            asciiLine = unicodedata.normalize('NFKD', line).encode('ascii', 'ignore')
     219            line = asciiLine
     220
     221            for il in importList:
     222                if line.find(il) != - 1:
     223                    output("from %s import * " % (il))
     224                    importList.remove(il)    # already got it
     225
     226    finally:
     227        output("")
     228        f.close()
     229
     230
     231def initImportList():
     232    global importList
     233
     234    importList = ['triangle',
     235                  'setmask',
     236                  'parameterize',
     237                  'setflowequation',
     238                  'meshconvert',
     239                  'solve']
     240
     241
     242def convertToPython(inFile, outFile=sys.stdout):
     243    #print ' in cnvrt to python w / file:' + inFile
    240244    initImportList()
    241     setupOutputLocation( outFile )
    242     outputTopOfSript( inFile )
    243     createImports( inFile )
    244     translateFile( inFile )
     245    setupOutputLocation(outFile)
     246    outputTopOfSript(inFile)
     247    createImports(inFile)
     248    translateFile(inFile)
    245249    #    outputBottomOfScript()
    246250
    247        
     251
    248252if __name__ == "__main__":
    249     #print ' in main w/ arg:' + sys.argv[1]+' '+sys.argv[2]
    250     if len(sys.argv)==2:
    251         convertToPython( sys.argv[1], sys.argv[2] )
     253    #print ' in main w / arg:' + sys.argv[1] + ' ' + sys.argv[2]
     254    if len(sys.argv) == 2:
     255        convertToPython(sys.argv[1], sys.argv[2])
    252256    else:
    253         convertToPython( sys.argv[1] )
    254 
    255 
    256 
     257        convertToPython(sys.argv[1])
Note: See TracChangeset for help on using the changeset viewer.