Debian Codegraph @

src/drel/py_from_ast.py

raw symbols SCIP
1 # These routines convert a dREL AST into Python text. The top-level
2 # AST builder encloses the python fragment produced by the AST traverser.
3 # The function transformer turns dREL function calls into
4 # the appropriate Python/User-defined/Numpy function calls.
5 #
6 #
7 # <*>=
8 # To maximize python3/python2 compatibility
9 from __future__ import print_function
10 from __future__ import unicode_literals
11 from __future__ import division
12 from __future__ import absolute_import
13
14 # The unicode type does not exist in Python3 as the str type
15 # encompasses unicode. PyCIFRW tests for 'unicode' would fail
16 # Suggestions for a better approach welcome.
17
18 if isinstance(u"abc",str): #Python3
19 unicode = str
20
21 import re
22 from CifFile import CifError
23 # Configuration.
24 #
25 # The function tables below describe how generic dREL operations are transformed into API-
26 # specific function calls. This is mostly concerned with calls to the ciffile object
27 # passed to the builder. Note that changing this interface will only work if the objects
28 # returned by the various calls behave as follows: (i) packets returned by
29 # the ``semantic packet'' call should have dataname-indexed values that are accessible through the
30 # Python 'getattr' function (ii) a whole column of data is returned for values returned
31 # by data access for looped datanames (iii) StarList and StarTable are understood
32 # value types (iv) the results of all applications are values ready for calculation.
33 #
34 #
35 # <Configuration>=
36 pycifrw_func_table = { #how to use PyCIFRW CifFile objects
37 "data_access": "ciffile[%s]", # argument is dataname to be accessed
38 "optional_data_access":"ciffile.get(%s,None)",
39 "element_no": "%s[%s]", # accessing a particular element of the result of data_access
40 "count_data": "len(%s)", # number of elements for result of data_access
41 "cat_names":"ciffile.dictionary.names_in_cat(%s)", #names in category %s
42 "has_name":"ciffile.has_key_or_alias(%s)",
43 "semantic_packet":"ciffile.GetKeyedSemanticPacket(%s,%s)" #get a packet for key, value
44 }
45
46 # The AST builder puts the infrastructure around the AST statement list to turn it into a
47 # function call with two arguments: a dictionary and a data file. The target id will
48 # usually be the dataname that is being defined. We always call this ``__dreltarget''
49 # within the generated method which is why we need to know the target_id.
50 #
51 # Note that the ``_cat.name'' syntax is significant in the dREL context, and therefore
52 # in the context of the generator. Only names with this form are possible targets,
53 # and the category part of the name is used to automatically generate the appropriate
54 # loop index when that category is referred to within the code.
55 #
56 # The generated function can be called to generate all values in a loop column, or only
57 # a single value, by setting keyword argument ``packet_no'' to the required packet, or
58 # -1. If the 'depends' keyword is True, a list of datanames that this function depends
59 # upon is returned as a second item.
60 #
61 # The 'loopable' argument is a table of categories that are loopable, with the values
62 # being ([key_ids], datanames).
63 #
64 #
65 # <AST builder>=
66 def make_python_function(in_ast,func_name,targetname, special_ids=[{}],
67 func_table = pycifrw_func_table, cif_dic=None,cat_meth=False,
68 func_def = False, have_sn=True,loopable={},debug=None,depends=False):
69 """Convert in_ast to python code"""
70 if debug is not None:
71 print("incoming AST:")
72 print(repr(in_ast))
73 func_text,withtable,dependencies,cur_row = start_traverse(in_ast,func_table,target_id=targetname,cat_meth=cat_meth,loopable=loopable,debug=debug,func=func_def,cif_dic=cif_dic)
74 if debug is not None:
75 print('Start========')
76 print(func_text)
77 print('End==========')
78 if func_def and not depends:
79 return func_text
80 elif func_def:
81 return func_text, None
82 # now indent the string
83 noindent = func_text.splitlines()
84 # get the minimum indent and remove empty lines
85 no_spaces = [re.match(r' *',a).end() for a in noindent if a] #drop empty lines
86 min_spaces = min(no_spaces)+4 # because we add 4 ourselves to everything
87 if len(withtable) > 0 or cur_row: # a loop method
88 # Creating functions for looped categories. We provide a shell function which
89 # internally calls the transformed function with the option of performing the
90 # calculation on a single packet or on the whole category. The existence of the
91 # "current_row" functionality means that we have to cover the situation where no
92 # other items in a category are referred to and so we need to work out the total
93 # number of packets during execution of the method.
94 #
95 #
96 # <Create function header for loop>=
97 d_vars = [a[1][0] for a in withtable.items()]
98 if cur_row:
99 d_vars = d_vars + ['__current_row']
100 dummy_vars = ",".join(d_vars)
101 actual_names = [k for k in withtable.keys()]
102 actual_names = [func_table["data_access"]% ("'"+a+"'") for a in actual_names]
103 # intercept optional values and replace with [] if None
104 optional_names = ["__option_w%d"%n for n,k in enumerate(withtable.keys()) if withtable[k][2]]
105 if cur_row:
106 actual_names+=['__row_id']
107 final_names = actual_names[:]
108 one_pack_names = [func_table["element_no"] % (a,"packet_no") for a in actual_names]
109 for n,k in enumerate(withtable.keys()):
110 if withtable[k][2]:
111 final_names[n]="__option_w%d"%n #pre-evaluated
112 one_pack_names[n] = "__option_w%d"%n
113 map_names = ",".join(final_names)
114 one_packet_each = ",".join(one_pack_names)
115 preamble = "def %s(ciffile,packet_no=-1):\n" % (func_name)
116 preamble +=" try:\n"
117 preamble +=" from itertools import repeat,imap\n" #note that imap might fail
118 preamble +=" except ImportError: #python3\n"
119 preamble +=" imap = map\n"
120 preamble +=" def drel_func(%s):\n" % dummy_vars
121 # for debugging
122 print_instruction = "'Function passed variables "+("{!r} "*len(d_vars))+"'.format("+dummy_vars+",)"
123 preamble +=" print(%s)\n" % print_instruction
124 # preamble +=" print('Globals inside looped drel_func:' + repr(globals())\n")
125 # the actual function gets inserted here
126 # Handle the optional names
127 end_body = "\n"
128 for n,one_opt in enumerate(withtable.keys()):
129 if withtable[one_opt][2]:
130 end_body += " try:\n"
131 end_body += " %s%d = %s\n" % ("__option_w",n,func_table["optional_data_access"]%("'"+one_opt+"'"))
132 end_body += " except:\n"
133 end_body += " %s%d = None\n" % ("__option_w",n)
134 end_body+= " if packet_no < 0: #map\n"
135 for one_opt in optional_names:
136 end_body += " if %s is None: %s = repeat(None)\n" % (one_opt,one_opt)
137
138 if cur_row and len(actual_names) > 1: #i.e. have real names from category
139 end_body +=" __row_id = range(%s)\n" % (func_table['count_data'] % ("'"+actual_names[0]+"'"))
140 elif cur_row and len(actual_names)==1: #so no actual names available
141
142 end_body += " cat_names = %s\n" % (func_table["cat_names"] % ("'"+getcatname(targetname)[0]+"'"))
143 end_body += " have_name = [a for a in cat_names if %s]\n" % (func_table["has_name"] % "a")
144 end_body += " if len(have_name)>0:\n"
145 end_body += " full_length = %s \n" % (func_table["count_data"] % (func_table["data_access"] % "have_name[0]"))
146 end_body += " __row_id = range(full_length)\n"
147 end_body += " else:\n"
148 end_body += " return []\n"
149
150 end_body+= " return list(imap(drel_func,%s))\n" % (map_names+",")
151 end_body+= " else:\n"
152 end_body+= " return drel_func(%s)\n" % one_packet_each
153
154 else:
155 # Un'with'ed data can simply be called with the dictionary and ciffile, with no
156 # need for any extra variables
157 #
158 #
159 # <Create function header for unlooped data>=
160 preamble = "def %s(ciffile):\n" % func_name
161 #preamble +=" global StarList#from CifFile.drel import drel_runtime\n"
162 end_body = ""
163
164 if cat_meth:
165 preamble += " "*8 + "__dreltarget = {}\n" # initialise
166 num_header = """
167 import math,cmath
168 try:
169 import numpy
170 except:
171 print("Can't import numerical python, this method may not work")
172 """
173 preamble += num_header
174 indented = map(lambda a:" "*8 + a +"\n",noindent) #indent dREL body
175 postamble = ""
176 postamble += " "*8 + "return __dreltarget"
177 final = preamble + "".join(indented) + postamble + end_body
178 if not depends:
179 return final
180 else: return final, dependencies
181
182 # The AST traverser is a recursive function which is passed a node.
183 # It returns a string. We define it inside an external function so that
184 # our global variables are actually just local variables of the
185 # enclosing function. Variable [[special_info.[special_id] ]] is a list
186 # of scopes, each containing a table of variables that need to be
187 # specially handled, either because they correspond to datanames (first
188 # entry in list) or to variables that have been aliased to categories
189 # via loop or with statements. The scoping is not used particularly
190 # often in the following code as the example methods do not really test
191 # out the scoping.
192 #
193 # A variable defined in a loop statement will also have a loop index
194 # that needs to be incremented and used to index a packet; this is the
195 # second entry in the list indexed by the variable alias. The second
196 # entry is also used to hold the dummy variable for the 'with'
197 # statement. The generated function can thus be mapped across the keys
198 # of the with table to calculate the whole column of a category.
199 #
200 # The final boolean entry determines whether the second entry is for looping (True) or
201 # not (False).
202 #
203 # At the beginning of the traverse we initialise special_id with the explicit
204 # category name if we are in a loopable category, so that any references to items
205 # in this category will be dealt with as for explicit with statements. Note that
206 # we append a single underscore to the alias to allow it to be picked up when
207 # the search for special ids is undertaken e.g. in the ATTRIBUTE case.
208 #
209 # The [[packet_vars]] entry is a table of packets that have been assigned to a
210 # variable name. We need to keep this around in order to properly manage them
211 # when their attributes are accessed, as this access will be by simple name,
212 # without the category ID.
213 #
214 # The [[need_current_row]] entry is fed back from the traverse and indicates that
215 # the current function will require access to the current packet.
216 #
217 # The [[rhs]] is an entry to indicate whether or not we are dealing with the rhs
218 # of an assignment. If False, then we are dealing with the lhs, and if None, then
219 # we are not in an assignment.
220 #
221 # The [[inif]] entry flags if we are inside an IF statement, in which case dataitems
222 # may not need to be provided in order to proceed with calculation.
223 #
224 #
225 # <AST traverser>=
226 def start_traverse(in_node,api_table,target_id=None,loopable={},cat_meth=False,debug=None, func=False,
227 cif_dic=None):
228 special_info = {"special_id":[{}],"target_id":target_id,"withtable":{},"sub_subject":"",
229 "depends":set(),"loopable_cats":loopable,"packet_vars":{},
230 "need_current_row":False,"rhs":None,"inif":False}
231 # create a virtual enclosing 'with' statement
232 if target_id is not None and not cat_meth and not func:
233 cat,name = getcatname(target_id)
234 special_info["special_id"][-1].update({"_"+cat:[cat,"",False]})
235 if cat in special_info["loopable_cats"].keys(): #
236 special_info["special_id"][-1]["_"+cat][1] = "looped_cat"
237 # Although in most cases we could simply directly write in the binary maths
238 # operator, we do a table lookup to facilitate reuse of this code with other
239 # language targets. The augmented assignment table gives the function name
240 # to use as we need to cover array structures as well.
241 #
242 #
243 # <Maths operator conversion table>=
244 mathop_table = {"+":None, "-":None, "<":"<", "*":None, "/":None,
245 "&":"&", "|":"|",
246 ">":">", "<=":"<=", ">=":">=", "!=":"!=",
247 "or":" or ", "and":" and ",
248 "==":"==", "in":" in ", "not in":" not in ",
249 "^":None,"**":"**"}
250
251 aug_assign_table = {"++=":"drel_runtime.aug_append",
252 "+=":"drel_runtime.aug_add",
253 "-=":"drel_runtime.aug_sub",
254 "--=":"drel_runtime.aug_remove"}
255
256 def traverse_ast(in_node,debug=debug):
257 if isinstance(in_node,(unicode,str)):
258 return in_node
259 if isinstance(in_node[0],list):
260 raise SyntaxError('First element of AST Node must be string: ' + repr(in_node))
261 node_type = in_node[0]
262 if debug == node_type:
263 print(node_type + ": " + repr(in_node))
264 if node_type == "ARGLIST":
265 pass
266 # These are the simple constants that we have detected.
267 #
268 #
269 # <Literal nodes>=
270 elif node_type == "BINARY":
271 return("%d" % int(in_node[1],base=2))
272 elif node_type == "FALSE":
273 return("False")
274 elif node_type == "REAL":
275 return(in_node[1])
276 elif node_type == "HEX":
277 return("%d" % int(in_node[1],base=16))
278 elif node_type == "INT":
279 return(in_node[1])
280 elif node_type == "IMAGINARY":
281 return(in_node[1])
282 elif node_type == "OCTAL":
283 return("%d" % int(in_node[1],base=8))
284
285 # We need to catch all variables and other primary items here. Note that
286 # for now literals are simply repeated, as the Python representation is
287 # the same as the dREL representation. We make a note of all tags
288 # mentioned so that we can create a dependency tree.
289 #
290 #
291 # <Other primaries>=
292 elif node_type == "ATOM":
293 if isinstance(in_node[1],(unicode,str)):
294 # pick up built-in literals
295 if in_node[1].lower() == 'twopi':
296 return "(2.0 * math.pi)"
297 if in_node[1].lower() == 'pi':
298 return "math.pi"
299 else:
300 return in_node[1]
301 else:
302 return traverse_ast(in_node[1])
303 elif node_type == "ITEM_TAG":
304 return in_node[1]
305 elif node_type == "LITERAL":
306 return in_node[1]
307 elif node_type == "LIST":
308 if len(in_node)==1: #empty list
309 return "StarList([])"
310 if special_info["rhs"] == True:
311 outstring = "StarList(["
312 else:
313 outstring = ""
314 for list_elem in in_node[1:]:
315 outstring = outstring + traverse_ast(list_elem) + ","
316 if special_info["rhs"] == True:
317 return outstring[:-1] + "])"
318 else:
319 return outstring[:-1]
320 elif node_type == "TABLE":
321 if len(in_node)==1:
322 return "StarTable({})"
323 else:
324 outstring = "{"
325 for table_elem in in_node[1:]:
326 outstring = outstring + traverse_ast(table_elem[0])+":"+traverse_ast(table_elem[1]) +","
327 return outstring[:-1] + "}"
328 # Subscriptions, of form primary [ subscript ]. A subscription may be a simple element lookup, as in
329 # a[1], or it may be a keyed lookup of a different category using the
330 # value within the square brackets e.g. p[m.symop]. If we find the primary is something that
331 # we are looping or withing, we immediately adopt the keyed lookup. If the
332 # primary is an item tag, then we can deduce that a keyed lookup follows as there is no other
333 # function for an item tag without accompanying attribute to make a full dataname.
334 # It is also possible for a delayed attribute lookup to occur, for example,
335 # a = atom_site[label] and later b = a.position, so we catch any subscriptions applied to
336 # loop category names.
337 #
338 # We convert list-valued subscriptions to a sequence of Python subscriptions in order
339 # to catch the valid numpy a[1,2,1...] style multi-dimensional array access.
340 #
341 # In all other cases we have a plain subscription as for normal Python.
342 #
343 #
344 # <Process subscriptions>=
345 elif node_type == "SUBSCRIPTION": # variable, single expression
346 newid = 0
347 if in_node[1][0] == "ATOM" and in_node[1][1][0] == "ITEM_TAG": #keyed lookup
348 print("Found category used as item tag: subscribing")
349 newid = [in_node[1][1][1][1:],False,False] #drop underscore and remember
350 else:
351 primary = traverse_ast(in_node[1])
352 # check to see if this is a special variable
353 for idtable in special_info["special_id"]:
354 newid = idtable.get(primary,0)
355 if newid: break
356 if primary in special_info["loopable_cats"].keys(): #loop category used
357 newid = [primary,False,False]
358 break
359 if newid:
360 #FIXME: the dataname may not be the <cat>.<obj> construction (eg pdCIF)
361 key_items = ["_"+newid[0]+"."+s for s in special_info["loopable_cats"][newid[0]][0]] #key name
362 special_info["depends"].update([k.lower() for k in key_items])
363 get_loop = api_table["semantic_packet"] % (traverse_ast(in_node[2]),"'"+newid[0]+"'")
364 special_info["sub_subject"] = newid[0] #in case of attribute reference following
365 print("Set sub_subject to %s" % special_info["sub_subject"])
366 return get_loop
367 else:
368 outstring = primary + "["
369 outstring = outstring + traverse_ast(in_node[2]) + "]"
370 return outstring
371
372 # Attribute references. We need to catch all attribute references to
373 # special variables (those defined by loop or with statements). For
374 # ``with'' variables, we create a dummy variable for every attribute
375 # reference, keyed by the actual dataname looked up via the (cat,obj)
376 # tuple. We store the order that it appears in the function call that
377 # is created, so that we can include the function within a 'map'
378 # statement and give the correct order of items. Additionally, if the
379 # variable appears inside an IF statement, evaluation may be optional,
380 # so a flag is set (True means optional). So the withtable has syntax
381 # {``dataname'':(dummyname,dummyorder,optional = True/False)}.
382 #
383 # Furthermore, the square bracket syntax for keyed access to data packets requires
384 # that the result of the keyed access is accessed by attribute. While dREL does not
385 # require the full dataname, PyCIFRW does, so we have to store the category that
386 # the keyed access comes from and add that back in - this is what 'sub_subject'
387 # contains. Note also that this access can be delayed by assigning to the
388 # packet (e.g. a = atom_site[label]; b = a.xyz), so we check the list of
389 # such assignments kept in special_info[``packet_vars''].
390 #
391 # In a further twist, when keyed access followed directly by attribute
392 # lookup in a single primary is performed on an explicit category, that
393 # category should have an underscore prepended on the principle the
394 # final result will be a dataname. So we need to check for this
395 # construction before deciding how to translate the 'primary' part of
396 # the construction to Python.
397 #
398 # Note also that we should not assume that a dataname is constructed as
399 # ``_category.object''. Rather, we should look up the correct form of
400 # the dataname using the provided dictionary.
401 #
402 #
403 # <Process attribute reference>=
404 elif node_type == "ATTRIBUTE": # id/tag , att
405 outstring = ""
406 newid = 0
407 # check for special ids
408 primary = traverse_ast(in_node[1]) # this will set sub_subject if necessary
409 for idtable in special_info["special_id"]:
410 newid = idtable.get(primary,0)
411 if newid: break
412 if newid:
413 #catch our output name
414 true_name = cif_dic.get_name_by_cat_obj(newid[0].lower(),in_node[2].lower(), give_default = True).lower()
415 if true_name == special_info.get("target_id","").lower():
416 outstring = "__dreltarget"
417 special_info["have_drel_target"] = True
418 # if we are looping, we add a loop prefix. If we are withing an
419 # unlooped category, we put the full name back.
420 elif newid[2] or (not newid[2] and not newid[1]): # looping or simple with
421 outstring = api_table["data_access"] % ('"' +true_name +'"')
422 special_info["depends"].add(true_name)
423 if newid[1]: # a loop statement requires an index
424 outstring += "[" + newid[1]+ "]"
425 else: # a with statement; capture the name and create a dummy variable
426 if true_name not in special_info["withtable"]: #new
427 position = len(special_info["withtable"])
428 new_var = "__w%d" % position
429 isoptional = special_info["inif"]
430 special_info["withtable"][true_name] = (new_var,position,isoptional)
431 outstring += special_info["withtable"][true_name][0]
432 special_info["depends"].add(true_name)
433 elif in_node[1][0] == "ATOM" and primary[0] == "_": # a cat/obj name
434 fullname = cif_dic.get_name_by_cat_obj(primary,in_node[2]).lower()
435 # a simple cat.obj dataname from the dictionary
436 if special_info.get("target_id","").lower() == fullname:
437 outstring = "__dreltarget"
438 special_info["have_drel_target"] = True
439 else:
440 special_info["depends"].add(fullname)
441 outstring = api_table["data_access"] % ("'" + fullname + "'")
442 else: # default to Python attribute access
443 # check for packet variables
444 if primary in special_info["packet_vars"]:
445 real_cat = special_info["packet_vars"][primary]
446 fullname = cif_dic.get_name_by_cat_obj(real_cat,in_node[2])
447 special_info['depends'].add(fullname)
448 elif special_info["sub_subject"]:
449 fullname = cif_dic.get_name_by_cat_obj(special_info["sub_subject"],in_node[2])
450 special_info['depends'].add(fullname)
451 else: # not anything special
452 fullname = in_node[2]
453 outstring = "getattr(" + primary + ",'" + fullname + "')"
454 # sub_subject no longer relevant after attribute resolution
455 special_info['sub_subject'] = ""
456 return outstring
457
458 # Function calls. We catch two special cases. If 'Current_Row'' is called
459 # we set a flag to ask the calling environment to provide us with a row
460 # number, as the generated function is always row-independent.
461 #
462 # The List constructor in dREL will convert a single argument into a list, or
463 # else multiple arguments are bundled into a list.
464 #
465 #
466 # <Process function call>=
467 elif node_type == "FUNC_CALL":
468 if in_node[1] == "Current_Row": #not a function but a keyword really
469 outstring = "__current_row"
470 special_info["need_current_row"]=True
471 else:
472 func_name,every_arg_prefix,postfix = get_function_name(in_node[1])
473 outstring = func_name + "( "
474 if func_name == "list" and len(in_node[2])>1: #special case
475 outstring = outstring + "["
476 for argument in in_node[2]:
477 outstring = outstring + every_arg_prefix + traverse_ast(argument) + ","
478 if postfix == None: # signal for dictionary defined
479 outstring = outstring + "ciffile)"
480 else:
481 outstring = outstring[:-1]
482 if func_name == "list" and len(in_node[2])>1:
483 outstring = outstring + "]"
484 outstring = outstring + ")" + postfix
485 return outstring
486
487 elif node_type == "SLICE": # primary [[start,finish,step],[...]
488 outstring = traverse_ast(in_node[1]) + "["
489 slice_list = in_node[2]
490 for one_slice in slice_list:
491 print("one_slice {}".format(one_slice))
492 if len(one_slice) == 0:
493 outstring += ":"
494 elif len(one_slice) == 1 and one_slice[0] == []:
495 outstring += ":"
496 elif len(one_slice) == 2 and one_slice[0] == []:
497 outstring += "0:" + traverse_ast(one_slice[1])
498 elif one_slice[0] == "EXPR": #not a slice as such
499 outstring += traverse_ast(one_slice)
500 elif len(one_slice) >0: # at least start
501 outstring += traverse_ast(one_slice[0]) + ":"
502 if len(one_slice) >1: #start,finish only
503 outstring += traverse_ast(one_slice[1])
504 if len(one_slice) == 3: #step as well
505 outstring += ":" + traverse_ast(one_slice[2])
506 outstring += ","
507 outstring = outstring[:-1] + "]"
508 return outstring
509
510 # Maths. We have to catch vector and matrix operations and farm them out
511 # to numpy. Not implemented yet. A binary maths operation is 'mathop'. We
512 # take a shortcut and assume that the operators are written identically in
513 # dREL and python, so that the AST contains the textual form of the operator.
514 #
515 #
516 # <Maths>=
517 elif node_type == "MATHOP":
518 op = mathop_table[in_node[1]]
519 first_arg = traverse_ast(in_node[2])
520 second_arg = traverse_ast(in_node[3])
521 if op is not None: #simple operation
522 outstring = first_arg + op + second_arg
523 else:
524 outstring = fix_mathops(in_node[1],first_arg,second_arg)
525 return outstring
526 elif node_type == "SIGN":
527 outstring = "drel_runtime.drel_dot(" + in_node[1] + "1," + traverse_ast(in_node[2])+")"
528 return outstring
529 elif node_type == "UNARY":
530 outstring = in_node[1] + " " + traverse_ast(in_node[2])
531 return outstring
532
533 # Compound statements. We make a copy of the target expressions in the FOR statement
534 # to allow these objects to be modified inside the suite.
535 #
536 # The expression inside an IF statement may never be executed, so we do not have to
537 # provide a value for any dataitems referenced here. We flag this by setting the
538 # ``inif'' variable to True, and any dataitems referenced when this flag is True
539 # are provided as keywords to the
540 #
541 #
542 # <Compound statements>=
543 elif node_type == "IF_EXPR": #IF_EXPR test true_suite [ELSE IF_EXPR] false_suite
544 outstring = "if "
545 outstring = outstring + traverse_ast(in_node[1])
546 outstring = outstring + ":"
547 old_inif = special_info["inif"]
548 special_info["inif"] = True
549 true_bit = traverse_ast(in_node[2])
550 outstring = outstring + add_indent("\n"+true_bit) #indent
551 elseif = in_node[3]
552 if len(elseif)!=0:
553 for one_cond in elseif: #each entry is condition, suite
554 outstring += "\nelif " + traverse_ast(one_cond[0]) + ":"
555 outstring += add_indent("\n" + traverse_ast(one_cond[1]))
556 if len(in_node)>4:
557 outstring = outstring + "\nelse:"
558 false_bit = traverse_ast(in_node[4])
559 outstring = outstring + add_indent("\n"+false_bit) #indent
560 special_info["inif"] = old_inif
561 return outstring
562
563 # dREL for statements include the final value, whereas a python range will include
564 # everything up to the final number
565 elif node_type == "DO": #DO ID = start, finish, incr, suite
566 outstring = "for " + in_node[1] + " in range(" + traverse_ast(in_node[2]) + ","
567 finish = traverse_ast(in_node[3])
568 increment = traverse_ast(in_node[4])
569 outstring = outstring + finish + "+1" + "," + increment
570 outstring = outstring + "):"
571 suite = add_indent("\n"+traverse_ast(in_node[5]))
572 return outstring + suite
573 elif node_type == "FOR": # FOR target_list expression_list suite
574 outstring = "for "
575 for express in in_node[1]:
576 outstring = outstring + traverse_ast(express) + ","
577 outstring = outstring[:-1] + " in "
578 special_info["rhs"] = True
579 for target in in_node[2]:
580 outstring += "copy("+traverse_ast(target) + "),"
581 special_info["rhs"] = None
582 outstring = outstring[:-1] + ":" + add_indent("\n" + traverse_ast(in_node[3]))
583 return outstring
584 elif node_type == "REPEAT": #REPEAT suite
585 outstring = "while True:" + add_indent("\n" + traverse_ast(in_node[1]))
586 return outstring
587 # With statements. ``With'' in dREL is ultimately just a simple alias
588 # (see separate document discussing this) if we consider that a looped
589 # item method is necessarily mapped across all packets of the category,
590 # or in other words it can *only* operate on the 'current packet'. So we
591 # make a memo of the aliases that are currently in use and don't
592 # actually output anything.
593 #
594 # We do need to catch the case where a looped category has an explicit
595 # ``with'' statement, as this should replace the implicit ``with''.
596 #
597 #
598 # <With statements>=
599 elif node_type == "WITH": #new_id old_id suite
600 # each entry in special_id is [alias:[cat_name,loop variable, is_loop]]
601 alias_id = in_node[1]
602 cat_id = in_node[2]
603 is_already_there = [a for a in special_info['special_id'][-1].keys() if \
604 special_info['special_id'][-1][a][0] == cat_id]
605 if len(is_already_there)>0:
606 del special_info['special_id'][-1][is_already_there[0]]
607 print("Found explicit loop category alias: %s for %s" % (alias_id,cat_id) )
608 special_info['special_id'][-1].update({alias_id:[cat_id,"",False]})
609 if in_node[2] in special_info['loopable_cats'].keys(): #flag this
610 special_info['special_id'][-1][alias_id][1] = "looped_cat"
611 outstring = traverse_ast(in_node[3])
612 return outstring
613
614 # Loop statements involve running over all packets in a category, substituting
615 # for datanames as necessary and inserting the packet index as well.
616 #
617 #
618 # <Loop statements>=
619 elif node_type == "LOOP": #ALIAS CAT LOOPVAR COMP COMPVAR SUITE
620 alias_id = in_node[1]
621 cat_id = in_node[2]
622 var_info = [cat_id,"",False]
623 if cat_id not in special_info['loopable_cats'].keys():
624 message = "%s is not a loopable category (must be one of:\n%s)" % (cat_id,special_info['loopable_cats'].keys())
625 print(message)
626 raise CifError(message)
627 #loop over some index
628 loop_num = len(special_info['special_id'][-1])+1
629 if in_node[3] == "": # provide our own
630 loop_index = "__pi%d" % loop_num
631 else:
632 loop_index = in_node[3]
633 var_info[1] = loop_index
634 var_info[2] = True
635 special_info['special_id'][-1].update({alias_id:var_info})
636 # now emit some text: first to find the length of the category
637 # loopable cats contains a list of names defined for the category
638 # this might not be robust as we ignore alternative resolutions of the (cat,name) pair
639 catnames = set([a[1][0] for a in cif_dic.cat_obj_lookup_table.items() if a[0][0]==cat_id.lower()])
640 outstring = "__pyallitems = " + repr(catnames)
641 outstring += "\nprint('names in cat = %s' % repr(__pyallitems))"
642 outstring += "\n" + "__pycitems = [a for a in __pyallitems if %s]" % (api_table["has_name"] % "a")
643 outstring += "\nprint('names in cat -> %s' % repr(__pycitems))\n"
644 cat_key = cif_dic[cat_id]['_category_key.name'][0] #take official key
645 # If there is nothing in the category, provoke category creation by evaluating the key
646 outstring += "if len(__pycitems)==0:\n"
647 outstring += " __pydummy = %s\n" % (api_table["data_access"] % repr(cat_key))
648 outstring += " __pycitems = [a for a in __pyallitems if %s]\n" % (api_table["has_name"] % "a")
649 outstring += " print('After category creation, names in cat ->' + repr(__pycitems))\n"
650 special_info["depends"].add(cat_key) #add key as a dependency
651 if var_info[2] == True:
652 access_string = api_table["count_data"] % (api_table["data_access"] % "__pycitems[0]")
653 outstring += "\n" + "__loop_range%d = range(%s)" % (loop_num,access_string)
654 else:
655 outstring += "\n" + "__loop_range%d = [0]" % loop_num
656 #outstring +="\n" + "for __noloop in [0]:"
657 # deal with this comparison test
658 if in_node[4] != "":
659 outstring += "\n" + "__loop_range%d = [a for a in __loop_range%d if a %s %s]" % (loop_num,loop_num,in_node[4],in_node[5])
660 # now output the looping command
661 outstring += "\n" + "for %s in __loop_range%d:" % (loop_index,loop_num)
662 # now the actual body of the loop
663 loop_body = traverse_ast(in_node[6])
664 outstring = outstring + add_indent("\n"+loop_body)
665 return outstring
666
667 # Function arguments can have their types explicitly specified, but we don't make use
668 # of this. See comments elsewhere on how to deal with function binding, or why we don't
669 # need to do imports at this level. The draft cif_core dictionary assumes access to
670 # the data file (see function SymEquiv, which does a key-based lookup of symmetry_equiv),
671 # so we define a compulsory third argument, which must be 'ciffile' to match the naming
672 # that occurs automatically in key lookup code generation.
673 #
674 #
675 # <Function definitions>=
676 elif node_type == "FUNCTION": #FUNCTION ID ARGLIST SUITE
677 func_name = in_node[1]
678 outstring = "def %s (" % func_name
679 for one_arg in in_node[2]:
680 outstring += one_arg[0] + ","
681 outstring = outstring + "ciffile):"
682 # imports
683 #import_lines = "import numpy\nfrom CifFile.drel import drel_runtime\n"
684 import_lines = ""
685 outstring = outstring + add_indent("\n" + import_lines + traverse_ast(in_node[3])+"\nreturn %s" % func_name)
686 return outstring
687
688
689 # \section{Top level constructions}.
690 # Ultimately we end up with a list of statements.
691 #
692 #
693 # <Top level constructions>=
694 elif node_type == "STATEMENTS":
695 outstring = ""
696 for one_statement in in_node[1]:
697 # try:
698 next_bit = traverse_ast(one_statement)
699 if not isinstance(next_bit,(unicode,str)):
700 print("Unable to traverse AST for %s" % one_statement[0])
701 else:
702 outstring = outstring + next_bit + "\n"
703 # except SyntaxError as message:
704 # print("Failed, so far have \n " + outstring)
705 # outstring += "raise SyntaxError, %s" % message
706 # except:
707 # print("Failed, so far have \n " + outstring)
708 # outstring += "raise SyntaxError, %s" % `one_statement`
709 return outstring
710 # Assignment. The category-level assignments write to a table indexed by
711 # object id, so the final result will be a set of list-valued datanames for
712 # insertion into the ciffile. These are dealt with by 'FANCY_ASSIGN'. The
713 # augmented assignments in dREL handle matrices as well, so we need to
714 # reimplement them, which we do by rewriting them in the form
715 #
716 # a = func(a,b)
717 #
718 # We also need to catch packet assignments (e.g. a = atom_site[label])
719 # so that we can properly rewrite the attribute access later on, thus
720 # we keep a track of all values and the final value of sub_subject.
721 # Note that we are assuming that only one packet subscription
722 # takes place per expression, which is reasonable given that
723 # mathematical manipulations are not defined for packets.
724 #
725 # We also set the 'rhs' flag to allow us to construct lists as
726 # StarLists when on the lhs, but not the rhs.
727 #
728 #
729 # <Assignment statements>=
730 elif node_type == "ASSIGN": #Target_list ,assigner, expression list
731 outstring = ""
732 lhs_values = []
733 special_info["rhs"] = False
734 for target_value in in_node[1]:
735 one_value = traverse_ast(target_value)
736 outstring = outstring + one_value +","
737 lhs_values.append(one_value)
738 lhs = outstring[:-1]
739 rhs = ""
740 special_info["rhs"] = True
741 for order,expression in enumerate(in_node[3]):
742 rhs += traverse_ast(expression)+","
743 if special_info["sub_subject"] != "": #a full packet
744 special_info["packet_vars"].update({lhs_values[order]:special_info["sub_subject"]})
745 special_info["sub_subject"] = ""
746 # we cannot expand a numpy array, hence the workaround here
747 #if in_node[2] == "++=":
748 # outstring = "_temp1 = %s;%s = %s(_temp1,%s)" % (lhs,lhs,aug_assign_table["++="],rhs[:-1])
749 if in_node[2] != "=":
750 outstring = "%s = %s(%s,%s)" % (lhs, aug_assign_table[in_node[2]],lhs,rhs[:-1])
751 else:
752 outstring = "%s = %s" % (lhs,rhs[:-1])
753 special_info["rhs"] = None
754 return outstring
755 elif node_type == "FANCY_ASSIGN": # [1] is cat name, [2] is list of objects
756 catname = in_node[1]
757 outstring = ""
758 special_info["rhs"] = True
759 for obj,value in in_node[2]:
760 real_id = cif_dic.get_name_by_cat_obj(catname, obj)
761 newvalue = traverse_ast(value)
762 outstring = outstring + "__dreltarget.update({'%s':__dreltarget.get('%s',[])+[%s]})\n" % (real_id,real_id,newvalue)
763 special_info["rhs"] = None
764 return outstring
765
766 elif node_type == "LIST":
767 outstring = "["
768 for one_element in in_node[1]:
769 outstring = outstring + traverse_ast(one_element) + ","
770 return outstring + "]"
771 elif node_type == "EXPR":
772 return traverse_ast(in_node[1])
773 # Expr list occurs only when a non-assignment statement appears as expr_stmt
774 elif node_type == "EXPRLIST":
775 outstring = ""
776 for one_expr in in_node[1]:
777 outstring += traverse_ast(one_expr) + "\n"
778 return outstring
779 elif node_type == "GROUP":
780 outstring = "("
781 for expression in in_node[1]:
782 outstring = outstring + traverse_ast(expression) + ","
783 return outstring[:-1] + ")"
784 elif node_type == "PRINT":
785 return 'print( ' + traverse_ast(in_node[1]) + ")"
786 elif node_type == "BREAK":
787 return 'break '
788 elif node_type == "NEXT":
789 return 'continue '
790
791 else:
792 return "Not found: %s" % repr(in_node)
793 result = traverse_ast(in_node)
794 # remove target id from dependencies
795 if special_info["target_id"] is not None:
796 special_info["depends"].discard(special_info["target_id"].lower())
797 if not special_info.get("have_drel_target",False):
798 print('WARNING: no assignment to __dreltarget in %s (this is OK for category methods)' % repr(target_id))
799 print(result)
800 return result,special_info["withtable"],special_info["depends"],special_info["need_current_row"]
801
802 # To avoid cluttering up the main switch statement, we call out to this function
803 # in order to find out what the Python name of the given function is. Where we have
804 # to provide our own function, that is also listed. Note that this only works for
805 # unary functions.
806 #
807 # We force all matrices to be 64-bit floats. If you check SeitzFromJones, you will
808 # find a matrix that defaults to integer type, meaning that any assignments of float
809 # values are rounded, thus the need for explicitly working with floats.
810 #
811 # User-defined functions (i.e. in dictionaries) have access to the data file (see
812 # use of 'symmetry_equiv' key access in SymEquiv) so this must be passed as a
813 # final argument. We assume anything that is not found here is user-defined, and
814 # add the 'ciffile' argument at the end.
815 #
816 #
817 # <Function transformer>=
818 def get_function_name(in_name):
819 """Return the Python name of the dREL function, an argument prefix,
820 and anything to be appended to the end"""
821 builtins = {"table":"dict",
822 "list":"list",
823 "array":"numpy.array",
824 "len":"len",
825 "abs":"abs",
826 "magn":"abs",
827 "atoi":"int",
828 "float":"float",
829 "repr":"repr",
830 "array":"numpy.array",
831 "norm":"numpy.linalg.norm",
832 "sqrt":"math.sqrt",
833 "exp":"math.exp",
834 "complex":"complex",
835 "max":"max",
836 "min":"min",
837 "strip":"drel_runtime.drel_strip",
838 "int":"drel_runtime.drel_int",
839 "eigen":"drel_runtime.drel_eigen",
840 "hash":"hash" #dREL extension
841 }
842 test_name = in_name.lower()
843 target_name = builtins.get(test_name,None)
844 if target_name is not None:
845 return target_name,"",""
846 if test_name in ['sind','cosd','tand']:
847 return "math."+test_name[:-1],"math.radians(",")"
848 if test_name in ['acosd','asind','atand','atan2d']:
849 return "math.degrees(math."+test_name[:-1],"",")"
850 if test_name == "mod":
851 return "divmod","","[1]"
852 if test_name == "upper":
853 return "","",".upper()"
854 if test_name == "transpose":
855 return "","",".T"
856 if test_name == 'expimag':
857 return "cmath.exp","1j*(",")"
858 if test_name in ['real','imag']:
859 return "","","." + test_name
860 if test_name == 'matrix':
861 return "numpy.matrix","",".astype('float64')"
862 if test_name == 'sort':
863 return "","",".sort()"
864 return in_name,"",None #dictionary defined
865
866 # Mathematical operations in dREL are complicated by the need to handle matrix
867 # operations transparently. The two operators that are affected are "^" (cross
868 # product) and "*" (matrix multiplication).
869 #
870 #
871 # <Mathematical operations>=
872 def fix_mathops(op,first_arg,second_arg):
873 """Return a string that will carry out the requested operation"""
874 if op == "^":
875 return "numpy.cross(%s,%s)" % (first_arg,second_arg)
876 elif op == "*": #could be matrix multiplication
877 return "drel_runtime.drel_dot(%s,%s)" % (first_arg,second_arg)
878 elif op == "+":
879 return "drel_runtime.drel_add(%s,%s)" % (first_arg, second_arg)
880 elif op == "-":
881 return "numpy.subtract(%s,%s)" % (first_arg, second_arg)
882 # beware integer division on this one...
883 elif op == "/":
884 return "numpy.true_divide(%s,%s)" % (first_arg, second_arg)
885
886 # We have a few simple utility functions for commonly-required operations.
887 #
888 #
889 # <Utility functions>=
890 def add_indent(text,n=4):
891 """Indent text by n spaces"""
892 return re.sub("\n","\n"+4*" ",text)
893
894 def getcatname(dataname):
895 """Return cat,name pair from dataname"""
896 try:
897 cat,name = dataname.split(".")
898 except ValueError: #no period in name
899 return cat,None
900 return cat[1:],name
901