Debian Codegraph @

src/StarFile.py

raw symbols SCIP
1 # \section{Introduction}
2 #
3 # This file implements a general STAR reading/writing utility. The basic
4 # objects ([[StarFile/StarBlock]]) read and write syntactically correct STAR files
5 # including save frames.
6 #
7 # The [[StarFile]] class is initialised with either no arguments (a new STAR file)
8 # or with the name of an already existing STAR file. Data items are
9 # accessed/changed/added using the python mapping type ie to get
10 # [[dataitem]] you would type [[value = cf[blockname][dataitem]]].
11 #
12 # Note also that a StarFile object can be accessed as a mapping type, ie using
13 # square brackets. Most mapping operations have been implemented (see below).
14 #
15 # We define a generic BlockCollection class that both CifFiles and StarFiles are
16 # subclasses of. It is also used when the user requests a collection of blocks
17 # from a StarFile.
18 #
19 # The LoopBlock class used to be the root class of StarBlocks and all loop blocks for
20 # recursive handling of nested loops, but with removal of nested loop support it is simpler
21 # to model a StarBlock as a collection of dataitems with additional information specifying
22 # which datanames are grouped together. LoopBlocks are still used to provide packet-based
23 # access to loops.
24 #
25 #
26 # <*>=
27 # To maximize python3/python2 compatibility
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 # <Copyright statement>=
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 # Python 2,3 compatibility
88 try:
89 from urllib import urlopen # for arbitrary opening
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 #not cStringIO as we cannot subclass
99 except ImportError:
100 from io import StringIO
101
102 if isinstance(u"abc",str): #Python 3
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 # Windows paths require special handling. pathlib is available from
113 # Python 3.4. For earlier Python versions dictionary import will not work
114 # on Windows
115 try:
116 from pathlib import Path
117 have_pathlib = True
118 except:
119 have_pathlib = False
120
121 # \section{Collection datatype}
122 #
123 # DDLm introduced data values which could be lists, tuples or hash tables. We define
124 # a distinct StarList class to distinguish them from loop lists, and take the
125 # opportunity to expand the getitem method to allow multiple arguments.
126 #
127 # We try and duplicate the behaviour of numpy slices for those times when dREL
128 # doesn't create a numpy array before we slice.
129 #
130 # <Define a collection datatype>=
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: #extended comma notation
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 # \section{Loop Block class}
155 #
156 # A LoopBlock is provided as a row-based interface to a collection of
157 # columns, so that iteration over packets is possible. It is
158 # initialised with a StarBlock object and dataname and returns an object
159 # that accesses the loop containing the dataname. Datavalues is not
160 # copied, meaning that changes to the data (e.g. appending a packet)
161 # will be apparent in the StarBlock parent (i.e the LoopBlock is like
162 # a view onto the parent).
163 #
164 #
165 # <LoopBlock class>=
166 class LoopBlock(object):
167 # Initialising: We do not check conformance to standards here: it assumed that
168 # this has been done by the creating routine.
169 #
170 #
171 # <Initialise Loop Block>=
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 # <Add emulation of a mapping type>=
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 #Avoid iterator even though that is Python3-esque
186 def items(self):
187 return list(zip(self.keys(),self.values()))
188
189 def __getitem__(self,dataname):
190 if isinstance(dataname,int): #a packet request
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 # for compatibility
217 def __getattr__(self,attname):
218 return getattr(self.parent_block,attname)
219
220 # <Selection of iterators>=
221 # When loading values, we want to iterate over the items until
222 # a "stop_" token is found - this is communicated via the "popout"
223 # attribute changing to True. We save the __iter__ method for
224 # iterating over packets. Also, when a new packet is begun, all
225 # subloops should be extended correspondingly. We are in a special
226 # situation where we do not enforce length matching, as we assume
227 # that things will be loaded in as we go.
228 #
229 # Each yield returns a list which should be appended to with a unitary
230 # item. So, as the number of packets increases, we need to make sure
231 # that the lowest level lists are extended as needed with empty lists.
232 #
233 #
234 # <A load iterator>=
235 def load_iter(self,coords=[]):
236 count = 0 #to create packet index
237 while not self.popout:
238 # ok, we have a new packet: append a list to our subloops
239 for aloop in self.loops:
240 aloop.new_enclosing_packet()
241 for iname in self.item_order:
242 if isinstance(iname,LoopBlock): #into a nested loop
243 for subitems in iname.load_iter(coords=coords+[count]):
244 # print 'Yielding %s' % `subitems`
245 yield subitems
246 # print 'End of internal loop'
247 else:
248 if self.dimension == 0:
249 # print 'Yielding %s' % `self[iname]`
250 yield self,self[iname]
251 else:
252 backval = self.block[iname]
253 for i in range(len(coords)):
254 # print 'backval, coords: %s, %s' % (`backval`,`coords`)
255 backval = backval[coords[i]]
256 yield self,backval
257 count = count + 1 # count packets
258 self.popout = False # reinitialise
259 # print 'Finished iterating'
260 yield self,'###Blank###' #this value should never be used
261
262 # an experimental fast iterator for level-1 loops (ie CIF)
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 # Add another list of the required shape to take into account a new outer packet
270 def new_enclosing_packet(self):
271 if self.dimension > 1: #otherwise have a top-level list
272 for iname in self.keys(): #includes lower levels
273 target_list = self[iname]
274 for i in range(3,self.dimension): #dim 2 upwards are lists of lists of...
275 target_list = target_list[-1]
276 target_list.append([])
277 # print '%s now %s' % (iname,`self[iname]`)
278
279 # We recursively expand out all values in nested loops and return a
280 # simple dictionary type. Although it only seems to make sense to call
281 # this from a dimension 0 LoopBlock, if we are not a level 0 LoopBlock,
282 # we drill down until we get a simple value to return, then start looping.
283 #
284 # We want to build up a return dictionary by adding keys from the deeper loops,
285 # but if we simply use the dictionary update method, we will find that we
286 # have stale keys from previous inner loops. Therefore, we keep our values as
287 # (key,value) tuples which we turn into a Star packet at the last moment.
288 #
289 # This is now updated to return StarPackets, which are like lists
290 # except that they also have attributes set.
291 #
292 #
293 # <A recursive iterator>=
294 def recursive_iter(self,dict_so_far={},coord=[]):
295 # print "Recursive iter: coord %s, keys %s, dim %d" % (`coord`,`self.block.keys()`,self.dimension)
296 my_length = 0
297 top_items = self.block.items()
298 top_values = self.block.values() #same order as items
299 drill_values = self.block.values()
300 for dimup in range(0,self.dimension): #look higher in the tree
301 if len(drill_values)>0: #this block has values
302 drill_values=drill_values[0] #drill in
303 else:
304 raise StarError("Malformed loop packet {}".format(repr( top_items[0] )))
305 my_length = len(drill_values[0]) #length of 'string' entry
306 if self.dimension == 0: #top level
307 for aloop in self.loops:
308 for apacket in aloop.recursive_iter():
309 # print "Recursive yielding %s" % repr( dict(top_items + apacket.items()) )
310 prep_yield = StarPacket(top_values+apacket.values()) #straight list
311 for name,value in top_items + apacket.items():
312 setattr(prep_yield,name,value)
313 yield prep_yield
314 else: #in some loop
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) #just values
319 kvvals = list(kvvals)
320 # print "Recursive kvpairs at %d: %s" % (i,repr( kvpairs ))
321 if self.loops:
322 for aloop in self.loops:
323 for apacket in aloop.recursive_iter(coord=coord+[i]):
324 # print "Recursive yielding %s" % repr( dict(kvpairs + apacket.items()) )
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: # we're at the bottom of the tree
330 # print "Recursive yielding %s" % repr( dict(kvpairs) )
331 prep_yield = StarPacket(kvvals)
332 for name,value in kvpairs:
333 setattr(prep_yield,name,value)
334 yield prep_yield
335
336 # small function to use the coordinates.
337 def coord_to_group(self,dataname,coords):
338 if not isinstance(dataname,unicode):
339 return dataname # flag inner loop processing
340 newm = self[dataname] # newm must be a list or tuple
341 for c in coords:
342 # print "Coord_to_group: %s ->" % (repr( newm )),
343 newm = newm[c]
344 # print repr( newm )
345 return newm
346
347 # Return a series of LoopBlocks with the appropriate packet chosen. This
348 # does not loop over interior blocks, so called at the top level it just
349 # returns the whole star block.
350 #
351 #
352 # <A one-level iterator>=
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 # Removing a data item. We delete the item, and if it is looped, and
363 # nothing is left in the loop, we remove the loop. [[RemoveLoopItem]]
364 # is here for compatibility only.
365 #
366 #
367 # <Remove a data item>=
368 def RemoveItem(self,itemname):
369 """Remove `itemname` from the block."""
370 # first check any loops
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 # now remove from loop
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: #will appear in order list
383 self.item_order.remove(testkey)
384
385 def RemoveLoopItem(self,itemname):
386 """*Deprecated*. Use `RemoveItem` instead"""
387 self.RemoveItem(itemname)
388
389 # Loops. We should distinguish two loop structures: the loop
390 # structures provided by the syntax, and the loop structures defined by
391 # the dictionary ('semantic' loops). The members of these loops do not
392 # coincide for 'joined' categories, where datanames may appear in either
393 # separate loops, or within one loop. Until we have a dictionary, we
394 # have no way to find the semantic loops.
395 #
396 # The first function below returns the particular loop block containing
397 # the specified dataname, so that we can manipulate its contents
398 # directly, and therefore refers to a syntactic loop.
399 #
400 #
401 # <Get complete looped data>=
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 # Packets. We store columns, so extracting packets is a much
408 # slower task.
409 #
410 #
411 # <Packet handling methods>=
412 # Get nth looped packet. This returns a packet of data.
413 #
414 #
415 # <Get nth loop packet>=
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 # Adding a packet. We are passed a StarPacket object, which is just a list which is accessible by attribute.
424 # As I have not yet produced a proper __init__ or __new__ method to allow creation of a new StarPacket, it is
425 # advisable to create a new packet by copying an old packet.
426 #
427 #
428 # <Add a packet>=
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 # Return order of items - this is just a copy of the list of datanames
436 # making up this loop.
437 #
438 #
439 # <Get item order>=
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 # Move an item to a different position in the loop. This only affects
447 # the printout order. We allow different capitalisation and have to
448 # absorb the possibility of nested loops in the order list, and being
449 # passed a loop reference in the [[itemname]] argument.
450 #
451 #
452 # <Change data item order>=
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 # This method is used when printing out, which is why it takes both
459 # names and numbers.
460 #
461 #
462 # <Return position of data item>=
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 # return loop position
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 # Get co-looped names. Sometimes we just want names, and will get the
482 # values ourselves on a need-to-know basis.
483 #
484 #
485 # <Get co-looped names>=
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 # Get co-looped names. Sometimes we just want names, and will get the
497 # values ourselves on a need-to-know basis.
498 #
499 #
500 # <Get co-looped names>=
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 # \section{Star Block class}
510 #
511 # A Star Block is no longer simply a LoopBlock. Historically it was distinguished
512 # by holding save frames, but this has been removed. Development note:
513 # in the original implementation, a StarBlock was just a special type of
514 # LoopBlock. In our new implementation, a LoopBlock is a simple
515 # structure that is created to access loops in a certain way.
516 #
517 # The other difference between LoopBlocks and StarBlocks is that the latter
518 # can have a dictionary attached, whereas inner LoopBlocks should not.
519 #
520 #
521 # <StarBlock class>=
522 class StarBlock(object):
523 # Initialising a StarBlock. If given non-zero data to initialise the
524 # block with, we either copy (if it is a dictionary) or else initialise
525 # each key-value pair separately (if tuples). We take care to include
526 # our special "loop" key if it is not in the supplied dictionary, but
527 # apart from this we make no check of the actual conformance of the
528 # dictionary items.
529 #
530 # To maximise efficiency, we store all keys as lower case, and keep
531 # a table of key vs the actual supplied capitalisation for printout.
532 #
533 # The [[overwrite]] argument allows values to be silently replaced, as per a
534 # normal python dictionary. However, when reading in from a file, we want to
535 # detect duplicated values, so we set this to false. As DDLm introduces the
536 # unicode character set, we need to indicate which character set we are
537 # prepared to accept.
538 #
539 # We store the data in [[self.block]]. Each entry in this table is a tuple
540 # with first element the string value, and second element the corresponding
541 # calculated or actual value. We use a tuple to emphasise that both values
542 # need to be changed together.
543 #
544 # Formatting hints are used on output to suggest column positions for
545 # looped datanames and delimiters. In practice these are used only for
546 # dictionaries where fine-tuned layout is helpful for human readers.
547 #
548 # We provide a simple function to change the maximum name length, so that
549 # we can read in a StarBlock and then enforce that the names are a maximum
550 # length as required by CIF. Values calculated with a dictionary are
551 # cached by setting self.cache_vals to True.
552 #
553 #
554 # <Initialise a StarBlock>=
555 def __init__(self,data = (), maxoutlength=2048, wraplength=80, overwrite=True,
556 characterset='ascii',maxnamelength=-1):
557 self.block = {} #the actual data storage (lower case keys)
558 self.loops = {} #each loop is indexed by a number and contains a list of datanames
559 self.item_order = [] #lower case, loops referenced by integer
560 self.formatting_hints = {}
561 self.true_case = {} #transform lower case to supplied case
562 self.provide_value = False #prefer string version always
563 self.dictionary = None #DDLm dictionary
564 self.popout = False #used during load iteration
565 self.curitem = -1 #used during iteration
566 self.cache_vals = True #store all calculated values
567 self.maxoutlength = maxoutlength
568 self.setmaxnamelength(maxnamelength) #to enforce CIF limit of 75 characters
569 self.set_characterset(characterset) #to check input names
570 self.wraplength = wraplength
571 self.overwrite = overwrite
572 self.string_delimiters = ["'",'"',"\n;"] #universal CIF set
573 self.list_delimiter = " " #CIF2 default
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 # loops as well
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 # Adding emulation of a mapping type. We add any of the other
605 # functions we would like to emulate. [[__len__]] returns the number
606 # of items in this block, either in a loop or not. So it is
607 # not the simple length of the dictionary.
608 #
609 # A Star Block can hold save frames in the outermost loop. From version
610 # 4.05 we do not allow save frames to be set from within the block;
611 # rather, an enclosing block collection should be created (e.g. a Star
612 # File) and the save frame added to that block collection with the
613 # 'enclosing' StarBlock set as its parent. We catch the saves key and
614 # print an error message to show deprecation.
615 #
616 #
617 # <Add StarBlock emulation of mapping type>=
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 # send the dictionary the required key and a pointer to us
636 try:
637 new_value = self.dictionary.derive_item(key,self,store_value=self.cache_vals,allow_defaults=False)
638 except StarDerivationFailure: #try now with defaults included
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 # we now have an item, we can try to convert it to a number if that is appropriate
649 # note numpy values are never stored but are converted to lists
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: # a string
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: # catch the question marks
662 do_calculate = False
663 if isinstance(rawitem,(list,tuple)):
664 known = [a for a in rawitem if a != '?']
665 if len(known) == 0: #all questions
666 do_calculate = True
667 elif rawitem == '?':
668 do_calculate = True
669 if do_calculate:
670 # remove old value
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 #can't do anything
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 # keys returns all internal keys
698 def keys(self):
699 return list(self.block.keys()) #always lower case
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 # doesn't appear to work
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 # return self.copy.im_class(newcopy) #catch inheritance
747 return newcopy
748
749 def update(self,adict):
750 for key in adict.keys():
751 self.AddItem(key,adict[key])
752
753 # This method is used when printing out, which is why it takes both
754 # names and numbers.
755 #
756 #
757 # <Return position of data item>=
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 # return loop position
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 # This routine moves around the order of objects in the printout. We can
809 # only move an item within the loop in which it appears.
810 #
811 #
812 # <Change order of data item>=
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: #top level
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 # <Return order of all data items>=
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 # Adding a data item.
835 #
836 # We check for consistency, by making sure the new item is not in the
837 # block already. If it is, we replace it (consistent with the meaning
838 # of square brackets in Python), unless [[self.overwrite]] is False, in
839 # which case an error is raised.
840 #
841 # We skip checking of data values if the [[precheck]] value is true- this
842 # is typically set if the item is being read from a file, and so is already
843 # checked, or will be checked in bulk at the end.
844 #
845 # Note that all strings are stored internally as unicode.
846 #
847 #
848 # <Add a data item>=
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) #everything is unicode internally
858 if not precheck:
859 self.check_data_name(key,self.maxnamelength) # make sure no nasty characters
860 # check for overwriting
861 if key in self:
862 if not self.overwrite:
863 raise StarError( 'Duplicated item name: {}'.format(key))
864 if not precheck: #need to sanitise
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 # update ancillary information first
872 lower_key = key.lower()
873 if not lower_key in self and self.FindLoop(lower_key)<0: #need to add to order
874 self.item_order.append(lower_key)
875 # always remove from our case table in case the case is different
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 # This is the original routine for adding a loop item, left in for consistency
887 # with old versions. Do not use.
888 #
889 #
890 # <Old multi-item add routine>=
891 def AddLoopItem(self,incomingdata,precheck=False,maxlength=-1):
892 """*Deprecated*. Use `AddItem` followed by `CreateLoop` if
893 necessary."""
894 # print "Received data %s" % `incomingdata`
895 # we accept tuples, strings, lists and dicts!!
896 # Direct insertion: we have a string-valued key, with an array
897 # of values -> single-item into our loop
898 if isinstance(incomingdata[0],(tuple,list)):
899 # a whole loop
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 # Checking the data names. The CIF 1.1 standard restricts characters in
910 # a data name to ASCII 33-126 and there should be a leading underscore. Items
911 # are allowed to have the blank characters as well, i.e. ascii 09,10,13 and 32.
912 # Data items may be lists, which we need to detect before checking. We assume
913 # that the item has been regularised before this check is called.
914 #
915 # The CIF2 standard allows all of Unicode, with certain blocks disallowed. The
916 # removal of the disallowed characters takes place on file read.
917 #
918 # We have the name length as a separate call as file reading will automatically
919 # produce datanames with the correct syntax, so during file reading we do not
920 # require any checking, but we do still need to check name length.
921 #
922 #
923 # <Check data name for STAR conformance>=
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 # print 'Checking %s for unicode characterset conformance' % dataname
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 # <Check data item for STAR conformance>=
956 def check_item_value(self,item):
957 test_item = item
958 if not isinstance(item,(list,dict,tuple)):
959 test_item = [item] #single item list
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 # Regularising data. We want the copy.deepcopy operation to work, so
974 # we cannot have any arrays passed into the master dictionary. We make
975 # sure everything goes in either as a single item or as a dict/list/tuple. We
976 # provide an empty datavalue with the same structure as the returned value
977 # so that the value/string alternate is correctly initialised/reset.
978 #
979 # Note that all string data should be Unicode. To maintain compatibility
980 # for Python 2 we apply Unicode to any string data.
981 #
982 #
983 # <Regularise data values>=
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 #assume StarList/StarDict contain unicode if necessary
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 #return dataitem,[None]*len(dataitem)
995 # so try to make into a list
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 # Removing a data item. We delete the item, and if it is looped, and
1004 # nothing is left in the loop, we remove the loop. [[RemoveLoopItem]]
1005 # is here for compatibility only.
1006 #
1007 #
1008 # <Remove a data item>=
1009 def RemoveItem(self,itemname):
1010 """Remove `itemname` from the block."""
1011 # first check any loops
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 # now remove from loop
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: #will appear in order list
1024 self.item_order.remove(testkey)
1025
1026 def RemoveLoopItem(self,itemname):
1027 """*Deprecated*. Use `RemoveItem` instead"""
1028 self.RemoveItem(itemname)
1029
1030 # Returning an item value. Note that a looped block has little
1031 # meaning without all the items in the loop. Routine [[GetLoop]] is
1032 # better in this case. This is a real time-intensive loop, so we
1033 # initially assume that the key we have been passed is the right
1034 # key (i.e. case is the same) and only check for case if this
1035 # fails.
1036 #
1037 # We define an alternative call that returns both the stored value
1038 # and whether or not it is a non-string value. This saves other
1039 # routines performing the same check. But any StarLists are
1040 # considered to be unready for use as values as they may in
1041 # fact be Arrays or Matrices and therefore require their
1042 # type to be changed.
1043 #
1044 # Note that if the value is '?', or a list of '?', we could
1045 # delete the dataitem altogether, however that would lead to
1046 # inconsistencies with previous calls to has_key, keys() etc.
1047 #
1048 #
1049 # <Return value of item>=
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 # prefer string value unless all are None
1064 # are we a looped value?
1065 if not isinstance(s,(tuple,list)) or isinstance(s,StarList):
1066 if not_none(s):
1067 return s,False #a string value
1068 else:
1069 return v,not isinstance(v,StarList) #a StarList is not calculation-ready
1070 elif not_none(s):
1071 return s,False #a list of string values
1072 else:
1073 if len(v)>0:
1074 return v,not isinstance(v[0],StarList)
1075 return v,True
1076
1077 # A StarBlock allows dealing with loops on a columnar level. For row-based
1078 # operations, a LoopBlock can be created with GetLoop and iterated over.
1079 #
1080 #
1081 # <Dealing with loops>=
1082 # Creating loops. In the latest version of PyCIFRW, a loop is simply a collection
1083 # of datanames that together make up the loop. It is indexed by a number, which goes
1084 # into the item_order array to produce the loop when printing out. No check of
1085 # dataname existence is done, so that a loop can be created before the datanames are
1086 # provided. In order to iterate over loop packets, a LoopBlock needs to be created
1087 # subsequently.
1088 #
1089 # When we create the loop, we remove the datanames from the item order list to prevent
1090 # them being output twice, and we also remove them from any other loop. Thus, at
1091 # any point in time, a dataname belongs to only one loop, but can be switched to
1092 # another loop trivially.
1093 #
1094 #
1095 # <Create a loop>=
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 # check lengths: these datanames should exist
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: #all are unlisted, turn into lists
1114 for d in datanames:
1115 self[d] = [self[d]]
1116 # store as lower case
1117 lc_datanames = [d.lower() for d in datanames]
1118 # remove these datanames from all other loops
1119 [self.loops[a].remove(b) for a in self.loops for b in lc_datanames if b in self.loops[a]]
1120 # remove empty loops
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 # remove these datanames from item ordering
1135 self.item_order = [a for a in self.item_order if a not in lc_datanames]
1136
1137 # Adding a dataname that has already been set to a loop. While relatively trivial, we still need
1138 # to check that it does not exist in any other loops, and remove this dataname from the item order
1139 # if it is present. We always use the canonical lower-case form. Also, the access to self[oldname]
1140 # may trigger a round of evaluation, which we wish to avoid, so we make sure to switch off calculations
1141 # in this case.
1142 #
1143 #
1144 # <Add name to loop>=
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 # check length
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 # remove from any other loops
1164 [self.loops[a].remove(lower_newname) for a in self.loops if lower_newname in self.loops[a]]
1165 # and add to this loop
1166 self.loops[loop_no].append(lower_newname)
1167 # remove from item_order if present
1168 try:
1169 self.item_order.remove(lower_newname)
1170 except ValueError:
1171 pass
1172
1173 # <Find a loop>=
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 # Loops. We should distinguish two loop structures: the loop
1185 # structures provided by the syntax, and the loop structures defined by
1186 # the dictionary ('semantic' loops). The members of these loops do not
1187 # coincide for 'joined' categories, where datanames may appear in either
1188 # separate loops, or within one loop. Until we have a dictionary, we
1189 # have no way to find the semantic loops.
1190 #
1191 # The first function below returns the particular loop block containing
1192 # the specified dataname, so that we can manipulate its contents
1193 # directly, and therefore refers to a syntactic loop.
1194 #
1195 #
1196 # <Get complete looped data>=
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 # Get co-looped names. Sometimes we just want names, and will get the
1203 # values ourselves on a need-to-know basis.
1204 #
1205 #
1206 # <Get co-looped names>=
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 # Get co-looped names. Sometimes we just want names, and will get the
1218 # values ourselves on a need-to-know basis.
1219 #
1220 #
1221 # <Get co-looped names>=
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 # Adding a dataname that has already been set to a loop. While relatively trivial, we still need
1231 # to check that it does not exist in any other loops, and remove this dataname from the item order
1232 # if it is present. We always use the canonical lower-case form. Also, the access to self[oldname]
1233 # may trigger a round of evaluation, which we wish to avoid, so we make sure to switch off calculations
1234 # in this case.
1235 #
1236 #
1237 # <Add name to loop>=
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 # check length
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 # remove from any other loops
1257 [self.loops[a].remove(lower_newname) for a in self.loops if lower_newname in self.loops[a]]
1258 # and add to this loop
1259 self.loops[loop_no].append(lower_newname)
1260 # remove from item_order if present
1261 try:
1262 self.item_order.remove(lower_newname)
1263 except ValueError:
1264 pass
1265
1266 # We might also want to remove a packet by key. We operate on the data
1267 # in place, and need access to the low-level information as we have to
1268 # remove both the string and value elements.
1269 #
1270 #
1271 # <Remove a packet>=
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 # The draft DDLm specification uses square brackets next to a
1285 # pre-specified identifier to mean "the packet of this category for
1286 # which the key equals this item". We implement a function which
1287 # fullfils this role for use in the pythonised dREL script. At this
1288 # StarFile level we have no idea as to which data name is the key, so
1289 # that is passed to us from the dictionary processing layer. Note we
1290 # assume a single key rather than multiple keys for this call, and let
1291 # the calling layer handle multiple or missing packets.
1292 #
1293 # We guarantee to return a single packet, or else raise a ValueError.
1294 #
1295 #
1296 # <Get packet by key>=
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 #print("Looking for %s in %s" % (keyvalue, my_loop.parent_block))
1303 #print('Packet check on:' + keyname)
1304 #[print(repr(getattr(a,keyname))) for a in my_loop]
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 # The current version of DDLm allows compound keys. We implement a routine to return
1315 # a single packet corresponding to the values of the specified datanames.
1316 #
1317 #
1318 # <Get packet by compound key>=
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 #print "Looking for %s in %s" % (keyvalue, self.parent_block[keyname])
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 # Plain single key. This is the older routine where we assume that
1338 # we only have a single key per category. We still have to put the
1339 # single key into a list as the __getattr__ method of the StarPacket
1340 # will assume that it has been passed a list of keys.
1341 #
1342 #
1343 # <Get semantic packet by key>=
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] #one only in each list
1354 p = StarPacket()
1355 # set case-sensitivity flag
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: #missing key
1363 try:
1364 test_key = self[cat_key] #generate key if possible
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: #cannot be generated
1371 continue
1372 except ValueError: #none/more than one, assume none
1373 continue
1374 #extra_packet = self.dictionary.generate_default_packet(cat_id,cat_key,keyvalue)
1375 p.merge_packet(extra_packet)
1376 # the following attributes used to calculate missing values
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 # Semantic loops. These are loops defined by a dictionary,
1388 # as opposed to the syntax. dREL requires us to be able to
1389 # extract a packet by key, and then attributes of this packet
1390 # are the individual objects that are found in that category,
1391 # regardless of whether they co-occur in one loop or child
1392 # loops.
1393 #
1394 # We use the dictionary ``cat_key_table'' to give us a list
1395 # of keys for each category. We find the corresponding loops, extract
1396 # any packets meeting the key requirements, and merge these
1397 # packets.
1398 #
1399 # A packet for dREL use will need to be able to derive further
1400 # values using the dictionary, e.g. when an attribute of that
1401 # packet is requested. In order to do this derivation, we need
1402 # to store the key names and values, so that the __getattr__ method
1403 # of the packet can properly derive the needed non-key values.
1404 #
1405 # With a deriving dictionary we run the danger that we will generate
1406 # keys for a child category for which no other values are defined. Such
1407 # keys are pointless as the only information we have is that they come
1408 # from the parent category, and so they can only be copies of the parent
1409 # key, and therefore the child category is identical to the parent
1410 # category as it has the same keys. We therefore do not generate keys
1411 # of child categories; if child category items are present, then the
1412 # key should already be present.
1413 #
1414 # ON the other hand, if the child category keys are present but the parent keys
1415 # are missing, then we in principle know that the child keys are a
1416 # subset of the parent keys, but we cannot use the key to derive any values,
1417 # as the keys are opaque.
1418 #
1419 # The final DDLm specification allowed compound keys for categories. When
1420 # combined with child categories, this means that a child key may be absent
1421 # but its parent key may be present and is considered equivalent.
1422 #
1423 #
1424 # <Get semantic packet by compound key>=
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 #if len(keyvalues)==1: #simplification
1435 # return self.GetKeyedSemanticPacket(keydict[1][0],cat_id)
1436 target_keys = self.dictionary.cat_key_table[cat_id]
1437 # update the dictionary passed to us with all equivalents, for
1438 # simplicity.
1439 parallel_keys = list(zip(*target_keys)) #transpose
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 # target_keys is a list of lists, each of which is a compound key
1448 p = StarPacket()
1449 # a little function to return the dataname for a key
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: #loop down the categories
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: #one or more are missing
1463 continue #should try harder?
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 # the following attributes used to calculate missing values
1471 p.key = true_keys
1472 p.cif_dictionary = self.dictionary
1473 p.fulldata = self
1474 return p
1475
1476
1477 # \section{Output}
1478 #
1479 # The philosophy of outputting strings is to create a StringIO
1480 # object, and pass this between all the routines. As there are
1481 # specific rules about when a new line can occur (especially
1482 # concerning semicolon-delimited strings) we subclass StringIO
1483 # and fiddle with the write method.
1484 #
1485 # The [[grammar]] attribute is consulted to determine what output
1486 # grammar to use.
1487 #
1488 #
1489 # <Functions for printing out>=
1490 # Setting up the output grammar. The output grammar determines the list
1491 # delimiters for CIF2/STAR2, and the available delimiters for 1.0/1.1/2.0, as well as
1492 # the allowed characters
1493 #
1494 #
1495 # <Set the output grammar>=
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 # For non-default output lengths, we include a function which will set
1508 # the internal attribute that controls maximum line length. As this is
1509 # a per-block value, this function is most likely called by the StarFile
1510 # object rather than directly.
1511 #
1512 # Two values control output line formatting: [[self.wraplength]] and
1513 # [[self.maxoutlength]]. [[self.wraplength]] is the value at which the
1514 # line will be wrapped normally, but long strings will not force an
1515 # internal wrap inside the string; [[self.maxoutlength]] is the absolute
1516 # maximum length.
1517 #
1518 #
1519 # <Set the output length>=
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 # Printing a section. We allow an optional order list to be given, in
1530 # case the caller wants to order things in some nice way. By default, we
1531 # use the item_order attribute. Naturally, looped items are grouped
1532 # together according to their order in the order list.
1533 #
1534 # Note that we must be careful to add spaces between data items, especially
1535 # when formatting string loop data, where our string addition could get
1536 # quite hairy. As we are doing so much concatenation, we use a stringIO
1537 # buffer to speed it up.
1538 #
1539 # As an alternative, we may have formatting hints, perhaps from a template that
1540 # we have input through 'process_template'. The formatting hints specify a desired
1541 # column and delimiter, and an order of output. We can always satisfy the output order,
1542 # but may have to fiddle with columns and delimiters depending on the datavalue contents.
1543 # The [[finish_at]] and [[start_from]] arguments cause output to stop/start when one of the
1544 # datanames in the arguments is found.
1545 #
1546 # We attempt some nice formatting by printing non-packet items with an apparent
1547 # tab stop at 40 characters. And of course, we stop providing values.
1548 #
1549 #
1550 # <Print a complete block>=
1551 def printsection(self,instring='',blockstart="",blockend="",indent=0,finish_at='',start_from=''):
1552 self.provide_value = False
1553 # first make an ordering
1554 self.create_ordering(finish_at,start_from) #create self.output_order
1555 # now do it...
1556 if not instring:
1557 outstring = CIFStringIO(target_width=80) # the returned string
1558 else:
1559 outstring = instring
1560 # print block delimiter
1561 outstring.write(blockstart,canbreak=True)
1562 while len(self.output_order)>0:
1563 #print "Remaining to output " + `self.output_order`
1564 itemname = self.output_order.pop(0)
1565 if not isinstance(itemname,int): #no loop
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) #space after itemname
1580 self.format_value(itemvalue,outstring,hints=item_spec)
1581 else:# we are asked to print a loop block
1582 outstring.set_tab(10) #guess this is OK?
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 # Formatting a loop section. We are passed an indent and destination string,
1597 # and are expected to append a list of item names to the string indented by
1598 # the indicated number of spaces. If we have loops, we add those in too.
1599 #
1600 #
1601 # <Format loop names>=
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][:] #copy
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 # Formatting a loop packet. Our final packet will involve collecting
1614 # the ith value of each item in our particular loop. Note that we have
1615 # to be careful with indentation, as the <return>; digraph must be
1616 # recognised.
1617 #
1618 #
1619 # <Format loop packets>=
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 #print 'Alldata: %s' % `alldata`
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 #print 'Packet data: %s' % `packet_data`
1629 #create a dictionary for quick lookup of formatting requirements
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") #new line each packet except first
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 # Formatting a single packet item.
1641 #
1642 #
1643 # <Format a single packet item>=
1644 def format_packet_item(self,pack_item,indent,outstring,format_hint):
1645 # print 'Formatting %s' % `pack_item`
1646 # temporary check for any non-unicode items
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 # Formatting a string. We make sure that the length of the item value
1657 # is less than [[self.maxoutlength]], or else we should split them, and so on. We check the
1658 # value for terminators and impossible apostrophes and length, before
1659 # deciding whether to print it and the item on a single line. We try to
1660 # respect carriage returns in the string, if the caller has tried to do
1661 # the formatting for us. If we are not putting apostrophes around a
1662 # string, we make the first character a space, to avoid problems if the
1663 # first character of a line is a semicolon.
1664 #
1665 # The STAR specification states that embedded quotes are allowed so long
1666 # as they are not followed by a space. So if we find any quotes followed
1667 # by spaces we output a semicolon-terminated string to avoid too much
1668 # messing around. This routine is called very often and could be
1669 # improved.
1670 #
1671 # We have to catch empty strings as well, which are legal. Another gotcha
1672 # concerns 'embedded' strings; if the datavalue begins with a quote, it
1673 # will be output verbatim (and misunderstood) unless spaces elsewhere
1674 # force quotation. Note that non-delimited strings may not start with
1675 # a reserved word ('data','save','global').
1676 #
1677 # The caller is allowed to request a particular delimiter, with 'None'
1678 # corresponding to no delimiter and the choices being apostrophe,
1679 # double quote, or semicolon. CIF2-style triple quotes are not
1680 # currently supported. The 'indent' argument allows the routine to
1681 # enforce indentation of multi-line strings by the specified amount.
1682 # Note that this will technically change the datavalue contents by
1683 # adding spaces, although for datavalues intended only for human
1684 # consumption this is irrelevant.
1685 #
1686 # 'lbprotocol' allows use of the line-breaking protocol from CIF1.1 to
1687 # express long lines, and 'pref_protocol' allows use of the CIF2
1688 # text-prefix protocol.
1689 #
1690 #
1691 # <Format a string>=
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;" #default (most conservative)
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 # we are left with semicolon strings
1716 # use our protocols:
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 # now check for embedded delimiters
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 # Formatting a data value. Data values may be stored as strings, numbers or compound values. We call this routine recursively to format data values. We use [[compound]] to flag that we are an embedded compound value, so that
1730 # we do not insert a line break before the top-level compound delimiter. If hints is supplied, it is a dictionary
1731 # containing an entry 'delimiter' that requests a particular delimiter.
1732 #
1733 #
1734 # <Format a data value>=
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): #not allowed
1741 raise StarError("Non-unicode value {0} found in block".format(itemvalue))
1742 if isinstance(itemvalue,unicode): #need to sanitize
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__')): #numpy
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) #start a new line inside
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) #never break between key and value
1766 stringsink.write('}',unindent=True)
1767 elif isinstance(itemvalue,(float,int,long)) or \
1768 (have_numpy and isinstance(itemvalue,(numpy.number))): #TODO - handle uncertainties
1769 stringsink.write(str(itemvalue),canbreak=True,startcol=startcol) #numbers
1770 else:
1771 raise ValueError('Value in unexpected format for output: {}'.format(repr( itemvalue )))
1772
1773 # Creating a proper ordering for output from the template information. When we output,
1774 # we expect the ordering to consist of a sequence of datanames or loop references. Our
1775 # templated ordering is essentially a list of datanames, so we now have to find which
1776 # loops each dataname corresponds to and adjust each loops ordering accordingly. For
1777 # dictionary use we allow only a segment of the file to be output be specifying a
1778 # finish_at/start_from dataname. For consistency, we default to outputting nothing if
1779 # start_from is not found, and outputting everything if finish_at is not found.
1780 #
1781 #
1782 # <Create a proper ordering>=
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: #in a loop somewhere
1791 target_loop = self.FindLoop(item)
1792 if target_loop not in new_order:
1793 new_order.append(target_loop)
1794 # adjust loop name order
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 # now handle partial output
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 #print('Final order: ' + repr(self.output_order))
1840
1841 # Converting a value to a string.
1842 #
1843 # The canonical version of a value is its string representation. This is different to its
1844 # output format, which will have delimiters and various conventions applied (see below).
1845 #
1846 #
1847 # <Convert value to string>=
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 #already strings
1854 # TODO...something else
1855 return v
1856
1857 # Wrapping a string
1858 #
1859 # If our formatting hints dictionary allows us to reformat a string, *and* the string does
1860 # not contain at least three spaces in a row (implying that it is already formatted), we
1861 # insert appropriate spaces and line feeds.
1862 #
1863 #
1864 # <Do wrapping>=
1865 def do_wrapping(self,instring,indent=3):
1866 """Wrap the provided string"""
1867 if " " in instring: #already formatted
1868 return instring
1869 self.wrapper.initial_indent = ' '*indent
1870 self.wrapper.subsequent_indent = ' '*indent
1871 # remove leading and trailing space
1872 instring = instring.strip()
1873 # split into paragraphs
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 # Merging. Normally merging of dictionaries is done at the data file
1880 # level, i.e. a whole block is replaced or added. However, in 'overlay'
1881 # mode, individual keys are added/replaced, which is a block level
1882 # operation.
1883 #
1884 # Looped item overlaps are tricky. We distinguish two cases: at least
1885 # one key in common, and all keys in common. The latter implies
1886 # addition of rows only. The former implies deletion of all co-occuring
1887 # looped items (as they will otherwise have data of different lengths) and
1888 # therefore either completely replacing the previous item, or adding
1889 # the new data to the end, and including the other co-looped items. But
1890 # this would mean that we were passed a loop block with different data
1891 # lengths in the new object, which is illegal, so we can only add to the
1892 # end if the new dictionary contains a subset of the attributes in the
1893 # current dictionary. Therefore we have the following rules
1894 #
1895 # (1) Identical attributes in new and old -> append
1896 # (2) New contains subset of old -> append values for common items and
1897 # delete extra looped items
1898 # (3) Old contains subset of new -> new completely replaces old
1899 #
1900 # The [[match_att]] keyword is used when old and new blocks have been matched
1901 # based on an internal attribute (usually _name or _item.name). This
1902 # attribute should not become looped in overlay mode, obviously, so we
1903 # need to have a record of it just in case.
1904 #
1905 # The rel_keys keyword contains a list of datanames which act as unique keys (in a database
1906 # sense) inside loop structures. If any keys match in separate datablocks, the row will
1907 # not be added, but simply replaced.
1908 #
1909 #
1910 # <Merge with another block>=
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: #a new dataname
1918 self[key] = new_block[key]
1919 # we get here if there are no keys in common, so we can now copy
1920 # the loops and not worry about overlaps
1921 for one_loop in new_block.loops.values():
1922 self.CreateLoop(one_loop)
1923 # we have lost case information
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) #don't touch the special ones
1930 except ValueError:
1931 pass
1932 for key in new_block.keys():
1933 if isinstance(key,unicode):
1934 self[key] = new_block[key]
1935 # creating the loop will remove items from other loops
1936 for one_loop in new_block.loops.values():
1937 self.CreateLoop(one_loop)
1938 # we have lost case information
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 #ignore this one
1947 new_value = new_block[attribute]
1948 #non-looped items
1949 if new_block.FindLoop(attribute)<0: #not looped
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] #do we have a key?
1955 try:
1956 newkeypos = map(lambda a:newkeys.index(a),loop_keys)
1957 newkeypos = newkeypos[0] #one key per loop for now
1958 loop_keys = loop_keys[0]
1959 except (ValueError,IndexError):
1960 newkeypos = []
1961 overlap_data = map(lambda a:listify(self[a]),overlaps) #old packet data
1962 new_data = map(lambda a:new_block[a],overlaps) #new packet data
1963 packet_data = transpose(overlap_data)
1964 new_p_data = transpose(new_data)
1965 # remove any packets for which the keys match between old and new; we
1966 # make the arbitrary choice that the old data stays
1967 if newkeypos:
1968 # get matching values in new list
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 # filter out any new data with these key values
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 # wipe out the old data and enter the new stuff
1977 byebyeloop = self.GetLoop(overlaps[0])
1978 # print("Removing '%r' with overlaps '%r'" % (byebyeloop, overlaps))
1979 # Note that if, in the original dictionary, overlaps are not
1980 # looped, GetLoop will return the block itself. So we check
1981 # for this case...
1982 if byebyeloop != self:
1983 self.remove_loop(byebyeloop)
1984 self.AddLoopItem((overlaps,overlap_data)) #adding old packets
1985 for pd in new_p_data: #adding new packets
1986 if pd not in packet_data:
1987 for i in range(len(overlaps)):
1988 #don't do this at home; we are appending
1989 #to something in place
1990 self[overlaps[i]].append(pd[i])
1991 self.overwrite = save_overwrite
1992
1993 # \section{Dictionaries}
1994 #
1995 # If a dictionary is attached to a StarBlock, we can use it to provide
1996 # automatic value conversion whenever a value is retrieved.
1997 #
1998 #
1999 # <Working with dictionaries>=
2000 # In DDL1 and DDL2, there is not a whole lot of point associating a DDL
2001 # dictionary with a CIF file in an ongoing way. However, with DDLm the dictionary
2002 # can be used when searching for attributes, so is no longer simply a checking
2003 # mechanism but is now also a generative mechanism. So there are advantages to
2004 # making this assignment for DDLm.
2005 #
2006 # If we are passed a non-DDLm dictionary, we ignore the request as there is
2007 # nothing we can do with it outside the normal validity checking, for which
2008 # a different routine is in place.
2009 #
2010 # Having a dictionary in place also implies that values that are returned are
2011 # automatically converted to the type given in the dictionary.
2012 #
2013 #
2014 # <Assigning a dictionary>=
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 # A StarPacket object looks very much like a list, in order
2028 # to support the DDLm semantics of allowing a particular value to
2029 # be accessed by attribute. DDLm also allows merged categories, which means
2030 # that a packet can contain datanames from the appropriate sub-categories.
2031 #
2032 # Furthermore, a StarPacket can derive missing values by calling the appropriate
2033 # dREL function. To do this, we store the key name used to create the packet.
2034 #
2035 # Note that all attributes must be lower case in order to meet the caseless
2036 # matching required by the STAR/CIF standards.
2037 #
2038 #
2039 # <Star packet class>=
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 # now pick out the new value
2061 # self.key is a list of the key values
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 # \section{BlockCollection}
2067 #
2068 # Starfiles and Ciffiles are both collections of blocks. We abstract
2069 # this into the [[BlockCollection]] class, and then inherit from it to
2070 # make a [[StarFile]] object. The philosophy is that the treatment of
2071 # the constituent blocks is managed by the enclosing block collection
2072 # based on how the block collection was initialised.
2073 #
2074 #
2075 # <BlockCollection class>=
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 # With the advent of CIF2, the allowed character set has expanded to
2107 # encompass most of Unicode. Our object needs to know about this
2108 # different characterset in order to check incoming values and datanames for
2109 # conformance. This is done via the 'characterset' keyword.
2110 #
2111 # DDLm dictionaries assume that all definitions in nested save frames
2112 # are equally accessible from other nested save frames, whereas in
2113 # instance files save frames are logically insulated from other save
2114 # frames at the same or lower levels. Block names may be duplicated if
2115 # they are in different enclosing frames, although all save frame names
2116 # have to be unique within a DDLm dictionary (as importation is allowed
2117 # to refer to the save frame names with no qualifications). We deal
2118 # with potential duplication by appending a '+' to the access key of
2119 # legitimate save frames with duplicate names. Our [[child_table]]
2120 # dictionary links the internal block key to its parent and mixed-case
2121 # name used when outputting the block.
2122 #
2123 # If scoping is 'instance', nested datablocks are invisible and only accessible
2124 # through the 'saves' attribute, which produces a view onto the same block
2125 # collection.
2126 #
2127 # To take account of dictionaries with 10s of thousands of entries
2128 # (e.g. the PDB) we optimise block merging for speed. Most of the
2129 # information in separate structures below could be derived from
2130 # [[child_table]], but we take the space hit for speed. The canonical
2131 # reference to a block is the lowercase version of the name. We use
2132 # these addresses to index into a table that contains the actual block
2133 # name and the parent blockname.
2134 #
2135 #
2136 # <Initialise BC data structures>=
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() # short_cuts
2143 self.renamed = {}
2144 self.PC = collections.namedtuple('PC',['block_id','parent'])
2145 self.child_table = {}
2146 self.visible_keys = [] # for efficiency
2147 self.block_input_order = [] # to output in same order
2148 self.scoping = scoping #will trigger setting of child table
2149 self.blocktype = blocktype
2150 self.master_template = {} #for outputting
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 #reset visibility
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 # Unlocking. When editing dictionaries with many datablocks, we would
2175 # rather just unlock all datablocks at once.
2176 #
2177 #
2178 # <Block collection locking>=
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 # Emulation of a mapping type. We also put odd little useful utilities
2190 # in this section.
2191 #
2192 #
2193 # <BC emulation of mapping type>=
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 #print 'Visible keys:' + `self.visible_keys`
2206 #print 'All keys' + `self.lower_keys`
2207 #print 'Child table' + `self.child_table`
2208 raise KeyError('No such item {}'.format(key))
2209
2210 # we have to get an ordered list of the current keys,
2211 # as we'll have to delete one of them anyway.
2212 # Deletion will delete any key regardless of visibility
2213
2214 def __delitem__(self,key):
2215 dummy = self[key] #raise error if not present
2216 lowerkey = key.lower()
2217 # get rid of all children recursively as well
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] #recursive call
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 # We iterate over all visible
2241 def __iter__(self):
2242 for one_block in self.keys():
2243 yield self[one_block]
2244
2245 # TODO: handle different case
2246 def keys(self):
2247 return self.visible_keys
2248
2249 # Note that has_key does not exist in 3.5
2250 def has_key(self,key):
2251 return key in self
2252
2253 def get(self,key,default=None):
2254 if key in self: # take account of case
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() #all blocks
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 #this sets visible keys
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 # Adding a new block. A new block is just a new item in our
2292 # dictionary, so we add a new entry. We return the new block name
2293 # in case we have changed it, so the calling routine can refer to it
2294 # later. Also, there is a limit of 75 characters for the block name length,
2295 # which we enforce here. By setting [[fix]] to true, blocknames will have
2296 # illegal whitespace changed to underscore.
2297 #
2298 # [[self.standard]] is used to enforce differences in treatments of
2299 # block names. If [[self.standard]] is set at all, blocks will not
2300 # replace a previous block with the same name. DDLm dictionaries
2301 # are not permitted identical save frame names, but those save frame
2302 # names may be identical to the enclosing datablock. We rename the
2303 # access key if an identically-named save frame is introduced
2304 # anywhere in the file by appending a '+'. These renames are stored
2305 # in the rename dictionary. The name appearing in the output file
2306 # is not changed, only the access key. If [[self.standard]] is 'Dic',
2307 # then we put block contents before save frames in accordance with
2308 # stylistic conventions when printing out.
2309 #
2310 # Note that we must take account of upper/lower case differences being irrelevant
2311 # for STAR/CIF, but that we want to preserve the original case.
2312 #
2313 # To allow for nested blocks, we can specify a parent block. When the
2314 # file is printed, the new block will appear inside the parent block if nested
2315 # frames have been requested or if the parent block is a top-level block.
2316 #
2317 # [[blockcontents]] cannot be set immediately to [[StarBlock]] as a default,
2318 # because it will evaluate the constructor once and then assign all new blocks
2319 # to the same object.
2320 #
2321 #
2322 # <Add a new data section>=
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: #already there
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: #can give a new key to this one
2343 while new_lowerbn in self.lower_keys: new_lowerbn = new_lowerbn + '+'
2344 elif parent is not None and new_lowerbn in toplevelnames: #can fix a different one
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 # now continue on to add in the new block
2349 if parent.lower() == new_lowerbn: #the new block's requested parent just got renamed!!
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 #in case calling routine wants to know
2374
2375 # Renaming a block. This is a slightly intricate operation as we have to
2376 # also make sure the original children are pointed to the new blockname. We assume
2377 # that both oldname and newname are already lower case. We can simply change the
2378 # key used to identify the block using [[_rekey]], or we cna change the block name
2379 # that is printed using [[rename]]. In the latter case, there must be no name collisions or the
2380 # operation will fail.
2381 #
2382 #
2383 # <Re-identify a data block>=
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] #old block
2388 is_visible = oldname in self.visible_keys
2389 move_block_info = self.child_table[oldname] #old info
2390 move_block_children = [a for a in self.child_table.items() if a[1].parent==oldname]
2391 # now rewrite the necessary bits
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] #do this after updating child table so we don't delete children
2395 self.dictionary.update({newname:move_block})
2396 self.lower_keys.add(newname)
2397 #print 'Block input order was: ' + `self.block_input_order`
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 # Making a Block Collection from a set of our own block names. This is used
2417 # in merging, where we must merge with a Block Collection. Any pointers to
2418 # parent blocks that are not in the list become None, ie. become top
2419 # level blocks. We use our own child table to find links between the
2420 # supplied block names and ourself. ::
2421 #
2422 #
2423 # <Make a BC from a name list>=
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 # Merging. Originally, this package envisaged Cif and STAR files as collections
2440 # of either Starblocks or Cifblocks, which differed only in their capacity to
2441 # hold save frames and nested loops. From version 4.05, we envisage Cif and Star
2442 # files as collections of StarBlocks, neither of which hold any nested save
2443 # frames. Instead, save frames relationships are held in a separate table,
2444 # which we look up when outputting.
2445 #
2446 # This was originally implemented for dictionary merging support, which is
2447 # now deprecated with the new DDLm way of combining dictionaries. We cannot
2448 # merge [[CifDic]] objects, because the internal data structures for DDL2 and
2449 # DDL1 are different (parent-child in particular), so any merge operation
2450 # would have to first recreate the original Cif structure before proceeding.
2451 #
2452 # Merging can be strict, overlay or replace. In all cases, if the block
2453 # name is different, we simply add it in. If it is the same, in strict
2454 # mode we flag an error, in replace mode we replace it, and in overlay
2455 # mode we actually add/replace individual data items. The default mode
2456 # will be determined from the setting of 'standard': if no standard
2457 # has been specified, the mode is 'replace', otherwise the mode is
2458 # 'strict'.
2459 #
2460 # If the single_block list is non-empty, we assume that we should merge
2461 # on the block level, using the given block names as the particular
2462 # blocks to merge. This is essentially what we have to do for DDL2
2463 # dictionaries, where all the definitions are stored in save frames inside a
2464 # single block.
2465 #
2466 # Note also the related situation where we are in 'strict' mode, and
2467 # the DDL1 dictionaries both have an "on_this_dictionary" block. So we
2468 # have an extra keyword argument "idblock" which contains a blockname
2469 # to ignore during merging, i.e. it will remain the same
2470 # as before merging.
2471 #
2472 # The suggested overlay method involves adding to loops, rather than
2473 # replacing them completely. Identical rows must be removed, and
2474 # any key values with identical values remaining after this have to
2475 # flag an error. We do not read in the ddl specifications themselves,
2476 # to avoid messing around with hard-coded filenames, so we require the calling
2477 # function to provide us with this file (not yet implemented).
2478 #
2479 # The [[match_att]] keyword allows us to match blocks/save frames on a
2480 # particular attribute, rather than the block name itself. This means
2481 # we can do the right thing and compare [[_name]] entries rather than
2482 # block names (the default behaviour).
2483 #
2484 # Note also a problem with the overlay protocol as written up in Vol. G:
2485 # if we try matching on item.name, we will run into trouble where _item.name
2486 # is looped in DDL2-style dictionaries. We cannot match on a complete match
2487 # against all item names in the list, because we would like to be able to add
2488 # item names in overlay mode. So we have to deduce the 'main' item name
2489 # from any parent-child information that we have using a helper function which
2490 # is passed to us.
2491 #
2492 # Nested save frames are emulated through child table lookups, so we should
2493 # merge this table when merging block collections. Unless [[parent]] is
2494 # not empty, we put all new blocks on the same level. Otherwise, any top-level
2495 # blocks in the incoming block collection (parent is None) are given the parent
2496 # specified in [[parent]]. In previous versions this was text, but due to the
2497 # inability to specify to future callers that the name has been changed, [[parent]]
2498 # is now itself a datablock.
2499 #
2500 # As for [[NewBlock]], we allow duplicate save frame names in the precise situation
2501 # where one of the blocks is a top-level block.
2502 #
2503 # The [[drop_att]] attribute allows a particular datablock attribute to be used
2504 # to determine if datablocks are semantically identical.
2505 #
2506 #
2507 # <Merge with another block collection>=
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 #an error will be thrown if we treat as a string
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: #rename our block
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: #we just renamed the prospective parent!
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 #print('Block input order now:' + repr(self.block_input_order))
2547 self.child_table.update(new_bc.child_table)
2548 if parent_name is not None: #redo the child_table entries
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 #default
2567 new_keys = [a[1].block_id for a in new_bc.child_table.items()] #get list of incoming blocks
2568 if match_att:
2569 #make a blockname -> item name map
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 #print `block_to_item`
2575 for key in new_keys: #run over incoming blocknames
2576 if key == idblock: continue #skip dictionary id
2577 basekey = key #default value
2578 if len(match_att)>0:
2579 attval = new_bc[key].get(match_att[0],0) #0 if ignoring matching
2580 else:
2581 attval = 0
2582 for ii in range(len(block_to_item)): #do this way to get looped names
2583 thisatt = block_to_item[ii] #keyname in old block
2584 #print "Looking for %s in %s" % (attval,thisatt)
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) #add the block
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 # print "Merging block %s with %s" % (basekey,key)
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 # Checking conformance. CIF and STAR standards differ in allowing
2605 # nested loops and maximum data name lengths. Although the CIF 1.1
2606 # standard allows very long lines (2048 characters), data names are
2607 # still restricted to be no more than 75 characters in length in the CIF
2608 # standard.
2609 #
2610 #
2611 # <Conformance checks>=
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 # When validating DDL2-type dictionaries against the DDL spec file, we have
2623 # to be able to see all values of parent data items across all save frames
2624 # in order to validate parent-child relations (I have inferred this, but
2625 # if I ever find a standard document this may turn out to be wrong). So this
2626 # method is provided to return a list of all values taken by the given
2627 # attribute within all of the blocks inside a block collection.
2628 #
2629 # A flat list is returned, even if looped values happen to occur in a data
2630 # block. This is because the one routine that calls this method is
2631 # interested in whether or not a given value occurs, rather than how
2632 # it occurs or what it occurs with. We also remove duplicate values.
2633 #
2634 #
2635 # <Collect all values of a single key in all blocks>=
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 # Switch scoping. We interpose some code in the normal [[__setattr__]]
2649 # method so detect a scoping switch. In some cases we want to hide save frames from our accesses,
2650 # in other cases we wish to make all frames visible. Setting the scoping attribute
2651 # allows this to be swapped around.
2652 # We do not assume that no change means we do not have to do anything.
2653 #
2654 #
2655 # <Switch save frame scoping rules>=
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 #only top-level datablocks visible
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 # Parent-child utilities. As we are now emulating parent-child relationships
2668 # using self.child_table, we provide some useful methods.
2669 #
2670 #
2671 # <Parent child utilities>=
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) #get first one
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 # This takes time
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 # first check that both blocks exist
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 #reset visibility
2741
2742 # Output template. We process the template file and immediately set all blocks
2743 # to this value. New blocks will not see this template, so we store the template
2744 # for application after the blocks are created.
2745 #
2746 #
2747 # <Set output template>=
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 # Writing all this stuff out to a string. We loop over each of the
2755 # individual sections, getting their string representation. We
2756 # implement this using the cStringIO module for faster work. Note that
2757 # the default output comment specifies a CIF 1.1 standard file.
2758 #
2759 # Note that child blocks must be save frames, so we hard-code 'save'.
2760 #
2761 # If [[self.grammar]] is '2.0', save frames are not nested and table/list delimiters
2762 # are spaces; if 'STAR2', save frames are nested. We allow the maximum line length
2763 # to be overridden here although preferably the output length is set when
2764 # initialising the file.
2765 #
2766 #
2767 # <Write out to string representation>=
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 # prepare all blocks
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 # loop over top-level
2791 # monitor output
2792 all_names = list(self.child_table.keys()) #i.e. lower case
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': #put contents before save frames
2803 outstring.write(self[blockref].printsection(finish_at='_dictionary_valid.application'))
2804 if self.grammar == 'STAR2': #nested save frames
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'): #non-nested save frames
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': #put contents after save frames
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 # \section{StarFile}
2850 #
2851 # If we are passed a filename, we open it and read it in, assuming that
2852 # it is a conformant STAR file. A StarFile object is a dictionary of
2853 # StarBlock objects, accessed by block name.
2854 # Parameter [[maxoutlength]] sets the maximum line size for output. If
2855 # [[maxoutlength]] is not specified, it defaults to the maximum input
2856 # length.
2857 #
2858 #
2859 # <StarFile class>=
2860 class StarFile(BlockCollection):
2861 # When initialising, we add those parts that are unique to the StarFile as
2862 # opposed to a simple collection of blocks - i.e. reading in from a file,
2863 # and some line length restrictions. We do not indent this section in the
2864 # noweb file, so that our comment characters output at the beginning of the
2865 # line.
2866 #
2867 #
2868 # <Initialise data structures>=
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 # A function to make sure we have the correct file location
2898 #
2899 #
2900 # <Set URI>=
2901 def set_uri(self,my_uri): self.my_uri = my_uri
2902
2903
2904 # We adjust the write method to intelligently output lines, taking
2905 # care with CIF/STAR rules for output. We allow the caller to specify:
2906 # (1) a line break prior to output (e.g. for a new dataname)
2907 # (2) a tab stepsize, in which case we try to pad out to this value
2908 # (3) that we can do a line break if we wish
2909 # (4) moving to a nested indent level, starting from the current position
2910 # (5) Whether or not to align the next item with the tab stops
2911 # (6) The column that this item should start at. If we are past this column, it is ignored.
2912 #
2913 # We never insert newlines inside supplied strings. Tabs are applied
2914 # after any requested line breaks, and both are applied before the next
2915 # item is output. If the character is flagged as a delimiter, it is only
2916 # output if the previous character is not a delimiter or if the next
2917 # character will be a line break.
2918 #
2919 # After adding any line breaks and/or tab stops, we recognise the following situations:
2920 # (1) The supplied string does not overflow the line: we output, and
2921 # update the length of the current line
2922 # (2) The supplied string does overflow the line.
2923 # (i) If we are allowed to break, we output a linefeed, and then the string.
2924 # (ii) Otherwise, we output the string
2925 # (3) The supplied string contains linefeeds: we update the current line length according
2926 # to the number of characters from the beginning of the line.
2927 #
2928 #
2929 # <Subclass StringIO>=
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 # do we need to break?
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: #insert a new line and indent
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: #try to break
2953 if not delimiter and outstring[0]!='\n': #ie <cr>;
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: #assume a break will be forced on next value
2960 output_delimiter = False #the line break becomes the delimiter
2961 #try to match requested column
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 #so that tabbing works as a backup
2970 #handle tabs
2971 if self.tabwidth >0 and do_tab and startcol < 0:
2972 next_stop = ((self.currentpos//self.tabwidth)+1)*self.tabwidth
2973 #print 'Currentpos %d: Next tab stop at %d' % (self.currentpos,next_stop)
2974 if self.currentpos < next_stop:
2975 StringIO.write(self,(next_stop-self.currentpos)*' ')
2976 self.currentpos = next_stop
2977 self.last_char = ' '
2978 #calculate indentation after tabs and col setting applied
2979 if newindent: #indent by current amount
2980 if self.indentlist[-1] == 0: #first time
2981 self.indentlist.append(self.currentpos)
2982 # print 'Indentlist: ' + `self.indentlist`
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 #check that we still need a delimiter
2991 if self.last_char in [' ','\n','\t']:
2992 output_delimiter = False
2993 #now output the string - every invocation comes through here
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 #remember the last character
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 # <Define an error class>=
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 # This is subclassed from AttributeError in order to allow hasattr
3030 # to work.
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 # Reading in a file. We use the Yapps3-generated [[YappsStarParser]]
3039 # module to provide grammar services. The structure returned from
3040 # parsing is a StarFile, with possible grammar violations due to
3041 # duplicate block names.
3042 #
3043 # We allow fast reads using the compiled StarScan module by passing the
3044 # option 'flex' to this routine. We also permit an already-opened
3045 # stream to be passed to us (thanks to Boris Dusek for this
3046 # contribution). There are 3 possible syntax variations: very old CIF
3047 # files allowed unquoted data values to begin with open square brackets,
3048 # version 1.1 disallowed this, and DDLm-conformant files interpret these
3049 # as actual bracket expressions. The different grammars are selected by
3050 # the 'grammar' argument.
3051 #
3052 # We allow reading CBF files, which can contain binary sections, by
3053 # removing all characters found between the strings '-BINARY-FORMAT-SECTION'.
3054 # This is not a robust approach as this string could theoretically be found
3055 # in a comment or datavalue.
3056 #
3057 # We save our URL for possible later use in finding files relative to
3058 # the location of this file e.g. with DDLm dictionary imports.
3059 #
3060 # This function never raises an Exception, instead returning exception
3061 # information in the second argument. The ReadStar function replicates
3062 # older behaviour by examining the return of this function and raising
3063 # an exception if available.
3064 #
3065 # <Read in a STAR file>=
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 # save desired scoping
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 # create an absolute URL
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: # Python > 3.4
3136 my_uri = Path(fullpath).as_uri()
3137 else: # works on Linux/Mac only
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 # print("Full URL is: " + my_uri)
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 #already opened for us
3157 text = filestream.read()
3158 if not isinstance(text,unicode):
3159 try:
3160 text = text.decode('utf-8-sig') #CIF is always ascii/utf8
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: # empty file, return empty block
3169 return prepared.set_uri(my_uri), [0, None, None, None]
3170 # filter out non-ASCII characters in CBF files if required. We assume
3171 # that the binary is enclosed in a fixed string that occurs
3172 # nowhere else.
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 # we recognise ctrl-Z as end of file
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 # honour the header string
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 # Only search for grammar 2.0 if CIF2.0
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 # handle encoding switch
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 # Syntax error
3215 except:
3216 # List that stores information about the syntax error
3217 result = [-1, sys.exc_info()[1], parser, Y]
3218
3219 if proto_star is not None:
3220 proto_star.set_grammar(grammar_name) #remember for output
3221 break
3222 if proto_star is None:
3223 return proto_star, result
3224
3225 # set visibility correctly
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 # Directly raise an error on parsing failure. This was the original
3232 # behaviour of ReadStar
3233 #
3234 # TODO: incorporate a pretty error printer here
3235 #
3236 def ReadStar(*args, **kwargs):
3237 proto_star, result = ReadStarWithError(*args, **kwargs)
3238 if result[0] < 0:
3239 raise StarError(str(result[1])) #to match legacy behaviour
3240 return proto_star
3241
3242 # Dimension of data. This would ordinarily be the number of nested levels,
3243 # and if we have a naked string, we have to return zero.
3244 # We recursively burrow down to the lowest level. If a list is of zero length,
3245 # we cannot burrow any further, so simply return one more than the current level.
3246 #
3247 # We return as well the length of the received packet. Note that we consider
3248 # dataitems which are *not* tuples or lists to be primitive. This includes
3249 # StarLists (which are a single data item) and numpy arrays. Unfortunately
3250 # this means we have to use the ungainly check involving the __class__ property,
3251 # as StarLists and Tuples are subclasses of list and tuple and will therefore
3252 # count as instances of them. In the context of DDLm it is probably more
3253 # elegant to define a special class for looped data rather than for primitive
3254 # lists as data items.
3255 #
3256 # This is a method of the module, rather than belonging to any particular class.
3257 #
3258 #
3259 # <Get data dimension>=
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 # print "Get_dim: %d: %s" % (current,`dataitem`)
3269 return get_dim(dataitem[0],current+1,len(dataitem))
3270 else: return current+1,0
3271
3272 # \section{Utility functions}
3273 #
3274 # These functions do not depend on knowing the internals of the various classes
3275 # and are therefore kept outside of the class definitions to allow general
3276 # use.
3277 #
3278 #
3279 # <Utility functions>=
3280 # \subsection{Line folding protocol}
3281 #
3282 # The line folding protocol allows lines to be broken by appending a backslash as the last
3283 # character of a line. It is signalled by a backslash as the first character of the line
3284 # following an opening semicolon. We use it to introduce line breaks where appropriate. We
3285 # search for whitespace between [[minwraplength]] and [[maxwraplength]], and if none is
3286 # forthcoming we wrap at maxlength-1 (-1 to allow for the backslash).
3287 #
3288 #
3289 # <Apply line folding>=
3290 def apply_line_folding(instring,minwraplength=60,maxwraplength=80):
3291 """Insert line folding characters into instring between min/max wraplength"""
3292 # first check that we need to do this
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" #header
3298 for l in lines:
3299 if len(l) < maxwraplength:
3300 outstring = outstring + l
3301 if len(l) > 0 and l[-1]=='\\': #who'da thunk it? A line ending with a backslash
3302 outstring = outstring + "\\\n" #
3303 outstring = outstring + "\n" # put back the split character
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: #just blindly insert
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] == '\\': #a backslash just happens to be here
3316 outstring = outstring + "\\\n"
3317 outstring = outstring + '\n'
3318 outstring = outstring[:-1] #remove final newline
3319 return outstring
3320
3321 # Believe it or not, a final backslash followed by whitespace is also considered
3322 # to be part of the line folding protocol, even though the last line obviously cannot
3323 # be folded together with the next line as there is no next line.
3324 #
3325 #
3326 # <Remove line folding>=
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 # \subsection{Line indenting}
3335 #
3336 # CIF2 introduces a line indenting protocol for embedding arbitrary
3337 # text strings in a semicolon-delimited string. If the first line ends in
3338 # one or two backslashes, the text before the first backslash defines an
3339 # indent that should appear at the beginning of all subsequent lines. For
3340 # brevity, two backslashes are used to signal that line folding should
3341 # be performed after indenting. Alternatively, the line folding signal
3342 # will simply correspond to a second 'header' line in the indented
3343 # text consisting of the indent followed by a backslash, optional
3344 # whitespace, and a line feed.
3345 #
3346 #
3347 # <Apply line indent>=
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 # Line indents are signalled by one or two backslashes at the end of
3365 # the first line. If this is detected,the text before the backslash is
3366 # removed from every line. We do not use regular expressions for the
3367 # replacement in case the prefix contains significant characters.
3368 #
3369 #
3370 # <Remove line indent>=
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 # keep any line folding instructions
3379 if prefix_match.group('folding')[:2]=='\\\\': #two backslashes
3380 outstring = instring[prefix_match.end('folding')-1:].replace("\n"+prefix_text,"\n")
3381 return "\\" + outstring #keep line folding first line
3382 else:
3383 outstring = instring[prefix_match.end('folding')-1:].replace("\n"+prefix_text,"\n")
3384 return outstring[1:] #drop first line ending, no longer necessary
3385 else:
3386 return instring
3387
3388
3389 # Listify - used to allow uniform treatment of datanames - otherwise sequence functions might
3390 # operate on a string instead of a list.
3391 #
3392 #
3393 # <List manipulations>=
3394 def listify(item):
3395 if isinstance(item,unicode): return [item]
3396 else: return item
3397
3398 #Transpose the list of lists passed to us
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 # This routine optimised to return as quickly as possible
3411 # as it is called a lot.
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 # Numpy arrays are more difficult to check as they don't seem
3424 # to implement automatic Python-style iteration (at least
3425 # matrices don't). So we have to pick up this case while
3426 # attempting to make dependence on Numpy optional.
3427 #
3428 #
3429 # <Check stringiness>=
3430 def check_stringiness(data):
3431 """Check that the contents of data are all strings"""
3432 if not hasattr(data,'dtype'): #so not Numpy
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 #should be data are None :)
3437 else:
3438 for one_item in data:
3439 if not check_stringiness(one_item): return False
3440 return True #all must be strings
3441 else: #numerical python
3442 import numpy
3443 if data.ndim == 0: #a bare value
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 # \subsection{Templating}
3453 #
3454 # A ``template'' is a CifFile containing a single block, where the
3455 # datanames are laid out in the way that the user desires. The layout
3456 # elements that are picked up from the template CifFile are: (1) order
3457 # (2) column position of datavalues (only the first row of a loop block
3458 # counts) (3) delimiters (4) column position of datanames. Within loops
3459 # all items will be indented as for the final name in the loop
3460 # header. The information that is gleaned is converted to entries in the
3461 # formatting_hints table which are then consulted when writing out.
3462 # Note that the order from formatting_hints will override the item_order
3463 # information.
3464 #
3465 # Additionally, if a semicolon-delimited value has a tab or sequence of 2 or
3466 # more spaces after a line ending, it is assumed to be free
3467 # text and the text values will be neatly formatted with the same
3468 # indentation as found after the first line ending in the value.
3469 #
3470 # Constraints on the template:
3471 # (1) There should only ever be one dataname on each line
3472 # (2) loop_ and datablock tokens should appear as the only non-blank
3473 # characters on their lines
3474 # (3) Comments are flagged by a '#' as the first character
3475 # (4) Blank lines are acceptable
3476 # (5) Datavalues should use only alphanumeric characters
3477 # (6) Semicolon-delimited strings are not recognised in loops
3478 #
3479 #
3480 # <Input a guide template>=
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: #a StringIO object
3487 template_file.seek(0) #reset
3488 template_string = template_file.read()
3489 #template_as_lines = template_string.split("\n")
3490 #template_as_lines = [l for l in template_as_lines if len(l)>0 and l[0]!='#']
3491 #template_as_lines = [l for l in template_as_lines if l.split()[0] != 'loop_']
3492 #template_full_lines = dict([(l.split()[0],l) for l in template_as_lines if len(l.split())>0])
3493 form_hints = [] #ordered array of hint dictionaries
3494 find_indent = "^ +"
3495 for item in template_as_cif.item_order: #order of input
3496 if not isinstance(item,int): #not nested
3497 hint_dict = {"dataname":item}
3498 # find the line in the file
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] != ";": #so we need to work out the column number
3508 hint_dict.update({"column":spec_pos})
3509 else: #need to put in the carriage return
3510 hint_dict.update({"delimiter":"\n;"})
3511 # can we format the text?
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"]: #find the indentation
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 #print '%s: %s' % (item,`hint_dict`)
3522 form_hints.append(hint_dict)
3523 else: #loop block
3524 testnames = template_as_cif.loops[item]
3525 total_items = len(template_as_cif.loops[item])
3526 testname = testnames[0]
3527 #find the loop spec line in the file
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 #find the name in the file for name pos
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 #find the value
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 # <API documentation flags>=
3568 #No documentation flags
3569