| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 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 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
if isinstance(u"abc",str): |
| 19 |
unicode = str |
| 20 |
|
| 21 |
import re |
| 22 |
from CifFile import CifError |
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
|
| 34 |
|
| 35 |
|
| 36 |
pycifrw_func_table = { |
| 37 |
"data_access": "ciffile[%s]", |
| 38 |
"optional_data_access":"ciffile.get(%s,None)", |
| 39 |
"element_no": "%s[%s]", |
| 40 |
"count_data": "len(%s)", |
| 41 |
"cat_names":"ciffile.dictionary.names_in_cat(%s)", |
| 42 |
"has_name":"ciffile.has_key_or_alias(%s)", |
| 43 |
"semantic_packet":"ciffile.GetKeyedSemanticPacket(%s,%s)" |
| 44 |
} |
| 45 |
|
| 46 |
|
| 47 |
|
| 48 |
|
| 49 |
|
| 50 |
|
| 51 |
|
| 52 |
|
| 53 |
|
| 54 |
|
| 55 |
|
| 56 |
|
| 57 |
|
| 58 |
|
| 59 |
|
| 60 |
|
| 61 |
|
| 62 |
|
| 63 |
|
| 64 |
|
| 65 |
|
| 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 |
|
| 83 |
noindent = func_text.splitlines() |
| 84 |
|
| 85 |
no_spaces = [re.match(r' *',a).end() for a in noindent if a] |
| 86 |
min_spaces = min(no_spaces)+4 |
| 87 |
if len(withtable) > 0 or cur_row: |
| 88 |
|
| 89 |
|
| 90 |
|
| 91 |
|
| 92 |
|
| 93 |
|
| 94 |
|
| 95 |
|
| 96 |
|
| 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 |
|
| 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 |
| 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" |
| 118 |
preamble +=" except ImportError: #python3\n" |
| 119 |
preamble +=" imap = map\n" |
| 120 |
preamble +=" def drel_func(%s):\n" % dummy_vars |
| 121 |
|
| 122 |
print_instruction = "'Function passed variables "+("{!r} "*len(d_vars))+"'.format("+dummy_vars+",)" |
| 123 |
preamble +=" print(%s)\n" % print_instruction |
| 124 |
|
| 125 |
|
| 126 |
|
| 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: |
| 139 |
end_body +=" __row_id = range(%s)\n" % (func_table['count_data'] % ("'"+actual_names[0]+"'")) |
| 140 |
elif cur_row and len(actual_names)==1: |
| 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 |
|
| 156 |
|
| 157 |
|
| 158 |
|
| 159 |
|
| 160 |
preamble = "def %s(ciffile):\n" % func_name |
| 161 |
|
| 162 |
end_body = "" |
| 163 |
|
| 164 |
if cat_meth: |
| 165 |
preamble += " "*8 + "__dreltarget = {}\n" |
| 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) |
| 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 |
|
| 183 |
|
| 184 |
|
| 185 |
|
| 186 |
|
| 187 |
|
| 188 |
|
| 189 |
|
| 190 |
|
| 191 |
|
| 192 |
|
| 193 |
|
| 194 |
|
| 195 |
|
| 196 |
|
| 197 |
|
| 198 |
|
| 199 |
|
| 200 |
|
| 201 |
|
| 202 |
|
| 203 |
|
| 204 |
|
| 205 |
|
| 206 |
|
| 207 |
|
| 208 |
|
| 209 |
|
| 210 |
|
| 211 |
|
| 212 |
|
| 213 |
|
| 214 |
|
| 215 |
|
| 216 |
|
| 217 |
|
| 218 |
|
| 219 |
|
| 220 |
|
| 221 |
|
| 222 |
|
| 223 |
|
| 224 |
|
| 225 |
|
| 226 |
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 |
|
| 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 |
|
| 238 |
|
| 239 |
|
| 240 |
|
| 241 |
|
| 242 |
|
| 243 |
|
| 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 |
|
| 267 |
|
| 268 |
|
| 269 |
|
| 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 |
|
| 286 |
|
| 287 |
|
| 288 |
|
| 289 |
|
| 290 |
|
| 291 |
|
| 292 |
elif node_type == "ATOM": |
| 293 |
if isinstance(in_node[1],(unicode,str)): |
| 294 |
|
| 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: |
| 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 |
|
| 329 |
|
| 330 |
|
| 331 |
|
| 332 |
|
| 333 |
|
| 334 |
|
| 335 |
|
| 336 |
|
| 337 |
|
| 338 |
|
| 339 |
|
| 340 |
|
| 341 |
|
| 342 |
|
| 343 |
|
| 344 |
|
| 345 |
elif node_type == "SUBSCRIPTION": |
| 346 |
newid = 0 |
| 347 |
if in_node[1][0] == "ATOM" and in_node[1][1][0] == "ITEM_TAG": |
| 348 |
print("Found category used as item tag: subscribing") |
| 349 |
newid = [in_node[1][1][1][1:],False,False] |
| 350 |
else: |
| 351 |
primary = traverse_ast(in_node[1]) |
| 352 |
|
| 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(): |
| 357 |
newid = [primary,False,False] |
| 358 |
break |
| 359 |
if newid: |
| 360 |
|
| 361 |
key_items = ["_"+newid[0]+"."+s for s in special_info["loopable_cats"][newid[0]][0]] |
| 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] |
| 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 |
|
| 373 |
|
| 374 |
|
| 375 |
|
| 376 |
|
| 377 |
|
| 378 |
|
| 379 |
|
| 380 |
|
| 381 |
|
| 382 |
|
| 383 |
|
| 384 |
|
| 385 |
|
| 386 |
|
| 387 |
|
| 388 |
|
| 389 |
|
| 390 |
|
| 391 |
|
| 392 |
|
| 393 |
|
| 394 |
|
| 395 |
|
| 396 |
|
| 397 |
|
| 398 |
|
| 399 |
|
| 400 |
|
| 401 |
|
| 402 |
|
| 403 |
|
| 404 |
elif node_type == "ATTRIBUTE": |
| 405 |
outstring = "" |
| 406 |
newid = 0 |
| 407 |
|
| 408 |
primary = traverse_ast(in_node[1]) |
| 409 |
for idtable in special_info["special_id"]: |
| 410 |
newid = idtable.get(primary,0) |
| 411 |
if newid: break |
| 412 |
if newid: |
| 413 |
|
| 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 |
|
| 419 |
|
| 420 |
elif newid[2] or (not newid[2] and not newid[1]): |
| 421 |
outstring = api_table["data_access"] % ('"' +true_name +'"') |
| 422 |
special_info["depends"].add(true_name) |
| 423 |
if newid[1]: |
| 424 |
outstring += "[" + newid[1]+ "]" |
| 425 |
else: |
| 426 |
if true_name not in special_info["withtable"]: |
| 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] == "_": |
| 434 |
fullname = cif_dic.get_name_by_cat_obj(primary,in_node[2]).lower() |
| 435 |
|
| 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: |
| 443 |
|
| 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: |
| 452 |
fullname = in_node[2] |
| 453 |
outstring = "getattr(" + primary + ",'" + fullname + "')" |
| 454 |
|
| 455 |
special_info['sub_subject'] = "" |
| 456 |
return outstring |
| 457 |
|
| 458 |
|
| 459 |
|
| 460 |
|
| 461 |
|
| 462 |
|
| 463 |
|
| 464 |
|
| 465 |
|
| 466 |
|
| 467 |
elif node_type == "FUNC_CALL": |
| 468 |
if in_node[1] == "Current_Row": |
| 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: |
| 475 |
outstring = outstring + "[" |
| 476 |
for argument in in_node[2]: |
| 477 |
outstring = outstring + every_arg_prefix + traverse_ast(argument) + "," |
| 478 |
if postfix == None: |
| 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": |
| 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": |
| 499 |
outstring += traverse_ast(one_slice) |
| 500 |
elif len(one_slice) >0: |
| 501 |
outstring += traverse_ast(one_slice[0]) + ":" |
| 502 |
if len(one_slice) >1: |
| 503 |
outstring += traverse_ast(one_slice[1]) |
| 504 |
if len(one_slice) == 3: |
| 505 |
outstring += ":" + traverse_ast(one_slice[2]) |
| 506 |
outstring += "," |
| 507 |
outstring = outstring[:-1] + "]" |
| 508 |
return outstring |
| 509 |
|
| 510 |
|
| 511 |
|
| 512 |
|
| 513 |
|
| 514 |
|
| 515 |
|
| 516 |
|
| 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: |
| 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 |
|
| 534 |
|
| 535 |
|
| 536 |
|
| 537 |
|
| 538 |
|
| 539 |
|
| 540 |
|
| 541 |
|
| 542 |
|
| 543 |
elif node_type == "IF_EXPR": |
| 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) |
| 551 |
elseif = in_node[3] |
| 552 |
if len(elseif)!=0: |
| 553 |
for one_cond in elseif: |
| 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) |
| 560 |
special_info["inif"] = old_inif |
| 561 |
return outstring |
| 562 |
|
| 563 |
|
| 564 |
|
| 565 |
elif node_type == "DO": |
| 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": |
| 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": |
| 585 |
outstring = "while True:" + add_indent("\n" + traverse_ast(in_node[1])) |
| 586 |
return outstring |
| 587 |
|
| 588 |
|
| 589 |
|
| 590 |
|
| 591 |
|
| 592 |
|
| 593 |
|
| 594 |
|
| 595 |
|
| 596 |
|
| 597 |
|
| 598 |
|
| 599 |
elif node_type == "WITH": |
| 600 |
|
| 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(): |
| 610 |
special_info['special_id'][-1][alias_id][1] = "looped_cat" |
| 611 |
outstring = traverse_ast(in_node[3]) |
| 612 |
return outstring |
| 613 |
|
| 614 |
|
| 615 |
|
| 616 |
|
| 617 |
|
| 618 |
|
| 619 |
elif node_type == "LOOP": |
| 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 |
|
| 628 |
loop_num = len(special_info['special_id'][-1])+1 |
| 629 |
if in_node[3] == "": |
| 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 |
|
| 637 |
|
| 638 |
|
| 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] |
| 645 |
|
| 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) |
| 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 |
|
| 657 |
|
| 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 |
|
| 661 |
outstring += "\n" + "for %s in __loop_range%d:" % (loop_index,loop_num) |
| 662 |
|
| 663 |
loop_body = traverse_ast(in_node[6]) |
| 664 |
outstring = outstring + add_indent("\n"+loop_body) |
| 665 |
return outstring |
| 666 |
|
| 667 |
|
| 668 |
|
| 669 |
|
| 670 |
|
| 671 |
|
| 672 |
|
| 673 |
|
| 674 |
|
| 675 |
|
| 676 |
elif node_type == "FUNCTION": |
| 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 |
|
| 683 |
|
| 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 |
|
| 690 |
|
| 691 |
|
| 692 |
|
| 693 |
|
| 694 |
elif node_type == "STATEMENTS": |
| 695 |
outstring = "" |
| 696 |
for one_statement in in_node[1]: |
| 697 |
|
| 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 |
|
| 704 |
|
| 705 |
|
| 706 |
|
| 707 |
|
| 708 |
|
| 709 |
return outstring |
| 710 |
|
| 711 |
|
| 712 |
|
| 713 |
|
| 714 |
|
| 715 |
|
| 716 |
|
| 717 |
|
| 718 |
|
| 719 |
|
| 720 |
|
| 721 |
|
| 722 |
|
| 723 |
|
| 724 |
|
| 725 |
|
| 726 |
|
| 727 |
|
| 728 |
|
| 729 |
|
| 730 |
elif node_type == "ASSIGN": |
| 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"] != "": |
| 744 |
special_info["packet_vars"].update({lhs_values[order]:special_info["sub_subject"]}) |
| 745 |
special_info["sub_subject"] = "" |
| 746 |
|
| 747 |
|
| 748 |
|
| 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": |
| 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 |
|
| 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 |
|
| 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 |
|
| 803 |
|
| 804 |
|
| 805 |
|
| 806 |
|
| 807 |
|
| 808 |
|
| 809 |
|
| 810 |
|
| 811 |
|
| 812 |
|
| 813 |
|
| 814 |
|
| 815 |
|
| 816 |
|
| 817 |
|
| 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" |
| 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 |
| 865 |
|
| 866 |
|
| 867 |
|
| 868 |
|
| 869 |
|
| 870 |
|
| 871 |
|
| 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 == "*": |
| 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 |
|
| 883 |
elif op == "/": |
| 884 |
return "numpy.true_divide(%s,%s)" % (first_arg, second_arg) |
| 885 |
|
| 886 |
|
| 887 |
|
| 888 |
|
| 889 |
|
| 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: |
| 899 |
return cat,None |
| 900 |
return cat[1:],name |
| 901 |
|