Changeset fa74acf in sasmodels


Ignore:
Timestamp:
Dec 15, 2017 10:26:39 AM (6 years ago)
Author:
Omer Eisenberg <omereis@…>
Children:
98a4f14
Parents:
fb5c8c7
git-author:
Omer Eisenberg <omereis@…> (12/15/17 10:23:40)
git-committer:
Omer Eisenberg <omereis@…> (12/15/17 10:26:39)
Message:

modified to fix some pylint errors

File:
1 edited

Legend:

Unmodified
Added
Removed
  • sasmodels/py2c.py

    rfb5c8c7 rfa74acf  
    1212    Variables definition in C 
    1313    ------------------------- 
    14     Defining variables within the Translate function is a bit of a guess work, using following rules. 
     14    Defining variables within the Translate function is a bit of a guess work, 
     15    using following rules. 
    1516    *   By default, a variable is a 'double'. 
    1617    *   Variable in a for loop is an int. 
    17     *   Variable that is references with brackets is an array of doubles. The variable within the brackets 
    18         is integer. For example, in the reference 'var1[var2]', var1 is a double array, and var2 is an integer. 
    19     *   Assignment to an argument makes that argument an array, and the index in that assignment is 0. 
     18    *   Variable that is references with brackets is an array of doubles. The 
     19        variable within the brackets is integer. For example, in the 
     20        reference 'var1[var2]', var1 is a double array, and var2 is an integer. 
     21    *   Assignment to an argument makes that argument an array, and the index in 
     22        that assignment is 0. 
    2023        For example, the following python code 
    21             def func (arg1, arg2): 
     24            def func(arg1, arg2): 
    2225                arg2 = 17. 
    2326        is translated to the following C code 
    24             double func (double arg1) 
     27            double func(double arg1) 
    2528            { 
    2629                arg2[0] = 17.0; 
    2730            } 
    2831        For example, the following python code is translated to the following C code 
    29             def func (arg1, arg2):          double func (double arg1) { 
     32            def func(arg1, arg2):          double func(double arg1) { 
    3033                arg2 = 17.                      arg2[0] = 17.0; 
    3134                                            } 
     
    3538Update Notes 
    3639============ 
    37 11/22 14:15, O.E.   Each 'visit_*' method is to build a C statement string. It shold insert 4 blanks per indentation level. 
    38                     The 'body' method will combine all the strings, by adding the 'current_statement' to the c_proc string list 
     4011/22 14:15, O.E.   Each 'visit_*' method is to build a C statement string. It 
     41                    shold insert 4 blanks per indentation level. 
     42                    The 'body' method will combine all the strings, by adding 
     43                    the 'current_statement' to the c_proc string list 
    3944   11/2017, OE: variables, argument definition implemented. 
    40    Note: An argument is considered an array if it is the target of an assignment. In that case it is translated to <var>[0] 
     45   Note: An argument is considered an array if it is the target of an 
     46        assignment. In that case it is translated to <var>[0] 
    414711/27/2017, OE: 'pow' basicly working 
    4248  /12/2017, OE: Multiple assignment: a1,a2,...,an=b1,b2,...bn implemented 
    43   /12/2017, OE: Power function, including special cases of square(x) (pow(x,2)) and cube(x) (pow(x,3)), implemented in translate_power, 
    44                 called from visit_BinOp 
    45 12/07/2017, OE: Translation of integer division, '\\' in python, implemented in translate_integer_divide, called from visit_BinOp 
     49  /12/2017, OE: Power function, including special cases of 
     50                square(x)(pow(x,2)) and cube(x)(pow(x,3)), implemented in 
     51                translate_power, called from visit_BinOp 
     5212/07/2017, OE: Translation of integer division, '\\' in python, implemented 
     53                in translate_integer_divide, called from visit_BinOp 
    465412/07/2017, OE: C variable definition handled in 'define_C_Vars' 
    47               : Python integer division, '//', translated to C in 'translate_integer_divide' 
    48 12/15/2017, OE: Precedence maintained by writing opening and closing parenthesesm '(',')', 
    49                 in procedure 'visit_BinOp'. 
     55              : Python integer division, '//', translated to C in 
     56                'translate_integer_divide' 
     5712/15/2017, OE: Precedence maintained by writing opening and closing 
     58                parenthesesm '(',')', in procedure 'visit_BinOp'. 
    5059""" 
    5160import ast 
     
    7281 
    7382CMPOP_SYMBOLS = {} 
    74 CMPOP_SYMBOLS[ast.Eq] = '==' 
     83CMPOP_SYMBOLS[ast.Eq]    = '==' 
    7584CMPOP_SYMBOLS[ast.NotEq] = '!=' 
    7685CMPOP_SYMBOLS[ast.Lt] = '<' 
     
    122131    except: 
    123132        return False 
    124      
     133 
    125134class SourceGenerator(NodeVisitor): 
    126135    """This visitor is able to transform a well formed syntax tree into python 
     
    168177    def write_c(self, x): 
    169178        self.current_statement += x 
    170          
     179 
    171180    def add_c_line(self, x): 
    172181        string = '' 
    173         for i in range (self.indentation): 
     182        for i in range(self.indentation): 
    174183            string += ("    ") 
    175184        string += str(x) 
    176         self.c_proc.append (str(string + "\n")) 
     185        self.c_proc.append(str(string + "\n")) 
    177186        x = '' 
    178187 
    179     def add_current_line (self): 
    180         if (len(self.current_statement) > 0): 
    181             self.add_c_line (self.current_statement) 
     188    def add_current_line(self): 
     189        if(len(self.current_statement) > 0): 
     190            self.add_c_line(self.current_statement) 
    182191            self.current_statement = '' 
    183192 
    184     def AddUniqueVar (self, new_var): 
    185         if ((new_var not in self.C_Vars)): 
    186             self.C_Vars.append (str (new_var)) 
    187  
    188     def WriteSincos (self, node): 
     193    def AddUniqueVar(self, new_var): 
     194        if((new_var not in self.C_Vars)): 
     195            self.C_Vars.append(str(new_var)) 
     196 
     197    def WriteSincos(self, node): 
    189198        angle = str(node.args[0].id) 
    190         self.write_c (node.args[1].id + " = sin (" + angle + ");") 
     199        self.write_c(node.args[1].id + " = sin(" + angle + ");") 
    191200        self.add_current_line() 
    192         self.write_c (node.args[2].id + " = cos (" + angle + ");") 
     201        self.write_c(node.args[2].id + " = cos(" + angle + ");") 
    193202        self.add_current_line() 
    194203        for arg in node.args: 
    195             self.AddUniqueVar (arg.id) 
     204            self.AddUniqueVar(arg.id) 
    196205 
    197206    def newline(self, node=None, extra=0): 
     
    200209            self.write_c('# line: %s' % node.lineno) 
    201210            self.new_lines = 1 
    202         if (len(self.current_statement)): 
    203             self.Statements.append (self.current_statement) 
     211        if(len(self.current_statement)): 
     212            self.Statements.append(self.current_statement) 
    204213            self.current_statement = '' 
    205214 
    206215    def body(self, statements): 
    207         if (len(self.current_statement)): 
    208             self.add_current_line () 
     216        if(len(self.current_statement)): 
     217            self.add_current_line() 
    209218        self.new_line = True 
    210219        self.indentation += 1 
    211220        for stmt in statements: 
    212221            target_name = '' 
    213             if (hasattr (stmt, 'targets')): 
    214                 if (hasattr(stmt.targets[0],'id')): 
     222            if(hasattr(stmt, 'targets')): 
     223                if(hasattr(stmt.targets[0], 'id')): 
    215224                    target_name = stmt.targets[0].id # target name needed for debug only 
    216225            self.visit(stmt) 
    217         self.add_current_line () # just for breaking point. to be deleted.  
     226        self.add_current_line() # just for breaking point. to be deleted. 
    218227        self.indentation -= 1 
    219228 
     
    234243# for C 
    235244        for arg in node.args: 
    236             self.arguments.append (arg.arg) 
    237  
    238         padding = [None] * (len(node.args) - len(node.defaults)) 
     245            self.arguments.append(arg.arg) 
     246 
     247        padding = [None] *(len(node.args) - len(node.defaults)) 
    239248        for arg, default in zip(node.args, padding + node.defaults): 
    240249            if default is not None: 
    241                 self.warnings.append ("Default Parameter unknown to C") 
    242                 w_str = "Default Parameters are unknown to C: '" + arg.arg + " = " + str(default.n) + "'" 
    243                 self.warnings.append (w_str) 
     250                self.warnings.append("Default Parameter unknown to C") 
     251                w_str = "Default Parameters are unknown to C: '" + arg.arg + \ 
     252                        " = " + str(default.n) + "'" 
     253                self.warnings.append(w_str) 
    244254#                self.write_python('=') 
    245255#                self.visit(default) 
     
    258268        self.visit(node.test) 
    259269        if node.msg is not None: 
    260            self.write_python(', ') 
    261            self.visit(node.msg) 
    262  
    263     def define_C_Vars (self, target): 
    264         if (hasattr (target, 'id')): 
     270            self.write_python(', ') 
     271            self.visit(node.msg) 
     272 
     273    def define_C_Vars(self, target): 
     274        if(hasattr(target, 'id')): 
    265275# a variable is considered an array if it apears in the agrument list 
    266276# and being assigned to. For example, the variable p in the following 
    267277# sniplet is a pointer, while q is not 
    268 # def somefunc (p, q): 
     278# def somefunc(p, q): 
    269279#  p = q + 1 
    270280#  return 
    271281# 
    272             if (target.id not in self.C_Vars): 
    273                 if (target.id in self.arguments): 
    274                     idx = self.arguments.index (target.id) 
     282            if(target.id not in self.C_Vars): 
     283                if(target.id in self.arguments): 
     284                    idx = self.arguments.index(target.id) 
    275285                    new_target = self.arguments[idx] + "[0]" 
    276                     if (new_target not in self.C_Pointers): 
     286                    if(new_target not in self.C_Pointers): 
    277287                        target.id = new_target 
    278                         self.C_Pointers.append (self.arguments[idx]) 
     288                        self.C_Pointers.append(self.arguments[idx]) 
    279289                else: 
    280                     self.C_Vars.append (target.id) 
    281  
    282     def add_semi_colon (self): 
     290                    self.C_Vars.append(target.id) 
     291 
     292    def add_semi_colon(self): 
    283293        semi_pos = self.current_statement.find(';') 
    284         if (semi_pos < 0): 
     294        if(semi_pos < 0): 
    285295            self.write_c(';') 
    286296 
    287297    def visit_Assign(self, node): 
    288         self.add_current_line () 
     298        self.add_current_line() 
    289299        for idx, target in enumerate(node.targets): # multi assign, as in 'a = b = c = 7' 
    290300            if idx: 
    291301                self.write_c(' = ') 
    292             self.define_C_Vars (target) 
     302            self.define_C_Vars(target) 
    293303            self.visit(target) 
    294         if (len(self.Tuples) > 0): 
    295             tplTargets = list (self.Tuples) 
     304        if(len(self.Tuples) > 0): 
     305            tplTargets = list(self.Tuples) 
    296306            self.Tuples.clear() 
    297307        self.write_c(' = ') 
     
    299309        self.visited_args = False 
    300310        self.visit(node.value) 
    301         self.add_semi_colon () 
     311        self.add_semi_colon() 
    302312#        self.write_c(';') 
    303         self.add_current_line () 
    304         for n,item in enumerate (self.Tuples): 
     313        self.add_current_line() 
     314        for n, item in enumerate(self.Tuples): 
    305315            self.visit(tplTargets[n]) 
    306316            self.write_c(' = ') 
    307317            self.visit(item) 
    308             self.add_semi_colon () 
    309             self.add_current_line () 
    310         if ((self.is_sequence) and (not self.visited_args)): 
     318            self.add_semi_colon() 
     319            self.add_current_line() 
     320        if((self.is_sequence) and (not self.visited_args)): 
    311321            for target in node.targets: 
    312                 if (hasattr (target, 'id')): 
    313                     if ((target.id in self.C_Vars) and (target.id not in self.C_DclPointers)): 
    314                         if (target.id not in self.C_DclPointers): 
    315                             self.C_DclPointers.append (target.id) 
    316                             if (target.id in self.C_Vars): 
     322                if(hasattr(target, 'id')): 
     323                    if((target.id in self.C_Vars) and(target.id not in self.C_DclPointers)): 
     324                        if(target.id not in self.C_DclPointers): 
     325                            self.C_DclPointers.append(target.id) 
     326                            if(target.id in self.C_Vars): 
    317327                                self.C_Vars.remove(target.id) 
    318328        self.current_statement = '' 
    319329 
    320330    def visit_AugAssign(self, node): 
    321         if (node.target.id not in self.C_Vars): 
    322             if (node.target.id not in self.arguments): 
    323                 self.C_Vars.append (node.target.id) 
     331        if(node.target.id not in self.C_Vars): 
     332            if(node.target.id not in self.arguments): 
     333                self.C_Vars.append(node.target.id) 
    324334        self.visit(node.target) 
    325335        self.write_c(' ' + BINOP_SYMBOLS[type(node.op)] + '= ') 
    326336        self.visit(node.value) 
    327         self.add_semi_colon () 
     337        self.add_semi_colon() 
    328338#        self.write_c(';') 
    329         self.add_current_line () 
     339        self.add_current_line() 
    330340 
    331341    def visit_ImportFrom(self, node): 
    332342        self.newline(node) 
    333         self.write_python('from %s%s import ' % ('.' * node.level, node.module)) 
     343        self.write_python('from %s%s import ' %('.' * node.level, node.module)) 
    334344        for idx, item in enumerate(node.names): 
    335345            if idx: 
     
    349359    def listToDeclare(self, Vars): 
    350360        s = '' 
    351         if (len(Vars) > 0): 
    352             s = ",".join (Vars) 
    353         return (s) 
    354  
    355     def write_C_Pointers (self, start_var): 
    356         if (len (self.C_DclPointers) > 0): 
     361        if(len(Vars) > 0): 
     362            s = ",".join(Vars) 
     363        return(s) 
     364 
     365    def write_C_Pointers(self, start_var): 
     366        if(len(self.C_DclPointers) > 0): 
    357367            vars = "" 
    358368            for c_ptr in self.C_DclPointers: 
    359                 if (len(vars) > 0): 
     369                if(len(vars) > 0): 
    360370                    vars += ", " 
    361                 if (c_ptr not in self.arguments): 
     371                if(c_ptr not in self.arguments): 
    362372                    vars += "*" + c_ptr 
    363                 if (c_ptr in self.C_Vars): 
    364                     if (c_ptr in self.C_Vars): 
    365                         self.C_Vars.remove (c_ptr) 
    366             if (len(vars) > 0): 
     373                if(c_ptr in self.C_Vars): 
     374                    if(c_ptr in self.C_Vars): 
     375                        self.C_Vars.remove(c_ptr) 
     376            if(len(vars) > 0): 
    367377                c_dcl = "    double " + vars + ";" 
    368                 self.c_proc.insert (start_var, c_dcl + "\n") 
     378                self.c_proc.insert(start_var, c_dcl + "\n") 
    369379                start_var += 1 
    370380        return start_var 
    371381 
    372     def insert_C_Vars (self, start_var): 
     382    def insert_C_Vars(self, start_var): 
    373383        fLine = False 
    374         start_var = self.write_C_Pointers (start_var) 
    375         if (len(self.C_IntVars) > 0): 
     384        start_var = self.write_C_Pointers(start_var) 
     385        if(len(self.C_IntVars) > 0): 
    376386            for var in self.C_IntVars: 
    377                 if (var in self.C_Vars): 
     387                if(var in self.C_Vars): 
    378388                    self.C_Vars.remove(var) 
    379389            s = self.listToDeclare(self.C_IntVars) 
    380             self.c_proc.insert (start_var, "    int " + s + ";\n") 
     390            self.c_proc.insert(start_var, "    int " + s + ";\n") 
    381391            fLine = True 
    382392            start_var += 1 
    383              
    384         if (len(self.C_Vars) > 0): 
     393 
     394        if(len(self.C_Vars) > 0): 
    385395            s = self.listToDeclare(self.C_Vars) 
    386             self.c_proc.insert (start_var, "    double " + s + ";\n") 
     396            self.c_proc.insert(start_var, "    double " + s + ";\n") 
    387397            fLine = True 
    388398            start_var += 1 
    389 #        if (len(self.C_IntVars) > 0): 
     399#        if(len(self.C_IntVars) > 0): 
    390400#            s = self.listToDeclare(self.C_IntVars) 
    391 #            self.c_proc.insert (start_var, "    int " + s + ";\n") 
     401#            self.c_proc.insert(start_var, "    int " + s + ";\n") 
    392402#            fLine = True 
    393403#            start_var += 1 
    394         if (len (self.C_Vectors) > 0): 
     404        if(len(self.C_Vectors) > 0): 
    395405            s = self.listToDeclare(self.C_Vectors) 
    396406            for n in range(len(self.C_Vectors)): 
    397407                name = "vec" + str(n+1) 
    398408                c_dcl = "    double " + name + "[] = {" + self.C_Vectors[n] + "};" 
    399                 self.c_proc.insert (start_var, c_dcl + "\n") 
     409                self.c_proc.insert(start_var, c_dcl + "\n") 
    400410                start_var += 1 
    401411        self.C_Vars.clear() 
     
    404414        self.C_Pointers.clear() 
    405415        self.C_DclPointers 
    406         if (fLine == True): 
    407             self.c_proc.insert (start_var, "\n") 
     416        if(fLine == True): 
     417            self.c_proc.insert(start_var, "\n") 
    408418        return 
    409419        s = '' 
     
    412422            if n < len(self.C_Vars) - 1: 
    413423                s += ", " 
    414         if (len(s) > 0): 
    415             self.c_proc.insert (start_var, "    double " + s + ";\n") 
    416             self.c_proc.insert (start_var + 1, "\n") 
    417  
    418     def writeInclude (self): 
    419         if (self.MathIncludeed == False): 
     424        if(len(s) > 0): 
     425            self.c_proc.insert(start_var, "    double " + s + ";\n") 
     426            self.c_proc.insert(start_var + 1, "\n") 
     427 
     428    def writeInclude(self): 
     429        if(self.MathIncludeed == False): 
    420430            self.add_c_line("#include <math.h>\n") 
    421431            self.add_c_line("static double pi = 3.14159265359;\n") 
    422432            self.MathIncludeed = True 
    423433 
    424     def ListToString (self, strings): 
     434    def ListToString(self, strings): 
    425435        s = '' 
    426436        for n in range(len(strings)): 
    427437            s += strings[n] 
    428             if (n < (len(strings) - 1)): 
     438            if(n < (len(strings) - 1)): 
    429439                s += ", " 
    430         return (s) 
    431  
    432     def getMethodSignature (self): 
    433 #        args_str = ListToString (self.arguments) 
     440        return(s) 
     441 
     442    def getMethodSignature(self): 
     443#        args_str = ListToString(self.arguments) 
    434444        args_str = '' 
    435445        for n in range(len(self.arguments)): 
    436446            args_str += "double " + self.arguments[n] 
    437             if (n < (len(self.arguments) - 1)): 
     447            if(n < (len(self.arguments) - 1)): 
    438448                args_str += ", " 
    439         return (args_str) 
    440 #        self.strMethodSignature = 'double ' + self.name + ' (' + args_str + ")" 
    441  
    442     def InsertSignature (self): 
     449        return(args_str) 
     450#        self.strMethodSignature = 'double ' + self.name + '(' + args_str + ")" 
     451 
     452    def InsertSignature(self): 
    443453        args_str = '' 
    444454        for n in range(len(self.arguments)): 
    445455            args_str += "double " + self.arguments[n] 
    446             if (self.arguments[n] in self.C_Pointers): 
     456            if(self.arguments[n] in self.C_Pointers): 
    447457                args_str += "[]" 
    448             if (n < (len(self.arguments) - 1)): 
     458            if(n < (len(self.arguments) - 1)): 
    449459                args_str += ", " 
    450         self.strMethodSignature = 'double ' + self.name + ' (' + args_str + ")" 
    451         if (self.signature_line >= 0): 
    452             self.c_proc.insert (self.signature_line, self.strMethodSignature) 
     460        self.strMethodSignature = 'double ' + self.name + '(' + args_str + ")" 
     461        if(self.signature_line >= 0): 
     462            self.c_proc.insert(self.signature_line, self.strMethodSignature) 
    453463 
    454464    def visit_FunctionDef(self, node): 
     
    466476# for C 
    467477        self.writeInclude() 
    468         self.getMethodSignature () 
     478        self.getMethodSignature() 
    469479# for C 
    470480        self.signature_line = len(self.c_proc) 
     
    474484        self.body(node.body) 
    475485        self.add_c_line("}\n") 
    476         self.InsertSignature () 
    477         self.insert_C_Vars (start_vars) 
     486        self.InsertSignature() 
     487        self.insert_C_Vars(start_vars) 
    478488        self.C_Pointers = [] 
    479489 
     
    522532            if len(else_) == 0: 
    523533                break 
    524 #            elif hasattr (else_, 'orelse'): 
     534#            elif hasattr(else_, 'orelse'): 
    525535            elif len(else_) == 1 and isinstance(else_[0], ast.If): 
    526536                node = else_[0] 
     
    530540                self.write_c(' {') 
    531541                self.body(node.body) 
    532                 self.add_current_line () 
     542                self.add_current_line() 
    533543                self.add_c_line('}') 
    534544#                break 
     
    540550                break 
    541551 
    542     def getNodeLineNo (self, node): 
     552    def getNodeLineNo(self, node): 
    543553        line_number = -1 
    544         if (hasattr (node,'value')): 
     554        if(hasattr(node,'value')): 
    545555            line_number = node.value.lineno 
    546556        elif hasattr(node,'iter'): 
    547557            if hasattr(node.iter,'lineno'): 
    548558                line_number = node.iter.lineno 
    549         return (line_number) 
    550  
    551     def GetNodeAsString (self, node): 
     559        return(line_number) 
     560 
     561    def GetNodeAsString(self, node): 
    552562        res = '' 
    553         if (hasattr(node,'n')): 
     563        if(hasattr(node, 'n')): 
    554564            res = str(node.n) 
    555         elif (hasattr(node,'id')): 
     565        elif(hasattr(node, 'id')): 
    556566            res = node.id 
    557         return (res) 
     567        return(res) 
    558568 
    559569    def GetForRange(self, node): 
     
    569579            self.current_statement = '' 
    570580        self.current_statement = temp_statement 
    571         if (len(for_args) == 1): 
     581        if(len(for_args) == 1): 
    572582            stop = for_args[0] 
    573         elif (len(for_args) == 2): 
     583        elif(len(for_args) == 2): 
    574584            start = for_args[0] 
    575585            stop = for_args[1] 
    576         elif (len(for_args) == 3): 
     586        elif(len(for_args) == 3): 
    577587            start = for_args[0] 
    578588            stop = for_args[1] 
     
    580590        else: 
    581591            raise("Ilegal for loop parameters") 
    582         return (start, stop, step) 
     592        return(start, stop, step) 
    583593 
    584594    def visit_For(self, node): 
     
    586596# Iterator name is in node.target.id. 
    587597        self.add_current_line() 
    588 #        if (len(self.current_statement) > 0): 
     598#        if(len(self.current_statement) > 0): 
    589599#            self.add_c_line(self.current_statement) 
    590600#            self.current_statement = '' 
    591601        fForDone = False 
    592602        self.current_statement = '' 
    593         if (hasattr(node.iter,'func')): 
    594             if (hasattr (node.iter.func,'id')): 
    595                 if (node.iter.func.id == 'range'): 
     603        if(hasattr(node.iter, 'func')): 
     604            if(hasattr(node.iter.func, 'id')): 
     605                if(node.iter.func.id == 'range'): 
    596606                    self.visit(node.target) 
    597607                    iterator = self.current_statement 
    598608                    self.current_statement = '' 
    599                     if (iterator not in self.C_IntVars): 
    600                         self.C_IntVars.append (iterator) 
     609                    if(iterator not in self.C_IntVars): 
     610                        self.C_IntVars.append(iterator) 
    601611                    start, stop, step = self.GetForRange(node) 
    602                     self.write_c ("for (" + iterator + "=" + str(start) + \ 
     612                    self.write_c("for(" + iterator + "=" + str(start) + \ 
    603613                                  " ; " + iterator + " < " + str(stop) + \ 
    604614                                  " ; " + iterator + " += " + str(step) + ") {") 
    605615                    self.body_or_else(node) 
    606                     self.write_c ("}") 
     616                    self.write_c("}") 
    607617                    fForDone = True 
    608         if (fForDone == False): 
    609             line_number = self.getNodeLineNo (node) 
     618        if(fForDone == False): 
     619            line_number = self.getNodeLineNo(node) 
    610620            self.current_statement = '' 
    611621            self.write_c('for ') 
     
    614624            self.visit(node.iter) 
    615625            self.write_c(':') 
    616             errStr = "Conversion Error in function " + self.name + ", Line #" + str (line_number) 
     626            errStr = "Conversion Error in function " + self.name + ", Line #" + str(line_number) 
    617627            errStr += "\nPython for expression not supported: '" + self.current_statement + "'" 
    618628            raise Exception(errStr) 
     
    640650 
    641651    def visit_Print(self, node): 
    642 # XXX: python 2.6 only  
     652# XXX: python 2.6 only 
    643653        self.newline(node) 
    644654        self.write_c('print ') 
     
    692702            self.write_c('return') 
    693703        else: 
    694             self.write_c('return (') 
     704            self.write_c('return(') 
    695705            self.visit(node.value) 
    696706        self.write_c(');') 
    697 #      self.add_current_statement (self) 
    698         self.add_c_line (self.current_statement) 
     707#      self.add_current_statement(self) 
     708        self.add_c_line(self.current_statement) 
    699709        self.current_statement = '' 
    700710 
     
    729739 
    730740    def visit_Attribute(self, node): 
    731         errStr = "Conversion Error in function " + self.name + ", Line #" + str (node.value.lineno) 
     741        errStr = "Conversion Error in function " + self.name + ", Line #" + str(node.value.lineno) 
    732742        errStr += "\nPython expression not supported: '" + node.value.id + "." + node.attr + "'" 
    733743        raise Exception(errStr) 
     
    742752            else: 
    743753                want_comma.append(True) 
    744         if (hasattr (node.func, 'id')): 
    745             if (node.func.id not in self.C_Functions): 
    746                 self.C_Functions.append (node.func.id) 
    747             if (node.func.id == 'abs'): 
    748                 self.write_c ("fabs ") 
    749             elif (node.func.id == 'int'): 
     754        if(hasattr(node.func, 'id')): 
     755            if(node.func.id not in self.C_Functions): 
     756                self.C_Functions.append(node.func.id) 
     757            if(node.func.id == 'abs'): 
     758                self.write_c("fabs ") 
     759            elif(node.func.id == 'int'): 
    750760                self.write_c('(int) ') 
    751             elif (node.func.id == "SINCOS"): 
    752                 self.WriteSincos (node) 
     761            elif(node.func.id == "SINCOS"): 
     762                self.WriteSincos(node) 
    753763                return 
    754764            else: 
     
    760770        for arg in node.args: 
    761771            write_comma() 
    762             self.visited_args = True  
     772            self.visited_args = True 
    763773            self.visit(arg) 
    764774        for keyword in node.keywords: 
     
    766776            self.write_c(keyword.arg + '=') 
    767777            self.visit(keyword.value) 
    768         if hasattr (node, 'starargs'): 
     778        if hasattr(node, 'starargs'): 
    769779            if node.starargs is not None: 
    770780                write_comma() 
    771781                self.write_c('*') 
    772782                self.visit(node.starargs) 
    773         if hasattr (node, 'kwargs'): 
     783        if hasattr(node, 'kwargs'): 
    774784            if node.kwargs is not None: 
    775785                write_comma() 
     
    780790    def visit_Name(self, node): 
    781791        self.write_c(node.id) 
    782         if ((node.id in self.C_Pointers) and (not self.SubRef)): 
     792        if((node.id in self.C_Pointers) and(not self.SubRef)): 
    783793            self.write_c("[0]") 
    784794        name = "" 
    785795        sub = node.id.find("[") 
    786         if (sub > 0): 
     796        if(sub > 0): 
    787797            name = node.id[0:sub].strip() 
    788798        else: 
    789799            name = node.id 
    790800#       add variable to C_Vars if it ins't there yet, not an argument and not a number 
    791         if ((name not in self.C_Functions) and (name not in self.C_Vars) and (name not in self.C_IntVars) and (name not in self.arguments) and (name.isnumeric () == False)): 
    792             if (self.InSubscript): 
    793                 self.C_IntVars.append (node.id) 
     801        if((name not in self.C_Functions) and (name not in self.C_Vars) and \ 
     802            (name not in self.C_IntVars) and (name not in self.arguments) and \ 
     803            (name.isnumeric() == False)): 
     804            if(self.InSubscript): 
     805                self.C_IntVars.append(node.id) 
    794806            else: 
    795                 self.C_Vars.append (node.id) 
     807                self.C_Vars.append(node.id) 
    796808 
    797809    def visit_Str(self, node): 
     
    816828            s = "" 
    817829            for idx, item in enumerate(node.elts): 
    818                 if ((idx > 0) and (len(s) > 0)): 
     830                if((idx > 0) and(len(s) > 0)): 
    819831                    s += ', ' 
    820                 if (hasattr (item, 'id')): 
     832                if(hasattr(item, 'id')): 
    821833                    s += item.id 
    822                 elif (hasattr(item,'n')): 
     834                elif(hasattr(item, 'n')): 
    823835                    s += str(item.n) 
    824             if (len(s) > 0): 
    825                 self.C_Vectors.append (s) 
     836            if(len(s) > 0): 
     837                self.C_Vectors.append(s) 
    826838                vec_name = "vec"  + str(len(self.C_Vectors)) 
    827839                self.write_c(vec_name) 
     
    843855        self.write_python('}') 
    844856 
    845     def get_special_power (self, string): 
     857    def get_special_power(self, string): 
    846858        function_name = '' 
    847859        is_negative_exp = False 
    848         if (isevaluable(str(self.current_statement))): 
     860        if(isevaluable(str(self.current_statement))): 
    849861            exponent = eval(string) 
    850862            is_negative_exp = exponent < 0 
    851863            abs_exponent = abs(exponent) 
    852             if (abs_exponent == 2): 
     864            if(abs_exponent == 2): 
    853865                function_name = "square" 
    854             elif (abs_exponent == 3): 
     866            elif(abs_exponent == 3): 
    855867                function_name = "cube" 
    856             elif (abs_exponent == 0.5): 
     868            elif(abs_exponent == 0.5): 
    857869                function_name = "sqrt" 
    858             elif (abs_exponent == 1.0/3.0): 
     870            elif(abs_exponent == 1.0/3.0): 
    859871                function_name = "cbrt" 
    860         if (function_name == ''): 
     872        if(function_name == ''): 
    861873            function_name = "pow" 
    862874        return function_name, is_negative_exp 
    863875 
    864     def translate_power (self, node): 
     876    def translate_power(self, node): 
    865877# get exponent by visiting the right hand argument. 
    866878        function_name = "pow" 
     
    871883        self.current_statement = '' 
    872884        self.visit(node.right) 
    873         exponent = self.current_statement.replace(' ','') 
    874         function_name, is_negative_exp = self.get_special_power (self.current_statement) 
     885        exponent = self.current_statement.replace(' ', '') 
     886        function_name, is_negative_exp = self.get_special_power(self.current_statement) 
    875887        self.current_statement = temp_statement 
    876         if (is_negative_exp): 
    877             self.write_c ("1.0 / (") 
    878         self.write_c (function_name + " (") 
     888        if(is_negative_exp): 
     889            self.write_c("1.0 /(") 
     890        self.write_c(function_name + "(") 
    879891        self.visit(node.left) 
    880         if (function_name == "pow"): 
     892        if(function_name == "pow"): 
    881893            self.write_c(", ") 
    882894            self.visit(node.right) 
    883895        self.write_c(")") 
    884         if (is_negative_exp): 
     896        if(is_negative_exp): 
    885897            self.write_c(")") 
    886898        self.write_c(" ") 
    887899 
    888     def translate_integer_divide (self, node): 
    889         self.write_c ("(int) (") 
     900    def translate_integer_divide(self, node): 
     901        self.write_c("(int)(") 
    890902        self.visit(node.left) 
    891         self.write_c (") / (int) (") 
     903        self.write_c(") /(int)(") 
    892904        self.visit(node.right) 
    893         self.write_c (")") 
     905        self.write_c(")") 
    894906 
    895907    def visit_BinOp(self, node): 
    896908        self.write_c("(") 
    897         if ('%s' % BINOP_SYMBOLS[type(node.op)] == BINOP_SYMBOLS[ast.Pow]): 
    898             self.translate_power (node) 
    899         elif ('%s' % BINOP_SYMBOLS[type(node.op)] == BINOP_SYMBOLS[ast.FloorDiv]): 
    900             self.translate_integer_divide (node) 
     909        if('%s' % BINOP_SYMBOLS[type(node.op)] == BINOP_SYMBOLS[ast.Pow]): 
     910            self.translate_power(node) 
     911        elif('%s' % BINOP_SYMBOLS[type(node.op)] == BINOP_SYMBOLS[ast.FloorDiv]): 
     912            self.translate_integer_divide(node) 
    901913        else: 
    902914            self.visit(node.left) 
     
    932944 
    933945    def visit_Subscript(self, node): 
    934         if (node.value.id not in self.C_Pointers): 
    935             self.C_Pointers.append (node.value.id) 
     946        if(node.value.id not in self.C_Pointers): 
     947            self.C_Pointers.append(node.value.id) 
    936948        self.SubRef = True 
    937949        self.visit(node.value) 
     
    951963        if node.step is not None: 
    952964            self.write_python(':') 
    953             if not (isinstance(node.step, Name) and node.step.id == 'None'): 
     965            if not(isinstance(node.step, Name) and node.step.id == 'None'): 
    954966                self.visit(node.step) 
    955967 
     
    10481060 
    10491061def Iq1(q, porod_scale, porod_exp, lorentz_scale, lorentz_length, peak_pos, lorentz_exp=17): 
    1050     z1 = z2 = z = abs (q - peak_pos) * lorentz_length 
    1051     if (q > p): 
     1062    z1 = z2 = z = abs(q - peak_pos) * lorentz_length 
     1063    if(q > p): 
    10521064        q = p + 17 
    10531065        p = q - 5 
    10541066    z3 = -8 
    10551067    inten = (porod_scale / q ** porod_exp 
    1056                 + lorentz_scale / (1 + z ** lorentz_exp)) 
     1068                + lorentz_scale /(1 + z ** lorentz_exp)) 
    10571069    return inten 
    10581070 
    10591071def Iq(q, porod_scale, porod_exp, lorentz_scale, lorentz_length, peak_pos, lorentz_exp=17): 
    1060     z1 = z2 = z = abs (q - peak_pos) * lorentz_length 
    1061     if (q > p): 
     1072    z1 = z2 = z = abs(q - peak_pos) * lorentz_length 
     1073    if(q > p): 
    10621074        q = p + 17 
    10631075        p = q - 5 
    1064     elif (q == p): 
     1076    elif(q == p): 
    10651077        q = p * q 
    10661078        q *= z1 
    10671079        p = z1 
    1068     elif (q == 17): 
     1080    elif(q == 17): 
    10691081        q = p * q - 17 
    10701082    else: 
     
    10721084    z3 = -8 
    10731085    inten = (porod_scale / q ** porod_exp 
    1074                 + lorentz_scale / (1 + z ** lorentz_exp)) 
     1086                + lorentz_scale /(1 + z ** lorentz_exp)) 
    10751087    return inten 
    10761088 
     
    10841096    if f is not None: 
    10851097        tree = ast.parse(inspect.getsource(f)) 
    1086         tree_source = to_source (tree) 
     1098        tree_source = to_source(tree) 
    10871099        print(tree_source) 
    10881100 
    1089 def translate (functions, constants=0): 
     1101def translate(functions, constants=0): 
    10901102    sniplets = [] 
    10911103    fname = functions[1] 
    1092     python_file = open (fname, "r") 
     1104    python_file = open(fname, "r") 
    10931105    source = python_file.read() 
    10941106    python_file.close() 
    1095     tree = ast.parse (source) 
    1096     sniplet = to_source (tree, functions) # in the future add filename, offset, constants 
     1107    tree = ast.parse(source) 
     1108    sniplet = to_source(tree, functions) # in the future add filename, offset, constants 
    10971109    sniplets.append(sniplet) 
    1098     return ("\n".join(sniplets)) 
    1099  
    1100 def get_file_names (): 
     1110    return("\n".join(sniplets)) 
     1111 
     1112def get_file_names(): 
    11011113    fname_in = "" 
    11021114    fname_out = "" 
    1103     if (len(sys.argv) > 1): 
     1115    if(len(sys.argv) > 1): 
    11041116        fname_in = sys.argv[1] 
    1105         fname_base = os.path.splitext (fname_in) 
    1106         if (len (sys.argv) == 2): 
    1107             fname_out = str (fname_base[0]) + '.c' 
     1117        fname_base = os.path.splitext(fname_in) 
     1118        if(len(sys.argv) == 2): 
     1119            fname_out = str(fname_base[0]) + '.c' 
    11081120        else: 
    11091121            fname_out = sys.argv[2] 
    1110         if (len (fname_in) > 0): 
    1111             python_file = open (sys.argv[1], "r") 
    1112             if (len (fname_out) > 0): 
    1113                 file_out = open (fname_out, "w+") 
     1122        if(len(fname_in) > 0): 
     1123            python_file = open(sys.argv[1], "r") 
     1124            if(len(fname_out) > 0): 
     1125                file_out = open(fname_out, "w+") 
    11141126    return len(sys.argv), fname_in, fname_out 
    11151127 
     
    11201132        fname_in = "" 
    11211133        fname_out = "" 
    1122         if (len (sys.argv) == 1): 
    1123             print ("Usage:\npython parse01.py <infile> [<outfile>] (if omitted, output file is '<infile>.c'") 
     1134        if(len(sys.argv) == 1): 
     1135            print("Usage:\npython parse01.py <infile> [<outfile>](if omitted, output file is '<infile>.c'") 
    11241136        else: 
    11251137            fname_in = sys.argv[1] 
    1126             fname_base = os.path.splitext (fname_in) 
    1127             if (len (sys.argv) == 2): 
    1128                 fname_out = str (fname_base[0]) + '.c' 
     1138            fname_base = os.path.splitext(fname_in) 
     1139            if(len(sys.argv) == 2): 
     1140                fname_out = str(fname_base[0]) + '.c' 
    11291141            else: 
    11301142                fname_out = sys.argv[2] 
    1131             if (len (fname_in) > 0): 
    1132                 python_file = open (sys.argv[1], "r") 
    1133                 if (len (fname_out) > 0): 
    1134                     file_out = open (fname_out, "w+") 
     1143            if(len(fname_in) > 0): 
     1144                python_file = open(sys.argv[1], "r") 
     1145                if(len(fname_out) > 0): 
     1146                    file_out = open(fname_out, "w+") 
    11351147                functions = ["MultAsgn", "Iq41", "Iq2"] 
    11361148                tpls = [functions, fname_in, 0] 
    1137                 c_txt = translate (tpls) 
    1138                 file_out.write (c_txt) 
     1149                c_txt = translate(tpls) 
     1150                file_out.write(c_txt) 
    11391151                file_out.close() 
    11401152    except Exception as excp: 
    1141         print ("Error:\n" + str(excp.args)) 
     1153        print("Error:\n" + str(excp.args)) 
    11421154    print("...Done") 
Note: See TracChangeset for help on using the changeset viewer.