| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
from __future__ import print_function |
| 29 |
from __future__ import unicode_literals |
| 30 |
from __future__ import division |
| 31 |
from __future__ import absolute_import |
| 32 |
|
| 33 |
|
| 34 |
__copyright = """ |
| 35 |
PYCIFRW License Agreement (Python License, Version 2) |
| 36 |
----------------------------------------------------- |
| 37 |
|
| 38 |
1. This LICENSE AGREEMENT is between the Australian Nuclear Science |
| 39 |
and Technology Organisation ("ANSTO"), and the Individual or |
| 40 |
Organization ("Licensee") accessing and otherwise using this software |
| 41 |
("PyCIFRW") in source or binary form and its associated documentation. |
| 42 |
|
| 43 |
2. Subject to the terms and conditions of this License Agreement, |
| 44 |
ANSTO hereby grants Licensee a nonexclusive, royalty-free, world-wide |
| 45 |
license to reproduce, analyze, test, perform and/or display publicly, |
| 46 |
prepare derivative works, distribute, and otherwise use PyCIFRW alone |
| 47 |
or in any derivative version, provided, however, that this License |
| 48 |
Agreement and ANSTO's notice of copyright, i.e., "Copyright (c) |
| 49 |
2001-2014 ANSTO; All Rights Reserved" are retained in PyCIFRW alone or |
| 50 |
in any derivative version prepared by Licensee. |
| 51 |
|
| 52 |
3. In the event Licensee prepares a derivative work that is based on |
| 53 |
or incorporates PyCIFRW or any part thereof, and wants to make the |
| 54 |
derivative work available to others as provided herein, then Licensee |
| 55 |
hereby agrees to include in any such work a brief summary of the |
| 56 |
changes made to PyCIFRW. |
| 57 |
|
| 58 |
4. ANSTO is making PyCIFRW available to Licensee on an "AS IS" |
| 59 |
basis. ANSTO MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR |
| 60 |
IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, ANSTO MAKES NO AND |
| 61 |
DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS |
| 62 |
FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYCIFRW WILL NOT |
| 63 |
INFRINGE ANY THIRD PARTY RIGHTS. |
| 64 |
|
| 65 |
5. ANSTO SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYCIFRW |
| 66 |
FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A |
| 67 |
RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYCIFRW, OR ANY |
| 68 |
DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. |
| 69 |
|
| 70 |
6. This License Agreement will automatically terminate upon a material |
| 71 |
breach of its terms and conditions. |
| 72 |
|
| 73 |
7. Nothing in this License Agreement shall be deemed to create any |
| 74 |
relationship of agency, partnership, or joint venture between ANSTO |
| 75 |
and Licensee. This License Agreement does not grant permission to use |
| 76 |
ANSTO trademarks or trade name in a trademark sense to endorse or |
| 77 |
promote products or services of Licensee, or any third party. |
| 78 |
|
| 79 |
8. By copying, installing or otherwise using PyCIFRW, Licensee agrees |
| 80 |
to be bound by the terms and conditions of this License Agreement. |
| 81 |
|
| 82 |
""" |
| 83 |
|
| 84 |
|
| 85 |
import sys |
| 86 |
|
| 87 |
|
| 88 |
try: |
| 89 |
from urllib import urlopen |
| 90 |
from urlparse import urlparse, urlunparse |
| 91 |
except: |
| 92 |
from urllib.request import urlopen |
| 93 |
from urllib.parse import urlparse,urlunparse |
| 94 |
import re,os |
| 95 |
import textwrap |
| 96 |
|
| 97 |
try: |
| 98 |
from StringIO import StringIO |
| 99 |
except ImportError: |
| 100 |
from io import StringIO |
| 101 |
|
| 102 |
if isinstance(u"abc",str): |
| 103 |
unicode = str |
| 104 |
long = int |
| 105 |
|
| 106 |
try: |
| 107 |
import numpy |
| 108 |
have_numpy = True |
| 109 |
except ImportError: |
| 110 |
have_numpy = False |
| 111 |
|
| 112 |
|
| 113 |
|
| 114 |
|
| 115 |
try: |
| 116 |
from pathlib import Path |
| 117 |
have_pathlib = True |
| 118 |
except: |
| 119 |
have_pathlib = False |
| 120 |
|
| 121 |
|
| 122 |
|
| 123 |
|
| 124 |
|
| 125 |
|
| 126 |
|
| 127 |
|
| 128 |
|
| 129 |
|
| 130 |
|
| 131 |
class StarList(list): |
| 132 |
def __getitem__(self,args): |
| 133 |
if isinstance(args, tuple) and len(args) == 1: |
| 134 |
args = args[0] |
| 135 |
if isinstance(args, int): |
| 136 |
return super(StarList, self).__getitem__(args) |
| 137 |
if isinstance(args,tuple) and len(args)>1: |
| 138 |
retval = StarList(map(lambda x: x.__getitem__(args[1:]), self)) |
| 139 |
return retval.__getitem__(args[0]) |
| 140 |
if len(self) > 0 and (isinstance(self[0],(str,dict)) or not hasattr(self[0], "__iter__")): |
| 141 |
return super(StarList,self).__getitem__(args) |
| 142 |
elif isinstance(args, (int, slice)): |
| 143 |
return StarList(map(lambda x: x.__getitem__(args), self)) |
| 144 |
else: |
| 145 |
return super(StarList,self).__getitem__(args[0]) |
| 146 |
|
| 147 |
def __str__(self): |
| 148 |
return "SL("+super(StarList,self).__str__() + ")" |
| 149 |
|
| 150 |
class StarDict(dict): |
| 151 |
pass |
| 152 |
|
| 153 |
|
| 154 |
|
| 155 |
|
| 156 |
|
| 157 |
|
| 158 |
|
| 159 |
|
| 160 |
|
| 161 |
|
| 162 |
|
| 163 |
|
| 164 |
|
| 165 |
|
| 166 |
class LoopBlock(object): |
| 167 |
|
| 168 |
|
| 169 |
|
| 170 |
|
| 171 |
|
| 172 |
def __init__(self,parent_block,dataname): |
| 173 |
self.loop_no = parent_block.FindLoop(dataname) |
| 174 |
if self.loop_no < 0: |
| 175 |
raise KeyError('{} is not in a loop structure'.format(dataname)) |
| 176 |
self.parent_block = parent_block |
| 177 |
|
| 178 |
|
| 179 |
def keys(self): |
| 180 |
return self.parent_block.loops[self.loop_no] |
| 181 |
|
| 182 |
def values(self): |
| 183 |
return [self.parent_block[a] for a in self.keys()] |
| 184 |
|
| 185 |
|
| 186 |
def items(self): |
| 187 |
return list(zip(self.keys(),self.values())) |
| 188 |
|
| 189 |
def __getitem__(self,dataname): |
| 190 |
if isinstance(dataname,int): |
| 191 |
return self.GetPacket(dataname) |
| 192 |
if dataname in self.keys(): |
| 193 |
return self.parent_block[dataname] |
| 194 |
else: |
| 195 |
raise KeyError('{} not in loop block'.format(dataname)) |
| 196 |
|
| 197 |
def __setitem__(self,dataname,value): |
| 198 |
self.parent_block[dataname] = value |
| 199 |
self.parent_block.AddLoopName(self.keys()[0],dataname) |
| 200 |
|
| 201 |
def __contains__(self,key): |
| 202 |
return key in self.parent_block.loops[self.loop_no] |
| 203 |
|
| 204 |
def has_key(self,key): |
| 205 |
return key in self |
| 206 |
|
| 207 |
def __iter__(self): |
| 208 |
packet_list = zip(*self.values()) |
| 209 |
names = self.keys() |
| 210 |
for p in packet_list: |
| 211 |
r = StarPacket(p) |
| 212 |
for n in range(len(names)): |
| 213 |
setattr(r,names[n].lower(),r[n]) |
| 214 |
yield r |
| 215 |
|
| 216 |
|
| 217 |
def __getattr__(self,attname): |
| 218 |
return getattr(self.parent_block,attname) |
| 219 |
|
| 220 |
|
| 221 |
|
| 222 |
|
| 223 |
|
| 224 |
|
| 225 |
|
| 226 |
|
| 227 |
|
| 228 |
|
| 229 |
|
| 230 |
|
| 231 |
|
| 232 |
|
| 233 |
|
| 234 |
|
| 235 |
def load_iter(self,coords=[]): |
| 236 |
count = 0 |
| 237 |
while not self.popout: |
| 238 |
|
| 239 |
for aloop in self.loops: |
| 240 |
aloop.new_enclosing_packet() |
| 241 |
for iname in self.item_order: |
| 242 |
if isinstance(iname,LoopBlock): |
| 243 |
for subitems in iname.load_iter(coords=coords+[count]): |
| 244 |
|
| 245 |
yield subitems |
| 246 |
|
| 247 |
else: |
| 248 |
if self.dimension == 0: |
| 249 |
|
| 250 |
yield self,self[iname] |
| 251 |
else: |
| 252 |
backval = self.block[iname] |
| 253 |
for i in range(len(coords)): |
| 254 |
|
| 255 |
backval = backval[coords[i]] |
| 256 |
yield self,backval |
| 257 |
count = count + 1 |
| 258 |
self.popout = False |
| 259 |
|
| 260 |
yield self,'###Blank###' |
| 261 |
|
| 262 |
|
| 263 |
def fast_load_iter(self): |
| 264 |
targets = map(lambda a:self.block[a],self.item_order) |
| 265 |
while targets: |
| 266 |
for target in targets: |
| 267 |
yield self,target |
| 268 |
|
| 269 |
|
| 270 |
def new_enclosing_packet(self): |
| 271 |
if self.dimension > 1: |
| 272 |
for iname in self.keys(): |
| 273 |
target_list = self[iname] |
| 274 |
for i in range(3,self.dimension): |
| 275 |
target_list = target_list[-1] |
| 276 |
target_list.append([]) |
| 277 |
|
| 278 |
|
| 279 |
|
| 280 |
|
| 281 |
|
| 282 |
|
| 283 |
|
| 284 |
|
| 285 |
|
| 286 |
|
| 287 |
|
| 288 |
|
| 289 |
|
| 290 |
|
| 291 |
|
| 292 |
|
| 293 |
|
| 294 |
def recursive_iter(self,dict_so_far={},coord=[]): |
| 295 |
|
| 296 |
my_length = 0 |
| 297 |
top_items = self.block.items() |
| 298 |
top_values = self.block.values() |
| 299 |
drill_values = self.block.values() |
| 300 |
for dimup in range(0,self.dimension): |
| 301 |
if len(drill_values)>0: |
| 302 |
drill_values=drill_values[0] |
| 303 |
else: |
| 304 |
raise StarError("Malformed loop packet {}".format(repr( top_items[0] ))) |
| 305 |
my_length = len(drill_values[0]) |
| 306 |
if self.dimension == 0: |
| 307 |
for aloop in self.loops: |
| 308 |
for apacket in aloop.recursive_iter(): |
| 309 |
|
| 310 |
prep_yield = StarPacket(top_values+apacket.values()) |
| 311 |
for name,value in top_items + apacket.items(): |
| 312 |
setattr(prep_yield,name,value) |
| 313 |
yield prep_yield |
| 314 |
else: |
| 315 |
for i in range(my_length): |
| 316 |
kvpairs = map(lambda a:(a,self.coord_to_group(a,coord)[i]),self.block.keys()) |
| 317 |
kvpairs = list(kvpairs) |
| 318 |
kvvals = map(lambda a:a[1],kvpairs) |
| 319 |
kvvals = list(kvvals) |
| 320 |
|
| 321 |
if self.loops: |
| 322 |
for aloop in self.loops: |
| 323 |
for apacket in aloop.recursive_iter(coord=coord+[i]): |
| 324 |
|
| 325 |
prep_yield = StarPacket(kvvals+apacket.values()) |
| 326 |
for name,value in kvpairs + apacket.items(): |
| 327 |
setattr(prep_yield,name,value) |
| 328 |
yield prep_yield |
| 329 |
else: |
| 330 |
|
| 331 |
prep_yield = StarPacket(kvvals) |
| 332 |
for name,value in kvpairs: |
| 333 |
setattr(prep_yield,name,value) |
| 334 |
yield prep_yield |
| 335 |
|
| 336 |
|
| 337 |
def coord_to_group(self,dataname,coords): |
| 338 |
if not isinstance(dataname,unicode): |
| 339 |
return dataname |
| 340 |
newm = self[dataname] |
| 341 |
for c in coords: |
| 342 |
|
| 343 |
newm = newm[c] |
| 344 |
|
| 345 |
return newm |
| 346 |
|
| 347 |
|
| 348 |
|
| 349 |
|
| 350 |
|
| 351 |
|
| 352 |
|
| 353 |
def flat_iterator(self): |
| 354 |
my_length = 0 |
| 355 |
top_keys = self.block.keys() |
| 356 |
if len(top_keys)>0: |
| 357 |
my_length = len(self.block[top_keys[0]]) |
| 358 |
for pack_no in range(my_length): |
| 359 |
yield(self.collapse(pack_no)) |
| 360 |
|
| 361 |
|
| 362 |
|
| 363 |
|
| 364 |
|
| 365 |
|
| 366 |
|
| 367 |
|
| 368 |
def RemoveItem(self,itemname): |
| 369 |
"""Remove `itemname` from the block.""" |
| 370 |
|
| 371 |
loop_no = self.FindLoop(itemname) |
| 372 |
testkey = itemname.lower() |
| 373 |
if testkey in self: |
| 374 |
del self.block[testkey] |
| 375 |
del self.true_case[testkey] |
| 376 |
|
| 377 |
if loop_no >= 0: |
| 378 |
self.loops[loop_no].remove(testkey) |
| 379 |
if len(self.loops[loop_no])==0: |
| 380 |
del self.loops[loop_no] |
| 381 |
self.item_order.remove(loop_no) |
| 382 |
else: |
| 383 |
self.item_order.remove(testkey) |
| 384 |
|
| 385 |
def RemoveLoopItem(self,itemname): |
| 386 |
"""*Deprecated*. Use `RemoveItem` instead""" |
| 387 |
self.RemoveItem(itemname) |
| 388 |
|
| 389 |
|
| 390 |
|
| 391 |
|
| 392 |
|
| 393 |
|
| 394 |
|
| 395 |
|
| 396 |
|
| 397 |
|
| 398 |
|
| 399 |
|
| 400 |
|
| 401 |
|
| 402 |
def GetLoop(self,keyname): |
| 403 |
"""Return a `StarFile.LoopBlock` object constructed from the loop containing `keyname`. |
| 404 |
`keyname` is only significant as a way to specify the loop.""" |
| 405 |
return LoopBlock(self,keyname) |
| 406 |
|
| 407 |
|
| 408 |
|
| 409 |
|
| 410 |
|
| 411 |
|
| 412 |
|
| 413 |
|
| 414 |
|
| 415 |
|
| 416 |
def GetPacket(self,index): |
| 417 |
thispack = StarPacket([]) |
| 418 |
for myitem in self.parent_block.loops[self.loop_no]: |
| 419 |
thispack.append(self[myitem][index]) |
| 420 |
setattr(thispack,myitem,thispack[-1]) |
| 421 |
return thispack |
| 422 |
|
| 423 |
|
| 424 |
|
| 425 |
|
| 426 |
|
| 427 |
|
| 428 |
|
| 429 |
def AddPacket(self,packet): |
| 430 |
for myitem in self.parent_block.loops[self.loop_no]: |
| 431 |
old_values = self.parent_block[myitem] |
| 432 |
old_values.append(packet.__getattribute__(myitem)) |
| 433 |
self.parent_block[myitem] = old_values |
| 434 |
|
| 435 |
|
| 436 |
|
| 437 |
|
| 438 |
|
| 439 |
|
| 440 |
def GetItemOrder(self): |
| 441 |
"""Return a list of datanames in this `LoopBlock` in the order that they will be |
| 442 |
printed""" |
| 443 |
return self.parent_block.loops[self.loop_no][:] |
| 444 |
|
| 445 |
|
| 446 |
|
| 447 |
|
| 448 |
|
| 449 |
|
| 450 |
|
| 451 |
|
| 452 |
|
| 453 |
def ChangeItemOrder(self,itemname,newpos): |
| 454 |
"""Change the position at which `itemname` appears when printing out to `newpos`.""" |
| 455 |
self.parent_block.loops[self.loop_no].remove(itemname.lower()) |
| 456 |
self.parent_block.loops[self.loop_no].insert(newpos,itemname.lower()) |
| 457 |
|
| 458 |
|
| 459 |
|
| 460 |
|
| 461 |
|
| 462 |
|
| 463 |
def GetItemPosition(self,itemname): |
| 464 |
"""A utility function to get the numerical order in the printout |
| 465 |
of `itemname`. An item has coordinate `(loop_no,pos)` with |
| 466 |
the top level having a `loop_no` of -1. If an integer is passed to |
| 467 |
the routine then it will return the position of the loop |
| 468 |
referenced by that number.""" |
| 469 |
if isinstance(itemname,int): |
| 470 |
|
| 471 |
return (-1, self.item_order.index(itemname)) |
| 472 |
if not itemname in self: |
| 473 |
raise ValueError('No such dataname {}'.format(itemname)) |
| 474 |
testname = itemname.lower() |
| 475 |
if testname in self.item_order: |
| 476 |
return (-1,self.item_order.index(testname)) |
| 477 |
loop_no = self.FindLoop(testname) |
| 478 |
loop_pos = self.loops[loop_no].index(testname) |
| 479 |
return loop_no,loop_pos |
| 480 |
|
| 481 |
|
| 482 |
|
| 483 |
|
| 484 |
|
| 485 |
|
| 486 |
def GetLoopNames(self,keyname): |
| 487 |
if keyname in self: |
| 488 |
return self.keys() |
| 489 |
for aloop in self.loops: |
| 490 |
try: |
| 491 |
return aloop.GetLoopNames(keyname) |
| 492 |
except KeyError: |
| 493 |
pass |
| 494 |
raise KeyError('Item does not exist') |
| 495 |
|
| 496 |
|
| 497 |
|
| 498 |
|
| 499 |
|
| 500 |
|
| 501 |
def GetLoopNames(self,keyname): |
| 502 |
"""Return all datanames appearing together with `keyname`""" |
| 503 |
loop_no = self.FindLoop(keyname) |
| 504 |
if loop_no >= 0: |
| 505 |
return self.loops[loop_no] |
| 506 |
else: |
| 507 |
raise KeyError('{} is not in any loop'.format(keyname)) |
| 508 |
|
| 509 |
|
| 510 |
|
| 511 |
|
| 512 |
|
| 513 |
|
| 514 |
|
| 515 |
|
| 516 |
|
| 517 |
|
| 518 |
|
| 519 |
|
| 520 |
|
| 521 |
|
| 522 |
class StarBlock(object): |
| 523 |
|
| 524 |
|
| 525 |
|
| 526 |
|
| 527 |
|
| 528 |
|
| 529 |
|
| 530 |
|
| 531 |
|
| 532 |
|
| 533 |
|
| 534 |
|
| 535 |
|
| 536 |
|
| 537 |
|
| 538 |
|
| 539 |
|
| 540 |
|
| 541 |
|
| 542 |
|
| 543 |
|
| 544 |
|
| 545 |
|
| 546 |
|
| 547 |
|
| 548 |
|
| 549 |
|
| 550 |
|
| 551 |
|
| 552 |
|
| 553 |
|
| 554 |
|
| 555 |
def __init__(self,data = (), maxoutlength=2048, wraplength=80, overwrite=True, |
| 556 |
characterset='ascii',maxnamelength=-1): |
| 557 |
self.block = {} |
| 558 |
self.loops = {} |
| 559 |
self.item_order = [] |
| 560 |
self.formatting_hints = {} |
| 561 |
self.true_case = {} |
| 562 |
self.provide_value = False |
| 563 |
self.dictionary = None |
| 564 |
self.popout = False |
| 565 |
self.curitem = -1 |
| 566 |
self.cache_vals = True |
| 567 |
self.maxoutlength = maxoutlength |
| 568 |
self.setmaxnamelength(maxnamelength) |
| 569 |
self.set_characterset(characterset) |
| 570 |
self.wraplength = wraplength |
| 571 |
self.overwrite = overwrite |
| 572 |
self.string_delimiters = ["'",'"',"\n;"] |
| 573 |
self.list_delimiter = " " |
| 574 |
self.wrapper = textwrap.TextWrapper() |
| 575 |
if isinstance(data,(tuple,list)): |
| 576 |
for item in data: |
| 577 |
self.AddLoopItem(item) |
| 578 |
elif isinstance(data,StarBlock): |
| 579 |
self.block = data.block.copy() |
| 580 |
self.item_order = data.item_order[:] |
| 581 |
self.true_case = data.true_case.copy() |
| 582 |
|
| 583 |
self.loops = data.loops.copy() |
| 584 |
|
| 585 |
def setmaxnamelength(self,maxlength): |
| 586 |
"""Set the maximum allowable dataname length (-1 for no check)""" |
| 587 |
self.maxnamelength = maxlength |
| 588 |
if maxlength > 0: |
| 589 |
bad_names = [a for a in self.keys() if len(a)>self.maxnamelength] |
| 590 |
if len(bad_names)>0: |
| 591 |
raise StarError('Datanames too long: ' + repr( bad_names )) |
| 592 |
|
| 593 |
def set_characterset(self,characterset): |
| 594 |
"""Set the characterset for checking datanames: may be `ascii` or `unicode`""" |
| 595 |
self.characterset = characterset |
| 596 |
if characterset == 'ascii': |
| 597 |
self.char_check = re.compile("[][ \n\r\t!%&\\(\\)*+,./:<=>?@0-9A-Za-z\\\\^`{}\\|~\"#$';_-]+",re.M) |
| 598 |
elif characterset == 'unicode': |
| 599 |
if sys.maxunicode < 1114111: |
| 600 |
self.char_check = re.compile(u"[][ \n\r\t!%&\\(\\)*+,./:<=>?@0-9A-Za-z\\\\^`{}\\|~\"#$';_\u00A0-\uD7FF\uE000-\uFDCF\uFDF0-\uFFFD-]+",re.M) |
| 601 |
else: |
| 602 |
self.char_check = re.compile(u"[][ \n\r\t!%&\\(\\)*+,./:<=>?@0-9A-Za-z\\\\^`{}\\|~\"#$';_\u00A0-\uD7FF\uE000-\uFDCF\uFDF0-\uFFFD\U00010000-\U0010FFFD-]+",re.M) |
| 603 |
|
| 604 |
|
| 605 |
|
| 606 |
|
| 607 |
|
| 608 |
|
| 609 |
|
| 610 |
|
| 611 |
|
| 612 |
|
| 613 |
|
| 614 |
|
| 615 |
|
| 616 |
|
| 617 |
|
| 618 |
def __str__(self): |
| 619 |
return self.printsection() |
| 620 |
|
| 621 |
def __setitem__(self,key,value): |
| 622 |
if key == "saves": |
| 623 |
raise StarError("""Setting the saves key is deprecated. Add the save block to |
| 624 |
an enclosing block collection (e.g. CIF or STAR file) with this block as child""") |
| 625 |
self.AddItem(key,value) |
| 626 |
|
| 627 |
def __getitem__(self,key): |
| 628 |
if key == "saves": |
| 629 |
raise StarError("""The saves key is deprecated. Access the save block from |
| 630 |
the enclosing block collection (e.g. CIF or STAR file object)""") |
| 631 |
try: |
| 632 |
rawitem,is_value = self.GetFullItemValue(key) |
| 633 |
except KeyError: |
| 634 |
if self.dictionary: |
| 635 |
|
| 636 |
try: |
| 637 |
new_value = self.dictionary.derive_item(key,self,store_value=self.cache_vals,allow_defaults=False) |
| 638 |
except StarDerivationFailure: |
| 639 |
try: |
| 640 |
new_value = self.dictionary.derive_item(key,self,store_value=self.cache_vals,allow_defaults=True) |
| 641 |
except StarDerivationFailure as s: |
| 642 |
print("In StarBlock.__getitem__, " + repr(s)) |
| 643 |
raise KeyError('No such item: {}'.format(key)) |
| 644 |
print('Set {} to derived value {}'.format(key, repr(new_value))) |
| 645 |
return new_value |
| 646 |
else: |
| 647 |
raise KeyError('No such item: {}'.format(key)) |
| 648 |
|
| 649 |
|
| 650 |
if not self.dictionary or not key in self.dictionary: return rawitem |
| 651 |
print('{}: is_value {} provide_value {} value {}'.format(key,repr( is_value ),repr( self.provide_value ),repr( rawitem ))) |
| 652 |
if is_value: |
| 653 |
if self.provide_value: return rawitem |
| 654 |
else: |
| 655 |
print('Turning {} into string'.format(repr( rawitem ))) |
| 656 |
return self.convert_to_string(key) |
| 657 |
else: |
| 658 |
if self.provide_value and ((not isinstance(rawitem,list) and rawitem != '?' and rawitem != ".") or \ |
| 659 |
(isinstance(rawitem,list) and '?' not in rawitem and '.' not in rawitem)): |
| 660 |
return self.dictionary.change_type(key,rawitem) |
| 661 |
elif self.provide_value: |
| 662 |
do_calculate = False |
| 663 |
if isinstance(rawitem,(list,tuple)): |
| 664 |
known = [a for a in rawitem if a != '?'] |
| 665 |
if len(known) == 0: |
| 666 |
do_calculate = True |
| 667 |
elif rawitem == '?': |
| 668 |
do_calculate = True |
| 669 |
if do_calculate: |
| 670 |
|
| 671 |
del self[key] |
| 672 |
try: |
| 673 |
new_value = self.dictionary.derive_item(key,self,store_value=True,allow_defaults=False) |
| 674 |
except StarDerivationFailure as s: |
| 675 |
try: |
| 676 |
new_value = self.dictionary.derive_item(key,self,store_value=True,allow_defaults=True) |
| 677 |
except StarDerivationFailure as s: |
| 678 |
|
| 679 |
print("Could not turn {} into a value:".format(repr(s))) |
| 680 |
return rawitem |
| 681 |
else: |
| 682 |
print('Set {} to derived value {}'.format(key, repr( new_value ))) |
| 683 |
return new_value |
| 684 |
return rawitem |
| 685 |
|
| 686 |
def __delitem__(self,key): |
| 687 |
self.RemoveItem(key) |
| 688 |
|
| 689 |
def __len__(self): |
| 690 |
blen = len(self.block) |
| 691 |
return blen |
| 692 |
|
| 693 |
def __nonzero__(self): |
| 694 |
if self.__len__() > 0: return 1 |
| 695 |
return 0 |
| 696 |
|
| 697 |
|
| 698 |
def keys(self): |
| 699 |
return list(self.block.keys()) |
| 700 |
|
| 701 |
def values(self): |
| 702 |
return [self[a] for a in self.keys()] |
| 703 |
|
| 704 |
def items(self): |
| 705 |
return list(zip(self.keys(),self.values())) |
| 706 |
|
| 707 |
def __contains__(self,key): |
| 708 |
if isinstance(key,(unicode,str)) and key.lower() in self.keys(): |
| 709 |
return True |
| 710 |
return False |
| 711 |
|
| 712 |
def has_key(self,key): |
| 713 |
return key in self |
| 714 |
|
| 715 |
def has_key_or_alias(self,key): |
| 716 |
"""Check if a dataname or alias is available in the block""" |
| 717 |
initial_test = key in self |
| 718 |
if initial_test: return True |
| 719 |
elif self.dictionary: |
| 720 |
aliases = [k for k in self.dictionary.alias_table.get(key,[]) if self.has_key(k)] |
| 721 |
if len(aliases)>0: |
| 722 |
return True |
| 723 |
return False |
| 724 |
|
| 725 |
def get(self,key,default=None): |
| 726 |
try: |
| 727 |
retval = self[key] |
| 728 |
except KeyError: |
| 729 |
retval = default |
| 730 |
return retval |
| 731 |
|
| 732 |
def clear(self): |
| 733 |
self.block = {} |
| 734 |
self.loops = {} |
| 735 |
self.item_order = [] |
| 736 |
self.true_case = {} |
| 737 |
|
| 738 |
|
| 739 |
def copy(self): |
| 740 |
newcopy = StarBlock() |
| 741 |
newcopy.block = self.block.copy() |
| 742 |
newcopy.loops = [] |
| 743 |
newcopy.item_order = self.item_order[:] |
| 744 |
newcopy.true_case = self.true_case.copy() |
| 745 |
newcopy.loops = self.loops.copy() |
| 746 |
|
| 747 |
return newcopy |
| 748 |
|
| 749 |
def update(self,adict): |
| 750 |
for key in adict.keys(): |
| 751 |
self.AddItem(key,adict[key]) |
| 752 |
|
| 753 |
|
| 754 |
|
| 755 |
|
| 756 |
|
| 757 |
|
| 758 |
def GetItemPosition(self,itemname): |
| 759 |
"""A utility function to get the numerical order in the printout |
| 760 |
of `itemname`. An item has coordinate `(loop_no,pos)` with |
| 761 |
the top level having a `loop_no` of -1. If an integer is passed to |
| 762 |
the routine then it will return the position of the loop |
| 763 |
referenced by that number.""" |
| 764 |
if isinstance(itemname,int): |
| 765 |
|
| 766 |
return (-1, self.item_order.index(itemname)) |
| 767 |
if not itemname in self: |
| 768 |
raise ValueError('No such dataname {}'.format(itemname)) |
| 769 |
testname = itemname.lower() |
| 770 |
if testname in self.item_order: |
| 771 |
return (-1,self.item_order.index(testname)) |
| 772 |
loop_no = self.FindLoop(testname) |
| 773 |
loop_pos = self.loops[loop_no].index(testname) |
| 774 |
return loop_no,loop_pos |
| 775 |
|
| 776 |
def ChangeTagName(self, old_name, new_name): |
| 777 |
lower_new_name = new_name.lower() |
| 778 |
lower_old_name = old_name.lower() |
| 779 |
loop_pos, pos = self.GetItemPosition(old_name) |
| 780 |
|
| 781 |
if loop_pos > 0: |
| 782 |
self.loops[loop_pos][pos] = lower_new_name |
| 783 |
|
| 784 |
else: |
| 785 |
self.item_order[pos] = lower_new_name |
| 786 |
|
| 787 |
updated_block = {} |
| 788 |
|
| 789 |
for lower_tag, value in self.block.items(): |
| 790 |
if lower_tag == lower_old_name: |
| 791 |
updated_block[lower_new_name] = value |
| 792 |
|
| 793 |
else: |
| 794 |
updated_block[lower_tag] = value |
| 795 |
|
| 796 |
updated_true_case = {} |
| 797 |
|
| 798 |
for lower_key, original_key in self.true_case.items(): |
| 799 |
if lower_key == lower_old_name: |
| 800 |
updated_true_case[lower_new_name] = new_name |
| 801 |
|
| 802 |
else: |
| 803 |
updated_true_case[lower_key] = original_key |
| 804 |
|
| 805 |
self.block = updated_block |
| 806 |
self.true_case = updated_true_case |
| 807 |
|
| 808 |
|
| 809 |
|
| 810 |
|
| 811 |
|
| 812 |
|
| 813 |
def ChangeItemOrder(self,itemname,newpos): |
| 814 |
"""Move the printout order of `itemname` to `newpos`. If `itemname` is |
| 815 |
in a loop, `newpos` refers to the order within the loop.""" |
| 816 |
if isinstance(itemname,(unicode,str)): |
| 817 |
true_name = itemname.lower() |
| 818 |
else: |
| 819 |
true_name = itemname |
| 820 |
loopno = self.FindLoop(true_name) |
| 821 |
if loopno < 0: |
| 822 |
self.item_order.remove(true_name) |
| 823 |
self.item_order.insert(newpos,true_name) |
| 824 |
else: |
| 825 |
self.loops[loopno].remove(true_name) |
| 826 |
self.loops[loopno].insert(newpos,true_name) |
| 827 |
|
| 828 |
|
| 829 |
def GetItemOrder(self): |
| 830 |
"""Return a list of datanames in the order in which they will be printed. Loops are |
| 831 |
referred to by numerical index""" |
| 832 |
return self.item_order[:] |
| 833 |
|
| 834 |
|
| 835 |
|
| 836 |
|
| 837 |
|
| 838 |
|
| 839 |
|
| 840 |
|
| 841 |
|
| 842 |
|
| 843 |
|
| 844 |
|
| 845 |
|
| 846 |
|
| 847 |
|
| 848 |
|
| 849 |
def AddItem(self,key,value,precheck=False): |
| 850 |
"""Add dataname `key` to block with value `value`. `value` may be |
| 851 |
a single value, a list or a tuple. If `precheck` is False (the default), |
| 852 |
all values will be checked and converted to unicode strings as necessary. If |
| 853 |
`precheck` is True, this checking is bypassed. No checking is necessary |
| 854 |
when values are read from a CIF file as they are already in correct form.""" |
| 855 |
if not isinstance(key,(unicode,str)): |
| 856 |
raise TypeError('Star datanames are strings only (got {})'.format(repr( key ))) |
| 857 |
key = unicode(key) |
| 858 |
if not precheck: |
| 859 |
self.check_data_name(key,self.maxnamelength) |
| 860 |
|
| 861 |
if key in self: |
| 862 |
if not self.overwrite: |
| 863 |
raise StarError( 'Duplicated item name: {}'.format(key)) |
| 864 |
if not precheck: |
| 865 |
regval,empty_val = self.regularise_data(value) |
| 866 |
pure_string = check_stringiness(regval) |
| 867 |
self.check_item_value(regval) |
| 868 |
else: |
| 869 |
regval,empty_val = value,None |
| 870 |
pure_string = True |
| 871 |
|
| 872 |
lower_key = key.lower() |
| 873 |
if not lower_key in self and self.FindLoop(lower_key)<0: |
| 874 |
self.item_order.append(lower_key) |
| 875 |
|
| 876 |
try: |
| 877 |
del self.true_case[lower_key] |
| 878 |
except KeyError: |
| 879 |
pass |
| 880 |
self.true_case[lower_key] = key |
| 881 |
if pure_string: |
| 882 |
self.block.update({lower_key:[regval,empty_val]}) |
| 883 |
else: |
| 884 |
self.block.update({lower_key:[empty_val,regval]}) |
| 885 |
|
| 886 |
|
| 887 |
|
| 888 |
|
| 889 |
|
| 890 |
|
| 891 |
def AddLoopItem(self,incomingdata,precheck=False,maxlength=-1): |
| 892 |
"""*Deprecated*. Use `AddItem` followed by `CreateLoop` if |
| 893 |
necessary.""" |
| 894 |
|
| 895 |
|
| 896 |
|
| 897 |
|
| 898 |
if isinstance(incomingdata[0],(tuple,list)): |
| 899 |
|
| 900 |
keyvallist = zip(incomingdata[0],incomingdata[1]) |
| 901 |
for key,value in keyvallist: |
| 902 |
self.AddItem(key,value) |
| 903 |
self.CreateLoop(incomingdata[0]) |
| 904 |
elif not isinstance(incomingdata[0],(unicode,str)): |
| 905 |
raise TypeError('Star datanames are strings only (got {})'.format(repr( incomingdata[0] ))) |
| 906 |
else: |
| 907 |
self.AddItem(incomingdata[0],incomingdata[1]) |
| 908 |
|
| 909 |
|
| 910 |
|
| 911 |
|
| 912 |
|
| 913 |
|
| 914 |
|
| 915 |
|
| 916 |
|
| 917 |
|
| 918 |
|
| 919 |
|
| 920 |
|
| 921 |
|
| 922 |
|
| 923 |
|
| 924 |
def check_data_name(self,dataname,maxlength=-1): |
| 925 |
if maxlength > 0: |
| 926 |
self.check_name_length(dataname,maxlength) |
| 927 |
if dataname[0]!='_': |
| 928 |
raise StarError( 'Dataname ' + dataname + ' does not begin with _') |
| 929 |
if self.characterset=='ascii': |
| 930 |
if len ([a for a in dataname if ord(a) < 33 or ord(a) > 126]) > 0: |
| 931 |
raise StarError( 'Dataname ' + dataname + ' contains forbidden characters') |
| 932 |
else: |
| 933 |
|
| 934 |
if len ([a for a in dataname if ord(a) < 33]) > 0: |
| 935 |
raise StarError( 'Dataname ' + dataname + ' contains forbidden characters (below code point 33)') |
| 936 |
if len ([a for a in dataname if ord(a) > 126 and ord(a) < 160]) > 0: |
| 937 |
raise StarError( 'Dataname ' + dataname + ' contains forbidden characters (between code point 127-159)') |
| 938 |
if len ([a for a in dataname if ord(a) > 0xD7FF and ord(a) < 0xE000]) > 0: |
| 939 |
raise StarError( 'Dataname ' + dataname + ' contains unsupported characters (between U+D800 and U+E000)') |
| 940 |
if len ([a for a in dataname if ord(a) > 0xFDCF and ord(a) < 0xFDF0]) > 0: |
| 941 |
raise StarError( 'Dataname ' + dataname + ' contains unsupported characters (between U+FDD0 and U+FDEF)') |
| 942 |
if len ([a for a in dataname if ord(a) == 0xFFFE or ord(a) == 0xFFFF]) > 0: |
| 943 |
raise StarError( 'Dataname ' + dataname + ' contains unsupported characters (U+FFFE and/or U+FFFF)') |
| 944 |
if len ([a for a in dataname if ord(a) > 0x10000 and (ord(a) & 0xE == 0xE)]) > 0: |
| 945 |
print('{} fails'.format(dataname)) |
| 946 |
for a in dataname: print('{}'.format(ord(a)),end="") |
| 947 |
print() |
| 948 |
raise StarError( u'Dataname ' + dataname + u' contains unsupported characters (U+xFFFE and/or U+xFFFF)') |
| 949 |
|
| 950 |
def check_name_length(self,dataname,maxlength): |
| 951 |
if len(dataname)>maxlength: |
| 952 |
raise StarError( 'Dataname {} exceeds maximum length {}'.format(dataname,maxlength)) |
| 953 |
return |
| 954 |
|
| 955 |
|
| 956 |
def check_item_value(self,item): |
| 957 |
test_item = item |
| 958 |
if not isinstance(item,(list,dict,tuple)): |
| 959 |
test_item = [item] |
| 960 |
def check_one (it): |
| 961 |
if isinstance(it,unicode): |
| 962 |
if it=='': return |
| 963 |
me = self.char_check.match(it) |
| 964 |
if not me: |
| 965 |
print("Fail value check: {}".format(it)) |
| 966 |
raise StarError('Bad character in {}'.format(it)) |
| 967 |
else: |
| 968 |
if me.span() != (0,len(it)): |
| 969 |
print("Fail value check, match only {}-{} in string {}".format(me.span()[0],me.span()[1],repr( it ))) |
| 970 |
raise StarError('Data item "' + repr( it ) + u'"... contains forbidden characters') |
| 971 |
[check_one(a) for a in test_item] |
| 972 |
|
| 973 |
|
| 974 |
|
| 975 |
|
| 976 |
|
| 977 |
|
| 978 |
|
| 979 |
|
| 980 |
|
| 981 |
|
| 982 |
|
| 983 |
|
| 984 |
def regularise_data(self,dataitem): |
| 985 |
"""Place dataitem into a list if necessary""" |
| 986 |
from numbers import Number |
| 987 |
if isinstance(dataitem,str): |
| 988 |
return unicode(dataitem),None |
| 989 |
if isinstance(dataitem,(Number,unicode,StarList,StarDict)): |
| 990 |
return dataitem,None |
| 991 |
if isinstance(dataitem,(tuple,list)): |
| 992 |
v,s = zip(*list([self.regularise_data(a) for a in dataitem])) |
| 993 |
return list(v),list(s) |
| 994 |
|
| 995 |
|
| 996 |
try: |
| 997 |
regval = list(dataitem) |
| 998 |
except TypeError as value: |
| 999 |
raise StarError( str(dataitem) + ' is wrong type for data value\n' ) |
| 1000 |
v,s = zip(*list([self.regularise_data(a) for a in regval])) |
| 1001 |
return list(v),list(s) |
| 1002 |
|
| 1003 |
|
| 1004 |
|
| 1005 |
|
| 1006 |
|
| 1007 |
|
| 1008 |
|
| 1009 |
def RemoveItem(self,itemname): |
| 1010 |
"""Remove `itemname` from the block.""" |
| 1011 |
|
| 1012 |
loop_no = self.FindLoop(itemname) |
| 1013 |
testkey = itemname.lower() |
| 1014 |
if testkey in self: |
| 1015 |
del self.block[testkey] |
| 1016 |
del self.true_case[testkey] |
| 1017 |
|
| 1018 |
if loop_no >= 0: |
| 1019 |
self.loops[loop_no].remove(testkey) |
| 1020 |
if len(self.loops[loop_no])==0: |
| 1021 |
del self.loops[loop_no] |
| 1022 |
self.item_order.remove(loop_no) |
| 1023 |
else: |
| 1024 |
self.item_order.remove(testkey) |
| 1025 |
|
| 1026 |
def RemoveLoopItem(self,itemname): |
| 1027 |
"""*Deprecated*. Use `RemoveItem` instead""" |
| 1028 |
self.RemoveItem(itemname) |
| 1029 |
|
| 1030 |
|
| 1031 |
|
| 1032 |
|
| 1033 |
|
| 1034 |
|
| 1035 |
|
| 1036 |
|
| 1037 |
|
| 1038 |
|
| 1039 |
|
| 1040 |
|
| 1041 |
|
| 1042 |
|
| 1043 |
|
| 1044 |
|
| 1045 |
|
| 1046 |
|
| 1047 |
|
| 1048 |
|
| 1049 |
|
| 1050 |
def GetItemValue(self,itemname): |
| 1051 |
"""Return value of `itemname`. If `itemname` is looped, a list |
| 1052 |
of all values will be returned.""" |
| 1053 |
return self.GetFullItemValue(itemname)[0] |
| 1054 |
|
| 1055 |
def GetFullItemValue(self,itemname): |
| 1056 |
"""Return the value associated with `itemname`, and a boolean flagging whether |
| 1057 |
(True) or not (False) it is in a form suitable for calculation. False is |
| 1058 |
always returned for strings and `StarList` objects.""" |
| 1059 |
try: |
| 1060 |
s,v = self.block[itemname.lower()] |
| 1061 |
except KeyError: |
| 1062 |
raise KeyError('Itemname {} not in datablock'.format(itemname)) |
| 1063 |
|
| 1064 |
|
| 1065 |
if not isinstance(s,(tuple,list)) or isinstance(s,StarList): |
| 1066 |
if not_none(s): |
| 1067 |
return s,False |
| 1068 |
else: |
| 1069 |
return v,not isinstance(v,StarList) |
| 1070 |
elif not_none(s): |
| 1071 |
return s,False |
| 1072 |
else: |
| 1073 |
if len(v)>0: |
| 1074 |
return v,not isinstance(v[0],StarList) |
| 1075 |
return v,True |
| 1076 |
|
| 1077 |
|
| 1078 |
|
| 1079 |
|
| 1080 |
|
| 1081 |
|
| 1082 |
|
| 1083 |
|
| 1084 |
|
| 1085 |
|
| 1086 |
|
| 1087 |
|
| 1088 |
|
| 1089 |
|
| 1090 |
|
| 1091 |
|
| 1092 |
|
| 1093 |
|
| 1094 |
|
| 1095 |
|
| 1096 |
def CreateLoop(self,datanames,order=-1,length_check=True): |
| 1097 |
"""Create a loop in the datablock. `datanames` is a list of datanames that |
| 1098 |
together form a loop. If length_check is True, they should have been initialised in the block |
| 1099 |
to have the same number of elements (possibly 0). If `order` is given, |
| 1100 |
the loop will appear at this position in the block when printing |
| 1101 |
out. A single-row loop will be created if the provided datanames are all |
| 1102 |
non-lists. A loop counts as a single position.""" |
| 1103 |
|
| 1104 |
if length_check: |
| 1105 |
|
| 1106 |
listed_values = [a for a in datanames if isinstance(self[a],list) and not isinstance(self[a],StarList)] |
| 1107 |
if len(listed_values) == len(datanames): |
| 1108 |
len_set = set([len(self[a]) for a in datanames]) |
| 1109 |
if len(len_set)>1: |
| 1110 |
raise ValueError('Request to loop datanames {} with different lengths: {}'.format(repr( datanames ),repr( len_set ))) |
| 1111 |
elif len(listed_values) != 0: |
| 1112 |
raise ValueError('Request to loop datanames where some are single values and some are not') |
| 1113 |
else: |
| 1114 |
for d in datanames: |
| 1115 |
self[d] = [self[d]] |
| 1116 |
|
| 1117 |
lc_datanames = [d.lower() for d in datanames] |
| 1118 |
|
| 1119 |
[self.loops[a].remove(b) for a in self.loops for b in lc_datanames if b in self.loops[a]] |
| 1120 |
|
| 1121 |
empty_loops = [a for a in self.loops.keys() if len(self.loops[a])==0] |
| 1122 |
for a in empty_loops: |
| 1123 |
self.item_order.remove(a) |
| 1124 |
del self.loops[a] |
| 1125 |
if len(self.loops)>0: |
| 1126 |
loopno = max(self.loops.keys()) + 1 |
| 1127 |
else: |
| 1128 |
loopno = 1 |
| 1129 |
self.loops[loopno] = list(lc_datanames) |
| 1130 |
if order >= 0: |
| 1131 |
self.item_order.insert(order,loopno) |
| 1132 |
else: |
| 1133 |
self.item_order.append(loopno) |
| 1134 |
|
| 1135 |
self.item_order = [a for a in self.item_order if a not in lc_datanames] |
| 1136 |
|
| 1137 |
|
| 1138 |
|
| 1139 |
|
| 1140 |
|
| 1141 |
|
| 1142 |
|
| 1143 |
|
| 1144 |
|
| 1145 |
def AddLoopName(self,oldname, newname): |
| 1146 |
"""Add `newname` to the loop containing `oldname`. If it is already in the new loop, no |
| 1147 |
error is raised. If `newname` is in a different loop, it is removed from that loop. |
| 1148 |
The number of values associated with `newname` must match the number of values associated |
| 1149 |
with all other columns of the new loop or a `ValueError` will be raised.""" |
| 1150 |
lower_newname = newname.lower() |
| 1151 |
loop_no = self.FindLoop(oldname) |
| 1152 |
if loop_no < 0: |
| 1153 |
raise KeyError('{} not in loop'.format(oldname)) |
| 1154 |
if lower_newname in self.loops[loop_no]: |
| 1155 |
return |
| 1156 |
|
| 1157 |
old_provides = self.provide_value |
| 1158 |
self.provide_value = False |
| 1159 |
loop_len = len(self[oldname]) |
| 1160 |
self.provide_value = old_provides |
| 1161 |
if len(self[newname]) != loop_len: |
| 1162 |
raise StarLengthError('Mismatch of loop column lengths for {}: should be {}'.format((newname,loop_len))) |
| 1163 |
|
| 1164 |
[self.loops[a].remove(lower_newname) for a in self.loops if lower_newname in self.loops[a]] |
| 1165 |
|
| 1166 |
self.loops[loop_no].append(lower_newname) |
| 1167 |
|
| 1168 |
try: |
| 1169 |
self.item_order.remove(lower_newname) |
| 1170 |
except ValueError: |
| 1171 |
pass |
| 1172 |
|
| 1173 |
|
| 1174 |
def FindLoop(self,keyname): |
| 1175 |
"""Find the loop that contains `keyname` and return its numerical index or |
| 1176 |
-1 if not present. The numerical index can be used to refer to the loop in |
| 1177 |
other routines.""" |
| 1178 |
loop_no = [a for a in self.loops.keys() if keyname.lower() in self.loops[a]] |
| 1179 |
if len(loop_no)>0: |
| 1180 |
return loop_no[0] |
| 1181 |
else: |
| 1182 |
return -1 |
| 1183 |
|
| 1184 |
|
| 1185 |
|
| 1186 |
|
| 1187 |
|
| 1188 |
|
| 1189 |
|
| 1190 |
|
| 1191 |
|
| 1192 |
|
| 1193 |
|
| 1194 |
|
| 1195 |
|
| 1196 |
|
| 1197 |
def GetLoop(self,keyname): |
| 1198 |
"""Return a `StarFile.LoopBlock` object constructed from the loop containing `keyname`. |
| 1199 |
`keyname` is only significant as a way to specify the loop.""" |
| 1200 |
return LoopBlock(self,keyname) |
| 1201 |
|
| 1202 |
|
| 1203 |
|
| 1204 |
|
| 1205 |
|
| 1206 |
|
| 1207 |
def GetLoopNames(self,keyname): |
| 1208 |
if keyname in self: |
| 1209 |
return self.keys() |
| 1210 |
for aloop in self.loops: |
| 1211 |
try: |
| 1212 |
return aloop.GetLoopNames(keyname) |
| 1213 |
except KeyError: |
| 1214 |
pass |
| 1215 |
raise KeyError('Item does not exist') |
| 1216 |
|
| 1217 |
|
| 1218 |
|
| 1219 |
|
| 1220 |
|
| 1221 |
|
| 1222 |
def GetLoopNames(self,keyname): |
| 1223 |
"""Return all datanames appearing together with `keyname`""" |
| 1224 |
loop_no = self.FindLoop(keyname) |
| 1225 |
if loop_no >= 0: |
| 1226 |
return self.loops[loop_no] |
| 1227 |
else: |
| 1228 |
raise KeyError('{} is not in any loop'.format(keyname)) |
| 1229 |
|
| 1230 |
|
| 1231 |
|
| 1232 |
|
| 1233 |
|
| 1234 |
|
| 1235 |
|
| 1236 |
|
| 1237 |
|
| 1238 |
def AddLoopName(self,oldname, newname): |
| 1239 |
"""Add `newname` to the loop containing `oldname`. If it is already in the new loop, no |
| 1240 |
error is raised. If `newname` is in a different loop, it is removed from that loop. |
| 1241 |
The number of values associated with `newname` must match the number of values associated |
| 1242 |
with all other columns of the new loop or a `ValueError` will be raised.""" |
| 1243 |
lower_newname = newname.lower() |
| 1244 |
loop_no = self.FindLoop(oldname) |
| 1245 |
if loop_no < 0: |
| 1246 |
raise KeyError('{} not in loop'.format(oldname)) |
| 1247 |
if lower_newname in self.loops[loop_no]: |
| 1248 |
return |
| 1249 |
|
| 1250 |
old_provides = self.provide_value |
| 1251 |
self.provide_value = False |
| 1252 |
loop_len = len(self[oldname]) |
| 1253 |
self.provide_value = old_provides |
| 1254 |
if len(self[newname]) != loop_len: |
| 1255 |
raise StarLengthError('Mismatch of loop column lengths for {}: should be {}'.format(newname,loop_len)) |
| 1256 |
|
| 1257 |
[self.loops[a].remove(lower_newname) for a in self.loops if lower_newname in self.loops[a]] |
| 1258 |
|
| 1259 |
self.loops[loop_no].append(lower_newname) |
| 1260 |
|
| 1261 |
try: |
| 1262 |
self.item_order.remove(lower_newname) |
| 1263 |
except ValueError: |
| 1264 |
pass |
| 1265 |
|
| 1266 |
|
| 1267 |
|
| 1268 |
|
| 1269 |
|
| 1270 |
|
| 1271 |
|
| 1272 |
def RemoveKeyedPacket(self,keyname,keyvalue): |
| 1273 |
"""Remove the packet for which dataname `keyname` takes |
| 1274 |
value `keyvalue`. Only the first such occurrence is |
| 1275 |
removed.""" |
| 1276 |
packet_coord = list(self[keyname]).index(keyvalue) |
| 1277 |
loopnames = self.GetLoopNames(keyname) |
| 1278 |
for dataname in loopnames: |
| 1279 |
self.block[dataname][0] = list(self.block[dataname][0]) |
| 1280 |
del self.block[dataname][0][packet_coord] |
| 1281 |
self.block[dataname][1] = list(self.block[dataname][1]) |
| 1282 |
del self.block[dataname][1][packet_coord] |
| 1283 |
|
| 1284 |
|
| 1285 |
|
| 1286 |
|
| 1287 |
|
| 1288 |
|
| 1289 |
|
| 1290 |
|
| 1291 |
|
| 1292 |
|
| 1293 |
|
| 1294 |
|
| 1295 |
|
| 1296 |
|
| 1297 |
def GetKeyedPacket(self,keyname,keyvalue,no_case=False): |
| 1298 |
"""Return the loop packet (a `StarPacket` object) where `keyname` has value |
| 1299 |
`keyvalue`. Ignore case in `keyvalue` if `no_case` is True. `ValueError` |
| 1300 |
is raised if no packet is found or more than one packet is found.""" |
| 1301 |
my_loop = self.GetLoop(keyname) |
| 1302 |
|
| 1303 |
|
| 1304 |
|
| 1305 |
if no_case: |
| 1306 |
one_pack= [a for a in my_loop if getattr(a,keyname).lower()==keyvalue.lower()] |
| 1307 |
else: |
| 1308 |
one_pack= [a for a in my_loop if getattr(a,keyname)==keyvalue] |
| 1309 |
if len(one_pack)!=1: |
| 1310 |
raise ValueError("Bad packet key {} = {}: returned {} packets".format(keyname,keyvalue,len(one_pack))) |
| 1311 |
print("Keyed packet: {}".format(one_pack[0])) |
| 1312 |
return one_pack[0] |
| 1313 |
|
| 1314 |
|
| 1315 |
|
| 1316 |
|
| 1317 |
|
| 1318 |
|
| 1319 |
def GetCompoundKeyedPacket(self,keydict): |
| 1320 |
"""Return the loop packet (a `StarPacket` object) where the `{key:(value,caseless)}` pairs |
| 1321 |
in `keydict` take the appropriate values. Ignore case for a given `key` if `caseless` is |
| 1322 |
True. `ValueError` is raised if no packet is found or more than one packet is found.""" |
| 1323 |
|
| 1324 |
keynames = list(keydict.keys()) |
| 1325 |
my_loop = self.GetLoop(keynames[0]) |
| 1326 |
for one_key in keynames: |
| 1327 |
keyval,no_case = keydict[one_key] |
| 1328 |
if no_case: |
| 1329 |
my_loop = list([a for a in my_loop if str(getattr(a,one_key)).lower()==str(keyval).lower()]) |
| 1330 |
else: |
| 1331 |
my_loop = list([a for a in my_loop if getattr(a,one_key)==keyval]) |
| 1332 |
if len(my_loop)!=1: |
| 1333 |
raise ValueError("Bad packet keys {}: returned {} packets".format(repr(keydict),len(my_loop))) |
| 1334 |
print("Compound keyed packet: {}".format(my_loop[0])) |
| 1335 |
return my_loop[0] |
| 1336 |
|
| 1337 |
|
| 1338 |
|
| 1339 |
|
| 1340 |
|
| 1341 |
|
| 1342 |
|
| 1343 |
|
| 1344 |
def GetKeyedSemanticPacket(self,keyvalue,cat_id): |
| 1345 |
"""Return a complete packet for category `cat_id` where the |
| 1346 |
category key for the category equals `keyvalue`. This routine |
| 1347 |
will understand any joined loops, so if separate loops in the |
| 1348 |
datafile belong to the |
| 1349 |
same category hierarchy (e.g. `_atom_site` and `_atom_site_aniso`), |
| 1350 |
the returned `StarPacket` object will contain datanames from |
| 1351 |
both categories.""" |
| 1352 |
target_keys = self.dictionary.cat_key_table[cat_id] |
| 1353 |
target_keys = [k[0] for k in target_keys] |
| 1354 |
p = StarPacket() |
| 1355 |
|
| 1356 |
lcase = False |
| 1357 |
if self.dictionary[target_keys[0]]['_type.contents'] in ['Code','Tag','Name']: |
| 1358 |
lcase = True |
| 1359 |
for cat_key in target_keys: |
| 1360 |
try: |
| 1361 |
extra_packet = self.GetKeyedPacket(cat_key,keyvalue,no_case=lcase) |
| 1362 |
except KeyError: |
| 1363 |
try: |
| 1364 |
test_key = self[cat_key] |
| 1365 |
print('Test key is {}'.format(repr( test_key ))) |
| 1366 |
if test_key is not None and\ |
| 1367 |
not (isinstance(test_key,list) and (None in test_key or len(test_key)==0)): |
| 1368 |
print('Getting packet for key {}'.format(repr( keyvalue ))) |
| 1369 |
extra_packet = self.GetKeyedPacket(cat_key,keyvalue,no_case=lcase) |
| 1370 |
except: |
| 1371 |
continue |
| 1372 |
except ValueError: |
| 1373 |
continue |
| 1374 |
|
| 1375 |
p.merge_packet(extra_packet) |
| 1376 |
|
| 1377 |
for keyname in target_keys: |
| 1378 |
if hasattr(p,keyname): |
| 1379 |
p.key = [keyname] |
| 1380 |
break |
| 1381 |
if not hasattr(p,"key"): |
| 1382 |
raise ValueError("No key found for {}, packet is {}".format(cat_id,str(p))) |
| 1383 |
p.cif_dictionary = self.dictionary |
| 1384 |
p.fulldata = self |
| 1385 |
return p |
| 1386 |
|
| 1387 |
|
| 1388 |
|
| 1389 |
|
| 1390 |
|
| 1391 |
|
| 1392 |
|
| 1393 |
|
| 1394 |
|
| 1395 |
|
| 1396 |
|
| 1397 |
|
| 1398 |
|
| 1399 |
|
| 1400 |
|
| 1401 |
|
| 1402 |
|
| 1403 |
|
| 1404 |
|
| 1405 |
|
| 1406 |
|
| 1407 |
|
| 1408 |
|
| 1409 |
|
| 1410 |
|
| 1411 |
|
| 1412 |
|
| 1413 |
|
| 1414 |
|
| 1415 |
|
| 1416 |
|
| 1417 |
|
| 1418 |
|
| 1419 |
|
| 1420 |
|
| 1421 |
|
| 1422 |
|
| 1423 |
|
| 1424 |
|
| 1425 |
def GetMultiKeyedSemanticPacket(self,keydict,cat_id): |
| 1426 |
"""Return a complete packet for category `cat_id` where the keyvalues are |
| 1427 |
provided as a dictionary of key:(value,caseless) pairs |
| 1428 |
This routine |
| 1429 |
will understand any joined loops, so if separate loops in the |
| 1430 |
datafile belong to the |
| 1431 |
same category hierarchy (e.g. `_atom_site` and `_atom_site_aniso`), |
| 1432 |
the returned `StarPacket` object will contain datanames from |
| 1433 |
the requested category and any children.""" |
| 1434 |
|
| 1435 |
|
| 1436 |
target_keys = self.dictionary.cat_key_table[cat_id] |
| 1437 |
|
| 1438 |
|
| 1439 |
parallel_keys = list(zip(*target_keys)) |
| 1440 |
print('Parallel keys:' + repr(parallel_keys)) |
| 1441 |
print('Keydict:' + repr(keydict)) |
| 1442 |
start_keys = list(keydict.keys()) |
| 1443 |
for one_name in start_keys: |
| 1444 |
key_set = [a for a in parallel_keys if one_name in a] |
| 1445 |
for one_key in key_set: |
| 1446 |
keydict[one_key] = keydict[one_name] |
| 1447 |
|
| 1448 |
p = StarPacket() |
| 1449 |
|
| 1450 |
def find_key(key): |
| 1451 |
for one_key in self.dictionary.key_equivs.get(key,[])+[key]: |
| 1452 |
if self.has_key(one_key): |
| 1453 |
return one_key |
| 1454 |
return None |
| 1455 |
for one_set in target_keys: |
| 1456 |
true_keys = [find_key(k) for k in one_set] |
| 1457 |
true_keys = [k for k in true_keys if k is not None] |
| 1458 |
if len(true_keys)==len(one_set): |
| 1459 |
truekeydict = dict([(t,keydict[k]) for t,k in zip(true_keys,one_set)]) |
| 1460 |
try: |
| 1461 |
extra_packet = self.GetCompoundKeyedPacket(truekeydict) |
| 1462 |
except KeyError: |
| 1463 |
continue |
| 1464 |
except ValueError: |
| 1465 |
continue |
| 1466 |
else: |
| 1467 |
continue |
| 1468 |
print('Merging packet for keys ' + repr(one_set)) |
| 1469 |
p.merge_packet(extra_packet) |
| 1470 |
|
| 1471 |
p.key = true_keys |
| 1472 |
p.cif_dictionary = self.dictionary |
| 1473 |
p.fulldata = self |
| 1474 |
return p |
| 1475 |
|
| 1476 |
|
| 1477 |
|
| 1478 |
|
| 1479 |
|
| 1480 |
|
| 1481 |
|
| 1482 |
|
| 1483 |
|
| 1484 |
|
| 1485 |
|
| 1486 |
|
| 1487 |
|
| 1488 |
|
| 1489 |
|
| 1490 |
|
| 1491 |
|
| 1492 |
|
| 1493 |
|
| 1494 |
|
| 1495 |
|
| 1496 |
def set_grammar(self,new_grammar): |
| 1497 |
self.string_delimiters = ["'",'"',"\n;",None] |
| 1498 |
if new_grammar in ['STAR2','2.0']: |
| 1499 |
self.string_delimiters += ['"""',"'''"] |
| 1500 |
if new_grammar == '2.0': |
| 1501 |
self.list_delimiter = " " |
| 1502 |
elif new_grammar == 'STAR2': |
| 1503 |
self.list_delimiter = ", " |
| 1504 |
elif new_grammar not in ['1.0','1.1']: |
| 1505 |
raise StarError('Request to set unknown grammar {}'.format(new_grammar)) |
| 1506 |
|
| 1507 |
|
| 1508 |
|
| 1509 |
|
| 1510 |
|
| 1511 |
|
| 1512 |
|
| 1513 |
|
| 1514 |
|
| 1515 |
|
| 1516 |
|
| 1517 |
|
| 1518 |
|
| 1519 |
|
| 1520 |
def SetOutputLength(self,wraplength=80,maxoutlength=2048): |
| 1521 |
"""Set the maximum output line length (`maxoutlength`) and the line length to |
| 1522 |
wrap at (`wraplength`). The wrap length is a target only and may not always be |
| 1523 |
possible.""" |
| 1524 |
if wraplength > maxoutlength: |
| 1525 |
raise StarError("Wrap length (requested {}) must be <= Maximum line length (requested {})".format((wraplength,maxoutlength))) |
| 1526 |
self.wraplength = wraplength |
| 1527 |
self.maxoutlength = maxoutlength |
| 1528 |
|
| 1529 |
|
| 1530 |
|
| 1531 |
|
| 1532 |
|
| 1533 |
|
| 1534 |
|
| 1535 |
|
| 1536 |
|
| 1537 |
|
| 1538 |
|
| 1539 |
|
| 1540 |
|
| 1541 |
|
| 1542 |
|
| 1543 |
|
| 1544 |
|
| 1545 |
|
| 1546 |
|
| 1547 |
|
| 1548 |
|
| 1549 |
|
| 1550 |
|
| 1551 |
def printsection(self,instring='',blockstart="",blockend="",indent=0,finish_at='',start_from=''): |
| 1552 |
self.provide_value = False |
| 1553 |
|
| 1554 |
self.create_ordering(finish_at,start_from) |
| 1555 |
|
| 1556 |
if not instring: |
| 1557 |
outstring = CIFStringIO(target_width=80) |
| 1558 |
else: |
| 1559 |
outstring = instring |
| 1560 |
|
| 1561 |
outstring.write(blockstart,canbreak=True) |
| 1562 |
while len(self.output_order)>0: |
| 1563 |
|
| 1564 |
itemname = self.output_order.pop(0) |
| 1565 |
if not isinstance(itemname,int): |
| 1566 |
item_spec = [i for i in self.formatting_hints if i['dataname'].lower()==itemname.lower()] |
| 1567 |
if len(item_spec)>0: |
| 1568 |
item_spec = item_spec[0] |
| 1569 |
col_pos = item_spec.get('column',-1) |
| 1570 |
name_pos = item_spec.get('name_pos',-1) |
| 1571 |
else: |
| 1572 |
col_pos = -1 |
| 1573 |
item_spec = {} |
| 1574 |
name_pos = -1 |
| 1575 |
if col_pos < 0: col_pos = 40 |
| 1576 |
outstring.set_tab(col_pos) |
| 1577 |
itemvalue = self[itemname] |
| 1578 |
outstring.write(self.true_case[itemname],mustbreak=True,do_tab=False,startcol=name_pos) |
| 1579 |
outstring.write(' ',canbreak=True,do_tab=False,delimiter=True) |
| 1580 |
self.format_value(itemvalue,outstring,hints=item_spec) |
| 1581 |
else: |
| 1582 |
outstring.set_tab(10) |
| 1583 |
loop_spec = [i['name_pos'] for i in self.formatting_hints if i["dataname"]=='loop'] |
| 1584 |
if loop_spec: |
| 1585 |
loop_indent = max(loop_spec[0],0) |
| 1586 |
else: |
| 1587 |
loop_indent = indent |
| 1588 |
outstring.write('loop_\n',mustbreak=True,do_tab=False,startcol=loop_indent) |
| 1589 |
self.format_names(outstring,indent+2,loop_no=itemname) |
| 1590 |
self.format_packets(outstring,indent+2,loop_no=itemname) |
| 1591 |
else: |
| 1592 |
returnstring = outstring.getvalue() |
| 1593 |
outstring.close() |
| 1594 |
return returnstring |
| 1595 |
|
| 1596 |
|
| 1597 |
|
| 1598 |
|
| 1599 |
|
| 1600 |
|
| 1601 |
|
| 1602 |
def format_names(self,outstring,indent=0,loop_no=-1): |
| 1603 |
"""Print datanames from `loop_no` one per line""" |
| 1604 |
temp_order = self.loops[loop_no][:] |
| 1605 |
format_hints = dict([(i['dataname'],i) for i in self.formatting_hints if i['dataname'] in temp_order]) |
| 1606 |
while len(temp_order)>0: |
| 1607 |
itemname = temp_order.pop(0) |
| 1608 |
req_indent = format_hints.get(itemname,{}).get('name_pos',indent) |
| 1609 |
outstring.write(' ' * req_indent,do_tab=False) |
| 1610 |
outstring.write(self.true_case[itemname],do_tab=False) |
| 1611 |
outstring.write("\n",do_tab=False) |
| 1612 |
|
| 1613 |
|
| 1614 |
|
| 1615 |
|
| 1616 |
|
| 1617 |
|
| 1618 |
|
| 1619 |
|
| 1620 |
def format_packets(self,outstring,indent=0,loop_no=-1): |
| 1621 |
alldata = [self[a] for a in self.loops[loop_no]] |
| 1622 |
loopnames = self.loops[loop_no] |
| 1623 |
|
| 1624 |
if all(isinstance(elem, str) for elem in alldata): |
| 1625 |
packet_data = list(zip(alldata)) |
| 1626 |
else: |
| 1627 |
packet_data = list(zip(*alldata)) |
| 1628 |
|
| 1629 |
|
| 1630 |
format_hints = dict([(i['dataname'],i) for i in self.formatting_hints if i['dataname'] in loopnames]) |
| 1631 |
for position in range(len(packet_data)): |
| 1632 |
if position > 0: |
| 1633 |
outstring.write("\n") |
| 1634 |
for point in range(len(packet_data[position])): |
| 1635 |
datapoint = packet_data[position][point] |
| 1636 |
format_hint = format_hints.get(loopnames[point],{}) |
| 1637 |
packstring = self.format_packet_item(datapoint,indent,outstring,format_hint) |
| 1638 |
outstring.write(' ',canbreak=True,do_tab=False,delimiter=True) |
| 1639 |
|
| 1640 |
|
| 1641 |
|
| 1642 |
|
| 1643 |
|
| 1644 |
def format_packet_item(self,pack_item,indent,outstring,format_hint): |
| 1645 |
|
| 1646 |
|
| 1647 |
if isinstance(pack_item,str) and not isinstance(pack_item,unicode): |
| 1648 |
raise StarError("Item {0!r} is not unicode".format(pack_item)) |
| 1649 |
if isinstance(pack_item,unicode): |
| 1650 |
delimiter = format_hint.get('delimiter',None) |
| 1651 |
startcol = format_hint.get('column',-1) |
| 1652 |
outstring.write(self._formatstring(pack_item,delimiter=delimiter),startcol=startcol) |
| 1653 |
else: |
| 1654 |
self.format_value(pack_item,outstring,hints = format_hint) |
| 1655 |
|
| 1656 |
|
| 1657 |
|
| 1658 |
|
| 1659 |
|
| 1660 |
|
| 1661 |
|
| 1662 |
|
| 1663 |
|
| 1664 |
|
| 1665 |
|
| 1666 |
|
| 1667 |
|
| 1668 |
|
| 1669 |
|
| 1670 |
|
| 1671 |
|
| 1672 |
|
| 1673 |
|
| 1674 |
|
| 1675 |
|
| 1676 |
|
| 1677 |
|
| 1678 |
|
| 1679 |
|
| 1680 |
|
| 1681 |
|
| 1682 |
|
| 1683 |
|
| 1684 |
|
| 1685 |
|
| 1686 |
|
| 1687 |
|
| 1688 |
|
| 1689 |
|
| 1690 |
|
| 1691 |
|
| 1692 |
def _formatstring(self,instring,delimiter=None,standard='CIF1',indent=0,hints={}): |
| 1693 |
if hints.get("reformat",False) and "\n" in instring: |
| 1694 |
instring = "\n"+self.do_wrapping(instring,hints["reformat_indent"]) |
| 1695 |
allowed_delimiters = set(self.string_delimiters) |
| 1696 |
if len(instring)==0: allowed_delimiters.difference_update([None]) |
| 1697 |
if len(instring) > (self.maxoutlength-2) or '\n' in instring: |
| 1698 |
allowed_delimiters.intersection_update(["\n;","'''",'"""']) |
| 1699 |
[allowed_delimiters.difference_update([None]) for k in '[]{}\v\t ,' if k in instring] |
| 1700 |
if len(instring)>0 and instring[0] in '_$#;(': |
| 1701 |
allowed_delimiters.difference_update([None]) |
| 1702 |
if len(instring)>3 and (instring[:4].lower()=='data' or instring[:4].lower()=='save'): |
| 1703 |
allowed_delimiters.difference_update([None]) |
| 1704 |
if len(instring)>5 and instring[:6].lower()=='global': |
| 1705 |
allowed_delimiters.difference_update([None]) |
| 1706 |
if '"' in instring: allowed_delimiters.difference_update(['"',None]) |
| 1707 |
if "'" in instring: allowed_delimiters.difference_update(["'",None]) |
| 1708 |
out_delimiter = "\n;" |
| 1709 |
if delimiter in allowed_delimiters: |
| 1710 |
out_delimiter = delimiter |
| 1711 |
elif "'" in allowed_delimiters: out_delimiter = "'" |
| 1712 |
elif '"' in allowed_delimiters: out_delimiter = '"' |
| 1713 |
if out_delimiter in ['"',"'",'"""',"'''"]: return out_delimiter + instring + out_delimiter |
| 1714 |
elif out_delimiter is None: return instring |
| 1715 |
|
| 1716 |
|
| 1717 |
maxlinelength = max([len(a) for a in instring.split('\n')]) |
| 1718 |
if maxlinelength > self.maxoutlength: |
| 1719 |
protocol_string = apply_line_folding(instring) |
| 1720 |
else: |
| 1721 |
protocol_string = instring |
| 1722 |
|
| 1723 |
if "\n;" in protocol_string: |
| 1724 |
prefix = "CIF:" |
| 1725 |
while prefix in protocol_string: prefix = prefix + ":" |
| 1726 |
protocol_string = apply_line_prefix(protocol_string,prefix+"> ") |
| 1727 |
return "\n;" + protocol_string + "\n;" |
| 1728 |
|
| 1729 |
|
| 1730 |
|
| 1731 |
|
| 1732 |
|
| 1733 |
|
| 1734 |
|
| 1735 |
def format_value(self,itemvalue,stringsink,compound=False,hints={}): |
| 1736 |
"""Format a Star data value""" |
| 1737 |
global have_numpy |
| 1738 |
delimiter = hints.get('delimiter',None) |
| 1739 |
startcol = hints.get('column',-1) |
| 1740 |
if isinstance(itemvalue,str) and not isinstance(itemvalue,unicode): |
| 1741 |
raise StarError("Non-unicode value {0} found in block".format(itemvalue)) |
| 1742 |
if isinstance(itemvalue,unicode): |
| 1743 |
stringsink.write(self._formatstring(itemvalue,delimiter=delimiter,hints=hints),canbreak = True,startcol=startcol) |
| 1744 |
elif isinstance(itemvalue,(list)) or (hasattr(itemvalue,'dtype') and hasattr(itemvalue,'__iter__')): |
| 1745 |
stringsink.set_tab(0) |
| 1746 |
stringsink.write('[',canbreak=True,newindent=True,mustbreak=compound,startcol=startcol) |
| 1747 |
if len(itemvalue)>0: |
| 1748 |
print('Formatting {}'.format(repr(itemvalue))) |
| 1749 |
self.format_value(itemvalue[0],stringsink) |
| 1750 |
for listval in itemvalue[1:]: |
| 1751 |
print('Formatting {}'.format(repr(listval))) |
| 1752 |
stringsink.write(self.list_delimiter,do_tab=False) |
| 1753 |
self.format_value(listval,stringsink,compound=True) |
| 1754 |
stringsink.write(']',unindent=True) |
| 1755 |
elif isinstance(itemvalue,dict): |
| 1756 |
stringsink.set_tab(0) |
| 1757 |
stringsink.write('{',newindent=True,mustbreak=compound,startcol=startcol) |
| 1758 |
items = list(itemvalue.items()) |
| 1759 |
if len(items)>0: |
| 1760 |
stringsink.write("'"+items[0][0]+"'"+':',canbreak=True) |
| 1761 |
self.format_value(items[0][1],stringsink) |
| 1762 |
for key,value in items[1:]: |
| 1763 |
stringsink.write(self.list_delimiter) |
| 1764 |
stringsink.write("'"+key+"'"+":",canbreak=True) |
| 1765 |
self.format_value(value,stringsink) |
| 1766 |
stringsink.write('}',unindent=True) |
| 1767 |
elif isinstance(itemvalue,(float,int,long)) or \ |
| 1768 |
(have_numpy and isinstance(itemvalue,(numpy.number))): |
| 1769 |
stringsink.write(str(itemvalue),canbreak=True,startcol=startcol) |
| 1770 |
else: |
| 1771 |
raise ValueError('Value in unexpected format for output: {}'.format(repr( itemvalue ))) |
| 1772 |
|
| 1773 |
|
| 1774 |
|
| 1775 |
|
| 1776 |
|
| 1777 |
|
| 1778 |
|
| 1779 |
|
| 1780 |
|
| 1781 |
|
| 1782 |
|
| 1783 |
def create_ordering(self,finish_at,start_from): |
| 1784 |
"""Create a canonical ordering that includes loops using our formatting hints dictionary""" |
| 1785 |
requested_order = list([i['dataname'] for i in self.formatting_hints if i['dataname']!='loop']) |
| 1786 |
new_order = [] |
| 1787 |
for item in requested_order: |
| 1788 |
if isinstance(item,unicode) and item.lower() in self.item_order: |
| 1789 |
new_order.append(item.lower()) |
| 1790 |
elif item in self: |
| 1791 |
target_loop = self.FindLoop(item) |
| 1792 |
if target_loop not in new_order: |
| 1793 |
new_order.append(target_loop) |
| 1794 |
|
| 1795 |
loopnames = self.loops[target_loop] |
| 1796 |
loop_order = [i for i in requested_order if i in loopnames] |
| 1797 |
unordered = [i for i in loopnames if i not in loop_order] |
| 1798 |
self.loops[target_loop] = loop_order + unordered |
| 1799 |
extras = list([i for i in self.item_order if i not in new_order]) |
| 1800 |
self.output_order = new_order + extras |
| 1801 |
|
| 1802 |
if start_from != '': |
| 1803 |
if start_from in requested_order: |
| 1804 |
sfi = requested_order.index(start_from) |
| 1805 |
loop_order = [self.FindLoop(k) for k in requested_order[sfi:] if self.FindLoop(k)>0] |
| 1806 |
candidates = list([k for k in self.output_order if k in requested_order[sfi:]]) |
| 1807 |
cand_pos = len(new_order) |
| 1808 |
if len(candidates)>0: |
| 1809 |
cand_pos = self.output_order.index(candidates[0]) |
| 1810 |
if len(loop_order)>0: |
| 1811 |
cand_pos = min(cand_pos,self.output_order.index(loop_order[0])) |
| 1812 |
if cand_pos < len(self.output_order): |
| 1813 |
print('Output starts from {}, requested {}'.format(self.output_order[cand_pos],start_from)) |
| 1814 |
self.output_order = self.output_order[cand_pos:] |
| 1815 |
else: |
| 1816 |
print('Start is beyond end of output list') |
| 1817 |
self.output_order = [] |
| 1818 |
elif start_from in extras: |
| 1819 |
self.output_order = self.output_order[self.output_order.index(start_from):] |
| 1820 |
else: |
| 1821 |
self.output_order = [] |
| 1822 |
if finish_at != '': |
| 1823 |
if finish_at in requested_order: |
| 1824 |
fai = requested_order.index(finish_at) |
| 1825 |
loop_order = list([self.FindLoop(k) for k in requested_order[fai:] if self.FindLoop(k)>0]) |
| 1826 |
candidates = list([k for k in self.output_order if k in requested_order[fai:]]) |
| 1827 |
cand_pos = len(new_order) |
| 1828 |
if len(candidates)>0: |
| 1829 |
cand_pos = self.output_order.index(candidates[0]) |
| 1830 |
if len(loop_order)>0: |
| 1831 |
cand_pos = min(cand_pos,self.output_order.index(loop_order[0])) |
| 1832 |
if cand_pos < len(self.output_order): |
| 1833 |
print('Output finishes before {}, requested before {}'.format(self.output_order[cand_pos],finish_at)) |
| 1834 |
self.output_order = self.output_order[:cand_pos] |
| 1835 |
else: |
| 1836 |
print('All of block output') |
| 1837 |
elif finish_at in extras: |
| 1838 |
self.output_order = self.output_order[:self.output_order.index(finish_at)] |
| 1839 |
|
| 1840 |
|
| 1841 |
|
| 1842 |
|
| 1843 |
|
| 1844 |
|
| 1845 |
|
| 1846 |
|
| 1847 |
|
| 1848 |
def convert_to_string(self,dataname): |
| 1849 |
"""Convert values held in dataname value fork to string version""" |
| 1850 |
v,is_value = self.GetFullItemValue(dataname) |
| 1851 |
if not is_value: |
| 1852 |
return v |
| 1853 |
if check_stringiness(v): return v |
| 1854 |
|
| 1855 |
return v |
| 1856 |
|
| 1857 |
|
| 1858 |
|
| 1859 |
|
| 1860 |
|
| 1861 |
|
| 1862 |
|
| 1863 |
|
| 1864 |
|
| 1865 |
def do_wrapping(self,instring,indent=3): |
| 1866 |
"""Wrap the provided string""" |
| 1867 |
if " " in instring: |
| 1868 |
return instring |
| 1869 |
self.wrapper.initial_indent = ' '*indent |
| 1870 |
self.wrapper.subsequent_indent = ' '*indent |
| 1871 |
|
| 1872 |
instring = instring.strip() |
| 1873 |
|
| 1874 |
paras = instring.split("\n\n") |
| 1875 |
wrapped_paras = [self.wrapper.fill(p) for p in paras] |
| 1876 |
return "\n".join(wrapped_paras) |
| 1877 |
|
| 1878 |
|
| 1879 |
|
| 1880 |
|
| 1881 |
|
| 1882 |
|
| 1883 |
|
| 1884 |
|
| 1885 |
|
| 1886 |
|
| 1887 |
|
| 1888 |
|
| 1889 |
|
| 1890 |
|
| 1891 |
|
| 1892 |
|
| 1893 |
|
| 1894 |
|
| 1895 |
|
| 1896 |
|
| 1897 |
|
| 1898 |
|
| 1899 |
|
| 1900 |
|
| 1901 |
|
| 1902 |
|
| 1903 |
|
| 1904 |
|
| 1905 |
|
| 1906 |
|
| 1907 |
|
| 1908 |
|
| 1909 |
|
| 1910 |
|
| 1911 |
def merge(self,new_block,mode="strict",match_att=[],match_function=None, |
| 1912 |
rel_keys = []): |
| 1913 |
if mode == 'strict': |
| 1914 |
for key in new_block.keys(): |
| 1915 |
if key in self and key not in match_att: |
| 1916 |
raise StarError( "Identical keys {} in strict merge mode".format(key)) |
| 1917 |
elif key not in match_att: |
| 1918 |
self[key] = new_block[key] |
| 1919 |
|
| 1920 |
|
| 1921 |
for one_loop in new_block.loops.values(): |
| 1922 |
self.CreateLoop(one_loop) |
| 1923 |
|
| 1924 |
self.true_case.update(new_block.true_case) |
| 1925 |
elif mode == 'replace': |
| 1926 |
newkeys = list(new_block.keys()) |
| 1927 |
for ma in match_att: |
| 1928 |
try: |
| 1929 |
newkeys.remove(ma) |
| 1930 |
except ValueError: |
| 1931 |
pass |
| 1932 |
for key in new_block.keys(): |
| 1933 |
if isinstance(key,unicode): |
| 1934 |
self[key] = new_block[key] |
| 1935 |
|
| 1936 |
for one_loop in new_block.loops.values(): |
| 1937 |
self.CreateLoop(one_loop) |
| 1938 |
|
| 1939 |
self.true_case.update(new_block.true_case) |
| 1940 |
elif mode == 'overlay': |
| 1941 |
print('Overlay mode, current overwrite is {}'.format(self.overwrite)) |
| 1942 |
raise StarError('Overlay block merge mode not implemented') |
| 1943 |
save_overwrite = self.overwrite |
| 1944 |
self.overwrite = True |
| 1945 |
for attribute in new_block.keys(): |
| 1946 |
if attribute in match_att: continue |
| 1947 |
new_value = new_block[attribute] |
| 1948 |
|
| 1949 |
if new_block.FindLoop(attribute)<0: |
| 1950 |
self[attribute] = new_value |
| 1951 |
my_loops = self.loops.values() |
| 1952 |
perfect_overlaps = [a for a in new_block.loops if a in my_loops] |
| 1953 |
for po in perfect_overlaps: |
| 1954 |
loop_keys = [a for a in po if a in rel_keys] |
| 1955 |
try: |
| 1956 |
newkeypos = map(lambda a:newkeys.index(a),loop_keys) |
| 1957 |
newkeypos = newkeypos[0] |
| 1958 |
loop_keys = loop_keys[0] |
| 1959 |
except (ValueError,IndexError): |
| 1960 |
newkeypos = [] |
| 1961 |
overlap_data = map(lambda a:listify(self[a]),overlaps) |
| 1962 |
new_data = map(lambda a:new_block[a],overlaps) |
| 1963 |
packet_data = transpose(overlap_data) |
| 1964 |
new_p_data = transpose(new_data) |
| 1965 |
|
| 1966 |
|
| 1967 |
if newkeypos: |
| 1968 |
|
| 1969 |
print("Old, new data:\n%s\n%s" % (repr(overlap_data[newkeypos]),repr(new_data[newkeypos]))) |
| 1970 |
key_matches = filter(lambda a:a in overlap_data[newkeypos],new_data[newkeypos]) |
| 1971 |
|
| 1972 |
new_p_data = filter(lambda a:a[newkeypos] not in key_matches,new_p_data) |
| 1973 |
if new_p_data: |
| 1974 |
new_data = transpose(new_p_data) |
| 1975 |
else: new_data = [] |
| 1976 |
|
| 1977 |
byebyeloop = self.GetLoop(overlaps[0]) |
| 1978 |
|
| 1979 |
|
| 1980 |
|
| 1981 |
|
| 1982 |
if byebyeloop != self: |
| 1983 |
self.remove_loop(byebyeloop) |
| 1984 |
self.AddLoopItem((overlaps,overlap_data)) |
| 1985 |
for pd in new_p_data: |
| 1986 |
if pd not in packet_data: |
| 1987 |
for i in range(len(overlaps)): |
| 1988 |
|
| 1989 |
|
| 1990 |
self[overlaps[i]].append(pd[i]) |
| 1991 |
self.overwrite = save_overwrite |
| 1992 |
|
| 1993 |
|
| 1994 |
|
| 1995 |
|
| 1996 |
|
| 1997 |
|
| 1998 |
|
| 1999 |
|
| 2000 |
|
| 2001 |
|
| 2002 |
|
| 2003 |
|
| 2004 |
|
| 2005 |
|
| 2006 |
|
| 2007 |
|
| 2008 |
|
| 2009 |
|
| 2010 |
|
| 2011 |
|
| 2012 |
|
| 2013 |
|
| 2014 |
|
| 2015 |
def assign_dictionary(self,dic): |
| 2016 |
if not dic.diclang=="DDLm": |
| 2017 |
print("Warning: ignoring dictionary {}".format(dic.my_uri)) |
| 2018 |
return |
| 2019 |
self.dictionary = dic |
| 2020 |
|
| 2021 |
def unassign_dictionary(self): |
| 2022 |
"""Remove dictionary-dependent behaviour""" |
| 2023 |
self.dictionary = None |
| 2024 |
|
| 2025 |
|
| 2026 |
|
| 2027 |
|
| 2028 |
|
| 2029 |
|
| 2030 |
|
| 2031 |
|
| 2032 |
|
| 2033 |
|
| 2034 |
|
| 2035 |
|
| 2036 |
|
| 2037 |
|
| 2038 |
|
| 2039 |
|
| 2040 |
class StarPacket(list): |
| 2041 |
def merge_packet(self,incoming): |
| 2042 |
"""Merge contents of incoming packet with this packet""" |
| 2043 |
new_attrs = [a for a in dir(incoming) if a[0] == '_' and a[1] != "_"] |
| 2044 |
self.extend(incoming) |
| 2045 |
for na in new_attrs: |
| 2046 |
setattr(self,na,getattr(incoming,na)) |
| 2047 |
|
| 2048 |
def __getattr__(self,att_name): |
| 2049 |
"""Derive a missing attribute""" |
| 2050 |
if att_name.lower() in self.__dict__: |
| 2051 |
return getattr(self,att_name.lower()) |
| 2052 |
if att_name in ('cif_dictionary','fulldata','key'): |
| 2053 |
raise AttributeError('Programming error: can only assign value of {}'.format(att_name)) |
| 2054 |
d = self.cif_dictionary |
| 2055 |
c = self.fulldata |
| 2056 |
k = self.key |
| 2057 |
assert isinstance(k,list) |
| 2058 |
d.derive_item(att_name,c,store_value=True) |
| 2059 |
|
| 2060 |
|
| 2061 |
|
| 2062 |
keydict = dict([(v,(getattr(self,v),True)) for v in k]) |
| 2063 |
full_pack = c.GetCompoundKeyedPacket(keydict) |
| 2064 |
return getattr(full_pack,att_name) |
| 2065 |
|
| 2066 |
|
| 2067 |
|
| 2068 |
|
| 2069 |
|
| 2070 |
|
| 2071 |
|
| 2072 |
|
| 2073 |
|
| 2074 |
|
| 2075 |
|
| 2076 |
class BlockCollection(object): |
| 2077 |
"""A container for StarBlock objects. The constructor takes |
| 2078 |
one non-keyword argument `datasource` to set the initial data. If |
| 2079 |
`datasource` is a Python dictionary, the values must be `StarBlock` |
| 2080 |
objects and the keys will be blocknames in the new object. Keyword |
| 2081 |
arguments: |
| 2082 |
|
| 2083 |
standard: |
| 2084 |
`CIF` or `Dic`. `CIF` enforces 75-character blocknames, and will |
| 2085 |
print block contents before that block's save frame. |
| 2086 |
|
| 2087 |
blocktype: |
| 2088 |
The type of blocks held in this container. Normally `StarBlock` |
| 2089 |
or `CifBlock`. |
| 2090 |
|
| 2091 |
characterset: |
| 2092 |
`ascii` or `unicode`. Blocknames and datanames appearing within |
| 2093 |
blocks are restricted to the appropriate characterset. Note that |
| 2094 |
only characters in the basic multilingual plane are accepted. This |
| 2095 |
restriction will be lifted when PyCIFRW is ported to Python3. |
| 2096 |
|
| 2097 |
scoping: |
| 2098 |
`instance` or `dictionary`: `instance` implies that save frames are |
| 2099 |
hidden from save frames lower in the hierarchy or in sibling |
| 2100 |
hierarchies. `dictionary` makes all save frames visible everywhere |
| 2101 |
within a data block. This setting is only relevant for STAR2 dictionaries and |
| 2102 |
STAR2 data files, as save frames are currently not used in plain CIF data |
| 2103 |
files. |
| 2104 |
|
| 2105 |
""" |
| 2106 |
|
| 2107 |
|
| 2108 |
|
| 2109 |
|
| 2110 |
|
| 2111 |
|
| 2112 |
|
| 2113 |
|
| 2114 |
|
| 2115 |
|
| 2116 |
|
| 2117 |
|
| 2118 |
|
| 2119 |
|
| 2120 |
|
| 2121 |
|
| 2122 |
|
| 2123 |
|
| 2124 |
|
| 2125 |
|
| 2126 |
|
| 2127 |
|
| 2128 |
|
| 2129 |
|
| 2130 |
|
| 2131 |
|
| 2132 |
|
| 2133 |
|
| 2134 |
|
| 2135 |
|
| 2136 |
|
| 2137 |
def __init__(self,datasource=None,standard='CIF',blocktype = StarBlock, |
| 2138 |
characterset='ascii',scoping='instance',**kwargs): |
| 2139 |
import collections |
| 2140 |
self.dictionary = {} |
| 2141 |
self.standard = standard |
| 2142 |
self.lower_keys = set() |
| 2143 |
self.renamed = {} |
| 2144 |
self.PC = collections.namedtuple('PC',['block_id','parent']) |
| 2145 |
self.child_table = {} |
| 2146 |
self.visible_keys = [] |
| 2147 |
self.block_input_order = [] |
| 2148 |
self.scoping = scoping |
| 2149 |
self.blocktype = blocktype |
| 2150 |
self.master_template = {} |
| 2151 |
self.set_grammar('2.0') |
| 2152 |
self.set_characterset(characterset) |
| 2153 |
if isinstance(datasource,BlockCollection): |
| 2154 |
self.merge_fast(datasource) |
| 2155 |
self.scoping = scoping |
| 2156 |
elif isinstance(datasource,dict): |
| 2157 |
for key,value in datasource.items(): |
| 2158 |
self[key]= value |
| 2159 |
self.header_comment = '' |
| 2160 |
|
| 2161 |
def set_grammar(self,new_grammar): |
| 2162 |
"""Set the syntax and grammar for output to `new_grammar`""" |
| 2163 |
if new_grammar not in ['1.1','1.0','2.0','STAR2']: |
| 2164 |
raise StarError('Unrecognised output grammar {}'.format(new_grammar)) |
| 2165 |
self.grammar = new_grammar |
| 2166 |
|
| 2167 |
def set_characterset(self,characterset): |
| 2168 |
"""Set the allowed characters for datanames and datablocks: may be `ascii` or `unicode`. If datanames |
| 2169 |
have already been added to any datablocks, they are not checked.""" |
| 2170 |
self.characterset = characterset |
| 2171 |
for one_block in self.lower_keys: |
| 2172 |
self[one_block].set_characterset(characterset) |
| 2173 |
|
| 2174 |
|
| 2175 |
|
| 2176 |
|
| 2177 |
|
| 2178 |
|
| 2179 |
def unlock(self): |
| 2180 |
"""Allow overwriting of all blocks in this collection""" |
| 2181 |
for a in self.lower_keys: |
| 2182 |
self[a].overwrite=True |
| 2183 |
|
| 2184 |
def lock(self): |
| 2185 |
"""Disallow overwriting for all blocks in this collection""" |
| 2186 |
for a in self.lower_keys: |
| 2187 |
self[a].overwrite = False |
| 2188 |
|
| 2189 |
|
| 2190 |
|
| 2191 |
|
| 2192 |
|
| 2193 |
|
| 2194 |
def __str__(self): |
| 2195 |
return self.WriteOut() |
| 2196 |
|
| 2197 |
def __setitem__(self,key,value): |
| 2198 |
self.NewBlock(key,value,parent=None) |
| 2199 |
|
| 2200 |
def __getitem__(self,key): |
| 2201 |
if isinstance(key,(unicode,str)): |
| 2202 |
lowerkey = key.lower() |
| 2203 |
if lowerkey in self.lower_keys: |
| 2204 |
return self.dictionary[lowerkey] |
| 2205 |
|
| 2206 |
|
| 2207 |
|
| 2208 |
raise KeyError('No such item {}'.format(key)) |
| 2209 |
|
| 2210 |
|
| 2211 |
|
| 2212 |
|
| 2213 |
|
| 2214 |
def __delitem__(self,key): |
| 2215 |
dummy = self[key] |
| 2216 |
lowerkey = key.lower() |
| 2217 |
|
| 2218 |
children = [a[0] for a in self.child_table.items() if a[1].parent == lowerkey] |
| 2219 |
for child in children: |
| 2220 |
del self[child] |
| 2221 |
del self.dictionary[lowerkey] |
| 2222 |
del self.child_table[lowerkey] |
| 2223 |
try: |
| 2224 |
self.visible_keys.remove(lowerkey) |
| 2225 |
except KeyError: |
| 2226 |
pass |
| 2227 |
self.lower_keys.remove(lowerkey) |
| 2228 |
self.block_input_order.remove(lowerkey) |
| 2229 |
|
| 2230 |
def __len__(self): |
| 2231 |
return len(self.visible_keys) |
| 2232 |
|
| 2233 |
def __contains__(self,item): |
| 2234 |
"""Support the 'in' operator""" |
| 2235 |
if not isinstance(item,(unicode,str)): return False |
| 2236 |
if item.lower() in self.visible_keys: |
| 2237 |
return True |
| 2238 |
return False |
| 2239 |
|
| 2240 |
|
| 2241 |
def __iter__(self): |
| 2242 |
for one_block in self.keys(): |
| 2243 |
yield self[one_block] |
| 2244 |
|
| 2245 |
|
| 2246 |
def keys(self): |
| 2247 |
return self.visible_keys |
| 2248 |
|
| 2249 |
|
| 2250 |
def has_key(self,key): |
| 2251 |
return key in self |
| 2252 |
|
| 2253 |
def get(self,key,default=None): |
| 2254 |
if key in self: |
| 2255 |
return self.__getitem__(key) |
| 2256 |
else: |
| 2257 |
return default |
| 2258 |
|
| 2259 |
def clear(self): |
| 2260 |
self.dictionary.clear() |
| 2261 |
self.lower_keys = set() |
| 2262 |
self.child_table = {} |
| 2263 |
self.visible_keys = [] |
| 2264 |
self.block_input_order = [] |
| 2265 |
|
| 2266 |
def copy(self): |
| 2267 |
newcopy = self.dictionary.copy() |
| 2268 |
for k,v in self.dictionary.items(): |
| 2269 |
newcopy[k] = v.copy() |
| 2270 |
newcopy = BlockCollection(newcopy) |
| 2271 |
newcopy.child_table = self.child_table.copy() |
| 2272 |
newcopy.lower_keys = self.lower_keys.copy() |
| 2273 |
newcopy.block_input_order = self.block_input_order.copy() |
| 2274 |
newcopy.characterset = self.characterset |
| 2275 |
newcopy.SetTemplate(self.master_template.copy()) |
| 2276 |
newcopy.scoping = self.scoping |
| 2277 |
return newcopy |
| 2278 |
|
| 2279 |
def update(self,adict): |
| 2280 |
for key in adict.keys(): |
| 2281 |
self[key] = adict[key] |
| 2282 |
|
| 2283 |
def items(self): |
| 2284 |
return [(a,self[a]) for a in self.keys()] |
| 2285 |
|
| 2286 |
def first_block(self): |
| 2287 |
"""Return the 'first' block. This is not necessarily the first block in the file.""" |
| 2288 |
if self.keys(): |
| 2289 |
return self[self.keys()[0]] |
| 2290 |
|
| 2291 |
|
| 2292 |
|
| 2293 |
|
| 2294 |
|
| 2295 |
|
| 2296 |
|
| 2297 |
|
| 2298 |
|
| 2299 |
|
| 2300 |
|
| 2301 |
|
| 2302 |
|
| 2303 |
|
| 2304 |
|
| 2305 |
|
| 2306 |
|
| 2307 |
|
| 2308 |
|
| 2309 |
|
| 2310 |
|
| 2311 |
|
| 2312 |
|
| 2313 |
|
| 2314 |
|
| 2315 |
|
| 2316 |
|
| 2317 |
|
| 2318 |
|
| 2319 |
|
| 2320 |
|
| 2321 |
|
| 2322 |
|
| 2323 |
def NewBlock(self,blockname,blockcontents=None,fix=True,parent=None): |
| 2324 |
"""Add a new block named `blockname` with contents `blockcontents`. If `fix` |
| 2325 |
is True, `blockname` will have spaces and tabs replaced by underscores. `parent` |
| 2326 |
allows a parent block to be set so that block hierarchies can be created. Depending on |
| 2327 |
the output standard, these blocks will be printed out as nested save frames or |
| 2328 |
ignored.""" |
| 2329 |
if blockcontents is None: |
| 2330 |
blockcontents = self.blocktype() |
| 2331 |
if self.standard == "CIF": |
| 2332 |
blockcontents.setmaxnamelength(75) |
| 2333 |
if len(blockname)>75: |
| 2334 |
raise StarError('Blockname {} is longer than 75 characters'.format(blockname)) |
| 2335 |
if fix: |
| 2336 |
newblockname = re.sub('[ \t]','_',blockname) |
| 2337 |
else: newblockname = blockname |
| 2338 |
new_lowerbn = newblockname.lower() |
| 2339 |
if new_lowerbn in self.lower_keys: |
| 2340 |
if self.standard is not None: |
| 2341 |
toplevelnames = [a[0] for a in self.child_table.items() if a[1].parent==None] |
| 2342 |
if parent is None and new_lowerbn not in toplevelnames: |
| 2343 |
while new_lowerbn in self.lower_keys: new_lowerbn = new_lowerbn + '+' |
| 2344 |
elif parent is not None and new_lowerbn in toplevelnames: |
| 2345 |
replace_name = new_lowerbn |
| 2346 |
while replace_name in self.lower_keys: replace_name = replace_name + '+' |
| 2347 |
self._rekey(new_lowerbn,replace_name) |
| 2348 |
|
| 2349 |
if parent.lower() == new_lowerbn: |
| 2350 |
parent = replace_name |
| 2351 |
else: |
| 2352 |
raise StarError( "Attempt to replace existing block " + blockname) |
| 2353 |
else: |
| 2354 |
del self[new_lowerbn] |
| 2355 |
self.dictionary.update({new_lowerbn:blockcontents}) |
| 2356 |
self.lower_keys.add(new_lowerbn) |
| 2357 |
self.block_input_order.append(new_lowerbn) |
| 2358 |
if parent is None: |
| 2359 |
self.child_table[new_lowerbn]=self.PC(newblockname,None) |
| 2360 |
self.visible_keys.append(new_lowerbn) |
| 2361 |
else: |
| 2362 |
if parent.lower() in self.lower_keys: |
| 2363 |
if self.scoping == 'instance': |
| 2364 |
self.child_table[new_lowerbn]=self.PC(newblockname,parent.lower()) |
| 2365 |
else: |
| 2366 |
self.child_table[new_lowerbn]=self.PC(newblockname,parent.lower()) |
| 2367 |
self.visible_keys.append(new_lowerbn) |
| 2368 |
else: |
| 2369 |
print('Warning:Parent block {} does not exist for child {}'.format(parent,newblockname)) |
| 2370 |
self[new_lowerbn].set_grammar(self.grammar) |
| 2371 |
self[new_lowerbn].set_characterset(self.characterset) |
| 2372 |
self[new_lowerbn].formatting_hints = self.master_template |
| 2373 |
return new_lowerbn |
| 2374 |
|
| 2375 |
|
| 2376 |
|
| 2377 |
|
| 2378 |
|
| 2379 |
|
| 2380 |
|
| 2381 |
|
| 2382 |
|
| 2383 |
|
| 2384 |
def _rekey(self,oldname,newname,block_id=''): |
| 2385 |
"""The block with key [[oldname]] gets [[newname]] as a new key, but the printed name |
| 2386 |
does not change unless [[block_id]] is given. Prefer [[rename]] for a safe version.""" |
| 2387 |
move_block = self[oldname] |
| 2388 |
is_visible = oldname in self.visible_keys |
| 2389 |
move_block_info = self.child_table[oldname] |
| 2390 |
move_block_children = [a for a in self.child_table.items() if a[1].parent==oldname] |
| 2391 |
|
| 2392 |
self.child_table.update(dict([(a[0],self.PC(a[1].block_id,newname)) for a in move_block_children])) |
| 2393 |
oldpos = self.block_input_order.index(oldname) |
| 2394 |
del self[oldname] |
| 2395 |
self.dictionary.update({newname:move_block}) |
| 2396 |
self.lower_keys.add(newname) |
| 2397 |
|
| 2398 |
self.block_input_order[oldpos:oldpos]=[newname] |
| 2399 |
if block_id == '': |
| 2400 |
self.child_table.update({newname:move_block_info}) |
| 2401 |
else: |
| 2402 |
self.child_table.update({newname:self.PC(block_id,move_block_info.parent)}) |
| 2403 |
if is_visible: self.visible_keys += [newname] |
| 2404 |
|
| 2405 |
def rename(self,oldname,newname): |
| 2406 |
"""Rename datablock from [[oldname]] to [[newname]]. Both key and printed name are changed. No |
| 2407 |
conformance checks are conducted.""" |
| 2408 |
realoldname = oldname.lower() |
| 2409 |
realnewname = newname.lower() |
| 2410 |
if realnewname in self.lower_keys: |
| 2411 |
raise StarError('Cannot change blockname {} to {} as {} already present'.format((oldname,newname,newname))) |
| 2412 |
if realoldname not in self.lower_keys: |
| 2413 |
raise KeyError('Cannot find old block {}'.format(realoldname)) |
| 2414 |
self._rekey(realoldname,realnewname,block_id=newname) |
| 2415 |
|
| 2416 |
|
| 2417 |
|
| 2418 |
|
| 2419 |
|
| 2420 |
|
| 2421 |
|
| 2422 |
|
| 2423 |
|
| 2424 |
def makebc(self,namelist,scoping='dictionary'): |
| 2425 |
"""Make a block collection from a list of block names""" |
| 2426 |
newbc = BlockCollection() |
| 2427 |
block_lower = [n.lower() for n in namelist] |
| 2428 |
proto_child_table = [a for a in self.child_table.items() if a[0] in block_lower] |
| 2429 |
newbc.child_table = dict(proto_child_table) |
| 2430 |
new_top_level = [(a[0],self.PC(a[1].block_id,None)) for a in newbc.child_table.items() if a[1].parent not in block_lower] |
| 2431 |
newbc.child_table.update(dict(new_top_level)) |
| 2432 |
newbc.lower_keys = set([a[0] for a in proto_child_table]) |
| 2433 |
newbc.dictionary = dict((a[0],self.dictionary[a[0]]) for a in proto_child_table) |
| 2434 |
newbc.scoping = scoping |
| 2435 |
newbc.block_input_order = block_lower |
| 2436 |
return newbc |
| 2437 |
|
| 2438 |
|
| 2439 |
|
| 2440 |
|
| 2441 |
|
| 2442 |
|
| 2443 |
|
| 2444 |
|
| 2445 |
|
| 2446 |
|
| 2447 |
|
| 2448 |
|
| 2449 |
|
| 2450 |
|
| 2451 |
|
| 2452 |
|
| 2453 |
|
| 2454 |
|
| 2455 |
|
| 2456 |
|
| 2457 |
|
| 2458 |
|
| 2459 |
|
| 2460 |
|
| 2461 |
|
| 2462 |
|
| 2463 |
|
| 2464 |
|
| 2465 |
|
| 2466 |
|
| 2467 |
|
| 2468 |
|
| 2469 |
|
| 2470 |
|
| 2471 |
|
| 2472 |
|
| 2473 |
|
| 2474 |
|
| 2475 |
|
| 2476 |
|
| 2477 |
|
| 2478 |
|
| 2479 |
|
| 2480 |
|
| 2481 |
|
| 2482 |
|
| 2483 |
|
| 2484 |
|
| 2485 |
|
| 2486 |
|
| 2487 |
|
| 2488 |
|
| 2489 |
|
| 2490 |
|
| 2491 |
|
| 2492 |
|
| 2493 |
|
| 2494 |
|
| 2495 |
|
| 2496 |
|
| 2497 |
|
| 2498 |
|
| 2499 |
|
| 2500 |
|
| 2501 |
|
| 2502 |
|
| 2503 |
|
| 2504 |
|
| 2505 |
|
| 2506 |
|
| 2507 |
|
| 2508 |
def merge_fast(self,new_bc,parent=None): |
| 2509 |
"""Do a fast merge. WARNING: this may change one or more of its frame headers in order to |
| 2510 |
remove duplicate frames. Please keep a handle to the block object instead of the text of |
| 2511 |
the header.""" |
| 2512 |
if self.standard is None: |
| 2513 |
mode = 'replace' |
| 2514 |
else: |
| 2515 |
mode = 'strict' |
| 2516 |
overlap_flag = not self.lower_keys.isdisjoint(new_bc.lower_keys) |
| 2517 |
if parent is not None: |
| 2518 |
parent_name = [a[0] for a in self.dictionary.items() if a[1] == parent] |
| 2519 |
if len(parent_name)==0 or len(parent_name)>1: |
| 2520 |
raise StarError("Unable to find unique parent block name: have {}".format(str(parent_name))) |
| 2521 |
parent_name = parent_name[0] |
| 2522 |
else: |
| 2523 |
parent_name = None |
| 2524 |
if overlap_flag and mode != 'replace': |
| 2525 |
double_keys = self.lower_keys.intersection(new_bc.lower_keys) |
| 2526 |
for dup_key in double_keys: |
| 2527 |
our_parent = self.child_table[dup_key].parent |
| 2528 |
their_parent = new_bc.child_table[dup_key].parent |
| 2529 |
if (our_parent is None and their_parent is not None and parent is None) or\ |
| 2530 |
parent is not None: |
| 2531 |
start_key = dup_key |
| 2532 |
while start_key in self.lower_keys: start_key = start_key+'+' |
| 2533 |
self._rekey(dup_key,start_key) |
| 2534 |
if parent_name.lower() == dup_key: |
| 2535 |
parent_name = start_key |
| 2536 |
elif our_parent is not None and their_parent is None and parent is None: |
| 2537 |
start_key = dup_key |
| 2538 |
while start_key in new_bc.lower_keys: start_key = start_key+'+' |
| 2539 |
new_bc._rekey(dup_key,start_key) |
| 2540 |
else: |
| 2541 |
raise StarError("The following key is duplicated: {}".format(dup_key)) |
| 2542 |
self.dictionary.update(new_bc.dictionary) |
| 2543 |
self.lower_keys.update(new_bc.lower_keys) |
| 2544 |
self.visible_keys += (list(new_bc.lower_keys)) |
| 2545 |
self.block_input_order += new_bc.block_input_order |
| 2546 |
|
| 2547 |
self.child_table.update(new_bc.child_table) |
| 2548 |
if parent_name is not None: |
| 2549 |
reparent_list = [(a[0],a[1].block_id) for a in new_bc.child_table.items() if a[1].parent==None] |
| 2550 |
reparent_dict = [(a[0],self.PC(a[1],parent_name.lower())) for a in reparent_list] |
| 2551 |
self.child_table.update(dict(reparent_dict)) |
| 2552 |
|
| 2553 |
def merge(self,new_bc,mode=None,parent=None,single_block=[], |
| 2554 |
idblock="",match_att=[],match_function=None): |
| 2555 |
if mode is None: |
| 2556 |
if self.standard is None: |
| 2557 |
mode = 'replace' |
| 2558 |
else: |
| 2559 |
mode = 'strict' |
| 2560 |
if single_block: |
| 2561 |
self[single_block[0]].merge(new_bc[single_block[1]],mode, |
| 2562 |
match_att=match_att, |
| 2563 |
match_function=match_function) |
| 2564 |
return None |
| 2565 |
base_keys = [a[1].block_id for a in self.child_table.items()] |
| 2566 |
block_to_item = base_keys |
| 2567 |
new_keys = [a[1].block_id for a in new_bc.child_table.items()] |
| 2568 |
if match_att: |
| 2569 |
|
| 2570 |
if match_function: |
| 2571 |
block_to_item = [match_function(self[a]) for a in self.keys()] |
| 2572 |
else: |
| 2573 |
block_to_item = [self[a].get(match_att[0],None) for a in self.keys()] |
| 2574 |
|
| 2575 |
for key in new_keys: |
| 2576 |
if key == idblock: continue |
| 2577 |
basekey = key |
| 2578 |
if len(match_att)>0: |
| 2579 |
attval = new_bc[key].get(match_att[0],0) |
| 2580 |
else: |
| 2581 |
attval = 0 |
| 2582 |
for ii in range(len(block_to_item)): |
| 2583 |
thisatt = block_to_item[ii] |
| 2584 |
|
| 2585 |
if attval == thisatt or \ |
| 2586 |
(isinstance(thisatt,list) and attval in thisatt): |
| 2587 |
basekey = base_keys.pop(ii) |
| 2588 |
block_to_item.remove(thisatt) |
| 2589 |
break |
| 2590 |
if not basekey in self or mode=="replace": |
| 2591 |
new_parent = new_bc.get_parent(key) |
| 2592 |
if parent is not None and new_parent is None: |
| 2593 |
new_parent = parent |
| 2594 |
self.NewBlock(basekey,new_bc[key],parent=new_parent) |
| 2595 |
else: |
| 2596 |
if mode=="strict": |
| 2597 |
raise StarError( "In strict merge mode: block {} in old and block {} in new files".format(basekey,key)) |
| 2598 |
elif mode=="overlay": |
| 2599 |
|
| 2600 |
self[basekey].merge(new_bc[key],mode,match_att=match_att) |
| 2601 |
else: |
| 2602 |
raise StarError( "Merge called with unknown mode {}".format(mode)) |
| 2603 |
|
| 2604 |
|
| 2605 |
|
| 2606 |
|
| 2607 |
|
| 2608 |
|
| 2609 |
|
| 2610 |
|
| 2611 |
|
| 2612 |
def checknamelengths(self,target_block,maxlength=-1): |
| 2613 |
if maxlength < 0: |
| 2614 |
return |
| 2615 |
else: |
| 2616 |
toolong = [a for a in target_block.keys() if len(a)>maxlength] |
| 2617 |
outstring = "" |
| 2618 |
if toolong: |
| 2619 |
outstring = "\n".join(toolong) |
| 2620 |
raise StarError( 'Following data names too long:' + outstring) |
| 2621 |
|
| 2622 |
|
| 2623 |
|
| 2624 |
|
| 2625 |
|
| 2626 |
|
| 2627 |
|
| 2628 |
|
| 2629 |
|
| 2630 |
|
| 2631 |
|
| 2632 |
|
| 2633 |
|
| 2634 |
|
| 2635 |
|
| 2636 |
def get_all(self,item_name): |
| 2637 |
raw_values = [self[a].get(item_name) for a in self.keys()] |
| 2638 |
raw_values = [a for a in raw_values if a != None] |
| 2639 |
ret_vals = [] |
| 2640 |
for rv in raw_values: |
| 2641 |
if isinstance(rv,list): |
| 2642 |
for rvv in rv: |
| 2643 |
if rvv not in ret_vals: ret_vals.append(rvv) |
| 2644 |
else: |
| 2645 |
if rv not in ret_vals: ret_vals.append(rv) |
| 2646 |
return ret_vals |
| 2647 |
|
| 2648 |
|
| 2649 |
|
| 2650 |
|
| 2651 |
|
| 2652 |
|
| 2653 |
|
| 2654 |
|
| 2655 |
|
| 2656 |
def __setattr__(self,attr_name,newval): |
| 2657 |
if attr_name == 'scoping': |
| 2658 |
if newval not in ('dictionary','instance'): |
| 2659 |
raise StarError("Star file may only have 'dictionary' or 'instance' scoping, not {}".format(newval)) |
| 2660 |
if newval == 'dictionary': |
| 2661 |
self.visible_keys = [a for a in self.lower_keys] |
| 2662 |
else: |
| 2663 |
|
| 2664 |
self.visible_keys = [a[0] for a in self.child_table.items() if a[1].parent==None] |
| 2665 |
object.__setattr__(self,attr_name,newval) |
| 2666 |
|
| 2667 |
|
| 2668 |
|
| 2669 |
|
| 2670 |
|
| 2671 |
|
| 2672 |
def get_parent(self,blockname): |
| 2673 |
"""Return the name of the block enclosing [[blockname]] in canonical form (lower case)""" |
| 2674 |
possibles = (a for a in self.child_table.items() if a[0] == blockname.lower()) |
| 2675 |
try: |
| 2676 |
first = next(possibles) |
| 2677 |
except: |
| 2678 |
raise StarError('no parent for {}'.format(blockname)) |
| 2679 |
try: |
| 2680 |
second = next(possibles) |
| 2681 |
except StopIteration: |
| 2682 |
return first[1].parent |
| 2683 |
raise StarError('More than one parent for {}'.format(blockname)) |
| 2684 |
|
| 2685 |
def get_roots(self): |
| 2686 |
"""Get the top-level blocks""" |
| 2687 |
return [a for a in self.child_table.items() if a[1].parent==None] |
| 2688 |
|
| 2689 |
def get_children(self,blockname,include_parent=False,scoping='dictionary'): |
| 2690 |
"""Get all children of [[blockname]] as a block collection. If [[include_parent]] is |
| 2691 |
True, the parent block will also be included in the block collection as the root.""" |
| 2692 |
newbc = BlockCollection() |
| 2693 |
block_lower = blockname.lower() |
| 2694 |
proto_child_table = [a for a in self.child_table.items() if self.is_child_of_parent(block_lower,a[1].block_id)] |
| 2695 |
newbc.child_table = dict(proto_child_table) |
| 2696 |
if not include_parent: |
| 2697 |
newbc.child_table.update(dict([(a[0],self.PC(a[1].block_id,None)) for a in proto_child_table if a[1].parent == block_lower])) |
| 2698 |
newbc.lower_keys = set([a[0] for a in proto_child_table]) |
| 2699 |
newbc.dictionary = dict((a[0],self.dictionary[a[0]]) for a in proto_child_table) |
| 2700 |
if include_parent: |
| 2701 |
newbc.child_table.update({block_lower:self.PC(self.child_table[block_lower].block_id,None)}) |
| 2702 |
newbc.lower_keys.add(block_lower) |
| 2703 |
newbc.dictionary.update({block_lower:self.dictionary[block_lower]}) |
| 2704 |
newbc.scoping = scoping |
| 2705 |
return newbc |
| 2706 |
|
| 2707 |
def get_immediate_children(self,parentname): |
| 2708 |
"""Get the next level of children of the given block as a list, without nested levels""" |
| 2709 |
child_handles = [a for a in self.child_table.items() if a[1].parent == parentname.lower()] |
| 2710 |
return child_handles |
| 2711 |
|
| 2712 |
|
| 2713 |
def get_child_list(self,parentname): |
| 2714 |
"""Get a list of all child categories in alphabetical order""" |
| 2715 |
child_handles = [a[0] for a in self.child_table.items() if self.is_child_of_parent(parentname.lower(),a[0])] |
| 2716 |
child_handles.sort() |
| 2717 |
return child_handles |
| 2718 |
|
| 2719 |
def is_child_of_parent(self,parentname,blockname): |
| 2720 |
"""Return `True` if `blockname` is a child of `parentname`""" |
| 2721 |
checkname = parentname.lower() |
| 2722 |
more_children = [a[0] for a in self.child_table.items() if a[1].parent == checkname] |
| 2723 |
if blockname.lower() in more_children: |
| 2724 |
return True |
| 2725 |
else: |
| 2726 |
for one_child in more_children: |
| 2727 |
if self.is_child_of_parent(one_child,blockname): return True |
| 2728 |
return False |
| 2729 |
|
| 2730 |
def set_parent(self,parentname,childname): |
| 2731 |
"""Set the parent block""" |
| 2732 |
|
| 2733 |
if parentname.lower() not in self.lower_keys: |
| 2734 |
raise KeyError('Parent block {} does not exist'.format(parentname)) |
| 2735 |
if childname.lower() not in self.lower_keys: |
| 2736 |
raise KeyError('Child block {} does not exist'.format(childname)) |
| 2737 |
old_entry = self.child_table[childname.lower()] |
| 2738 |
self.child_table[childname.lower()]=self.PC(old_entry.block_id, |
| 2739 |
parentname.lower()) |
| 2740 |
self.scoping = self.scoping |
| 2741 |
|
| 2742 |
|
| 2743 |
|
| 2744 |
|
| 2745 |
|
| 2746 |
|
| 2747 |
|
| 2748 |
def SetTemplate(self,template_file): |
| 2749 |
"""Use `template_file` as a template for all block output""" |
| 2750 |
self.master_template = process_template(template_file) |
| 2751 |
for b in self.dictionary.values(): |
| 2752 |
b.formatting_hints = self.master_template |
| 2753 |
|
| 2754 |
|
| 2755 |
|
| 2756 |
|
| 2757 |
|
| 2758 |
|
| 2759 |
|
| 2760 |
|
| 2761 |
|
| 2762 |
|
| 2763 |
|
| 2764 |
|
| 2765 |
|
| 2766 |
|
| 2767 |
|
| 2768 |
def WriteOut(self,comment='',wraplength=80,maxoutlength=0,blockorder=None,saves_after=None): |
| 2769 |
"""Return the contents of this file as a string, wrapping if possible at `wraplength` |
| 2770 |
characters and restricting maximum line length to `maxoutlength`. Delimiters and |
| 2771 |
save frame nesting are controlled by `self.grammar`. If `blockorder` is |
| 2772 |
provided, blocks are output in this order unless nested save frames have been |
| 2773 |
requested (STAR2). The default block order is the order in which blocks were input. |
| 2774 |
`saves_after` inserts all save frames after the given dataname, |
| 2775 |
which allows less important items to appear later. Useful in conjunction with a |
| 2776 |
template for dictionary files.""" |
| 2777 |
if maxoutlength != 0: |
| 2778 |
self.SetOutputLength(maxoutlength) |
| 2779 |
if not comment: |
| 2780 |
comment = self.header_comment |
| 2781 |
outstring = StringIO() |
| 2782 |
if self.grammar == "2.0" and comment[0:10] != r"#\#CIF_2.0": |
| 2783 |
outstring.write(r"#\#CIF_2.0" + "\n") |
| 2784 |
outstring.write(comment) |
| 2785 |
|
| 2786 |
for b in self.dictionary.values(): |
| 2787 |
b.set_grammar(self.grammar) |
| 2788 |
b.formatting_hints = self.master_template |
| 2789 |
b.SetOutputLength(wraplength,self.maxoutlength) |
| 2790 |
|
| 2791 |
|
| 2792 |
all_names = list(self.child_table.keys()) |
| 2793 |
if blockorder is None: |
| 2794 |
blockorder = self.block_input_order |
| 2795 |
top_block_names = [(a,self.child_table[a].block_id) for a in blockorder if self.child_table[a].parent is None] |
| 2796 |
for blockref,blockname in top_block_names: |
| 2797 |
data_str = 'data_' |
| 2798 |
if blockname.startswith('_'): |
| 2799 |
data_str = 'data' |
| 2800 |
outstring.write('\n' + data_str +blockname+'\n') |
| 2801 |
all_names.remove(blockref) |
| 2802 |
if self.standard == 'Dic': |
| 2803 |
outstring.write(self[blockref].printsection(finish_at='_dictionary_valid.application')) |
| 2804 |
if self.grammar == 'STAR2': |
| 2805 |
child_refs = self.get_immediate_children(blockref) |
| 2806 |
for child_ref,child_info in child_refs: |
| 2807 |
child_name = child_info.block_id |
| 2808 |
outstring.write('\n\n' + 'save_' + child_name + '\n') |
| 2809 |
self.block_to_string_nested(child_ref,child_name,outstring,4) |
| 2810 |
outstring.write('\n' + 'save_'+ '\n') |
| 2811 |
elif self.grammar in ('1.0','1.1','2.0'): |
| 2812 |
child_refs = [a for a in blockorder if self.is_child_of_parent(blockref,a)] |
| 2813 |
for child_ref in child_refs: |
| 2814 |
child_name = self.child_table[child_ref].block_id |
| 2815 |
outstring.write('\n\n' + 'save_' + child_name + '\n') |
| 2816 |
outstring.write(str(self[child_ref])) |
| 2817 |
outstring.write('\n\n' + 'save_' + '\n') |
| 2818 |
all_names.remove(child_ref.lower()) |
| 2819 |
else: |
| 2820 |
raise StarError('Grammar {} is not recognised for output'.format(self.grammar)) |
| 2821 |
if self.standard != 'Dic': |
| 2822 |
outstring.write(str(self[blockref])) |
| 2823 |
else: |
| 2824 |
outstring.write(self[blockref].printsection(start_from='_dictionary_valid.application')) |
| 2825 |
returnstring = outstring.getvalue() |
| 2826 |
outstring.close() |
| 2827 |
if len(all_names)>0: |
| 2828 |
print('WARNING: following blocks not output: {}'.format(repr(all_names))) |
| 2829 |
else: |
| 2830 |
print('All blocks output.') |
| 2831 |
return returnstring |
| 2832 |
|
| 2833 |
def block_to_string_nested(self,block_ref,block_id,outstring,indentlevel=0): |
| 2834 |
"""Output a complete datablock indexed by [[block_ref]] and named [[block_id]], including children, |
| 2835 |
and syntactically nesting save frames""" |
| 2836 |
child_refs = self.get_immediate_children(block_ref) |
| 2837 |
self[block_ref].set_grammar(self.grammar) |
| 2838 |
if self.standard == 'Dic': |
| 2839 |
outstring.write(str(self[block_ref])) |
| 2840 |
for child_ref,child_info in child_refs: |
| 2841 |
child_name = child_info.block_id |
| 2842 |
outstring.write('\n' + 'save_' + child_name + '\n') |
| 2843 |
self.block_to_string_nested(child_ref,child_name,outstring,indentlevel) |
| 2844 |
outstring.write('\n' + ' '*indentlevel + 'save_' + '\n') |
| 2845 |
if self.standard != 'Dic': |
| 2846 |
outstring.write(str(self[block_ref])) |
| 2847 |
|
| 2848 |
|
| 2849 |
|
| 2850 |
|
| 2851 |
|
| 2852 |
|
| 2853 |
|
| 2854 |
|
| 2855 |
|
| 2856 |
|
| 2857 |
|
| 2858 |
|
| 2859 |
|
| 2860 |
class StarFile(BlockCollection): |
| 2861 |
|
| 2862 |
|
| 2863 |
|
| 2864 |
|
| 2865 |
|
| 2866 |
|
| 2867 |
|
| 2868 |
|
| 2869 |
def __init__(self,datasource=None,maxinlength=-1,maxoutlength=0, |
| 2870 |
scoping='instance',grammar=None,from_str=False,scantype='standard', |
| 2871 |
permissive=False, **kwargs): |
| 2872 |
super(StarFile,self).__init__(datasource=datasource,**kwargs) |
| 2873 |
self.my_uri = getattr(datasource,'my_uri','') |
| 2874 |
if maxoutlength == 0: |
| 2875 |
self.maxoutlength = 2048 |
| 2876 |
else: |
| 2877 |
self.maxoutlength = maxoutlength |
| 2878 |
self.scoping = scoping |
| 2879 |
self.parsing_result = [] |
| 2880 |
if isinstance(datasource,(unicode,str)) or hasattr(datasource,"read"): |
| 2881 |
proto_star, result = ReadStarWithError(datasource,prepared=self,grammar=grammar,scantype=scantype, |
| 2882 |
maxlength = maxinlength,permissive=permissive, from_str=from_str) |
| 2883 |
self.parsing_result = result |
| 2884 |
|
| 2885 |
self.header_comment = \ |
| 2886 |
"""#\\#STAR |
| 2887 |
########################################################################## |
| 2888 |
# STAR Format file |
| 2889 |
# Produced by PySTARRW module |
| 2890 |
# |
| 2891 |
# This is a STAR file. STAR is a superset of the CIF file type. For |
| 2892 |
# more information, please refer to International Tables for Crystallography, |
| 2893 |
# Volume G, Chapter 2.1 |
| 2894 |
# |
| 2895 |
########################################################################## |
| 2896 |
""" |
| 2897 |
|
| 2898 |
|
| 2899 |
|
| 2900 |
|
| 2901 |
def set_uri(self,my_uri): self.my_uri = my_uri |
| 2902 |
|
| 2903 |
|
| 2904 |
|
| 2905 |
|
| 2906 |
|
| 2907 |
|
| 2908 |
|
| 2909 |
|
| 2910 |
|
| 2911 |
|
| 2912 |
|
| 2913 |
|
| 2914 |
|
| 2915 |
|
| 2916 |
|
| 2917 |
|
| 2918 |
|
| 2919 |
|
| 2920 |
|
| 2921 |
|
| 2922 |
|
| 2923 |
|
| 2924 |
|
| 2925 |
|
| 2926 |
|
| 2927 |
|
| 2928 |
|
| 2929 |
|
| 2930 |
class CIFStringIO(StringIO): |
| 2931 |
def __init__(self,target_width=80,**kwargs): |
| 2932 |
StringIO.__init__(self,**kwargs) |
| 2933 |
self.currentpos = 0 |
| 2934 |
self.target_width = target_width |
| 2935 |
self.tabwidth = -1 |
| 2936 |
self.indentlist = [0] |
| 2937 |
self.last_char = "" |
| 2938 |
|
| 2939 |
def write(self,outstring,canbreak=False,mustbreak=False,do_tab=True,newindent=False,unindent=False, |
| 2940 |
delimiter=False,startcol=-1): |
| 2941 |
"""Write a string with correct linebreak, tabs and indents""" |
| 2942 |
|
| 2943 |
if delimiter: |
| 2944 |
if len(outstring)>1: |
| 2945 |
raise ValueError('Delimiter {} is longer than one character'.format(repr( outstring ))) |
| 2946 |
output_delimiter = True |
| 2947 |
if mustbreak: |
| 2948 |
temp_string = '\n' + ' ' * self.indentlist[-1] |
| 2949 |
StringIO.write(self,temp_string) |
| 2950 |
self.currentpos = self.indentlist[-1] |
| 2951 |
self.last_char = temp_string[-1] |
| 2952 |
if self.currentpos+len(outstring)>self.target_width: |
| 2953 |
if not delimiter and outstring[0]!='\n': |
| 2954 |
if canbreak: |
| 2955 |
temp_string = '\n' + ' ' * self.indentlist[-1] |
| 2956 |
StringIO.write(self,temp_string) |
| 2957 |
self.currentpos = self.indentlist[-1] |
| 2958 |
self.last_char = temp_string[-1] |
| 2959 |
else: |
| 2960 |
output_delimiter = False |
| 2961 |
|
| 2962 |
if startcol > 0: |
| 2963 |
if self.currentpos < startcol: |
| 2964 |
StringIO.write(self,(startcol - self.currentpos)* ' ') |
| 2965 |
self.currentpos = startcol |
| 2966 |
self.last_char = ' ' |
| 2967 |
else: |
| 2968 |
print('Could not format {} at column {} as already at {}'.format(outstring,startcol,self.currentpos)) |
| 2969 |
startcol = -1 |
| 2970 |
|
| 2971 |
if self.tabwidth >0 and do_tab and startcol < 0: |
| 2972 |
next_stop = ((self.currentpos//self.tabwidth)+1)*self.tabwidth |
| 2973 |
|
| 2974 |
if self.currentpos < next_stop: |
| 2975 |
StringIO.write(self,(next_stop-self.currentpos)*' ') |
| 2976 |
self.currentpos = next_stop |
| 2977 |
self.last_char = ' ' |
| 2978 |
|
| 2979 |
if newindent: |
| 2980 |
if self.indentlist[-1] == 0: |
| 2981 |
self.indentlist.append(self.currentpos) |
| 2982 |
|
| 2983 |
else: |
| 2984 |
self.indentlist.append(self.indentlist[-1]+2) |
| 2985 |
elif unindent: |
| 2986 |
if len(self.indentlist)>1: |
| 2987 |
self.indentlist.pop() |
| 2988 |
else: |
| 2989 |
print('Warning: cannot unindent any further') |
| 2990 |
|
| 2991 |
if self.last_char in [' ','\n','\t']: |
| 2992 |
output_delimiter = False |
| 2993 |
|
| 2994 |
if (delimiter and output_delimiter) or not delimiter: |
| 2995 |
StringIO.write(self,outstring) |
| 2996 |
last_line_break = outstring.rfind('\n') |
| 2997 |
if last_line_break >=0: |
| 2998 |
self.currentpos = len(outstring)-last_line_break |
| 2999 |
else: |
| 3000 |
self.currentpos = self.currentpos + len(outstring) |
| 3001 |
|
| 3002 |
if len(outstring)>0: |
| 3003 |
self.last_char = outstring[-1] |
| 3004 |
|
| 3005 |
def set_tab(self,tabwidth): |
| 3006 |
"""Set the tab stop position""" |
| 3007 |
self.tabwidth = tabwidth |
| 3008 |
|
| 3009 |
|
| 3010 |
class StarError(Exception): |
| 3011 |
def __init__(self,value): |
| 3012 |
self.value = value |
| 3013 |
def __str__(self): |
| 3014 |
return '\nStar Format error: '+ self.value |
| 3015 |
|
| 3016 |
class StarLengthError(Exception): |
| 3017 |
def __init__(self,value): |
| 3018 |
self.value = value |
| 3019 |
def __str__(self): |
| 3020 |
return '\nStar length error: ' + self.value |
| 3021 |
|
| 3022 |
class StarDerivationError(Exception): |
| 3023 |
def __init__(self,fail_name): |
| 3024 |
self.fail_name = fail_name |
| 3025 |
def __str__(self): |
| 3026 |
return "Derivation of {} failed, None returned".format(self.fail_name) |
| 3027 |
|
| 3028 |
|
| 3029 |
|
| 3030 |
|
| 3031 |
|
| 3032 |
class StarDerivationFailure(AttributeError): |
| 3033 |
def __init__(self,fail_name): |
| 3034 |
self.fail_name = fail_name |
| 3035 |
def __str__(self): |
| 3036 |
return "Derivation of {} failed".format(self.fail_name) |
| 3037 |
|
| 3038 |
|
| 3039 |
|
| 3040 |
|
| 3041 |
|
| 3042 |
|
| 3043 |
|
| 3044 |
|
| 3045 |
|
| 3046 |
|
| 3047 |
|
| 3048 |
|
| 3049 |
|
| 3050 |
|
| 3051 |
|
| 3052 |
|
| 3053 |
|
| 3054 |
|
| 3055 |
|
| 3056 |
|
| 3057 |
|
| 3058 |
|
| 3059 |
|
| 3060 |
|
| 3061 |
|
| 3062 |
|
| 3063 |
|
| 3064 |
|
| 3065 |
|
| 3066 |
def ReadStarWithError(filename,prepared = None, maxlength=-1, |
| 3067 |
scantype='standard',grammar='STAR2',CBF=False, permissive=False, from_str=False): |
| 3068 |
|
| 3069 |
""" Read in a STAR file, returning the contents in the `prepared` object. |
| 3070 |
|
| 3071 |
* `filename` may be a URL, a file |
| 3072 |
path on the local system, or any object with a `read` method. |
| 3073 |
|
| 3074 |
* `prepared` provides a `StarFile` or `CifFile` object that the contents of `filename` |
| 3075 |
will be added to. |
| 3076 |
|
| 3077 |
* `maxlength` is the maximum allowable line length in the input file. This has been set at |
| 3078 |
2048 characters for CIF but is unlimited (-1) for STAR files. |
| 3079 |
|
| 3080 |
* `grammar` chooses the STAR grammar variant. `1.0` is the original 1992 CIF/STAR grammar and `1.1` |
| 3081 |
is identical except for the exclusion of square brackets as the first characters in |
| 3082 |
undelimited datanames. `2.0` will read files in the CIF2.0 standard, and `STAR2` will |
| 3083 |
read files according to the STAR2 publication. If grammar is `None` or `auto`, autodetection |
| 3084 |
will be attempted in the order `2.0`, `1.1` and `1.0`. This will always succeed for conformant CIF2.0 files. |
| 3085 |
Note that (nested) save frames are read in all grammar variations and then flagged afterwards if |
| 3086 |
they do not match the requested grammar. |
| 3087 |
|
| 3088 |
* `scantype` can be `standard` or `flex`. `standard` provides pure Python parsing at the |
| 3089 |
cost of a factor of 10 or so in speed. `flex` will tokenise the input CIF file using |
| 3090 |
fast C routines. Note that running PyCIFRW in Jython uses native Java regular expressions |
| 3091 |
to provide a speedup regardless of this argument. |
| 3092 |
|
| 3093 |
* `CBF` flags that the input file is in Crystallographic Binary File format. The binary block is |
| 3094 |
excised from the input data stream before parsing and is not available in the returned object. |
| 3095 |
|
| 3096 |
* `permissive` allows non UTF8 encodings (currently only latin1) in the input file. These are a |
| 3097 |
violation of the standard. |
| 3098 |
|
| 3099 |
""" |
| 3100 |
|
| 3101 |
|
| 3102 |
save_scoping = prepared.scoping |
| 3103 |
import CifFile.YappsStarParser_1_1 as Y11 |
| 3104 |
import CifFile.YappsStarParser_1_0 as Y10 |
| 3105 |
import CifFile.YappsStarParser_2_0 as Y20 |
| 3106 |
import CifFile.YappsStarParser_STAR2 as YST |
| 3107 |
if prepared is None: |
| 3108 |
prepared = StarFile() |
| 3109 |
if grammar == "auto" or grammar is None: |
| 3110 |
try_list = [('2.0',Y20),('1.1',Y11),('1.0',Y10)] |
| 3111 |
elif grammar == '1.0': |
| 3112 |
try_list = [('1.0',Y10)] |
| 3113 |
elif grammar == '1.1': |
| 3114 |
try_list = [('1.1',Y11)] |
| 3115 |
elif grammar == '2.0': |
| 3116 |
try_list = [('2.0',Y20)] |
| 3117 |
elif grammar == 'STAR2': |
| 3118 |
try_list = [('STAR2',YST)] |
| 3119 |
else: |
| 3120 |
raise AttributeError('Unknown STAR/CIF grammar requested, {}'.format(repr( grammar ))) |
| 3121 |
|
| 3122 |
if from_str: |
| 3123 |
text = filename |
| 3124 |
my_uri = '' |
| 3125 |
|
| 3126 |
else: |
| 3127 |
if isinstance(filename,(unicode,str)): |
| 3128 |
|
| 3129 |
relpath = urlparse(filename) |
| 3130 |
if len(relpath.scheme) <= 1: |
| 3131 |
if not os.path.isabs(filename): |
| 3132 |
fullpath = os.path.join(os.getcwd(),filename) |
| 3133 |
else: |
| 3134 |
fullpath = filename |
| 3135 |
if have_pathlib: |
| 3136 |
my_uri = Path(fullpath).as_uri() |
| 3137 |
else: |
| 3138 |
newrel = list(relpath) |
| 3139 |
newrel[0] = "file" |
| 3140 |
newrel[2] = fullpath |
| 3141 |
my_uri = urlunparse(newrel) |
| 3142 |
else: |
| 3143 |
my_uri = urlunparse(relpath) |
| 3144 |
|
| 3145 |
filestream = urlopen(my_uri) |
| 3146 |
try: |
| 3147 |
text = filestream.read().decode('utf-8-sig') |
| 3148 |
except UnicodeDecodeError: |
| 3149 |
if permissive: |
| 3150 |
text = filestream.read().decode('latin1') |
| 3151 |
print("WARNING: {} violates standard (latin1 encoding instead of UTF8).".format(filename)) |
| 3152 |
else: |
| 3153 |
raise StarError("{}: bad encoding (must be utf8 or ascii)".format(filename)) |
| 3154 |
filestream.close() |
| 3155 |
else: |
| 3156 |
filestream = filename |
| 3157 |
text = filestream.read() |
| 3158 |
if not isinstance(text,unicode): |
| 3159 |
try: |
| 3160 |
text = text.decode('utf-8-sig') |
| 3161 |
except UnicodeDecodeError: |
| 3162 |
if permissive: |
| 3163 |
text = filestream.read().decode('latin1') |
| 3164 |
print("WARNING: text violates CIF standard (latin1 encoding instead of UTF8)") |
| 3165 |
else: |
| 3166 |
raise StarError("Bad input encoding (must be utf8 or ascii)") |
| 3167 |
my_uri = "" |
| 3168 |
if not text: |
| 3169 |
return prepared.set_uri(my_uri), [0, None, None, None] |
| 3170 |
|
| 3171 |
|
| 3172 |
|
| 3173 |
if CBF: |
| 3174 |
text_bits = text.split("-BINARY-FORMAT-SECTION-") |
| 3175 |
text = text_bits[0] |
| 3176 |
for section in range(2,len(text_bits),2): |
| 3177 |
text = text+" (binary omitted)"+text_bits[section] |
| 3178 |
|
| 3179 |
endoffile = text.find(chr(26)) |
| 3180 |
if endoffile >= 0: |
| 3181 |
text = text[:endoffile] |
| 3182 |
split = text.split('\n') |
| 3183 |
if maxlength > 0: |
| 3184 |
toolong = [a for a in split if len(a)>maxlength] |
| 3185 |
if toolong: |
| 3186 |
pos = split.index(toolong[0]) |
| 3187 |
raise StarError( 'Line {} contains more than {} characters'.format(pos+1,maxlength)) |
| 3188 |
|
| 3189 |
if text[:10] != r"#\#CIF_2.0" and ('2.0',Y20) in try_list: |
| 3190 |
try_list.remove(('2.0',Y20),) |
| 3191 |
if not try_list: |
| 3192 |
raise StarError('File {} missing CIF2.0 header'.format(filename)) |
| 3193 |
|
| 3194 |
|
| 3195 |
if text[:10] == r"#\#CIF_2.0" and ('2.0',Y20) in try_list: |
| 3196 |
try_list = [('2.0',Y20)] |
| 3197 |
|
| 3198 |
for grammar_name,Y in try_list: |
| 3199 |
|
| 3200 |
result = [0, None, None, None] |
| 3201 |
|
| 3202 |
if scantype == 'standard' or grammar_name in ['2.0','STAR2']: |
| 3203 |
parser = Y.StarParser(Y.StarParserScanner(text)) |
| 3204 |
else: |
| 3205 |
parser = Y.StarParser(Y.yappsrt.Scanner(None,[],text,scantype='flex')) |
| 3206 |
|
| 3207 |
if grammar_name in ['2.0','STAR2']: |
| 3208 |
prepared.set_characterset('unicode') |
| 3209 |
else: |
| 3210 |
prepared.set_characterset('ascii') |
| 3211 |
proto_star = None |
| 3212 |
try: |
| 3213 |
proto_star = getattr(parser,"input")(prepared) |
| 3214 |
|
| 3215 |
except: |
| 3216 |
|
| 3217 |
result = [-1, sys.exc_info()[1], parser, Y] |
| 3218 |
|
| 3219 |
if proto_star is not None: |
| 3220 |
proto_star.set_grammar(grammar_name) |
| 3221 |
break |
| 3222 |
if proto_star is None: |
| 3223 |
return proto_star, result |
| 3224 |
|
| 3225 |
|
| 3226 |
proto_star.scoping = 'dictionary' |
| 3227 |
proto_star.set_uri(my_uri) |
| 3228 |
proto_star.scoping = save_scoping |
| 3229 |
return proto_star, result |
| 3230 |
|
| 3231 |
|
| 3232 |
|
| 3233 |
|
| 3234 |
|
| 3235 |
|
| 3236 |
def ReadStar(*args, **kwargs): |
| 3237 |
proto_star, result = ReadStarWithError(*args, **kwargs) |
| 3238 |
if result[0] < 0: |
| 3239 |
raise StarError(str(result[1])) |
| 3240 |
return proto_star |
| 3241 |
|
| 3242 |
|
| 3243 |
|
| 3244 |
|
| 3245 |
|
| 3246 |
|
| 3247 |
|
| 3248 |
|
| 3249 |
|
| 3250 |
|
| 3251 |
|
| 3252 |
|
| 3253 |
|
| 3254 |
|
| 3255 |
|
| 3256 |
|
| 3257 |
|
| 3258 |
|
| 3259 |
|
| 3260 |
def get_dim(dataitem,current=0,packlen=0): |
| 3261 |
zerotypes = [int, float, str] |
| 3262 |
if type(dataitem) in zerotypes: |
| 3263 |
return current, packlen |
| 3264 |
if not dataitem.__class__ == ().__class__ and \ |
| 3265 |
not dataitem.__class__ == [].__class__: |
| 3266 |
return current, packlen |
| 3267 |
elif len(dataitem)>0: |
| 3268 |
|
| 3269 |
return get_dim(dataitem[0],current+1,len(dataitem)) |
| 3270 |
else: return current+1,0 |
| 3271 |
|
| 3272 |
|
| 3273 |
|
| 3274 |
|
| 3275 |
|
| 3276 |
|
| 3277 |
|
| 3278 |
|
| 3279 |
|
| 3280 |
|
| 3281 |
|
| 3282 |
|
| 3283 |
|
| 3284 |
|
| 3285 |
|
| 3286 |
|
| 3287 |
|
| 3288 |
|
| 3289 |
|
| 3290 |
def apply_line_folding(instring,minwraplength=60,maxwraplength=80): |
| 3291 |
"""Insert line folding characters into instring between min/max wraplength""" |
| 3292 |
|
| 3293 |
lines = instring.split('\n') |
| 3294 |
line_len = [len(l) for l in lines] |
| 3295 |
if max(line_len) < maxwraplength and re.match("\\[ \v\t\f]*\n",instring) is None: |
| 3296 |
return instring |
| 3297 |
outstring = "\\\n" |
| 3298 |
for l in lines: |
| 3299 |
if len(l) < maxwraplength: |
| 3300 |
outstring = outstring + l |
| 3301 |
if len(l) > 0 and l[-1]=='\\': |
| 3302 |
outstring = outstring + "\\\n" |
| 3303 |
outstring = outstring + "\n" |
| 3304 |
else: |
| 3305 |
current_bit = l |
| 3306 |
while len(current_bit) > maxwraplength: |
| 3307 |
space_pos = re.search('[ \v\f\t]+',current_bit[minwraplength:]) |
| 3308 |
if space_pos is not None and space_pos.start()<maxwraplength-1: |
| 3309 |
outstring = outstring + current_bit[:minwraplength+space_pos.start()] + "\\\n" |
| 3310 |
current_bit = current_bit[minwraplength+space_pos.start():] |
| 3311 |
else: |
| 3312 |
outstring = outstring + current_bit[:maxwraplength-1] + "\\\n" |
| 3313 |
current_bit = current_bit[maxwraplength-1:] |
| 3314 |
outstring = outstring + current_bit |
| 3315 |
if current_bit[-1] == '\\': |
| 3316 |
outstring = outstring + "\\\n" |
| 3317 |
outstring = outstring + '\n' |
| 3318 |
outstring = outstring[:-1] |
| 3319 |
return outstring |
| 3320 |
|
| 3321 |
|
| 3322 |
|
| 3323 |
|
| 3324 |
|
| 3325 |
|
| 3326 |
|
| 3327 |
def remove_line_folding(instring): |
| 3328 |
"""Remove line folding from instring""" |
| 3329 |
if re.match(r"\\[ \v\t\f]*" +"\n",instring) is not None: |
| 3330 |
return re.sub(r"\\[ \v\t\f]*$" + "\n?","",instring,flags=re.M) |
| 3331 |
else: |
| 3332 |
return instring |
| 3333 |
|
| 3334 |
|
| 3335 |
|
| 3336 |
|
| 3337 |
|
| 3338 |
|
| 3339 |
|
| 3340 |
|
| 3341 |
|
| 3342 |
|
| 3343 |
|
| 3344 |
|
| 3345 |
|
| 3346 |
|
| 3347 |
|
| 3348 |
def apply_line_prefix(instring,prefix): |
| 3349 |
"""Prefix every line in instring with prefix""" |
| 3350 |
if prefix[0] != ";" and "\\" not in prefix: |
| 3351 |
header = re.match(r"(\\[ \v\t\f]*" +"\n)",instring) |
| 3352 |
if header is not None: |
| 3353 |
print('Found line folded string for prefixing...') |
| 3354 |
not_header = instring[header.end():] |
| 3355 |
outstring = prefix + "\\\\\n" + prefix |
| 3356 |
else: |
| 3357 |
print('No folding in input string...') |
| 3358 |
not_header = instring |
| 3359 |
outstring = prefix + "\\\n" + prefix |
| 3360 |
outstring = outstring + not_header.replace("\n","\n"+prefix) |
| 3361 |
return outstring |
| 3362 |
raise StarError("Requested prefix starts with semicolon or contains a backslash: " + prefix) |
| 3363 |
|
| 3364 |
|
| 3365 |
|
| 3366 |
|
| 3367 |
|
| 3368 |
|
| 3369 |
|
| 3370 |
|
| 3371 |
def remove_line_prefix(instring): |
| 3372 |
"""Remove prefix from every line if present""" |
| 3373 |
prefix_match = re.match("(?P<prefix>[^;\\\n][^\n\\\\]+)(?P<folding>\\\\{1,2}[ \t\v\f]*\n)",instring) |
| 3374 |
if prefix_match is not None: |
| 3375 |
prefix_text = prefix_match.group('prefix') |
| 3376 |
print('Found prefix {}'.format(prefix_text)) |
| 3377 |
prefix_end = prefix_match.end('folding') |
| 3378 |
|
| 3379 |
if prefix_match.group('folding')[:2]=='\\\\': |
| 3380 |
outstring = instring[prefix_match.end('folding')-1:].replace("\n"+prefix_text,"\n") |
| 3381 |
return "\\" + outstring |
| 3382 |
else: |
| 3383 |
outstring = instring[prefix_match.end('folding')-1:].replace("\n"+prefix_text,"\n") |
| 3384 |
return outstring[1:] |
| 3385 |
else: |
| 3386 |
return instring |
| 3387 |
|
| 3388 |
|
| 3389 |
|
| 3390 |
|
| 3391 |
|
| 3392 |
|
| 3393 |
|
| 3394 |
def listify(item): |
| 3395 |
if isinstance(item,unicode): return [item] |
| 3396 |
else: return item |
| 3397 |
|
| 3398 |
|
| 3399 |
def transpose(base_list): |
| 3400 |
new_lofl = [] |
| 3401 |
full_length = len(base_list) |
| 3402 |
opt_range = range(full_length) |
| 3403 |
for i in range(len(base_list[0])): |
| 3404 |
new_packet = [] |
| 3405 |
for j in opt_range: |
| 3406 |
new_packet.append(base_list[j][i]) |
| 3407 |
new_lofl.append(new_packet) |
| 3408 |
return new_lofl |
| 3409 |
|
| 3410 |
|
| 3411 |
|
| 3412 |
def not_none(itemlist): |
| 3413 |
"""Return true only if no values of None are present""" |
| 3414 |
if itemlist is None: |
| 3415 |
return False |
| 3416 |
if not isinstance(itemlist,(tuple,list)): |
| 3417 |
return True |
| 3418 |
for x in itemlist: |
| 3419 |
if not not_none(x): return False |
| 3420 |
return True |
| 3421 |
|
| 3422 |
|
| 3423 |
|
| 3424 |
|
| 3425 |
|
| 3426 |
|
| 3427 |
|
| 3428 |
|
| 3429 |
|
| 3430 |
def check_stringiness(data): |
| 3431 |
"""Check that the contents of data are all strings""" |
| 3432 |
if not hasattr(data,'dtype'): |
| 3433 |
from numbers import Number |
| 3434 |
if isinstance(data,Number): return False |
| 3435 |
elif isinstance(data,(unicode,str)): return True |
| 3436 |
elif data is None:return False |
| 3437 |
else: |
| 3438 |
for one_item in data: |
| 3439 |
if not check_stringiness(one_item): return False |
| 3440 |
return True |
| 3441 |
else: |
| 3442 |
import numpy |
| 3443 |
if data.ndim == 0: |
| 3444 |
if data.dtype.kind in ['S','U']: return True |
| 3445 |
else: return False |
| 3446 |
else: |
| 3447 |
for one_item in numpy.nditer(data): |
| 3448 |
print('numpy data: ' + repr( one_item )) |
| 3449 |
if not check_stringiness(one_item): return False |
| 3450 |
return True |
| 3451 |
|
| 3452 |
|
| 3453 |
|
| 3454 |
|
| 3455 |
|
| 3456 |
|
| 3457 |
|
| 3458 |
|
| 3459 |
|
| 3460 |
|
| 3461 |
|
| 3462 |
|
| 3463 |
|
| 3464 |
|
| 3465 |
|
| 3466 |
|
| 3467 |
|
| 3468 |
|
| 3469 |
|
| 3470 |
|
| 3471 |
|
| 3472 |
|
| 3473 |
|
| 3474 |
|
| 3475 |
|
| 3476 |
|
| 3477 |
|
| 3478 |
|
| 3479 |
|
| 3480 |
|
| 3481 |
def process_template(template_file): |
| 3482 |
"""Process a template datafile to formatting instructions""" |
| 3483 |
template_as_cif = StarFile(template_file,grammar="2.0").first_block() |
| 3484 |
if isinstance(template_file,(unicode,str)): |
| 3485 |
template_string = open(template_file).read() |
| 3486 |
else: |
| 3487 |
template_file.seek(0) |
| 3488 |
template_string = template_file.read() |
| 3489 |
|
| 3490 |
|
| 3491 |
|
| 3492 |
|
| 3493 |
form_hints = [] |
| 3494 |
find_indent = "^ +" |
| 3495 |
for item in template_as_cif.item_order: |
| 3496 |
if not isinstance(item,int): |
| 3497 |
hint_dict = {"dataname":item} |
| 3498 |
|
| 3499 |
start_pos = re.search("(^[ \t]*(?P<name>" + item + ")[ \t\n]+)(?P<spec>([\\S]+)|(^;))",template_string,re.I|re.M) |
| 3500 |
if start_pos.group("spec") != None: |
| 3501 |
spec_pos = start_pos.start("spec")-start_pos.start(0) |
| 3502 |
spec_char = template_string[start_pos.start("spec"):start_pos.start("spec")+3] |
| 3503 |
if spec_char[0] in '\'";': |
| 3504 |
hint_dict.update({"delimiter":spec_char[0]}) |
| 3505 |
if spec_char == '"""' or spec_char == "'''": |
| 3506 |
hint_dict.update({"delimiter":spec_char}) |
| 3507 |
if spec_char[0] != ";": |
| 3508 |
hint_dict.update({"column":spec_pos}) |
| 3509 |
else: |
| 3510 |
hint_dict.update({"delimiter":"\n;"}) |
| 3511 |
|
| 3512 |
text_val = template_as_cif[item] |
| 3513 |
hint_dict["reformat"] = "\n\t" in text_val or "\n " in text_val |
| 3514 |
if hint_dict["reformat"]: |
| 3515 |
p = re.search(find_indent,text_val,re.M) |
| 3516 |
if p.group() is not None: |
| 3517 |
hint_dict["reformat_indent"]=p.end() - p.start() |
| 3518 |
if start_pos.group('name') != None: |
| 3519 |
name_pos = start_pos.start('name') - start_pos.start(0) |
| 3520 |
hint_dict.update({"name_pos":name_pos}) |
| 3521 |
|
| 3522 |
form_hints.append(hint_dict) |
| 3523 |
else: |
| 3524 |
testnames = template_as_cif.loops[item] |
| 3525 |
total_items = len(template_as_cif.loops[item]) |
| 3526 |
testname = testnames[0] |
| 3527 |
|
| 3528 |
loop_regex = "(^[ \t]*(?P<loop>loop_)[ \t\n\r]+(?P<name>" + testname + ")([ \t\n\r]+_[\\S]+){" + str(total_items - 1) + "}[ \t]*$(?P<packet>(.(?!_loop|_[\\S]+))*))" |
| 3529 |
loop_line = re.search(loop_regex,template_string,re.I|re.M|re.S) |
| 3530 |
loop_so_far = loop_line.end() |
| 3531 |
packet_text = loop_line.group('packet') |
| 3532 |
loop_indent = loop_line.start('loop') - loop_line.start(0) |
| 3533 |
form_hints.append({"dataname":'loop','name_pos':loop_indent}) |
| 3534 |
packet_regex = "[ \t]*(?P<all>(?P<sqqq>'''([^\n\r\f']*)''')|(?P<sq>'([^\n\r\f']*)'+)|(?P<dq>\"([^\n\r\"]*)\"+)|(?P<none>[^\\s]+))" |
| 3535 |
packet_pos = re.finditer(packet_regex,packet_text) |
| 3536 |
line_end_pos = re.finditer("^",packet_text,re.M) |
| 3537 |
next_end = next(line_end_pos).end() |
| 3538 |
last_end = next_end |
| 3539 |
for loopname in testnames: |
| 3540 |
|
| 3541 |
name_regex = "(^[ \t]*(?P<name>" + loopname + "))" |
| 3542 |
name_match = re.search(name_regex,template_string,re.I|re.M|re.S) |
| 3543 |
loop_name_indent = name_match.start('name')-name_match.start(0) |
| 3544 |
hint_dict = {"dataname":loopname,"name_pos":loop_name_indent} |
| 3545 |
|
| 3546 |
thismatch = next(packet_pos) |
| 3547 |
while thismatch.start('all') > next_end: |
| 3548 |
try: |
| 3549 |
last_end = next_end |
| 3550 |
next_end = next(line_end_pos).start() |
| 3551 |
print('next end {}'.format(next_end)) |
| 3552 |
except StopIteration: |
| 3553 |
break |
| 3554 |
print('Start {}, last_end {}'.format(thismatch.start('all'),last_end)) |
| 3555 |
col_pos = thismatch.start('all') - last_end + 1 |
| 3556 |
if thismatch.group('none') is None: |
| 3557 |
if thismatch.group('sqqq') is not None: |
| 3558 |
hint_dict.update({'delimiter':"'''"}) |
| 3559 |
else: |
| 3560 |
hint_dict.update({'delimiter':thismatch.groups()[0][0]}) |
| 3561 |
hint_dict.update({'column':col_pos}) |
| 3562 |
print('{}: {}'.format(loopname,repr( hint_dict ))) |
| 3563 |
form_hints.append(hint_dict) |
| 3564 |
return form_hints |
| 3565 |
|
| 3566 |
|
| 3567 |
|
| 3568 |
|
| 3569 |
|