Debian Codegraph @

src/CifFile_module.py

raw symbols SCIP
1 # \section{Introduction}
2 #
3 # This file implements a general CIF reading/writing utility. The basic
4 # objects ([[CifFile/CifBlock]]) read and write syntactically correct
5 # CIF 1.1 files including save frames. Objects for validating CIFs are
6 # built on these basic objects: A [[CifDic]] object is derived from a
7 # [[CifFile]] created from a DDL1/2 dictionary; and the
8 # [[ValidCifFile/ValidCifBlock]] objects allow creation/checking of CIF
9 # files against a list of CIF dictionaries.
10 #
11 # The [[CifFile]] class is initialised with either no arguments (a new CIF file)
12 # or with the name of an already existing CIF file. Data items are
13 # accessed/changed/added using the python mapping type ie to get
14 # [[dataitem]] you would type [[value = cf[blockname][dataitem]]].
15 #
16 # Note also that a CifFile object can be accessed as a mapping type, ie using
17 # square brackets. Most mapping operations have been implemented (see below).
18 #
19 # We build upon the objects defined in the StarFile class, by imposing a few
20 # extra restrictions where necessary.
21 #
22 #
23 # <*>=
24 # To maximize python3/python2 compatibility
25 from __future__ import print_function
26 from __future__ import unicode_literals
27 from __future__ import division
28 from __future__ import absolute_import
29
30 import collections
31 import ast #for parsing dimension literals
32
33 try:
34 from cStringIO import StringIO
35 except ImportError:
36 from io import StringIO
37
38 # Python 2,3 compatibility
39 try:
40 from urllib import urlopen # for arbitrary opening
41 from urlparse import urlparse, urljoin
42 except:
43 from urllib.request import urlopen
44 from urllib.parse import urlparse, urljoin
45
46 from prettytable import PrettyTable
47
48 # The unicode type does not exist in Python3 as the str type
49 # encompasses unicode. PyCIFRW tests for 'unicode' would fail
50 # Suggestions for a better approach welcome.
51 #
52 # long type no longer exists in Python3, so we alias to int
53 #
54 if isinstance(u"abc",str): #Python3
55 unicode = str
56 long = int
57
58 # <Copyright statement>=
59 __copyright = """
60 PYCIFRW License Agreement (Python License, Version 2)
61 -----------------------------------------------------
62
63 1. This LICENSE AGREEMENT is between the Australian Nuclear Science
64 and Technology Organisation ("ANSTO"), and the Individual or
65 Organization ("Licensee") accessing and otherwise using this software
66 ("PyCIFRW") in source or binary form and its associated documentation.
67
68 2. Subject to the terms and conditions of this License Agreement,
69 ANSTO hereby grants Licensee a nonexclusive, royalty-free, world-wide
70 license to reproduce, analyze, test, perform and/or display publicly,
71 prepare derivative works, distribute, and otherwise use PyCIFRW alone
72 or in any derivative version, provided, however, that this License
73 Agreement and ANSTO's notice of copyright, i.e., "Copyright (c)
74 2001-2014 ANSTO; All Rights Reserved" are retained in PyCIFRW alone or
75 in any derivative version prepared by Licensee.
76
77 3. In the event Licensee prepares a derivative work that is based on
78 or incorporates PyCIFRW or any part thereof, and wants to make the
79 derivative work available to others as provided herein, then Licensee
80 hereby agrees to include in any such work a brief summary of the
81 changes made to PyCIFRW.
82
83 4. ANSTO is making PyCIFRW available to Licensee on an "AS IS"
84 basis. ANSTO MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
85 IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, ANSTO MAKES NO AND
86 DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
87 FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYCIFRW WILL NOT
88 INFRINGE ANY THIRD PARTY RIGHTS.
89
90 5. ANSTO SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYCIFRW
91 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A
92 RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYCIFRW, OR ANY
93 DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
94
95 6. This License Agreement will automatically terminate upon a material
96 breach of its terms and conditions.
97
98 7. Nothing in this License Agreement shall be deemed to create any
99 relationship of agency, partnership, or joint venture between ANSTO
100 and Licensee. This License Agreement does not grant permission to use
101 ANSTO trademarks or trade name in a trademark sense to endorse or
102 promote products or services of Licensee, or any third party.
103
104 8. By copying, installing or otherwise using PyCIFRW, Licensee agrees
105 to be bound by the terms and conditions of this License Agreement.
106
107 """
108
109
110 import re,sys
111 from . import StarFile
112 from .StarFile import StarList #put in global scope for exec statement
113 from . import CifSyntaxError
114 try:
115 import numpy #put in global scope for exec statement
116 from .drel import drel_runtime #put in global scope for exec statement
117 except ImportError:
118 pass #will fail when using dictionaries for calcs
119 from copy import copy #must be in global scope for exec statement
120 import json
121
122 # Decorators. The following decorator keeps track of calls in order to
123 # detect recursion. We raise a special recursion error to allow the
124 # [[derive_item]] method to act accordingly. We also propagate the
125 # first-seen value of 'allow_defaults' recursively, so that the original call can
126 # control whether or not to use default values. Typically methods can
127 # be tried without, and then with, default values, to ensure that all
128 # possibilities for deriving the function are attempted first.
129 #
130 #
131 # <Decorators>=
132 def track_recursion(in_this_func):
133 """Keep an eye on a function call to make sure that the key argument hasn't been
134 seen before"""
135 def wrapper(*args,**kwargs):
136 key_arg = args[1]
137 if key_arg in wrapper.called_list:
138 print('Recursion watch: {} already called {} times'.format(key_arg,wrapper.called_list.count(key_arg)))
139 raise CifRecursionError( key_arg,wrapper.called_list[:]) #failure
140 if len(wrapper.called_list) == 0: #first time
141 wrapper.stored_use_defaults = kwargs.get("allow_defaults",False)
142 print('All recursive calls will set allow_defaults to ' + repr(wrapper.stored_use_defaults))
143 else:
144 kwargs["allow_defaults"] = wrapper.stored_use_defaults
145 wrapper.called_list.append(key_arg)
146 print('Recursion watch: call stack: ' + repr(wrapper.called_list))
147 try:
148 result = in_this_func(*args,**kwargs)
149 except StarFile.StarDerivationError as s:
150 if len(wrapper.called_list) == 1: #no more
151 raise StarFile.StarDerivationFailure(wrapper.called_list[0])
152 else:
153 raise
154 finally:
155 wrapper.called_list.pop()
156 if len(wrapper.called_list) == 0:
157 wrapper.stored_used_defaults = 'error'
158 return result
159 wrapper.called_list = []
160 return wrapper
161
162 # \section{Cif Block class}
163 #
164 # CifBlocks exist(ed) as a separate class in order to enforce non-nested
165 # loops and maximum dataname lengths. As nested loops have been removed
166 # completely from PyCIFRW, they are no longer necessary but kept here for
167 # backwards compatibility.
168 #
169 #
170 # <CifBlock class>=
171 class CifBlock(StarFile.StarBlock):
172 """
173 A class to hold a single block of a CIF file. A `CifBlock` object can be treated as
174 a Python dictionary, in particular, individual items can be accessed using square
175 brackets e.g. `b['_a_dataname']`. All other Python dictionary methods are also
176 available (e.g. `keys()`, `values()`). Looped datanames will return a list of values.
177
178 ## Initialisation
179
180 When provided, `data` should be another `CifBlock` whose contents will be copied to
181 this block.
182
183 * if `strict` is set, maximum name lengths will be enforced
184
185 * `maxoutlength` is the maximum length for output lines
186
187 * `wraplength` is the ideal length to make output lines
188
189 * When set, `overwrite` allows the values of datanames to be changed (otherwise an error
190 is raised).
191
192 * `compat_mode` will allow deprecated behaviour of creating single-dataname loops using
193 the syntax `a[_dataname] = [1,2,3,4]`. This should now be done by calling `CreateLoop`
194 after setting the dataitem value.
195 """
196 # A CifBlock is a StarBlock with a very few restrictions.
197 #
198 #
199 # <Initialise Cif Block>=
200 def __init__(self,data = (), strict = 1, compat_mode=False, **kwargs):
201 """When provided, `data` should be another CifBlock whose contents will be copied to
202 this block.
203
204 * if `strict` is set, maximum name lengths will be enforced
205
206 * `maxoutlength` is the maximum length for output lines
207
208 * `wraplength` is the ideal length to make output lines
209
210 * When set, `overwrite` allows the values of datanames to be changed (otherwise an error
211 is raised).
212
213 * `compat_mode` will allow deprecated behaviour of creating single-dataname loops using
214 the syntax `a[_dataname] = [1,2,3,4]`. This should now be done by calling `CreateLoop`
215 after setting the dataitem value.
216 """
217 if strict: maxnamelength=75
218 else:
219 maxnamelength=-1
220 super(CifBlock,self).__init__(data=data,maxnamelength=maxnamelength,**kwargs)
221 self.dictionary = None #DDL dictionary referring to this block
222 self.compat_mode = compat_mode #old-style behaviour of setitem
223
224 def RemoveCifItem(self,itemname):
225 """Remove `itemname` from the CifBlock"""
226 self.RemoveItem(itemname)
227
228 # The second line in the copy method switches the class of the
229 # returned object to be a CifBlock. It may not be necessary.
230 #
231 #
232 # <Adjust emulation of a mapping type>=
233 def __setitem__(self,key,value):
234 self.AddItem(key,value)
235 # for backwards compatibility make a single-element loop
236 if self.compat_mode:
237 if isinstance(value,(tuple,list)) and not isinstance(value,StarFile.StarList):
238 # single element loop
239 self.CreateLoop([key])
240
241 def copy(self):
242 newblock = super(CifBlock,self).copy()
243 return self.copy.im_class(newblock) #catch inheritance
244
245 # This function was added for the dictionary validation routines. It
246 # will return a list where each member is itself a list of item names,
247 # corresponding to the names in each loop of the file.
248 #
249 #
250 # <Return all looped names>=
251 def loopnames(self):
252 return [self.loops[a] for a in self.loops]
253
254
255 # \section{CifFile}
256 #
257 # A CifFile is subclassed from a StarFile. Our StarFile class has an
258 # optional check of line length, which we use.
259 #
260 # A CifFile object is a dictionary of
261 # CifBlock objects, accessed by block name. As the maximum line length
262 # is subject to change, we allow the length to be specified, with the
263 # current default set at 2048 characters (Cif 1.1). For reading in files,
264 # we only
265 # flag a length error if the parameter [[strict]] is true, in which case
266 # we use parameter [[maxinlength]] as our maximum line length on input.
267 # Parameter [[maxoutlength]] sets the maximum line size for output. If
268 # [[maxoutlength]] is not specified, it defaults to the maximum input
269 # length.
270 #
271 # Note that this applies to the input only. For changing output length,
272 # you can provide an optional parameter in the [[WriteOut]] method.
273 #
274 # allow_partial reads permissively, so that a parsing error will simply
275 # return the CIF file so far, together with the error information. It
276 # is False by default for backwards compatibility.
277 #
278 # <CifFile class>=
279 class CifFile(StarFile.StarFile):
280 # When initialising, we add those parts that are unique to the CifFile as
281 # opposed to a simple collection of blocks - i.e. reading in from a file,
282 # and some line length restrictions. We do not indent this section in this
283 # noweb file, so that our comment characters output at the beginning of the
284 # line.
285 #
286 #
287 # <Initialise data structures>=
288 def __init__(self,datasource=None,strict=1,standard='CIF',from_str=False,
289 allow_partial = False, **kwargs):
290 super(CifFile,self).__init__(datasource=datasource,standard=standard, from_str=from_str, **kwargs)
291 self.strict = strict
292 self.header_comment = \
293 """
294 ##########################################################################
295 # Crystallographic Information Format file
296 # Produced by PyCifRW module
297 #
298 # This is a CIF file. CIF has been adopted by the International
299 # Union of Crystallography as the standard for data archiving and
300 # transmission.
301 #
302 # For information on this file format, follow the CIF links at
303 # http://www.iucr.org
304 ##########################################################################
305 """
306 pr = self.get_parsing_result()
307 if not allow_partial and len(pr) > 0 and pr[0] < 0: #Fail aggressively
308 print_cif_syntax_error(pr, self.my_uri)
309 raise pr[1]
310
311 def get_parsing_result(self):
312 return self.parsing_result
313
314 # DDLm tags have a '.' in their name, whereas the original DDL1
315 # tags do not.
316 #
317 def convert_to_canonical(self, dictionary):
318 """DDLm tags have a '.' in their name, whereas DDL1 tags do
319 not. This routine consults the provided dictionary to find
320 the canonical names for all data names in the data file,
321 and changes them, returning a list of data names that were
322 not found in the dictionary.
323 """
324
325 tags_without_alias = []
326 for block_name, block_contents in self.items():
327
328 for tag, value in block_contents.items():
329 # The tag does not have any point
330 # The tag is DDL1
331 tag_definition = dictionary.get(tag, None)
332
333 if tag_definition is None:
334 tags_without_alias.append(tag)
335 continue
336
337 tag_name_ddlm = tag_definition.get("_definition.id").lower()
338
339 # The tag of the definition and the one that appears in the cif
340 # file are different. Therefore the tag in the cif is an alias.
341 if tag_name_ddlm != tag:
342 # Add a new block with the proper tag
343 self[block_name].ChangeTagName(tag, tag_name_ddlm)
344
345 return tags_without_alias
346
347 def to_json(self):
348 cif_dict = {}
349
350 # Add meta data
351 cif_dict['filename'] = self.my_uri
352 cif_dict['version'] = self.grammar
353
354 tags_dict = {}
355 for key in self.keys():
356 datablock_dict = {}
357 datablock = self[key]
358
359 for tag in datablock.keys():
360 value = self[key][tag]
361 datablock_dict[tag] = value
362
363 tags_dict[key] = datablock_dict
364
365 cif_dict['tags'] = tags_dict
366 cif_json = json.dumps(cif_dict, indent=2)
367
368 return cif_json
369
370 # Defining an error class: we simply derive a 'nothing' class from the root
371 # Python class
372 #
373 #
374 # <Define an error class>=
375
376 class CifError(Exception):
377 def __init__(self,value):
378 self.value = value
379 def __str__(self):
380 return '\nCif Format error: '+ self.value
381
382 class ValidCifError(Exception):
383 def __init__(self,value):
384 self.value = value
385 def __str__(self):
386 return '\nCif Validity error: ' + self.value
387
388 class CifRecursionError(Exception):
389 def __init__(self,key_value,call_stack):
390 self.key_value = key_value
391 self.call_stack = call_stack
392 def __str__(self):
393 return "Derivation has recursed, {} seen twice (call stack {})".format(self.key_value,repr(self.call_stack))
394
395
396 # \section {Dictionaries}
397 #
398 # To avoid ambiguity with the Python dictionary type, we use capital
399 # D to denote CIF Dictionaries where misinterpretation is possible.
400 #
401 # We build our Dictionary behaviour on top of the StarFile object, which
402 # is notionally a collection of StarBlocks. A Dictionary is simply a
403 # collection of datablocks, where each datablock corresponds to a single
404 # definition. DDL1 had no category definitions.
405 #
406 # We adopt a data model whereby the excess information in a DDL2
407 # dictionary is absorbed into special methods (and I am thinking here
408 # of the [[_item_type_list.construct]] stuff which appears at the
409 # global level), which we initialise ourselves for a DDL1 dictionary.
410 #
411 # The square bracket notation is repurposed to mean access to the
412 # appropriate definition, as the save frame name and the definition
413 # may be slightly (or completely) different.
414 #
415 #
416 # <CIF Dictionary type>=
417 # \subsection {Dictionary blocks}
418 #
419 # A dictionary block is essentially identical to a StarBlock, with
420 # the extra semantics of chasing through `_import.get` calls in
421 # order to transparently return attributes defined in separate
422 # dictionaries. If the `_import_cache` is empty, this is skipped.
423 #
424 #
425 # <Dictionary block type>=
426 class DicBlock(StarFile.StarBlock):
427 """A definition block within a dictionary, which allows imports
428 to be transparently followed"""
429
430 def __init__(self,*args,**kwargs):
431 super(DicBlock,self).__init__(*args,**kwargs)
432 self._import_cache = {}
433
434 def __getitem__(self,dataname):
435 value = None
436 if super(DicBlock,self).has_key("_import.get") and self._import_cache:
437 value = self.follow_import(super(DicBlock,self).__getitem__("_import.get"),dataname)
438 try:
439 final_value = super(DicBlock,self).__getitem__(dataname)
440 except KeyError: #not there
441 final_value = value
442 if final_value is None:
443 raise KeyError("{} not found".format(dataname))
444 return final_value
445
446 #
447 # We cannot just do `key in self` as we need to mirror
448 # the logic in __getitem__
449 #
450 def has_key(self,key):
451 try:
452 self[key]
453 except KeyError:
454 return False
455 return True
456
457 def add_dict_cache(self,name,cached):
458 """Add a loaded dictionary to this block's cache"""
459 self._import_cache[name]=cached
460
461 def follow_import(self,import_info,dataname):
462 """Find the dataname values from the imported dictionary. `import_info`
463 is a list of import locations"""
464 latest_value = None
465 for import_ref in import_info:
466 file_loc = import_ref["file"]
467 if file_loc not in self._import_cache:
468 raise ValueError("Dictionary for import {} not found".format(file_loc))
469 import_from = self._import_cache[file_loc]
470 miss = import_ref.get('miss','Exit')
471 target_key = import_ref["save"]
472 try:
473 import_target = import_from[target_key]
474 except KeyError:
475 if miss == 'Exit':
476 raise CifError('Import frame {} not found in {}'.format(target_key,file_loc))
477 else: continue
478 # now import appropriately
479 mode = import_ref.get("mode",'Contents').lower()
480 if mode == "contents": #only this is used at this level
481 latest_value = import_target.get(dataname,latest_value)
482 return latest_value
483
484 class CifDic(StarFile.StarFile):
485 """Create a Cif Dictionary object from the provided source, which can
486 be a filename/URL or a CifFile. Optional arguments (relevant to DDLm
487 only):
488
489 * do_minimum (Boolean):
490 Do not set up the dREL system for auto-calculation or perform
491 imports. This implies do_imports=False and do_dREL=False
492
493 * do_imports = No/Full/Contents/All:
494 If not 'No', intepret _import.get statements for
495 Full mode/Contents mode/Both respectively. See also option 'heavy'
496
497 * do_dREL = True/False:
498 Parse and convert all dREL methods to Python. Implies do_imports=All
499
500 * heavy = True/False:
501 (Experimental). If True, importation overwrites definitions. If False,
502 attributes are resolved dynamically.
503 """
504 # \subsection {Initialisation}
505 #
506 # We want to be able to accept strings, giving the file name
507 # of the CIF dictionary, and pre-initialised [[CifFile]] objects. We do
508 # not accept [[CifDic]] objects. Our initialisation procedure
509 # first unifies the interface to the Dictionary, and then runs through the
510 # Dictionary producing a normalised form. Following this, type
511 # and category information can be collected for later reference.
512 #
513 # Validation functions are listed so that it would be possible to
514 # add and remove them from the "valid set". This behaviour has
515 # not yet been implemented.
516 #
517 # When loading DDLm dictionaries we may recursively call this
518 # initialisation function with a dictionary to be imported as the
519 # argument. In this case we do not want to do all the method derivation,
520 # as the necessary categories will be loaded into the calling dictionary
521 # rather than the currently initialising dictionary. So there is a
522 # keyword argument to stop the operations that should operate on the
523 # dictionary as a whole taking place.
524 #
525 # The dREL methods require Numpy support, but we do not wish to introduce
526 # a global dependence on Numpy. Therefore, we introduce a 'switch' which
527 # will return Numpy arrays from the __getitem__ method instead of StarLists.
528 # It is intended that the dREL methods will turn this on only during
529 # execution, then turn it off afterwards.
530 #
531 # Note that DDLm importation logic provides many choices. We have a choice
532 # of 'No', 'Contents', 'Full' and 'All' for the amount that is imported. If
533 # `heavy` is False, no definition material will be replaced, rather the
534 # import will be resolved dynamically.
535 #
536 #
537 # <Initialise Cif dictionary>=
538 def __init__(self,dic,do_minimum=False,do_imports='All', do_dREL=True,
539 grammar='auto',heavy=True,verbose_import=True,verbose_validation=True,**kwargs):
540 self.do_minimum = do_minimum
541 if do_minimum:
542 do_imports = 'No'
543 do_dREL = False
544 if do_dREL: do_imports = 'All'
545 if heavy == 'Light' and do_imports not in ('contents','No'):
546 raise(ValueError,"Light imports only available for mode 'contents'")
547 self.template_cache = {} #for DDLm imports
548 self.ddlm_functions = {} #for DDLm functions
549 self.switch_numpy(False) #no Numpy arrays returned
550 super(CifDic,self).__init__(datasource=dic,grammar=grammar,blocktype=DicBlock,**kwargs)
551 self.verbose_import=verbose_import
552 self.verbose_validation=verbose_validation
553 self.standard = 'Dic' #for correct output order
554 self.scoping = 'dictionary'
555 (self.dicname,self.dicversion,self.diclang) = self.dic_determine()
556 if self.verbose_import:
557 print('{} is a {} dictionary'.format(self.dicname,self.diclang))
558 self.scopes_mandatory = {}
559 self.scopes_naughty = {}
560 self._import_dics = [] #Non-empty for DDLm only
561 # rename and expand out definitions using "_name" in DDL dictionaries
562 if self.diclang == "DDL1":
563 self.DDL1_normalise() #this removes any non-definition entries
564 self.create_def_block_table() #From now on, [] uses definition_id
565 if self.diclang == "DDL1":
566 self.ddl1_cat_load()
567 elif self.diclang == "DDL2":
568 self.DDL2_normalise() #iron out some DDL2 tricky bits
569 elif self.diclang == "DDLm":
570 self.scoping = 'dictionary' #expose all save frames
571 self._import_dics = self.get_dictionaries_to_import()
572 if do_imports != 'No':
573 self.obtain_imports(import_mode=do_imports,heavy=heavy)#recursively calls this routine
574 self.create_alias_table()
575 self.create_cat_obj_table()
576 self.create_cat_key_table()
577 if do_dREL:
578 print('Doing full dictionary initialisation')
579 self.initialise_drel()
580 self.add_category_info(full=do_dREL)
581 # initialise type information
582 self.typedic={}
583 self.primdic = {} #typecode<->primitive type translation
584 self.add_type_info()
585 self.install_validation_functions()
586
587 def add_alias_blocks(self):
588 '''
589 Function to add alias tags to the dictionary. If a datablock has the "_alias.definition_id" tag,
590 a new datablock is created with the same information of the original datablock.
591
592 It requires the dictionary to be fully formed.
593 '''
594 # Retrieve all the alias blocks
595 data_blocks_to_edit = []
596 for block_name in self.keys():
597 block = self[block_name]
598
599 if "_alias.definition_id" in block.keys():
600 data_blocks_to_edit.append(block_name)
601
602 # Add the alias blocks to the dictionary
603 for data_block in data_blocks_to_edit:
604 alias_temp = self[data_block]["_alias.definition_id"]
605 contents = self[data_block]
606
607 # Remove alias tag from original datablock ?
608 #del self[data_block]["_alias.definition_id"]
609
610 if isinstance(alias_temp, list):
611 for alias in alias_temp:
612 #contents["_definition.id"] = alias.lower()
613 #self[alias.lower()] = contents
614 self.NewBlock(alias.lower(), contents)
615 self.block_id_table[alias.lower()] = alias.lower()
616
617 else:
618 # Keep the DDLm version of the tag
619 #contents["_definition.id"] = alias_temp.lower()
620 #self[alias_temp.lower()] = contents
621 self.NewBlock(alias_temp.lower(), contents)
622 self.block_id_table[alias_temp.lower()] = alias_temp.lower()
623
624 return self
625
626 # These routines seek to impose a uniform structure on dictionaries
627 # written in DDL1, DDL2 and DDLm. Historically, the richer and more
628 # systematic DDL2 approach was used to describe DDL1 definitions. With
629 # the advent of DDLm, the DDLm paradigm is likely to overtake DDL2. When
630 # interpreting the following routines, therefore, bear in mind that they
631 # were originally written with DDL2 in mind, and are gradually shifting
632 # to DDLm.
633 #
634 #
635 # <DDL-specific initialisation routines>=
636 # This function determines whether we have a DDLm, DDL2 or DDL1 dictionary. We are
637 # built from a [[CifFile]] object. The current method looks for an
638 # [[on_this_dictionary]] block, which implies DDL1, or a single block,
639 # which implies DDL2/DDLM. This is also where we define some universal
640 # keys for uniform access to DDL attributes.
641 #
642 #
643 # <Dictionary determination function>=
644
645 def dic_determine(self):
646 if "on_this_dictionary" in self:
647 self.master_block = super(CifDic,self).__getitem__("on_this_dictionary")
648 self.def_id_spec = "_name"
649 self.cat_id_spec = "_category.id" #we add this ourselves
650 self.type_spec = "_type"
651 self.enum_spec = "_enumeration"
652 self.cat_spec = "_category"
653 self.esd_spec = "_type_conditions"
654 self.must_loop_spec = "_list"
655 self.must_exist_spec = "_list_mandatory"
656 self.list_ref_spec = "_list_reference"
657 self.key_spec = "_list_mandatory"
658 self.unique_spec = "_list_uniqueness"
659 self.child_spec = "_list_link_child"
660 self.parent_spec = "_list_link_parent"
661 self.related_func = "_related_function"
662 self.related_item = "_related_item"
663 self.primitive_type = "_type"
664 self.dep_spec = "xxx"
665 self.cat_list = [] #to save searching all the time
666
667 # Categories to which their loop id uniqueness validation
668 # needs to be avoided due to dictionary ambiguities
669 self.black_list_categories = {
670 'refln',
671 'diffrn_refln',
672 'diffrn_standard_refln',
673 'exptl_crystal_face',
674 'geom_bond',
675 'geom_angle',
676 'geom_contact',
677 'geom_hbond',
678 'geom_torsion'
679 }
680 name = super(CifDic,self).__getitem__("on_this_dictionary")["_dictionary_name"]
681 version = super(CifDic,self).__getitem__("on_this_dictionary")["_dictionary_version"]
682 return (name,version,"DDL1")
683 elif len(self.get_roots()) == 1: # DDL2/DDLm
684 self.master_block = super(CifDic,self).__getitem__(self.get_roots()[0][0])
685 # now change to dictionary scoping
686 self.scoping = 'dictionary'
687 name = self.master_block["_dictionary.title"]
688 version = self.master_block["_dictionary.version"]
689 if self.master_block.has_key("_dictionary.class"): #DDLm
690 self.enum_spec = '_enumeration_set.state'
691 self.key_spec = '_category.key_id'
692 self.must_exist_spec = None
693 self.cat_spec = '_name.category_id'
694 self.primitive_type = '_type.contents'
695 self.cat_id_spec = "_definition.id"
696 self.def_id_spec = "_definition.id"
697 self.unique_spec = "_category_key.name"
698 self.alias_spec = "_alias.definition_id"
699 self.related_func = "_definition_replaced.by"
700 # Categories to which their loop id uniqueness validation
701 # needs to be avoided due to dictionary ambiguities
702 self.black_list_categories = {
703 'publ_author'
704 }
705 return(name,version,"DDLm")
706 else: #DDL2
707 self.cat_id_spec = "_category.id"
708 self.def_id_spec = "_item.name"
709 self.key_spec = "_category_mandatory.name"
710 self.type_spec = "_item_type.code"
711 self.enum_spec = "_item_enumeration.value"
712 self.esd_spec = "_item_type_conditions.code"
713 self.cat_spec = "_item.category_id"
714 self.loop_spec = "there_is_no_loop_spec!"
715 self.must_loop_spec = "xxx"
716 self.must_exist_spec = "_item.mandatory_code"
717 self.child_spec = "_item_linked.child_name"
718 self.parent_spec = "_item_linked.parent_name"
719 self.related_func = "_item_related.function_code"
720 self.related_item = "_item_related.related_name"
721 self.unique_spec = "_category_key.name"
722 self.list_ref_spec = "xxx"
723 self.primitive_type = "_type"
724 self.alias_spec = "_alias.definition_id"
725 self.dep_spec = "_item_dependent.dependent_name"
726 return (name,version,"DDL2")
727 else:
728 raise CifError("Unable to determine dictionary DDL version")
729
730 # DDL1 differences. Firstly, in DDL1 you can loop a [[_name]] to get
731 # definitions of related names (e.g. x,y,z). Secondly, the data block
732 # name is missing the initial underscore, so we need to read the [[_name]]
733 # value. There is one block without a [[_name]] attribute, which we
734 # proceed to destroy (exercise for the reader: which one?).
735 #
736 # A further complex difference is in the way that ranges are specified.
737 # A DDL2 dictionary generally loops the [[_item_range.maximum/minimum]]
738 # items, in order to specify inclusion of the endpoints of the range,
739 # whereas DDL1 dictionaries simply specify ranges as [[n:m]]. We
740 # translate these values into [[item_range]] specifications.
741 #
742 # If the [[_list]] item is missing for a dictionary definition, it defaults
743 # to no, i.e. the item cannot be listed. We explicitly include this in
744 # our transformations.
745 #
746 # The dictionaries also contain categories, which are used to impose
747 # constraints on groupings of items in lists. Category names in DDL2
748 # dictionaries have no leading underscore, and the constraints
749 # are stored directly in the category definition. So, with a DDL1
750 # dictionary, we rewrite things to match the DDL2 methods. In
751 # particular, the [[list_uniqueness]] item becomes the [[category_key.name]]
752 # attribute of the category. This may apply to [[_list_mandatory]] and
753 # /or [[_list_reference]] to, but the current specification is vague.
754 #
755 # Also, it is possible for cross-item references (e.g. in a
756 # [[_list_reference]])
757 # to include a whole range of items by terminating the name with an
758 # underscore. It is then understood to include anything starting with
759 # those characters. We explicitly try to expand these references out.
760 #
761 # Note the way we convert to DDL2-style type definitions; any definition
762 # having a _type_construct regular expression triggers the definition of
763 # a whole new type, which is stored as per DDL2, for the later type
764 # dictionary construction process to find.
765 #
766 #
767 # <Deal with DDL1 differences>=
768 def DDL1_normalise(self):
769 # switch off block name collision checks
770 self.standard = None
771 # add default type information in DDL2 style
772 # initial types and constructs
773 base_types = ["char","numb","null"]
774 prim_types = base_types[:]
775 base_constructs = [".*",
776 '(-?(([0-9]*[.][0-9]+)|([0-9]+)[.]?)([(][0-9]+[)])?([eEdD][+-]?[0-9]+)?([(][0-9]+[)])?)|\\?|\\.',
777 "\"\" "]
778 for key,value in self.items():
779 newnames = [key] #keep by default
780 if "_name" in value:
781 real_name = value["_name"]
782 if isinstance(real_name,list): #looped values
783 for looped_name in real_name:
784 new_value = value.copy()
785 new_value["_name"] = looped_name #only looped name
786 self[looped_name] = new_value
787 newnames = real_name
788 else:
789 self[real_name] = value
790 newnames = [real_name]
791 # delete the old one
792 if key not in newnames:
793 del self[key]
794 # loop again to normalise the contents of each definition
795 for key,value in self.items():
796 #unlock the block
797 save_overwrite = value.overwrite
798 value.overwrite = True
799 # deal with a missing _list, _type_conditions
800 if "_list" not in value: value["_list"] = 'no'
801 if "_type_conditions" not in value: value["_type_conditions"] = 'none'
802 # deal with enumeration ranges
803 if "_enumeration_range" in value:
804 max,min = self.getmaxmin(value["_enumeration_range"])
805 if min == ".":
806 self[key].AddLoopItem((("_item_range.maximum","_item_range.minimum"),((max,max),(max,min))))
807 elif max == ".":
808 self[key].AddLoopItem((("_item_range.maximum","_item_range.minimum"),((max,min),(min,min))))
809 else:
810 self[key].AddLoopItem((("_item_range.maximum","_item_range.minimum"),((max,max,min),(max,min,min))))
811 #add any type construct information
812 if "_type_construct" in value:
813 base_types.append(value["_name"]+"_type") #ie dataname_type
814 base_constructs.append(value["_type_construct"]+"$")
815 prim_types.append(value["_type"]) #keep a record
816 value["_type"] = base_types[-1] #the new type name
817
818 #make categories conform with ddl2
819 #note that we must remove everything from the last underscore
820 if value.get("_category",None) == "category_overview" \
821 and value.get("_name",None) is not None:
822 last_under = value["_name"].rindex("_")
823
824 # Take into account the bracket
825 if "]" in value["_name"]:
826 last_under = len(value["_name"])
827
828 catid = value["_name"][1:last_under]
829 value["_category.id"] = catid #remove square bracks
830 if catid not in self.cat_list: self.cat_list.append(catid)
831 value.overwrite = save_overwrite
832 # we now add any missing categories before filling in the rest of the
833 # information
834 for key,value in self.items():
835 #print('processing ddl1 definition %s' % key)
836 if "_category" in self[key]:
837 if self[key]["_category"] not in self.cat_list:
838 # rogue category, add it in
839 newcat = self[key]["_category"]
840 fake_name = "_" + newcat + "_[]"
841 newcatdata = CifBlock()
842 newcatdata["_category"] = "category_overview"
843 newcatdata["_category.id"] = newcat
844 newcatdata["_type"] = "null"
845 self[fake_name] = newcatdata
846 self.cat_list.append(newcat)
847 # write out the type information in DDL2 style
848 self.master_block.AddLoopItem((
849 ("_item_type_list.code","_item_type_list.construct",
850 "_item_type_list.primitive_code"),
851 (base_types,base_constructs,prim_types)
852 ))
853
854 # Loading the DDL1 categories with DDL2-type information. DDL2 people wisely
855 # put category-wide information in the category definition rather than
856 # spreading it out between category items. We collect this information together
857 # here.
858 #
859 # This routine is the big time-waster in initialising a DDL1 dictionary, so we have
860 # attempted to optimize it by locally defining functions, instead of using lambdas,
861 # and making one loop through the dictionary instead of hundreds.
862 #
863 #
864 # <Load categories with DDL2-type information>=
865 def ddl1_cat_load(self):
866 deflist = self.keys() #slight optimization
867 cat_mand_dic = {}
868 cat_unique_dic = {}
869 # a function to extract any necessary information from each definition
870 def get_cat_info(single_def):
871 if self[single_def].get(self.must_exist_spec)=='yes':
872 thiscat = self[single_def]["_category"]
873 curval = cat_mand_dic.get(thiscat,[])
874 curval.append(single_def)
875 cat_mand_dic[thiscat] = curval
876 # now the unique items...
877 # cif_core.dic throws us a curly one: the value of list_uniqueness is
878 # not the same as the defined item for publ_body_label, so we have
879 # to collect both together. We assume a non-listed entry, which
880 # is true for all current (May 2005) ddl1 dictionaries.
881 if self[single_def].get(self.unique_spec,None)!=None:
882 thiscat = self[single_def]["_category"]
883 new_unique = self[single_def][self.unique_spec]
884 uis = cat_unique_dic.get(thiscat,[])
885 if single_def not in uis: uis.append(single_def)
886 if new_unique not in uis: uis.append(new_unique)
887 cat_unique_dic[thiscat] = uis
888
889 [get_cat_info(a) for a in deflist] # apply the above function
890 for cat in cat_mand_dic.keys():
891 self[cat]["_category_mandatory.name"] = cat_mand_dic[cat]
892 for cat in cat_unique_dic.keys():
893 self[cat]["_category_key.name"] = cat_unique_dic[cat]
894
895 # DDL2 has a few idiosyncracies of its own. For some reason, in the
896 # definition of a parent item, all the child items are listed and their
897 # mandatory/not mandatory status specified. This duplicates information
898 # under the child item itself, although there is something on the web
899 # indicating
900 # that this is purely cosmetic and not strictly necessary. For our purposes, we want to extract
901 # the mandatory/not mandatory nature of the current item, which appears
902 # to be conventionally at the top of the list (we do not assume this below).
903 # The only way of determining what the actual item name is is to look at
904 # the save frame name, which is a bit of a fragile tactic - especially
905 # as dictionary merge operations are supposed to look for _item.name.
906 #
907 # So, in these cases, we have to assume the save frame name is the one we
908 # want, and find this entry in the list.
909 #
910 # Additionally, the child entry doesn't contain the category specification,
911 # so we add this into the child entry at the same time, together with a
912 # pointer to the parent item.
913 #
914 # Such entries then have a loop listing parents and children down the whole
915 # hierarchy, starting with the current item. We disentangle this, placing
916 # parent item attributes in the child items, moving sub-children down to
917 # their level. Sub children may not exist at all, so we create them if
918 # necessary.
919 #
920 # To make life more interesting, the PDBX have an entry_pc placeholder in
921 # which additional (and sometimes repeated) parent-child relationships
922 # can be expressed. We cannot assume that any given parent-child relationship
923 # is stated at a single site in the file. What is more, it appears that
924 # multiple parents for a single child are defined in the _entry.pdbx_pc entry.
925 # Our changes to the file pre-checking are therefore restricted to making
926 # sure that the child contains information about the parents; we do not
927 # interfere with the parent's information about the children, even if we
928 # consider that to be superfluous. Note that we will have to add
929 # parent-child validity checks to check consistency among all these
930 # relationships.
931 #
932 # Update: in the DDL-2.1.6 file, only the parents/children are looped,
933 # rather than the item names, so we have to check looping separately.
934 #
935 # Next: DDL2 contains aliases to DDL1 item names, so in theory we should be
936 # able to use a DDL2 dictionary to validate a DDL1-style CIF file. We
937 # create separate definition blocks for each alias to enable this.
938 #
939 # Also, we flatten out any single-element lists for item_name. This is
940 # simply to avoid the value of e.g. category_id being a single-element list
941 # instead of a string.
942 #
943 # Note also that _item.category_id in DDL2 is 'implicit', meaning in this case
944 # that you can determine it from the item name. We add in the category for
945 # simplicity.
946 #
947 #
948 # <Iron out DDL2 strangeness>=
949 # In order to handle parent-child relationships in a regular way, we want to assume
950 # that all parent-child entries occur in a loop, with both members present. This
951 # routine does that for us. If the parent is missing, it is assumed to be the
952 # currently-defined item. If the child is missing, likewise.
953 #
954 #
955 # <Loopify parent-child relationships>=
956 def create_pcloop(self,definition):
957 old_children = self[definition].get('_item_linked.child_name',[])
958 old_parents = self[definition].get('_item_linked.parent_name',[])
959 if isinstance(old_children,unicode):
960 old_children = [old_children]
961 if isinstance(old_parents,unicode):
962 old_parents = [old_parents]
963 if (len(old_children)==0 and len(old_parents)==0) or \
964 (len(old_children) > 1 and len(old_parents)>1):
965 return
966 if len(old_children)==0:
967 old_children = [definition]*len(old_parents)
968 if len(old_parents)==0:
969 old_parents = [definition]*len(old_children)
970 newloop = CifLoopBlock(dimension=1)
971 newloop.AddLoopItem(('_item_linked.parent_name',old_parents))
972 newloop.AddLoopItem(('_item_linked.child_name',old_children))
973 try:
974 del self[definition]['_item_linked.parent_name']
975 del self[definition]['_item_linked.child_name']
976 except KeyError:
977 pass
978 self[definition].insert_loop(newloop)
979
980
981
982 def DDL2_normalise(self):
983 listed_defs = filter(lambda a:isinstance(self[a].get('_item.name'),list),self.keys())
984 # now filter out all the single element lists!
985 dodgy_defs = filter(lambda a:len(self[a]['_item.name']) > 1, listed_defs)
986 for item_def in dodgy_defs:
987 # As some DDL2 dictionaries neglect children, we repopulate the skeleton or non-existent definitions that
988 # may be provided in the dictionary.
989 #
990 #
991 # <Repopulate child definitions>=
992 # print("DDL2 norm: processing %s" % item_def)
993 thisdef = self[item_def]
994 packet_no = thisdef['_item.name'].index(item_def)
995 realcat = thisdef['_item.category_id'][packet_no]
996 realmand = thisdef['_item.mandatory_code'][packet_no]
997 # first add in all the missing categories
998 # we don't replace the entry in the list corresponding to the
999 # current item, as that would wipe out the information we want
1000 for child_no in range(len(thisdef['_item.name'])):
1001 if child_no == packet_no: continue
1002 child_name = thisdef['_item.name'][child_no]
1003 child_cat = thisdef['_item.category_id'][child_no]
1004 child_mand = thisdef['_item.mandatory_code'][child_no]
1005 if child_name not in self:
1006 self[child_name] = CifBlock()
1007 self[child_name]['_item.name'] = child_name
1008 self[child_name]['_item.category_id'] = child_cat
1009 self[child_name]['_item.mandatory_code'] = child_mand
1010 self[item_def]['_item.name'] = item_def
1011 self[item_def]['_item.category_id'] = realcat
1012 self[item_def]['_item.mandatory_code'] = realmand
1013
1014 # Populating parent and child links. The DDL2 model uses parent-child relationships
1015 # to create relational database behaviour. This means that the emphasis is on simply
1016 # linking two ids together directionally. This link is not necessarily inside a definition that
1017 # is being linked, but we require that any parents and children are identified within the
1018 # definition that they relate to. This means we have to sometimes relocate and expand links.
1019 # As an item can simultaneously be both a parent and a child, we need to explicitly fill in
1020 # the links even within a single definition.
1021 #
1022 #
1023 # <Populate parent and child links correctly>=
1024 target_defs = [a for a in self.keys() if '_item_linked.child_name' in self[a] or \
1025 '_item_linked.parent_name' in self[a]]
1026 # now dodgy_defs contains all definition blocks with more than one child/parent link
1027 for item_def in dodgy_defs: self.create_pcloop(item_def) #regularise appearance
1028 for item_def in dodgy_defs:
1029 print('Processing {}'.format(item_def))
1030 thisdef = self[item_def]
1031 child_list = thisdef['_item_linked.child_name']
1032 parents = thisdef['_item_linked.parent_name']
1033 # for each parent, find the list of children.
1034 family = list(zip(parents,child_list))
1035 notmychildren = family #We aim to remove non-children
1036 # Loop over the parents, relocating as necessary
1037 while len(notmychildren):
1038 # get all children of first entry
1039 mychildren = [a for a in family if a[0]==notmychildren[0][0]]
1040 print("Parent {}: {} children".format(notmychildren[0][0],len(mychildren)))
1041 for parent,child in mychildren: #parent is the same for all
1042 # Make sure that we simply add in the new entry for the child, not replace it,
1043 # otherwise we might spoil the child entry loop structure
1044 try:
1045 childloop = self[child].GetLoop('_item_linked.parent_name')
1046 except KeyError:
1047 print('Creating new parent entry {} for definition {}'.format(parent,child))
1048 self[child]['_item_linked.parent_name'] = [parent]
1049 childloop = self[child].GetLoop('_item_linked.parent_name')
1050 childloop.AddLoopItem(('_item_linked.child_name',[child]))
1051 continue
1052 else:
1053 # A parent loop already exists and so will a child loop due to the
1054 # call to create_pcloop above
1055 pars = [a for a in childloop if getattr(a,'_item_linked.child_name','')==child]
1056 goodpars = [a for a in pars if getattr(a,'_item_linked.parent_name','')==parent]
1057 if len(goodpars)>0: #no need to add it
1058 print('Skipping duplicated parent - child entry in {}: {} - {}'.format(child,parent,child))
1059 continue
1060 print('Adding {} to {} entry'.format(parent,child))
1061 newpacket = childloop.GetPacket(0) #essentially a copy, I hope
1062 setattr(newpacket,'_item_linked.child_name',child)
1063 setattr(newpacket,'_item_linked.parent_name',parent)
1064 childloop.AddPacket(newpacket)
1065 #
1066 # Make sure the parent also points to the children. We get
1067 # the current entry, then add our
1068 # new values if they are not there already
1069 #
1070 parent_name = mychildren[0][0]
1071 old_children = self[parent_name].get('_item_linked.child_name',[])
1072 old_parents = self[parent_name].get('_item_linked.parent_name',[])
1073 oldfamily = zip(old_parents,old_children)
1074 newfamily = []
1075 print('Old parents -> {}'.format(repr(old_parents)))
1076 for jj, childname in mychildren:
1077 alreadythere = [a for a in oldfamily if a[0]==parent_name and a[1] ==childname]
1078 if len(alreadythere)>0: continue
1079 #'Adding new child %s to parent definition at %s' % (childname,parent_name)
1080 old_children.append(childname)
1081 old_parents.append(parent_name)
1082 # Now output the loop, blowing away previous definitions. If there is something
1083 # else in this category, we are destroying it.
1084 newloop = CifLoopBlock(dimension=1)
1085 newloop.AddLoopItem(('_item_linked.parent_name',old_parents))
1086 newloop.AddLoopItem(('_item_linked.child_name',old_children))
1087 del self[parent_name]['_item_linked.parent_name']
1088 del self[parent_name]['_item_linked.child_name']
1089 self[parent_name].insert_loop(newloop)
1090 print('New parents -> {}'.format(repr(self[parent_name]['_item_linked.parent_name'])))
1091 # now make a new,smaller list
1092 notmychildren = [a for a in notmychildren if a[0]!=mychildren[0][0]]
1093
1094 # now flatten any single element lists
1095 single_defs = filter(lambda a:len(self[a]['_item.name'])==1,listed_defs)
1096 for flat_def in single_defs:
1097 flat_keys = self[flat_def].GetLoop('_item.name').keys()
1098 for flat_key in flat_keys: self[flat_def][flat_key] = self[flat_def][flat_key][0]
1099 # now deal with the multiple lists
1100 # next we do aliases
1101 all_aliases = [a for a in self.keys() if self[a].has_key('_item_aliases.alias_name')]
1102 for aliased in all_aliases:
1103 my_aliases = listify(self[aliased]['_item_aliases.alias_name'])
1104 for alias in my_aliases:
1105 self[alias] = self[aliased].copy() #we are going to delete stuff...
1106 del self[alias]["_item_aliases.alias_name"]
1107
1108 # DDLm introduces validity information in the enclosing datablock. It is a loop of scope,
1109 # attribute values where the scope is one of dictionary (everywhere), category (whole
1110 # category) and item (just the single definition). Validity can be mandatory,
1111 # encouraged or not allowed. It only appears in the DDLm attributes dictionary, so
1112 # this information is blank unless we are dealing with the DDLm dictionary.
1113 #
1114 #
1115 # <Parse DDLm validity information>=
1116 def ddlm_parse_valid(self):
1117 if "_dictionary_valid.scope" not in self.master_block:
1118 return
1119 for scope_pack in self.master_block.GetLoop("_dictionary_valid.scope"):
1120 scope = getattr(scope_pack,"_dictionary_valid.scope")
1121 stance = getattr(scope_pack, "_dictionary_valid.option")
1122 valid_info = getattr(scope_pack,"_dictionary_valid.attributes")
1123 if stance == "Mandatory":
1124 self.scopes_mandatory[scope] = self.expand_category_opt(valid_info)
1125 elif stance == "Prohibited":
1126 self.scopes_naughty[scope] = self.expand_category_opt(valid_info)
1127
1128 # Section{DDLm functionality}
1129 #
1130 # DDLm is a far more complex dictionary standard than DDL2. We are able to import
1131 # definitions in two modes, "Full" and "Contents". "Contents" simply copies the attributes
1132 # found in the target definition, and is useful as a templating mechanism for commonly-seen
1133 # attributes. "Full" brings in the entire definition block and all child definitions, and
1134 # is useful for including entire dictionaries. As a special case, if we import a 'Head'
1135 # definition into a 'Head' definition, we actually make all non-Head categories of the
1136 # imported dictionary into child categories of the importing dictionary 'Head' category,
1137 # and the imported 'Head' category disappears.
1138 #
1139 # ``Contents'' and ``Full'' modes are implemented dynamically, that is,
1140 # when the value of an attribute is requested the dictionary resolves
1141 # imports.
1142 #
1143 # The merging method of the StarFile object is purely syntactic and so does not understand
1144 # DDLm relationships. We add all blocks as the children of the top-level dictionary block,
1145 # and then in the case of a new 'Head' block we simply reparent the immediate semantic
1146 # children of the old 'Head' block.
1147 #
1148 #
1149 # <Perform DDLm imports>=
1150 # <Get import information>=
1151 def get_dictionaries_to_import(self):
1152 import_frames = list([(a,self[a]['_import.get']) for a in self.keys() if '_import.get' in self[a]])
1153
1154 dictionaries = set()
1155 for parent_block,import_list in import_frames:
1156 for import_ref in import_list:
1157 dictionary_name = import_ref.get("file", "")
1158 dictionaries.add(dictionary_name)
1159
1160 return list(dictionaries)
1161
1162 def obtain_imports(self,import_mode,heavy=False):
1163 """Collate import information"""
1164 self._import_dics = []
1165 import_frames = list([(a,self[a]['_import.get']) for a in self.keys() if '_import.get' in self[a]])
1166 if self.verbose_import:
1167 print('Import mode {} applied to following frames'.format(import_mode))
1168 print(str([a[0] for a in import_frames]))
1169 if import_mode != 'All':
1170 for i in range(len(import_frames)):
1171 import_frames[i] = (import_frames[i][0],[a for a in import_frames[i][1] if a.get('mode','Contents').lower() == import_mode.lower()])
1172 print('Importing following frames in mode {}'.format(import_mode))
1173 print(str(import_frames))
1174 #resolve all references
1175 for parent_block,import_list in import_frames:
1176 for import_ref in import_list:
1177 file_loc = import_ref["file"]
1178 full_uri = self.resolve_path(file_loc)
1179 if full_uri not in self.template_cache:
1180 dic_as_cif = CifFile(full_uri,grammar=self.grammar, characterset=self.characterset)
1181 self.template_cache[full_uri] = CifDic(dic_as_cif,do_imports=import_mode,heavy=heavy,do_dREL=False, verbose_import=self.verbose_import) #this will recurse internal imports
1182
1183 if self.verbose_import:
1184 print('Added {} to cached dictionaries'.format(full_uri))
1185 import_from = self.template_cache[full_uri]
1186 dupl = import_ref.get('dupl','Exit')
1187 miss = import_ref.get('miss','Exit')
1188 target_key = import_ref["save"]
1189 try:
1190 import_target = import_from[target_key]
1191 except KeyError:
1192 if miss == 'Exit':
1193 raise CifError('Import frame {} not found in {}'.format(target_key,full_uri))
1194 else: continue
1195 # now import appropriately
1196 mode = import_ref.get("mode",'Contents').lower()
1197 if target_key in self and mode=='full': #so blockname will be duplicated
1198 if dupl == 'Exit':
1199 raise CifError('Import frame {} already in dictionary'.format(target_key))
1200 elif dupl == 'Ignore':
1201 continue
1202 if heavy:
1203 self.ddlm_import(parent_block,import_from,import_target,target_key,mode)
1204 else:
1205 self.ddlm_import_light(parent_block,import_from,import_target,target_key,file_loc,mode)
1206 # The original way of doing imports was to completely merge the information from the
1207 # imported file. This is slightly more efficient if information about import statements
1208 # is not required.
1209 #
1210 #
1211 # <Heavy import routine>=
1212
1213 def ddlm_import(self,parent_block,import_from,import_target,target_key,mode='All'):
1214 """Import other dictionaries in place"""
1215
1216 """
1217 Parent_block -> Key of the tag that imports data
1218 Import_from -> Dictionary to import
1219 Import_target -> Block to be imported
1220 Target_key -> Key to be imported
1221 """
1222 if mode == 'contents': #merge attributes only
1223 self[parent_block].merge(import_target)
1224 elif mode =="full":
1225 # Do the syntactic merge
1226 syntactic_head = self[self.get_parent(parent_block)] #root frame if no nesting
1227 from_cat_head = import_target['_name.object_id']
1228 child_frames = import_from.ddlm_all_children(from_cat_head)
1229 # Check for Head merging Head
1230 if self[parent_block].get('_definition.class','Datum')=='Head' and \
1231 import_target.get('_definition.class','Datum')=='Head':
1232 head_to_head = True
1233 else:
1234 head_to_head = False
1235 child_frames.remove(from_cat_head)
1236 # As we are in syntax land, we call the CifFile methods
1237 child_blocks = list([import_from.block_id_table[a.lower()] for a in child_frames])
1238 child_blocks = super(CifDic,import_from).makebc(child_blocks)
1239 # Prune out any datablocks that have identical definitions
1240 from_defs = dict([(a,child_blocks[a].get('_definition.id','').lower()) for a in child_blocks.keys()])
1241 double_defs = list([b for b in from_defs.items() if self.has_key(b[1])])
1242 if self.verbose_import:
1243 print('Definitions for {} superseded'.format(repr(double_defs)))
1244
1245 # Merge different tags of duplicated blocks
1246 self.merge_duplicates(child_blocks, double_defs)
1247
1248 for b in double_defs:
1249 del child_blocks[b[0]]
1250 super(CifDic,self).merge_fast(child_blocks,parent=syntactic_head) #
1251 if self.verbose_import:
1252 print('Syntactic merge of {} ({} defs) in {} mode, now have {} defs'.format(target_key,len(child_frames),
1253 mode,len(self)))
1254 # Now the semantic merge
1255 # First expand our definition <-> blockname tree
1256 self.create_def_block_table()
1257 merging_cat = self[parent_block]['_name.object_id'] #new parent
1258 if head_to_head:
1259 child_frames = self.ddlm_immediate_children(from_cat_head) #old children
1260 #the new parent is the importing category for all old children
1261 for f in child_frames:
1262 self[f].overwrite = True
1263 self[f]['_name.category_id'] = merging_cat
1264 self[f].overwrite = False
1265 # remove the old head
1266 del self[from_cat_head]
1267 if self.verbose_import:
1268 print('Semantic merge: {} defs reparented from {} to {}'.format(len(child_frames),from_cat_head,merging_cat))
1269 else: #imported category is only child
1270 from_frame = import_from[target_key]['_definition.id'] #so we can find it
1271 child_frame = [d for d in self.keys() if self[d]['_definition.id']==from_frame][0]
1272 self[child_frame]['_name.category_id'] = merging_cat
1273 if self.verbose_import:
1274 print('Semantic merge: category for {} : now {}'.format(from_frame,merging_cat))
1275 # it will never happen again...
1276 del self[parent_block]["_import.get"]
1277
1278 def merge_duplicates(self, child_blocks, double_defs):
1279 '''
1280 Duplicated blocks may have different definitions. Therefore deleting them will end up
1281 creating an incomplete dictionary.
1282 This functions checks among the duplicated tags, and if a duplicated pair has different
1283 tags, the remaining tags of the imported block are added to the base block.
1284 '''
1285
1286 for double_def in double_defs:
1287 # Tag name in the dictionary to be imported
1288 tag_name = double_def[0]
1289 # Tag name in the base dictionary
1290 base_tag_name = double_def[1]
1291
1292 duplicated_block = child_blocks[tag_name]
1293 base_block = self[base_tag_name]
1294
1295 duplicated_block_keys = set(duplicated_block.keys())
1296 base_block_keys = set(base_block.keys())
1297
1298 # Add category key name
1299
1300 # What to do in case of lists?
1301 # Half the ids are the same, and the other half are not
1302 #if self.unique_spec in duplicated_block_keys and \
1303 # base_block[self.unique_spec] != duplicated_block[self.unique_spec]:
1304 # original_cat_key = base_block[self.unique_spec]
1305 # duplicated_cat_key = duplicated_block[self.unique_spec]
1306 #
1307 # cat_key_set = {original_cat_key, duplicated_cat_key}
1308 #
1309 #
1310 #
1311 # self[base_tag_name][self.unique_spec] = cat_key_set
1312
1313 # Both blocks are equal, continue to the next duplicated block
1314 if len(duplicated_block_keys) == len(base_block_keys) \
1315 and duplicated_block_keys == base_block_keys:
1316 continue
1317
1318 # Only add the missing tag values to the base dictionary
1319 for property_name in duplicated_block.keys():
1320 if property_name not in base_block_keys:
1321 property_value = duplicated_block[property_name]
1322 self[base_tag_name][property_name] = property_value
1323
1324 def resolve_path(self,file_loc):
1325 url_comps = urlparse(file_loc)
1326 if url_comps[0]: return file_loc #already full URI
1327 new_url = urljoin(self.my_uri,file_loc)
1328 #print("Transformed %s to %s for import " % (file_loc,new_url))
1329 return new_url
1330
1331 # It is possible to not perform imports at reading time, but simply to register the links
1332 # and resolve the imports if and when a definition is accessed.
1333 #
1334 #
1335 # <Light import routine>=
1336 def ddlm_import_light(self,parent_block,import_from,import_target,target_key,file_loc,mode='All'):
1337 """Register the imported dictionaries but do not alter any definitions. `parent_block`
1338 contains the id of the block that is importing. `import_target` is the block that
1339 should be imported. `import_from` is the CifFile that contains the definitions."""
1340 if mode == 'contents': #merge attributes only
1341 self[parent_block].add_dict_cache(file_loc,import_from)
1342 elif mode =="full":
1343 # Check for Head merging Head
1344 if self[parent_block].get('_definition.class','Datum')=='Head' and \
1345 import_target.get('_definition.class','Datum')=='Head':
1346 head_to_head = True
1347 else:
1348 head_to_head = False
1349 # Figure out the actual definition ID
1350 head_id = import_target["_definition.id"]
1351 # Adjust parent information
1352 merging_cat = self[parent_block]['_name.object_id']
1353 from_cat_head = import_target['_name.object_id']
1354 if not head_to_head: # imported category is only child
1355 import_target["_name.category_id"]=merging_cat
1356 self._import_dics = [(import_from,head_id)]+self._import_dics #prepend
1357
1358 # Lightweight importation simply records the import information without performing the
1359 # import, and then when keys are accessed it checks through the imported dictionaries. The
1360 # semantics are such that the last dictionary imported should be the first dictionary
1361 # checked, as imports overwrite any definitions in preceding imports.
1362 #
1363 #
1364 # <Lookup imports for whole dictionary>=
1365 def lookup_imports(self,key):
1366 """Check the list of imported dictionaries for this definition"""
1367 for one_dic,head_def in self._import_dics:
1368 from_cat_head = one_dic[head_def]['_name.object_id']
1369 possible_keys = one_dic.ddlm_all_children(from_cat_head)
1370 if key in possible_keys:
1371 return one_dic[key]
1372 raise KeyError("{} not found in import dictionaries".format(key))
1373
1374
1375
1376 # CIF Dictionaries use the square bracket notation to refer to the definition, as for CifFile
1377 # objects, but the key is the definition itself, rather than the block name. So we have to create
1378 # a lookup table. However, template dictionaries may not have a _definition.id, which means we
1379 # have to revert to their blockname, so we use blockname as a default. We also completely
1380 # ignore case, which is a bit liberal, as definitions themselves are case-sensitive. We catch
1381 # duplicate definitions (e.g. as a result of incorrect merging).
1382 #
1383 # If a definition is not found, we search any dictionaries that were imported in 'Full' mode.
1384 # This means that definitions in the dictionary proper override anything in the imported
1385 # dictionaries, as per definitions.
1386 #
1387 #
1388 # <Repurpose standard python methods>=
1389 def create_def_block_table(self):
1390 """ Create an internal table matching definition to block id """
1391 proto_table = [(super(CifDic,self).__getitem__(a),a) for a in super(CifDic,self).keys()]
1392 # now get the actual ids instead of blocks
1393 proto_table = list([(a[0].get(self.cat_id_spec,a[0].get(self.def_id_spec,a[1])),a[1]) for a in proto_table])
1394 # remove non-definitions
1395 if self.diclang != "DDL1":
1396 top_blocks = list([a[0].lower() for a in self.get_roots()])
1397 else:
1398 top_blocks = ["on_this_dictionary"]
1399 # catch dodgy duplicates
1400 uniques = set([a[0] for a in proto_table])
1401 if len(uniques)<len(proto_table):
1402 def_names = list([a[0] for a in proto_table])
1403 dodgy = [a for a in def_names if def_names.count(a)>1]
1404 raise CifError('Duplicate definitions in dictionary:' + repr(dodgy))
1405 self.block_id_table = dict([(a[0].lower(),a[1].lower()) for a in proto_table if a[1].lower() not in top_blocks])
1406
1407 def __getitem__(self,key):
1408 """Access a datablock by definition id, after the lookup has been created"""
1409 try:
1410 return super(CifDic,self).__getitem__(self.block_id_table[key.lower()])
1411 except AttributeError: #block_id_table not present yet
1412 return super(CifDic,self).__getitem__(key)
1413 except KeyError: # key is missing
1414 try: # print(Definition for %s not found, reverting to CifFile' % key)
1415 return super(CifDic,self).__getitem__(key)
1416 except KeyError: # try imports
1417 return self.lookup_imports(key)
1418
1419 def __setitem__(self,key,value):
1420 """Add a new definition block"""
1421 super(CifDic,self).__setitem__(key,value)
1422 try:
1423 self.block_id_table[value['_definition.id']]=key
1424 except AttributeError: #does not exist yet
1425 pass
1426
1427 def NewBlock(self,*args,**kwargs):
1428 newname = super(CifDic,self).NewBlock(*args,**kwargs)
1429 try:
1430 self.block_id_table[self[newname]['_definition.id']]=newname
1431 except AttributeError: #no block_id table
1432 pass
1433
1434 def __delitem__(self,key):
1435 """Remove a definition"""
1436 try:
1437 super(CifDic,self).__delitem__(self.block_id_table[key.lower()])
1438 del self.block_id_table[key.lower()]
1439 except (AttributeError,KeyError): #block_id_table not present yet
1440 super(CifDic,self).__delitem__(key)
1441 return
1442 # fix other datastructures
1443 # cat_obj table
1444
1445 def keys(self):
1446 """Return all definitions"""
1447 try:
1448 return self.block_id_table.keys()
1449 except AttributeError:
1450 return super(CifDic,self).keys()
1451
1452 def has_key(self,key):
1453 return key in self
1454
1455 def __contains__(self,key):
1456 try:
1457 return key.lower() in self.block_id_table
1458 except AttributeError:
1459 return super(CifDic,self).__contains__(key)
1460
1461 def items(self):
1462 """Return (key,value) pairs"""
1463 return list([(a,self[a]) for a in self.keys()])
1464
1465 # Any Starfile method that uses the square-bracket notation or
1466 # build-in syntax (e.g. del) to access keys may fail if the set of keys
1467 # it uses is not that provided by the keys() method above, as the
1468 # object delegation using super() does not apply. As we have set
1469 # up our methods above to 'fall through' to the underlying CifFile,
1470 # the process of renaming may or may not have called our del
1471 # method to remove the definition, so we check.
1472 #
1473 #
1474 # <Repurpose Starfile methods>=
1475 def unlock(self):
1476 """Allow overwriting of all definitions in this collection"""
1477 for a in self.keys():
1478 self[a].overwrite=True
1479
1480 def lock(self):
1481 """Disallow changes in definitions"""
1482 for a in self.keys():
1483 self[a].overwrite=False
1484
1485 def rename(self,oldname,newname,blockname_as_well=True):
1486 """Change a _definition.id from oldname to newname, and if `blockname_as_well` is True,
1487 change the underlying blockname too."""
1488 if blockname_as_well:
1489 super(CifDic,self).rename(self.block_id_table[oldname.lower()],newname)
1490 self.block_id_table[newname.lower()]=newname
1491 if oldname.lower() in self.block_id_table: #not removed
1492 del self.block_id_table[oldname.lower()]
1493 else:
1494 self.block_id_table[newname.lower()]=self.block_id_table[oldname.lower()]
1495 del self.block_id_table[oldname.lower()]
1496 return
1497
1498 # \subsection{Semantic information}
1499 #
1500 #
1501 # <Obtaining semantic information from the dictionary>=
1502 # For convenience we provide ways of interrogating the semantic tree
1503 # of categories. Note that if we are passed the top-level datablock, the
1504 # semantic children are the syntactic children. An additional method
1505 # finds the 'dangling' definitions, which are definitions that have no
1506 # category definition present - these might be definitions added by this
1507 # dictionary to categories found in other dictionaries.
1508 #
1509 #
1510 # <Operations with semantic children>=
1511 def get_root_category(self):
1512 """Get the single 'Head' category of this dictionary"""
1513 root_cats = [r for r in self.keys() if self[r].get('_definition.class','Datum')=='Head']
1514 if len(root_cats)>1 or len(root_cats)==0:
1515 raise CifError("Cannot determine a unique Head category, got".format(repr(root_cats)))
1516 return root_cats[0]
1517
1518 def ddlm_immediate_children(self,catname):
1519 """Return a list of datanames for the immediate children of catname. These are
1520 semantic children (i.e. based on _name.category_id), not structural children as
1521 in the case of StarFile.get_immediate_children"""
1522
1523 straight_children = [a for a in self.keys() if self[a].get('_name.category_id','').lower() == catname.lower()]
1524 return list(straight_children)
1525
1526 def ddlm_all_children(self,catname):
1527 """Return a list of all children, including the `catname`"""
1528 all_children = self.ddlm_immediate_children(catname)
1529 cat_children = [a for a in all_children if self[a].get('_definition.scope','Item') == 'Category']
1530 for c in cat_children:
1531 all_children.remove(c)
1532 all_children += self.ddlm_all_children(c)
1533 return all_children + [catname]
1534
1535 def is_semantic_child(self,parent,maybe_child):
1536 """Return true if `maybe_child` is a child of `parent`"""
1537 all_children = self.ddlm_all_children(parent)
1538 return maybe_child in all_children
1539
1540 def ddlm_danglers(self):
1541 """Return a list of definitions that do not have a category defined
1542 for them, or are children of an unattached category"""
1543 top_block = self.get_root_category()
1544 connected = set(self.ddlm_all_children(top_block))
1545 all_keys = set(self.keys())
1546 unconnected = all_keys - connected
1547 return list(unconnected)
1548
1549 def get_ddlm_parent(self,itemname):
1550 """Get the parent category of itemname"""
1551 parent = self[itemname].get('_name.category_id','')
1552 if parent == '': # use the top block by default
1553 raise CifError("{} has no parent".format(itemname))
1554 return parent
1555
1556 # Some methods for interrogating categories for names.
1557 #
1558 #
1559 # <Get category information>=
1560 def expand_category_opt(self,name_list):
1561 """Return a list of all non-category items in a category or return the name
1562 if the name is not a category"""
1563 new_list = []
1564 for name in name_list:
1565 if self.get(name,{}).get('_definition.scope','Item') == 'Category':
1566 new_list += self.expand_category_opt([a for a in self.keys() if \
1567 self[a].get('_name.category_id','').lower() == name.lower()])
1568 else:
1569 new_list.append(name)
1570 return new_list
1571
1572 def get_categories(self):
1573 """Return a list of category names"""
1574 return list([c for c in self.keys() if self[c].get("_definition.scope")=='Category'])
1575
1576 # This method was added to facilitate running dREL scripts, which treat
1577 # certain variables as having attributes which all belong to a single category.
1578 # We return only the extension in keeping with dREL syntax. If [[names_only]]
1579 # is true, we return only the object part of the dataname. Note that sub
1580 # categories are excluded. TODO: use cat-obj table for speed.
1581 #
1582 #
1583 # <List all items in a category>=
1584 def names_in_cat(self,cat,names_only=False):
1585 names = [a for a in self.keys() if self[a].get('_name.category_id','').lower()==cat.lower()]
1586 if not names_only:
1587 return list([a for a in names if self[a].get('_definition.scope','Item')=='Item'])
1588 else:
1589 return list([self[a]["_name.object_id"] for a in names])
1590
1591
1592
1593 # A dataname can appear in a file under a different name if it has been aliased. We create
1594 # an alias table to speed up lookup. The table is indexed by true name, with a list of
1595 # alternatives.
1596 #
1597 #
1598 # <Create alias table>=
1599 def create_alias_table(self):
1600 """Populate an alias table that we can look up when searching for a dataname"""
1601 all_aliases = [a for a in self.keys() if '_alias.definition_id' in self[a]]
1602 self.alias_table = dict([[a,self[a]['_alias.definition_id']] for a in all_aliases])
1603
1604 # DDLm internally refers to data items by the category.object notation, with the twist
1605 # that child categories of loops can have their objects appear in the parent category. So
1606 # this table prepares a complete list of (cat,obj):dataname correspondences, as the
1607 # implementation of parent-child requires looking up a table each time searching for
1608 # children.
1609 #
1610 # The recursive [[expand_base_table]] function returns a dictionary of (name,definition_id) pairs
1611 # indexing the corresponding datanames. We must catch any keys and exclude them from this
1612 # process, as they are allowed to have the same [[object_id]] as their parent key in the
1613 # enclosing datablock and will overwrite the entry for the parent key if left in. We also
1614 # note that the example dictionary allows these types of name collisions if an item is
1615 # intended to be identical (e.g. _atom_site_aniso.type_symbol and atom_site.type_symbol),
1616 # so we create a short list of possible alternative names for each (cat,obj) pair.
1617 #
1618 # The create_nested_key_table stores information about which keys index child categories. This
1619 # way applications can search for any loops containing these keys and expand packets for dREL
1620 # accordingly.
1621 #
1622 #
1623 # <Create category/object table>=
1624 def create_cat_obj_table(self):
1625 """Populate a table indexed by (cat,obj) and returning the correct dataname"""
1626
1627 # Collect all explicit (cat,obj) pairs for data names
1628
1629 base_table = dict([((self[a].get('_name.category_id','').lower(),self[a].get('_name.object_id','').lower()),[self[a].get('_definition.id','')]) \
1630 for a in self.keys() if self[a].get('_definition.scope','Item')=='Item'])
1631
1632 # Find all loop category parent-child relationships
1633
1634 loopable = self.get_loopable_cats()
1635 loopers = [self.ddlm_immediate_children(a) for a in loopable]
1636
1637 if self.verbose_import:
1638 print('Loopable cats:' + repr(loopable))
1639
1640 loop_children = [[b for b in a if b.lower() in loopable ] for a in loopers]
1641 expand_list = dict([(a,b) for a,b in zip(loopable,loop_children) if len(b)>0])
1642
1643 if self.verbose_import:
1644 print("Expansion list:" + repr(expand_list))
1645
1646 extra_table = {} #for debugging we keep it separate from base_table until the end
1647
1648 # Define a function that puts all child category objects into the parent category,
1649 # returning the list of new names so it can be used recursively
1650
1651 def expand_base_table(parent_cat,child_cats):
1652
1653 extra_names = []
1654
1655 parent_names = [(self[n]['_name.object_id'].lower(),self[n]['_definition.id']) \
1656 for n in self.names_in_cat(parent_cat) if self[n].get('_type.purpose','')!='Key']
1657
1658 # first deal with all the child categories
1659
1660 for child_cat in child_cats:
1661 nn = []
1662
1663 if child_cat in expand_list: # a nested category: grab its names
1664 nn = expand_base_table(child_cat,expand_list[child_cat])
1665 # store child names
1666 extra_names += nn
1667
1668 # get all child names for this category
1669
1670 child_names = [(self[n]['_name.object_id'].lower(),self[n]['_definition.id']) \
1671 for n in self.names_in_cat(child_cat) if self[n].get('_type.purpose','') != 'Key']
1672 # update child category with parent names (it can also see the parent)
1673
1674 extra_table.update(dict([((child_cat,obj),[name]) for obj, name in parent_names if (child_cat, obj) not in extra_table]))
1675
1676 # and include those from child categories
1677
1678 child_names += extra_names
1679
1680 # update our reference table for the parent category
1681
1682 extra_table.update(dict([((parent_cat,obj),[name]) for obj,name in child_names if (parent_cat,obj) not in extra_table]))
1683
1684
1685 # and the repeated ones get appended instead
1686
1687 repeats = [a for a in child_names if a in extra_table]
1688
1689 for obj,name in repeats:
1690 extra_table[(parent_cat,obj)] += [name]
1691
1692 # and finally, add our own names to the return list
1693
1694 child_names += [(self[n]['_name.object_id'].lower(),self[n]['_definition.id']) \
1695 for n in self.names_in_cat(parent_cat) if self[n].get('_type.purpose','')!='Key']
1696 return child_names
1697
1698 # Process all parent-child hierarchies that we've found.
1699
1700 [expand_base_table(parent,child) for parent,child in expand_list.items()]
1701
1702 if self.verbose_import:
1703 print('Expansion cat/obj values: ' + repr(extra_table))
1704
1705 # pick over our expanded information: repeats append, new get added
1706
1707 non_repeats = dict([a for a in extra_table.items() if a[0] not in base_table])
1708 repeats = [a for a in extra_table.keys() if a in base_table]
1709 base_table.update(non_repeats)
1710
1711 for k in repeats:
1712 base_table[k] += extra_table[k]
1713
1714 self.cat_obj_lookup_table = base_table
1715 self.loop_expand_list = expand_list
1716
1717 def get_loopable_cats(self):
1718 """A short utility function which returns a list of looped categories. This
1719 is preferred to a fixed attribute as that fixed attribute would need to be
1720 updated after any edits"""
1721 return [a.lower() for a in self.keys() if self[a].get('_definition.class','')=='Loop']
1722
1723 def create_cat_key_table(self):
1724 """Create a utility table with a list of keys applicable to each category. A key is
1725 a compound key, that is, it is a list"""
1726 self.cat_key_table = dict([(c,[listify(self[c].get("_category_key.name",
1727 [self[c].get("_category.key_id")]))]) for c in self.get_loopable_cats()])
1728 def collect_keys(parent_cat,child_cats):
1729 kk = []
1730 for child_cat in child_cats:
1731 if child_cat in self.loop_expand_list:
1732 kk += collect_keys(child_cat)
1733 # add these keys to our list
1734 kk += [listify(self[child_cat].get('_category_key.name',[self[child_cat].get('_category.key_id')]))]
1735 self.cat_key_table[parent_cat] = self.cat_key_table[parent_cat] + kk
1736 return kk
1737 for k,v in self.loop_expand_list.items():
1738 collect_keys(k,v)
1739 if self.verbose_import:
1740 print('Keys for categories' + repr(self.cat_key_table))
1741
1742 # Preparing our type expressions
1743 #
1744 # In DDL2 dictionaries our type expressions are given in the main
1745 # block as POSIX regexps, so we can pass them on to the re package.
1746 # For DDL1 dictionaries we could get them from the DDL1 language
1747 # definition, but for now we just hard code them. Essentially only
1748 # the number definition is important, as the syntax check during
1749 # reading/writing will catch any char violations.
1750 #
1751 # Note that the python re engine is not POSIX compliant in that it will
1752 # not return the longest leftmost match, but rather the first leftmost
1753 # match. John Bollinger suggested an obvious fix: we append a [[$]] to force
1754 # a full match.
1755 #
1756 # In other regexp editing, the [[\{]] sequence inside the character sets of
1757 # some of the regexps is actually interpreted as an escaped bracket, so the
1758 # backslash vanishes. We add it back in by doing a very hackish and ugly
1759 # substitution which substitues these two characters anywhere that they
1760 # occur inside square brackets. A final change is to insert a [[\r]] wherever
1761 # we find a [[\n]] - it seems that this has been left out.
1762 # After these changes, and appending on default
1763 # expressions as well, we can now work with DDL2 expressions directly.
1764 #
1765 # We keep the primitive code for the single reason that we need to
1766 # know when we are dealing with a number that has an esd appended, and
1767 # this is flagged by the primitive code being of type 'numb'.
1768 #
1769 #
1770 # <Add type information>=
1771 def add_type_info(self):
1772 if "_item_type_list.construct" in self.master_block:
1773 types = self.master_block["_item_type_list.code"]
1774 prim_types = self.master_block["_item_type_list.primitive_code"]
1775 constructs = list([a + "$" for a in self.master_block["_item_type_list.construct"]])
1776 # add in \r wherever we see \n, and change \{ to \\{
1777 def regex_fiddle(mm_regex):
1778 brack_match = r"((.*\[.+)(\\{)(.*\].*))"
1779 ret_match = r"((.*\[.+)(\\n)(.*\].*))"
1780 fixed_regexp = mm_regex[:] #copy
1781 # fix the brackets
1782 bm = re.match(brack_match,mm_regex)
1783 if bm != None:
1784 fixed_regexp = bm.expand(r"\2\\\\{\4")
1785 # fix missing \r
1786 rm = re.match(ret_match,fixed_regexp)
1787 if rm != None:
1788 fixed_regexp = rm.expand(r"\2\3\\r\4")
1789 #print("Regexp %s becomes %s" % (mm_regex,fixed_regexp))
1790 return fixed_regexp
1791 constructs = map(regex_fiddle,constructs)
1792 for typecode,construct in zip(types,constructs):
1793 self.typedic[typecode] = re.compile(construct,re.MULTILINE|re.DOTALL)
1794 # now make a primitive <-> type construct mapping
1795 for typecode,primtype in zip(types,prim_types):
1796 self.primdic[typecode] = primtype
1797
1798 # Dictionaries have the category-wide information in the category
1799 # definition area. We do not need to fill all of this in if we are
1800 # not planning on running dREL.
1801 #
1802 #
1803 # <Add category information>=
1804 def add_category_info(self,full=True):
1805 if self.diclang == "DDLm":
1806 # For help in validation we create a lookup table which matches a category to
1807 # its ultimate parent. This allows us to quickly check whether or not a data
1808 # item is allowed to be co-looped with other data items. Note that we may have
1809 # to draw in external dictionaries to do this properly, but to avoid holding
1810 # the whole lot in memory, we simply stop searching up the parent tree if the
1811 # parent block is missing.
1812 #
1813 #
1814 # <Create category parent table>=
1815 catblocks = [c for c in self.keys() if self[c].get('_definition.scope')=='Category']
1816 looped_cats = [a for a in catblocks if self[a].get('_definition.class','Set') == 'Loop']
1817 self.parent_lookup = {}
1818 for one_cat in looped_cats:
1819 parent_cat = one_cat
1820 parent_def = self[parent_cat]
1821 next_up = parent_def['_name.category_id'].lower()
1822 while next_up in self and self[next_up].get('_definition.class','Set') == 'Loop':
1823 parent_def = self[next_up]
1824 parent_cat = next_up
1825 next_up = parent_def['_name.category_id'].lower()
1826 self.parent_lookup[one_cat] = parent_cat
1827
1828 if full:
1829 # The key hierarchy. This is in many ways reinventing the parent-child
1830 # relationships that are laid out in DDL2 definitions. In order to
1831 # access a particular packet using multiple datanames as compound keys,
1832 # we need to be aware of which keys are related to which other
1833 # keys. Relationships are always made explicit via the
1834 # '_name.linked_item_id' attribute in DDLm, which always points to the
1835 # parent. This is always present, even though it may be often be inferred
1836 # using Loop category parent/child relationships, as compound keys in
1837 # categories might introduce ambiguity.
1838 #
1839 # This datastructure allows us to provide a key, and obtain a list of
1840 # equivalent keys, being all those above it in the hierarchy, that is,
1841 # which it can be replaced by. If we are not doing dREL, we can afford
1842 # to skip this.
1843 #
1844 #
1845 # <Create key hierarchy>=
1846 self.key_equivs = {}
1847 for one_cat in looped_cats: #follow them up
1848 if '_category_key.name' not in self[one_cat].keys():
1849 continue
1850
1851 lower_keys = listify(self[one_cat]['_category_key.name'])
1852 start_keys = lower_keys[:]
1853 while len(lower_keys)>0:
1854 if lower_keys[0] not in self.keys():
1855 break
1856
1857 this_cat = self[lower_keys[0]]['_name.category_id']
1858 parent = [a for a in looped_cats if self[this_cat]['_name.category_id'].lower()==a]
1859 #print(Processing %s, keys %s, parent %s" % (this_cat,repr(lower_keys),repr(parent)))
1860 if len(parent)>1:
1861 raise CifError("Category {} has more than one parent: {}".format(one_cat,repr(parent)))
1862 if len(parent)==0: break
1863 parent = parent[0]
1864 parent_keys = listify(self[parent]['_category_key.name'])
1865
1866 linked_key_found = True
1867 for l in lower_keys:
1868 if "_name.linked_item_id" not in self[l].keys():
1869 linked_key_found = False
1870
1871 if linked_key_found:
1872 linked_keys = [self[l]["_name.linked_item_id"] for l in lower_keys]
1873 # sanity check
1874 if set(parent_keys) != set(linked_keys):
1875 raise CifError("Parent keys and linked keys are different! {}/{}".format(parent_keys,linked_keys))
1876 # now add in our information
1877 for parent,child in zip(linked_keys,start_keys):
1878 self.key_equivs[child] = self.key_equivs.get(child,[])+[parent]
1879 lower_keys = linked_keys #preserves order of start keys
1880
1881 else:
1882 # It is assumed that there are no more linked_keys, therefore return an empty list
1883 lower_keys = []
1884
1885 else:
1886 self.parent_lookup = {}
1887 self.key_equivs = {}
1888
1889 # These methods were added when developing interactive editing tools, which allow
1890 # shifting categories around.
1891 #
1892 #
1893 # <Definition manipulation methods>=
1894 # Changing a category name involves changing the [[_name.category_id]]
1895 # in all children as well as the category definition itself and
1896 # datablock names, then updating our internal structures.
1897 #
1898 #
1899 # <Changing and updating categories>=
1900 def change_category_name(self,oldname,newname):
1901 self.unlock()
1902 """Change the category name from [[oldname]] to [[newname]]"""
1903 if oldname not in self:
1904 raise KeyError('Cannot rename non-existent category {} to {}'.format(oldname,newname))
1905 if newname in self:
1906 raise KeyError('Cannot rename {} to {} as {} already exists'.format(oldname,newname,oldname))
1907 child_defs = self.ddlm_immediate_children(oldname)
1908 self.rename(oldname,newname) #NB no name integrity checks
1909 self[newname]['_name.object_id']=newname
1910 self[newname]['_definition.id']=newname
1911 for child_def in child_defs:
1912 self[child_def]['_name.category_id'] = newname
1913 if self[child_def].get('_definition.scope','Item')=='Item':
1914 newid = self.create_catobj_name(newname,self[child_def]['_name.object_id'])
1915 self[child_def]['_definition.id']=newid
1916 self.rename(child_def,newid[1:]) #no underscore at the beginning
1917 self.lock()
1918
1919 def create_catobj_name(self,cat,obj):
1920 """Combine category and object in approved fashion to create id"""
1921 return ('_'+cat+'.'+obj)
1922
1923 def change_category(self,itemname,catname):
1924 """Move itemname into catname, return new handle"""
1925 defid = self[itemname]
1926 if defid['_name.category_id'].lower()==catname.lower():
1927 print('Already in category, no change')
1928 return itemname
1929 if catname not in self: #don't have it
1930 print('No such category {}'.format(catname))
1931 return itemname
1932 self.unlock()
1933 objid = defid['_name.object_id']
1934 defid['_name.category_id'] = catname
1935 newid = itemname # stays the same for categories
1936 if defid.get('_definition.scope','Item') == 'Item':
1937 newid = self.create_catobj_name(catname,objid)
1938 defid['_definition.id']= newid
1939 self.rename(itemname,newid)
1940 self.set_parent(catname,newid)
1941 self.lock()
1942 return newid
1943
1944 def change_name(self,one_def,newobj):
1945 """Change the object_id of one_def to newobj. This is not used for
1946 categories, but can be used for dictionaries"""
1947 if '_dictionary.title' not in self[one_def]: #a dictionary block
1948 newid = self.create_catobj_name(self[one_def]['_name.category_id'],newobj)
1949 self.unlock()
1950 self.rename(one_def,newid)
1951 self[newid]['_definition.id']=newid
1952 self[newid]['_name.object_id']=newobj
1953 else:
1954 self.unlock()
1955 newid = newobj
1956 self.rename(one_def,newobj)
1957 self[newid]['_dictionary.title'] = newid
1958 self.lock()
1959 return newid
1960
1961 # Note that our semantic parent is given by catparent, but our syntactic parent is
1962 # always just the root block
1963 def add_category(self,catname,catparent=None,is_loop=True,allow_dangler=False):
1964 """Add a new category to the dictionary with name [[catname]].
1965 If [[catparent]] is None, the category will be a child of
1966 the topmost 'Head' category or else the top data block. If
1967 [[is_loop]] is false, a Set category is created. If [[allow_dangler]]
1968 is true, the parent category does not have to exist."""
1969 if catname in self:
1970 raise CifError('Attempt to add existing category {}'.format(catname))
1971 self.unlock()
1972 syntactic_root = self.get_roots()[0][0]
1973 if catparent is None:
1974 semantic_root = [a for a in self.keys() if self[a].get('_definition.class',None)=='Head']
1975 if len(semantic_root)>0:
1976 semantic_root = semantic_root[0]
1977 else:
1978 semantic_root = syntactic_root
1979 else:
1980 semantic_root = catparent
1981 realname = super(CifDic,self).NewBlock(catname,parent=syntactic_root)
1982 self.block_id_table[catname.lower()]=realname
1983 self[catname]['_name.object_id'] = catname
1984 if not allow_dangler or catparent is None:
1985 self[catname]['_name.category_id'] = self[semantic_root]['_name.object_id']
1986 else:
1987 self[catname]['_name.category_id'] = catparent
1988 self[catname]['_definition.id'] = catname
1989 self[catname]['_definition.scope'] = 'Category'
1990 if is_loop:
1991 self[catname]['_definition.class'] = 'Loop'
1992 else:
1993 self[catname]['_definition.class'] = 'Set'
1994 self[catname]['_description.text'] = 'No definition provided'
1995 self.lock()
1996 return catname
1997
1998 def add_definition(self,itemname,catparent,def_text='PLEASE DEFINE ME',allow_dangler=False):
1999 """Add itemname to category [[catparent]]. If itemname contains periods,
2000 all text before the final period is ignored. If [[allow_dangler]] is True,
2001 no check for a parent category is made."""
2002 self.unlock()
2003 if '.' in itemname:
2004 objname = itemname.split('.')[-1]
2005 else:
2006 objname = itemname
2007 objname = objname.strip('_')
2008 if not allow_dangler and (catparent not in self or self[catparent]['_definition.scope']!='Category'):
2009 raise CifError('No category {} in dictionary'.format(catparent))
2010 fullname = '_'+catparent.lower()+'.'+objname
2011 print('New name: {}'.format(fullname))
2012 syntactic_root = self.get_roots()[0][0]
2013 realname = super(CifDic,self).NewBlock(fullname, fix=False, parent=syntactic_root) #low-level change
2014 # update our dictionary structures
2015 self.block_id_table[fullname]=realname
2016 self[fullname]['_definition.id']=fullname
2017 self[fullname]['_name.object_id']=objname
2018 self[fullname]['_name.category_id']=catparent
2019 self[fullname]['_definition.class']='Datum'
2020 self[fullname]['_description.text']=def_text
2021 return realname
2022
2023 def remove_definition(self,defname):
2024 """Remove a definition from the dictionary."""
2025 if defname not in self:
2026 return
2027 if self[defname].get('_definition.scope')=='Category':
2028 children = self.ddlm_immediate_children(defname)
2029 [self.remove_definition(a) for a in children]
2030 cat_id = self[defname]['_definition.id'].lower()
2031 del self[defname]
2032
2033 # The DDLm architecture identifies a data definition by (category,object) which
2034 # identifies a unique textual dataname appearing in the data file. Because of category
2035 # joins when nested categories are looped, a single dataname may be referred to
2036 # by several different category identifiers. The [[get_name_by_cat_obj]] routine
2037 # will search all loop categories within the given category hierarchy until
2038 # it finds the appropriate one.
2039 #
2040 # If [[give_default]] is True, the default construction '_catid.objid'
2041 # is returned if nothin is found in the dictionary. This should only be
2042 # used during testing as the lack of a corresponding definition in the
2043 # dictionary means that it is unlikely that anything sensible will
2044 # result.
2045 #
2046 #
2047 # <Getting category information>=
2048 def get_cat_obj(self,name):
2049 """Return (cat,obj) tuple. [[name]] must contain only a single period"""
2050 cat,obj = name.split('.')
2051 return (cat.strip('_'),obj)
2052
2053 def get_name_by_cat_obj(self,category,object,give_default=False):
2054 """Return the dataname corresponding to the given category and object"""
2055 if category[0] == '_': #accidentally left in
2056 true_cat = category[1:].lower()
2057 else:
2058 true_cat = category.lower()
2059 try:
2060 return self.cat_obj_lookup_table[(true_cat,object.lower())][0]
2061 except KeyError:
2062 if give_default:
2063 return '_'+true_cat+'.'+object
2064 raise KeyError('No such category,object in the dictionary: {} {}'.format(true_cat,object))
2065
2066
2067 # \subsection {Outputting dictionaries}
2068 #
2069 # We would like dictionary blocks to be output in a readable order, that is,
2070 # parent categories before their child definitions. The base BlockCollection
2071 # output routines have no knowledge of save frame interrelations, so we have
2072 # to override the output block order returned by the get_child_list routine.
2073 #
2074 #
2075 # <Dictionary output routines>=
2076 def WriteOut(self,**kwargs):
2077 myblockorder = self.get_full_child_list()
2078 self.set_grammar(self.grammar)
2079 self.standard = 'Dic'
2080 return super(CifDic,self).WriteOut(blockorder = myblockorder,**kwargs)
2081
2082 def get_full_child_list(self):
2083 """Return a list of definition blocks in order parent-child-child-child-parent-child..."""
2084 top_block = self.get_roots()[0][0]
2085 root_cat = [a for a in self.keys() if self[a].get('_definition.class','Datum')=='Head']
2086 if len(root_cat) == 1:
2087 all_names = [top_block] + self.recurse_child_list(root_cat[0])
2088 unrooted = self.ddlm_danglers()
2089 double_names = set(unrooted).intersection(set(all_names))
2090 if len(double_names)>0:
2091 raise CifError('Names are children of internal and external categories:{}'.format(repr(double_names)))
2092 remaining = unrooted[:]
2093 for no_root in unrooted:
2094 if self[no_root].get('_definition.scope','Item')=='Category':
2095 all_names += [no_root]
2096 remaining.remove(no_root)
2097 these_children = [n for n in unrooted if self[n]['_name.category_id'].lower()==no_root.lower()]
2098 all_names += these_children
2099 [remaining.remove(n) for n in these_children]
2100 # now sort by category
2101 ext_cats = set([self[r].get('_name.category_id',self.cat_from_name(r)).lower() for r in remaining])
2102 for e in ext_cats:
2103 cat_items = [r for r in remaining if self[r].get('_name.category_id',self.cat_from_name(r)).lower() == e]
2104 [remaining.remove(n) for n in cat_items]
2105 all_names += cat_items
2106 if len(remaining)>0:
2107 print('WARNING: following items do not seem to belong to a category??')
2108 print(repr(remaining))
2109 all_names += remaining
2110 print('Final block order: ' + repr(all_names))
2111 return all_names
2112 raise ValueError('Dictionary contains no/multiple Head categories, please print as plain CIF instead')
2113
2114 def cat_from_name(self,one_name):
2115 """Guess the category from the name. This should be used only when this is not important semantic information,
2116 for example, when printing out"""
2117 (cat,obj) = one_name.split(".")
2118 if cat[0] == "_": cat = cat[1:]
2119 return cat
2120
2121 def recurse_child_list(self,parentname):
2122 """Recursively expand the logical child list of [[parentname]]"""
2123 final_list = [parentname]
2124 child_blocks = [a for a in self.child_table.keys() if self[a].get('_name.category_id','').lower() == parentname.lower()]
2125 child_blocks.sort() #we love alphabetical order
2126 child_items = [a for a in child_blocks if self[a].get('_definition.scope','Item') == 'Item']
2127 final_list += child_items
2128 child_cats = [a for a in child_blocks if self[a].get('_definition.scope','Item') == 'Category']
2129 for child_cat in child_cats:
2130 final_list += self.recurse_child_list(child_cat)
2131 return final_list
2132
2133
2134
2135 # This method was added for DDLm support. We are passed a category and a
2136 # value, and must find a packet which has a matching key. We use the keyname
2137 # as a way of finding the loop.
2138 #
2139 #
2140 # <Return a single packet by key>=
2141 def get_key_pack(self,category,value,data):
2142 keyname = self[category][self.unique_spec]
2143 onepack = data.GetPackKey(keyname,value)
2144 return onepack
2145
2146 # This support function uses re capturing to work out the number's value. The
2147 # re contains 7 groups: group 0 is the entire expression; group 1 is the overall
2148 # match in the part prior to esd brackets; group 2 is the match with a decimal
2149 # point, group 3 is the digits after the decimal point, group 4 is the match
2150 # without a decimal point. Group 5 is the esd bracket contents, and
2151 # group 6 is the exponent.
2152 #
2153 # The esd should be returned as an independent number. We count the number
2154 # of digits after the decimal point, create the esd in terms of this, and then,
2155 # if necessary, apply the exponent.
2156 #
2157 #
2158 # <Extract number and esd>=
2159 def get_number_with_esd(numstring):
2160 numb_re = '((-?(([0-9]*[.]([0-9]+))|([0-9]+)[.]?))([(][0-9]+[)])?([eEdD][+-]?[0-9]+)?)|(\\?)|(\\.)'
2161 our_match = re.match(numb_re,numstring)
2162 if our_match:
2163 a,base_num,b,c,dad,dbd,esd,exp,q,dot = our_match.groups()
2164 # print("Debug: {} -> {!r}".format(numstring, our_match.groups()))
2165 else:
2166 return None,None
2167 if dot or q: return None,None #a dot or question mark
2168 if exp: #has exponent
2169 exp = exp.replace("d","e") # mop up old fashioned numbers
2170 exp = exp.replace("D","e")
2171 base_num = base_num + exp
2172 # print("Debug: have %s for base_num from %s" % (base_num,numstring))
2173 base_num = float(base_num)
2174 # work out esd, if present.
2175 if esd:
2176 esd = float(esd[1:-1]) # no brackets
2177 if dad: # decimal point + digits
2178 esd = esd * (10 ** (-1* len(dad)))
2179 if exp:
2180 esd = esd * (10 ** (float(exp[1:])))
2181 return base_num,esd
2182
2183 # This function analyses a DDL1-type range expression, returning
2184 # a maximum and minimum value. If the number
2185 # format were ever to change, we need to change this right here, right
2186 # now.
2187 #
2188 #
2189 # <Analyse range>=
2190 def getmaxmin(self,rangeexp):
2191 regexp = '(-?(([0-9]*[.]([0-9]+))|([0-9]+)[.]?)([eEdD][+-]?[0-9]+)?)*'
2192 regexp = regexp + ":" + regexp
2193 regexp = re.match(regexp,rangeexp)
2194 try:
2195 minimum = regexp.group(1)
2196 maximum = regexp.group(7)
2197 except AttributeError:
2198 print("Can't match {}".format(rangeexp))
2199 if minimum == None: minimum = "."
2200 else: minimum = float(minimum)
2201 if maximum == None: maximum = "."
2202 else: maximum = float(maximum)
2203 return maximum,minimum
2204
2205 # \section{Linkage to dREL}
2206 #
2207 # The drel_ast_yacc package will generate an Abstract Syntax Tree, which
2208 # we then convert to a Python function using [[py_from_ast.make_function]]. We use
2209 # it during initialisation to transform all methods to python expressions,
2210 # and then the [[derive_item]] method will use this to try to derive the
2211 # expression. Note that newline is the only recognised statement separator
2212 # in dREL, so we make sure all lines are separated in this way. We also allow
2213 # multiple 'Evaluation' methods, which is an enhancement of the current
2214 # standard.
2215 #
2216 # The [[make_function]] function requires dictionary information to be
2217 # supplied regarding looped categories and keys.
2218 #
2219 # If we were really serious about dictionary-driven software, the attribute
2220 # lookups that follow would not use get(), but square brackets and allow default
2221 # values to be returned. However, that would require assigning a dictionary
2222 # to the dictionary and consequent automated searches which I cannot be bothered
2223 # to do at this stage. Just be aware that the default value in the get()
2224 # statement is the _enumeration.default specified in ddl.dic.
2225 #
2226 #
2227 # <Linkage to dREL>=
2228 # Full initialisation. This can take some time so we optionally skip it, but can
2229 # call this function separately at a later stage if needed.
2230 #
2231 #
2232 # <Initialise dREL functions>=
2233 def initialise_drel(self):
2234 """Parse drel functions and prepare data structures in dictionary"""
2235 self.ddlm_parse_valid() #extract validity information from data block
2236 self.transform_drel() #parse the drel functions
2237 self.add_drel_funcs() #put the drel functions into the namespace
2238
2239 # <Transform drel to python>=
2240 def transform_drel(self):
2241 from .drel import drel_ast_yacc
2242 from .drel import py_from_ast
2243 import traceback
2244 parser = drel_ast_yacc.parser
2245 lexer = drel_ast_yacc.lexer
2246 my_namespace = self.keys()
2247 my_namespace = dict(zip(my_namespace,my_namespace))
2248 default_attrs = ["_units.code", "_enumeration.default"]
2249 # we provide a table of loopable categories {cat_name:((key1,key2..),[item_name,...]),...})
2250 loopable_cats = self.get_loopable_cats()
2251 loop_keys = [listify(self[a]["_category_key.name"]) for a in loopable_cats if "_category_key.name" in self[a].keys()]
2252 loop_keys = [[self[a]['_name.object_id'] for a in b if a in self.keys()] for b in loop_keys]
2253 cat_names = [self.names_in_cat(a,names_only=True) for a in loopable_cats]
2254 loop_info = dict(zip(loopable_cats,zip(loop_keys,cat_names)))
2255 # parser.listable_items = [a for a in self.keys() if "*" in self[a].get("_type.dimension","")]
2256 derivable_list = [a for a in self.keys() if "_method.expression" in self[a] \
2257 and self[a].get("_name.category_id","")!= "function"]
2258 for derivable in derivable_list:
2259 # reset the list of visible names for parser
2260 special_ids = [dict(zip(self.keys(),self.keys()))]
2261 print("Target id: {}".format(derivable))
2262 drel_exprs = self[derivable]["_method.expression"]
2263 drel_purposes = self[derivable]["_method.purpose"]
2264 all_methods = []
2265 if not isinstance(drel_exprs,list):
2266 drel_exprs = [drel_exprs]
2267 drel_purposes = [drel_purposes]
2268 for drel_purpose,drel_expr in zip(drel_purposes,drel_exprs):
2269
2270 target_id = derivable
2271 drel_expr = "\n".join(drel_expr.splitlines())
2272 # print("Transforming %s" % drel_expr)
2273 # List categories are treated differently...
2274 try:
2275 meth_ast = parser.parse(drel_expr+"\n",lexer=lexer)
2276 except:
2277 print('Syntax error in method for {}; leaving as is'.format(derivable))
2278 a,b = sys.exc_info()[:2]
2279 print((repr(a),repr(b)))
2280 print(traceback.print_tb(sys.exc_info()[-1],None,sys.stdout))
2281 # reset the lexer
2282 lexer.begin('INITIAL')
2283 continue
2284 # Construct the python method
2285 cat_meth = False
2286 if self[derivable].get('_definition.scope','Item') == 'Category':
2287 cat_meth = True
2288
2289 # Default methods have a different target_id
2290 if drel_purpose == "Definition":
2291
2292 # Find the DDLm attribute that is being redefined
2293 target_id = [d for d in default_attrs if d in drel_expr]
2294 if len(target_id) != 1:
2295 continue
2296 target_id = target_id[0]
2297 print("Found default attribute {} for {}".format(target_id, derivable))
2298
2299 pyth_meth = py_from_ast.make_python_function(meth_ast,"pyfunc",target_id,
2300 loopable=loop_info,
2301 cif_dic = self,cat_meth=cat_meth)
2302 all_methods.append((target_id, pyth_meth))
2303 if len(all_methods)>0:
2304 save_overwrite = self[derivable].overwrite
2305 self[derivable].overwrite = True
2306 self[derivable]["_method.py_expression"] = all_methods
2307 self[derivable].overwrite = save_overwrite
2308 #print("Final result:\n " + repr(self[derivable]["_method.py_expression"]))
2309
2310 # Drel functions are all stored in category 'functions' in our final dictionary. We want to
2311 # convert them to executable python code and store them in an appropriate namespace which we
2312 # can then pass to our individual item methods. As dREL accepts only linefeed as a terminator,
2313 # we convert the input text as required.
2314 #
2315 #
2316 # <Store dREL functions>=
2317 def add_drel_funcs(self):
2318 from .drel import drel_ast_yacc
2319 from .drel import py_from_ast
2320 funclist = [a for a in self.keys() if self[a].get("_name.category_id","")=='function']
2321 # LOOK AT _function.sawtooth
2322 # It is trying to take the code expression because in some dics it appears inside a loop
2323 funcnames = []
2324 for a in funclist:
2325 if not self[a].loops.keys():
2326 temp = (self[a]["_name.object_id"],self[a]["_method.expression"])
2327 else:
2328 temp = (self[a]["_name.object_id"], getattr(self[a].GetKeyedPacket("_method.purpose","Evaluation"),"_method.expression"))
2329
2330 funcnames.append(temp)
2331 # create executable python code...
2332 parser = drel_ast_yacc.parser
2333 # we provide a table of loopable categories {cat_name:(key,[item_name,...]),...})
2334 loopable_cats = self.get_loopable_cats()
2335 loop_keys = [listify(self[a]["_category_key.name"]) for a in loopable_cats if "_category_key.name" in self[a].keys()]
2336 loop_keys = [[self[a]['_name.object_id'] for a in b if a in self.keys()] for b in loop_keys]
2337 cat_names = [self.names_in_cat(a,names_only=True) for a in loopable_cats]
2338 loop_info = dict(zip(loopable_cats,zip(loop_keys,cat_names)))
2339 for funcname,funcbody in funcnames:
2340 newline_body = "\n".join(funcbody.splitlines())
2341 parser.target_id = funcname
2342 res_ast = parser.parse(newline_body)
2343 py_function = py_from_ast.make_python_function(res_ast,None,targetname=funcname,func_def=True,loopable=loop_info,cif_dic = self)
2344 #print('dREL library function ->\n' + py_function)
2345 global_table = globals()
2346 exec(py_function, global_table) #add to namespace
2347 #print('Globals after dREL functions added:' + repr(globals()))
2348 self.ddlm_functions = globals() #for outside access
2349
2350 # When a dictionary is available during CIF file access, we can resolve a missing dataname in
2351 # four ways: (1) check if it is defined under an alias; (2) use a dREL method to calculate the
2352 # value; (3) use default values if defined. We resolve in this priority. Note that we also
2353 # convert to the appropriate type. A subsection of (2) is that, if the entire category is
2354 # missing, we can either use DDLm category construction information or a category
2355 # method to find our values; we only do this if no items in the category are present. We
2356 # raise a StarDerivationError if we cannot derive the item, and internally we set result
2357 # to None as we go through the various ways of deriving the item.
2358 #
2359 # The store_value flag asks us to update the ciffile object with the new value. We remove any
2360 # numpy dependencies before doing this, which means that we must recreate the numpy type
2361 # when returning it.
2362 #
2363 # The [[allow_defaults]] flag allows default values to be derived. In a situation where
2364 # multiple methods are available for deriving an item, a calculation that accepts
2365 # default values will return incorrect values in any situation where an alternative
2366 # calculation method would have given correct values. For example, if the default value
2367 # of axis.vector[n] is 0, but I can use an alternative derivation for axis.vector from
2368 # a different setting, then a calculation that creates axis.vector from the components
2369 # will give the wrong answer as it will fill in default values when the components are
2370 # missing. The track_recursion decorator code handles this by propagating the initial
2371 # value of allow_defaults to nested calls.
2372 #
2373 #
2374 # <Derive item information>=
2375 @track_recursion
2376 def derive_item(self,start_key,cifdata,store_value = False,allow_defaults=True):
2377 key = start_key #starting value
2378 result = None #success is a non-None value
2379 default_result = False #we have not used a default value
2380 # Aliases. If we have this item under a different name, find it and
2381 # return it immediately after putting it into the correct type. We could
2382 # be passed either the dictionary defined dataname, or any of its
2383 # previous names. We have stored our aliases as a table indexed by
2384 # dictionary-defined dataname in order to potentially translate from old
2385 # to new datanames. Once we find a dataname that
2386 # is present in the datafile, we return it. Note that we have two types
2387 # of check: in one we are given an old-style dataname, and have to find
2388 # the new or other old version (in which case we have to check the key
2389 # of the table) and in the other check we are given the latest version
2390 # of the dataname and have to check for older names in the datafile -
2391 # this latter is the dREL situation so we have optimised for it be
2392 # checking that first and making the modern datanames the table keys.
2393 # Note that this section of code occurs first in the 'derive_item'
2394 # routine and will change the value of 'key' to the dictionary value
2395 # even if nothing is available in the datafile, thereby enabling the
2396 # other derivation routes possible.
2397 #
2398 #
2399 # <Resolve using aliases>=
2400 # check for aliases
2401 # check for an older form of a new value
2402 found_it = [k for k in self.alias_table.get(key,[]) if k in cifdata]
2403 if len(found_it)>0:
2404 corrected_type = self.change_type(key,cifdata[found_it[0]])
2405 return corrected_type
2406 # now do the reverse check - any alternative form
2407 alias_name = [a for a in self.alias_table.items() if key in a[1]]
2408 print('Aliases for {}: {}'.format(key,repr(alias_name)))
2409 if len(alias_name)==1:
2410 key = alias_name[0][0] #actual definition name
2411 if key in cifdata: return self.change_type(key,cifdata[key])
2412 found_it = [k for k in alias_name[0][1] if k in cifdata]
2413 if len(found_it)>0:
2414 return self.change_type(key,cifdata[found_it[0]])
2415 elif len(alias_name)>1:
2416 raise CifError('Dictionary error: dataname alias appears in different definitions: ' + repr(alias_name))
2417
2418 the_category = self[key]["_name.category_id"]
2419 cat_names = [a for a in self.keys() if self[a].get("_name.category_id",None)==the_category]
2420 has_cat_names = [a for a in cat_names if cifdata.has_key_or_alias(a)]
2421 # store any default value in case we have a problem
2422 def_val = self[key].get("_enumeration.default","")
2423 def_index_val = self[key].get("_enumeration.def_index_id","")
2424 if len(has_cat_names)==0: # try category method
2425 # \subsection{Creating categories}
2426 #
2427 # A category can be created from scratch (i.e. the identifiers produced)
2428 # if the appropriate DDLm attributes are defined - currently,
2429 # experimental attributes 'category_construct_local' are included in the test
2430 # dictionaries for this purpose. They define two types of 'pullback'
2431 # (see any category theory textbook), which we can use to create a
2432 # category. If these attributes are absent, we can instead execute a
2433 # category method. We only add any new category items calculated in
2434 # this way if the category does not exist or (i) the category IDs are
2435 # not already present and (ii) the set of attributes calculated is an
2436 # exact match for the set of datanames already present.
2437 #
2438 #
2439 # <Populate a category>=
2440 cat_result = {}
2441 pulled_from_cats = [k for k in self.keys() if '_category_construct_local.components' in self[k]]
2442 pulled_from_cats = [(k,[
2443 self[n]['_name.category_id'] for n in self[k]['_category_construct_local.components']]
2444 ) for k in pulled_from_cats]
2445 pulled_to_cats = [k[0] for k in pulled_from_cats if the_category in k[1]]
2446 if '_category_construct_local.type' in self[the_category]:
2447 print("**Now constructing category {} using DDLm attributes**".format(the_category))
2448 try:
2449 cat_result = self.construct_category(the_category,cifdata,store_value=True)
2450 except (CifRecursionError,StarFile.StarDerivationError):
2451 print('** Failed to construct category {} (error)'.format(the_category))
2452 # Trying a pull-back when the category is partially populated
2453 # will not work, hence we test that cat_result has no keys
2454 if len(pulled_to_cats)>0 and len(cat_result)==0:
2455 print("**Now populating category {} from pulled-back category {}".format(the_category,repr(pulled_to_cats)))
2456 try:
2457 cat_result = self.push_from_pullback(the_category,pulled_to_cats,cifdata,store_value=True)
2458 except (CifRecursionError,StarFile.StarDerivationError):
2459 print('** Failed to construct category {} from pullback information (error)'.format(the_category))
2460 if '_method.py_expression' in self[the_category] and key not in cat_result:
2461 print("**Now applying category method for {} in search of {}**".format(the_category,key))
2462 cat_result = self.derive_item(the_category,cifdata,store_value=True)
2463 print("**Tried pullbacks, obtained for {} ".format(the_category + repr(cat_result)))
2464 # do we now have our value?
2465 if key in cat_result:
2466 return cat_result[key]
2467
2468 # Recalculate in case it actually worked
2469 has_cat_names = [a for a in cat_names if cifdata.has_key_or_alias(a)]
2470 the_funcs = [f[1] for f in self[key].get('_method.py_expression',[]) if f[0] == key.lower()]
2471 if len(the_funcs) > 0: #attempt to calculate it
2472 # Executing a dREL method. The execution defines a function, 'pyfunc' which is
2473 # then itself executed in global scope. This has caused us some grief in order to
2474 # get the bindings right (e.g. having StarList in scope). Essentially, anything
2475 # that the method might refer to should be in scope at this point, otherwise the
2476 # way Python works it will be too late to have things in scope within the enclosing
2477 # routine that calls this function. Importing the necessary modules at the beginning
2478 # of the module file (as done here) seems to be a reliable way to go.
2479 #
2480 #
2481 # <Execute pythonised dREL method>=
2482 #global_table = globals()
2483 #global_table.update(self.ddlm_functions)
2484 for one_func in the_funcs:
2485 print('Executing function for {}:'.format(key))
2486 #print(one_func)
2487 exec(one_func, globals()) #will access dREL functions, puts "pyfunc" in scope
2488 # print('in following global environment: ' + repr(global_table))
2489 stored_setting = cifdata.provide_value
2490 cifdata.provide_value = True
2491 try:
2492 result = pyfunc(cifdata)
2493 except CifRecursionError as s:
2494 print(s)
2495 result = None
2496 except StarFile.StarDerivationError as s:
2497 print(s)
2498 result = None
2499 finally:
2500 cifdata.provide_value = stored_setting
2501 if result is not None:
2502 break
2503 #print("Function returned {!r}".format(result))
2504
2505 if result is None and allow_defaults: # try defaults
2506 # Using the defaults system. We also check out any default values
2507 # which we could return in case of error. Note that ddlm adds the
2508 # '_enumerations.def_index_id' as an alternative way to derive a value
2509 # from a table. During development, we deliberately allow errors
2510 # arising from the method to be propagated so that we can see anything
2511 # that might be wrong.
2512 #
2513 # If we are using default values, we need to fill in the whole column
2514 # of a looped category. This is taken care of at the end of the derivation
2515 # function, so we simply set a flag to say that this is necessary.
2516 #
2517 #
2518 # <Work out default value of dataname>=
2519 if def_val:
2520 result = self.change_type(key,def_val)
2521 default_result = True
2522 elif def_index_val: #derive a default value
2523 index_vals = self[key]["_enumeration_default.index"]
2524 val_to_index = cifdata[def_index_val] #what we are keying on
2525 lcase_comp = False
2526 if self[def_index_val]['_type.contents'] in ['Code','Name','Tag']:
2527 lcase_comp = True
2528 index_vals = [a.lower() for a in index_vals]
2529 # Handle loops
2530 if isinstance(val_to_index,list):
2531 if lcase_comp:
2532 val_to_index = [a.lower() for a in val_to_index]
2533 keypos = [index_vals.index(a) for a in val_to_index]
2534 result = [self[key]["_enumeration_default.value"][a] for a in keypos]
2535 else:
2536 if lcase_comp:
2537 val_to_index = val_to_index.lower()
2538 keypos = index_vals.index(val_to_index) #value error if no such value available
2539 result = self[key]["_enumeration_default.value"][keypos]
2540 default_result = True #flag that it must be extended
2541 result = self.change_type(key,result)
2542 print("Indexed on {} to get {} for {}".format(def_index_val,repr(result),repr(val_to_index)))
2543
2544 # Or else find any default functions
2545 else:
2546 def_func = [f[1] for f in self[key].get("_method.py_expression",[]) if f[0] == "_enumeration.default"]
2547 if len(def_func) == 1:
2548 print('Executing default function for {}:'.format(key))
2549 #print(one_func)
2550 exec(def_func[0], globals()) #will access dREL functions, puts "pyfunc" in scope
2551 # print('in following global environment: ' + repr(global_table))
2552 stored_setting = cifdata.provide_value
2553 cifdata.provide_value = True
2554 try:
2555 result = pyfunc(cifdata)
2556 except CifRecursionError as s:
2557 print(s)
2558 result = None
2559 except StarFile.StarDerivationError as s:
2560 print(s)
2561 result = None
2562 finally:
2563 cifdata.provide_value = stored_setting
2564
2565 # read it in
2566 if result is None: #can't do anything else
2567 print('Warning: no way of deriving item {}, allow_defaults is {}'.format(key,repr(allow_defaults)))
2568 raise StarFile.StarDerivationError(start_key)
2569 # Adjusting our calculated value. If we have used a default value or we have None, we
2570 # need to make the dimension match the currently-existing length of the category.
2571 #
2572 #
2573 # <Adjust value to be appropriate length>=
2574 is_looped = False
2575 if self[the_category].get('_definition.class','Set')=='Loop':
2576 is_looped = True
2577 if len(has_cat_names)>0: #this category already exists
2578 if result is None or default_result: #need to create a list of values
2579 loop_len = len(cifdata[has_cat_names[0]])
2580 out_result = [result]*loop_len
2581 result = out_result
2582 else: #nothing exists in this category, we can't store this at all
2583 print('Resetting result {} for {} to null list as category is empty'.format(key,result))
2584 result = []
2585
2586 # now try to insert the new information into the right place
2587 # find if items of this category already appear...
2588 # Never cache empty values
2589 if not (isinstance(result,list) and len(result)==0) and\
2590 store_value:
2591 if self[key].get("_definition.scope","Item")=='Item':
2592 if is_looped:
2593 result = self.store_new_looped_value(key,cifdata,result,default_result)
2594 else:
2595 result = self.store_new_unlooped_value(key,cifdata,result)
2596 else:
2597 self.store_new_cat_values(cifdata,result,the_category)
2598 return result
2599
2600 # Storing a dREL-derived value back into our CifFile. The dREL value (or potentially
2601 # a simple default value) may correspond to an entire column, or even an entire loop
2602 # for category methods. We have to distinguish between list values that are StarLists,
2603 # that is, a single CIF value, and list values that correspond to a column of a loop.
2604 # Additionally, testing has revealed that we cannot judge the type of elements in a list
2605 # by the first element (e.g. could be a plain list, then a numpy array).
2606 #
2607 # The [[conv_from_numpy]] mini-functions are designed to handle arbitrary numpy arrays
2608 # quickly.
2609 #
2610 #
2611 # <Storing a dREL-derived value>=
2612 def store_new_looped_value(self,key,cifdata,result,default_result):
2613 """Store a looped value from the dREL system into a CifFile"""
2614 # try to change any matrices etc. to lists
2615 the_category = self[key]["_name.category_id"]
2616 out_result = result
2617 if result is not None and not default_result:
2618 # find any numpy arrays
2619 def conv_from_numpy(one_elem):
2620 if not hasattr(one_elem,'dtype'):
2621 if isinstance(one_elem,(list,tuple)):
2622 return StarFile.StarList([conv_from_numpy(a) for a in one_elem])
2623 return one_elem
2624 if one_elem.size > 1: #so is not a float
2625 return StarFile.StarList([conv_from_numpy(a) for a in one_elem.tolist()])
2626 else:
2627 try:
2628 return one_elem.item(0)
2629 except:
2630 return one_elem
2631 out_result = [conv_from_numpy(a) for a in result]
2632 # so out_result now contains a value suitable for storage
2633 cat_names = [a for a in self.keys() if self[a].get("_name.category_id",None)==the_category]
2634 has_cat_names = [a for a in cat_names if a in cifdata]
2635 print('Adding {}, found pre-existing names: '.format(key) + repr(has_cat_names))
2636 if len(has_cat_names)>0: #this category already exists
2637 cifdata[key] = out_result #lengths must match or else!!
2638 cifdata.AddLoopName(has_cat_names[0],key)
2639 else:
2640 cifdata[key] = out_result
2641 cifdata.CreateLoop([key])
2642 print('Loop info:' + repr(cifdata.loops))
2643 return out_result
2644
2645 def store_new_unlooped_value(self,key,cifdata,result):
2646 """Store a single value from the dREL system"""
2647 if result is not None and hasattr(result,'dtype'):
2648 if result.size > 1:
2649 out_result = StarFile.StarList(result.tolist())
2650 cifdata[key] = out_result
2651 else:
2652 cifdata[key] = result.item(0)
2653 else:
2654 cifdata[key] = result
2655 return result
2656
2657 # Constructing categories using DDLm attributes. We have defined local
2658 # attributes that describe category construction using mathematical
2659 # 'pullbacks'. We can use these to fill a category, but also to populate
2660 # a category if the pullback category is available. We use [[list]] to coerce
2661 # all values to a list in case we are passed a numpy array, which does not
2662 # have an 'index' method.
2663 #
2664 #
2665 # <Construct a category>=
2666 def construct_category(self,category,cifdata,store_value=True):
2667 """Construct a category using DDLm attributes"""
2668 con_type = self[category].get('_category_construct_local.type',None)
2669 if con_type == None:
2670 return {}
2671 if con_type == 'Pullback' or con_type == 'Filter':
2672 morphisms = self[category]['_category_construct_local.components']
2673 morph_values = [cifdata[a] for a in morphisms] # the mapped values for each cat
2674 cats = [self[a]['_name.category_id'] for a in morphisms]
2675 cat_keys = [self[a]['_category.key_id'] for a in cats]
2676 cat_values = [list(cifdata[a]) for a in cat_keys] #the category key values for each cat
2677 if con_type == 'Filter':
2678 int_filter = self[category].get('_category_construct_local.integer_filter',None)
2679 text_filter = self[category].get('_category_construct_local.text_filter',None)
2680 if int_filter is not None:
2681 morph_values.append([int(a) for a in int_filter])
2682 if text_filter is not None:
2683 morph_values.append(text_filter)
2684 cat_values.append(range(len(morph_values[-1])))
2685 # create the mathematical product filtered by equality of dataname values
2686 pullback_ids = [(x,y) for x in cat_values[0] for y in cat_values[1] \
2687 if morph_values[0][cat_values[0].index(x)]==morph_values[1][cat_values[1].index(y)]]
2688 # now prepare for return
2689 if len(pullback_ids)==0:
2690 return {}
2691 newids = self[category]['_category_construct_local.new_ids']
2692 fullnewids = [self.cat_obj_lookup_table[(category,n)][0] for n in newids]
2693 if con_type == 'Pullback':
2694 final_results = {fullnewids[0]:[x[0] for x in pullback_ids],fullnewids[1]:[x[1] for x in pullback_ids]}
2695 final_results.update(self.duplicate_datanames(cifdata,cats[0],category,key_vals = final_results[fullnewids[0]],skip_names=newids))
2696 final_results.update(self.duplicate_datanames(cifdata,cats[1],category,key_vals = final_results[fullnewids[1]],skip_names=newids))
2697 elif con_type == 'Filter': #simple filter
2698 final_results = {fullnewids[0]:[x[0] for x in pullback_ids]}
2699 final_results.update(self.duplicate_datanames(cifdata,cats[0],category,key_vals = final_results[fullnewids[0]],skip_names=newids))
2700 if store_value:
2701 self.store_new_cat_values(cifdata,final_results,category)
2702 return final_results
2703
2704 # Going the other way. If we have the pulled-back category, we can populate the
2705 # pulled-from categories with their identifier items using projections from the
2706 # pulled-back category. In the special case that we have a pullback that uses
2707 # a filter function with a single element, we can automatically populate the
2708 # whole commutative square. We also by default populate identically-named
2709 # datanames.
2710 #
2711 # The projection datanames are given in _category_construct_local.new_ids, and they always
2712 # map to the key of the projected-to category.
2713 #
2714 #
2715 # <Insert category items from pullback information>=
2716 def push_from_pullback(self,target_category,source_categories,cifdata,store_value=True):
2717 """Each of the categories in source_categories are pullbacks that include
2718 the target_category"""
2719 target_key = self[target_category]['_category.key_id']
2720 result = {target_key:[]}
2721 first_time = True
2722 # for each source category, determine which element goes to the target
2723 for sc in source_categories:
2724 components = self[sc]['_category_construct_local.components']
2725 comp_cats = [self[c]['_name.category_id'] for c in components]
2726 new_ids = self[sc]['_category_construct_local.new_ids']
2727 source_ids = [self.cat_obj_lookup_table[(sc,n)][0] for n in new_ids]
2728 if len(components) == 2: # not a filter
2729 element_pos = comp_cats.index(target_category)
2730 old_id = source_ids[element_pos]
2731 print('Using {} to populate {}'.format(old_id,target_key))
2732 result[target_key].extend(cifdata[old_id])
2733 # project through all identical names
2734 extra_result = self.duplicate_datanames(cifdata,sc,target_category,skip_names=new_ids+[target_key])
2735 # we only include keys that are common to all categories
2736 if first_time:
2737 result.update(extra_result)
2738 else:
2739 for k in extra_result.keys():
2740 if k in result:
2741 print('Updating {}: was {}'.format(k,repr(result[k])))
2742 result[k].extend(extra_result[k])
2743 else:
2744 extra_result = self.duplicate_datanames(cifdata,sc,target_category,skip_names=new_ids)
2745 if len(extra_result)>0 or source_ids[0] in cifdata: #something is present
2746 result[target_key].extend(cifdata[source_ids[0]])
2747 for k in extra_result.keys():
2748 if k in result:
2749 print('Reverse filter: Updating {}: was {}'.format(k,repr(result[k])))
2750 result[k].extend(extra_result[k])
2751 else:
2752 result[k]=extra_result[k]
2753 # Bonus derivation if there is a singleton filter
2754 if self[sc]['_category_construct_local.type'] == 'Filter':
2755 int_filter = self[sc].get('_category_construct_local.integer_filter',None)
2756 text_filter = self[sc].get('_category_construct_local.text_filter',None)
2757 if int_filter is not None:
2758 filter_values = int_filter
2759 else:
2760 filter_values = text_filter
2761 if len(filter_values)==1: #a singleton
2762 extra_dataname = self[sc]['_category_construct_local.components'][0]
2763 if int_filter is not None:
2764 new_value = [int(filter_values[0])] * len(cifdata[source_ids[0]])
2765 else:
2766 new_value = filter_values * len(cifdata[source_ids[0]])
2767 if extra_dataname not in result:
2768 result[extra_dataname] = new_value
2769 else:
2770 result[extra_dataname].extend(new_value)
2771 else:
2772 raise ValueError('Unexpected category construct type' + self[sc]['_category_construct_local.type'])
2773 first_time = False
2774 # check for sanity - all dataname lengths must be identical
2775 datalen = len(set([len(a) for a in result.values()]))
2776 if datalen != 1:
2777 raise AssertionError('Failed to construct equal-length category items,'+ repr(result))
2778 if store_value:
2779 print('Now storing ' + repr(result))
2780 self.store_new_cat_values(cifdata,result,target_category)
2781 return result
2782
2783 def duplicate_datanames(self,cifdata,from_category,to_category,key_vals=None,skip_names=[]):
2784 """Copy across datanames for which the from_category key equals [[key_vals]]"""
2785 result = {}
2786 s_names_in_cat = set(self.names_in_cat(from_category,names_only=True))
2787 t_names_in_cat = set(self.names_in_cat(to_category,names_only=True))
2788 can_project = s_names_in_cat & t_names_in_cat
2789 can_project -= set(skip_names) #already dealt with
2790 source_key = self[from_category]['_category.key_id']
2791 print('Source dataname set: ' + repr(s_names_in_cat))
2792 print('Target dataname set: ' + repr(t_names_in_cat))
2793 print('Projecting through following datanames from {} to {}'.format(from_category,to_category) + repr(can_project))
2794 for project_name in can_project:
2795 full_from_name = self.cat_obj_lookup_table[(from_category.lower(),project_name.lower())][0]
2796 full_to_name = self.cat_obj_lookup_table[(to_category.lower(),project_name.lower())][0]
2797 if key_vals is None:
2798 try:
2799 result[full_to_name] = cifdata[full_from_name]
2800 except StarFile.StarDerivationError:
2801 pass
2802 else:
2803 all_key_vals = cifdata[source_key]
2804 filter_pos = [all_key_vals.index(a) for a in key_vals]
2805 try:
2806 all_data_vals = cifdata[full_from_name]
2807 except StarFile.StarDerivationError:
2808 pass
2809 result[full_to_name] = [all_data_vals[i] for i in filter_pos]
2810 return result
2811
2812 # Storing category results. dREL allows 'category methods', which initialise an entire
2813 # category. The dREL system that we have written returns a dictionary of lists, with the
2814 # dictionary keys being item names. It is sufficient for us to extract each of these names
2815 # and pass them to our normal storage routine. If some of the values in the category key
2816 # are duplicated, we bail, as we may overwrite previous values. We also bail if we
2817 # do not have exactly the same datanames available, as we are too lazy to insert 'unknown'
2818 # in the non-matching positions.
2819 #
2820 #
2821 # <Storing a whole new dREL-derived category>=
2822 def store_new_cat_values(self,cifdata,result,the_category):
2823 """Store the values in [[result]] into [[cifdata]]"""
2824 the_key = [a for a in result.keys() if self[a].get('_type.purpose','')=='Key']
2825 double_names = [a for a in result.keys() if a in cifdata]
2826 if len(double_names)>0:
2827 already_present = [a for a in self.names_in_cat(the_category) if a in cifdata]
2828 if set(already_present) != set(result.keys()):
2829 print("Category {} not updated, mismatched datanames: {}".format(the_category, repr(set(already_present)^set(result.keys()))))
2830 return
2831 #check key values
2832 old_keys = set(cifdata[the_key])
2833 common_keys = old_keys & set(result[the_key])
2834 if len(common_keys)>0:
2835 print("Category {} not updated, key values in common:".format(common_keys))
2836 return
2837 #extend result values with old values
2838 for one_name,one_value in result.items():
2839 result[one_name].extend(cifdata[one_name])
2840 for one_name, one_value in result.items():
2841 try:
2842 self.store_new_looped_value(one_name,cifdata,one_value,False)
2843 except StarFile.StarError:
2844 print('{}: Not replacing {} with calculated {}'.format(one_name,repr(cifdata[one_name]),repr(one_value)))
2845 #put the key as the first item
2846 print('Fixing item order for {}'.format(repr(the_key)))
2847 for one_key in the_key: #should only be one
2848 cifdata.ChangeItemOrder(one_key,0)
2849
2850
2851 # If a key is missing, we may sometimes fill in default values for it, for example,
2852 # a missing atom type may be assumed to have a number in cell of 0.
2853 #
2854 #
2855 # <Generating default packets>=
2856 def generate_default_packet(self,catname,catkey,keyvalue):
2857 """Return a StarPacket with items from ``catname`` and a key value
2858 of ``keyvalue``"""
2859 newpack = StarPacket()
2860 for na in self.names_in_cat(catname):
2861 def_val = self[na].get("_enumeration.default","")
2862 if def_val:
2863 final_val = self.change_type(na,def_val)
2864 newpack.extend(final_val)
2865 setattr(newpack,na,final_val)
2866 if len(newpack)>0:
2867 newpack.extend(keyvalue)
2868 setattr(newpack,catkey,keyvalue)
2869 return newpack
2870
2871
2872 # In the single case of executing dREL methods, we wish to return numpy
2873 # Arrays from our __getitem__ so that the mathematical operations proceed
2874 # as expected for matrix etc. objects. This needs to be reimplimented:
2875 # currently numpy must be installed for 'numerification' to work.
2876 #
2877 #
2878 # <Switch on numpy arrays>=
2879 def switch_numpy(self,to_val):
2880 pass
2881
2882 # This function converts the string-valued items returned from the parser into
2883 # types that correspond to the dictionary specifications. For DDLm it must also
2884 # deal with potentially complex structures containing both strings and numbers. We
2885 # have tried to avoid introducing a dependence on Numpy in general for PyCIFRW,
2886 # but once we get into the realm of DDLm we require Numpy arrays in order to
2887 # handle the various processing tasks. This routine is the one that will
2888 # create the arrays from the StarList types, so needs access to numpy. However,
2889 # this routine is only called if a DDLm dictionary has been provided, so we
2890 # should still have no Numpy dependence for non DDLm cases
2891 #
2892 # For safety, we check that our object is really string-valued. In practice,
2893 # this means that it is either a string, a list of strings, or a list of
2894 # StarLists as these are the only datastructures that an as-parsed file will
2895 # contain.
2896 #
2897 #
2898 # <Convert string to appropriate type>=
2899 def change_type(self,itemname,inval):
2900 if inval == "?": return inval
2901 change_function = convert_type(self[itemname])
2902 if isinstance(inval,list) and not isinstance(inval,StarFile.StarList): #from a loop
2903 newval = list([change_function(a) for a in inval])
2904 else:
2905 newval = change_function(inval)
2906 return newval
2907
2908 # \section{Validation}
2909 #
2910 # A DDL provides lots of information that can be used to check a datafile or dictionary
2911 # for consistency. Currently, the DDL-appropriate routines are installed at initialisation
2912 # time.
2913 #
2914 #
2915 # <Validation routines>=
2916 # Each dictionary has a set of validation functions associated with it based
2917 # on the information contained in the DDL. The following function is called
2918 # on initialisation.
2919 #
2920 #
2921 # <Install validation functions>=
2922 def install_validation_functions(self):
2923 """Install the DDL-appropriate validation checks"""
2924 if self.diclang != 'DDLm':
2925 # functions which check conformance
2926 self.item_validation_funs = [
2927 self.validate_item_type,
2928 self.validate_item_esd,
2929 self.validate_item_enum,
2930 self.validate_enum_range,
2931 self.validate_looping
2932 ]
2933 # functions checking loop values
2934 self.loop_validation_funs = [
2935 self.validate_loop_membership,
2936 self.validate_loop_key,
2937 self.validate_loop_references
2938 ]
2939
2940 # Ensure that loop id tags are unique, more functions may be added
2941 # in the future
2942 self.loop_id_uniqueness_funs = [
2943 self.validate_loop_key_uniqueness
2944 ]
2945
2946 # where we need to look at other values
2947 self.global_validation_funs = [
2948 self.validate_exclusion,
2949 self.validate_parent,
2950 self.validate_child,
2951 self.validate_dependents,
2952 self.validate_uniqueness
2953 ]
2954 # where only a full block will do
2955 self.block_validation_funs = [
2956 self.validate_mandatory_category
2957 ]
2958 # removal is quicker with special checks
2959 self.global_remove_validation_funs = [
2960 self.validate_remove_parent_child
2961 ]
2962 elif self.diclang == 'DDLm':
2963 self.item_validation_funs = [
2964 self.validate_item_enum,
2965 self.validate_item_esd_ddlm,
2966 ]
2967 self.loop_validation_funs = [
2968 self.validate_looping_ddlm,
2969 self.validate_loop_key_ddlm,
2970 self.validate_loop_membership
2971 ]
2972 self.loop_id_uniqueness_funs = [
2973 self.validate_loop_key_uniqueness_ddlm
2974 ]
2975 self.global_validation_funs = []
2976 self.block_validation_funs = [
2977 self.check_mandatory_items,
2978 self.check_prohibited_items
2979 ]
2980 self.global_remove_validation_funs = []
2981 self.optimize = False # default value
2982 self.done_parents = []
2983 self.done_children = []
2984 self.done_keys = []
2985
2986 # Some things are independent of where an item occurs in the file; we
2987 # check those things here. All functions are expected to return a
2988 # dictionary with at least one key: "result", as well as optional
2989 # keys depending on the type of error.
2990 #
2991 #
2992 # <Item-level validation>=
2993 # Validate the type of an item
2994 #
2995 # We use the expressions for type that we have available to check that
2996 # the type of the item passed to us matches up. We may have a list of
2997 # items, so be aware of that. We define a tiny matching function so
2998 # that we do not have to do a double match to catch the non-matching
2999 # case, which returns None and thus an attribute error if we immediately
3000 # try to get a group.
3001 #
3002 # Note also that none of the extant dictionaries use the 'none' or 'seq'
3003 # values for type. The seq value in particular would complicate matters.
3004 #
3005 #
3006 # <Validate the type of an item (DDL1/2)>=
3007 def validate_item_type(self,item_name,item_value):
3008 def mymatch(m,a):
3009 res = m.match(a)
3010 if res != None: return res.group()
3011 else: return ""
3012 target_type = self[item_name].get(self.type_spec)
3013 if target_type == None: # e.g. a category definition
3014 return {"result":True} # not restricted in any way
3015 matchexpr = self.typedic[target_type]
3016 item_values = listify(item_value)
3017 #for item in item_values:
3018 #print("Type match " + item_name + " " + item + ":",)
3019 #skip dots and question marks
3020 check_all = [a for a in item_values if a !="." and a != "?"]
3021 check_all = [a for a in check_all if mymatch(matchexpr,a) != a]
3022 if len(check_all)>0: return {"result":False,"bad_values":check_all}
3023 else: return {"result":True}
3024
3025 # DDLm types are far more nuanced, and we are not provided with prepacked
3026 # regular expressions in order to check them. We have identified the following
3027 # checks: that the type is in the correct container; that the contents are as
3028 # described in _type.contents; that 'State' purpose datanames have a list of
3029 # enumerated states; that 'Link' purpose datanames have '_name.linked_item_id'
3030 # in the same definition; that 'SU' purpose datanames also has the above.
3031 #
3032 #
3033 # <Validate the type of an item (DDLm)>=
3034 def decide(self,result_list):
3035 """Construct the return list"""
3036 if len(result_list)==0:
3037 return {"result":True}
3038 else:
3039 return {"result":False,"bad_values":result_list}
3040
3041 def validate_item_container(self, item_name,item_value):
3042 container_type = self[item_name]['_type.container']
3043 item_values = listify(item_value)
3044 if container_type == 'Single':
3045 okcheck = [a for a in item_values if not isinstance(a,(int,float,long,unicode))]
3046 return self.decide(okcheck)
3047 if container_type in ('Multiple','List'):
3048 okcheck = [a for a in item_values if not isinstance(a,StarList)]
3049 return self.decide(okcheck)
3050 if container_type == 'Array': #A list with numerical values
3051 okcheck = [a for a in item_values if not isinstance(a,StarList)]
3052 first_check = self.decide(okcheck)
3053 if not first_check['result']: return first_check
3054 #num_check = [a for a in item_values if len([b for b in a if not isinstance
3055
3056 # Esds. Numbers are sometimes not allowed to have esds appended. The
3057 # default is that esds are not OK, and we should also skip anything that
3058 # has character type, as that is automatically not a candidate for esds.
3059 #
3060 # Note that we make use of the primitive type here; there are some
3061 # cases where a string type looks like an esd, so unless we know
3062 # we have a number we ignore these cases.
3063 #
3064 # DDLm requires an esd if _type.purpose is Measurand, and should not have an
3065 # esd if _type.purpose is Number.
3066 #
3067 #
3068 # <Validate esd presence>=
3069 def validate_item_esd(self,item_name,item_value):
3070 if self[item_name].get(self.primitive_type) != 'numb':
3071 return {"result":None}
3072 can_esd = self[item_name].get(self.esd_spec,"none") == "esd"
3073 if can_esd: return {"result":True} #must be OK!
3074 item_values = listify(item_value)
3075 check_all = list([a for a in item_values if get_number_with_esd(a)[1] != None])
3076 if len(check_all)>0: return {"result":False,"bad_values":check_all}
3077 return {"result":True}
3078
3079 def validate_item_esd_ddlm(self,item_name,item_value):
3080 if self[item_name].get('self.primitive_type') not in \
3081 ['Count','Index','Integer','Real','Imag','Complex','Binary','Hexadecimal','Octal']:
3082 return {"result":None}
3083 can_esd = True
3084 if self[item_name].get('_type.purpose') != 'Measurand':
3085 can_esd = False
3086 item_values = listify(item_value)
3087 check_all = [get_number_with_esd(a)[1] for a in item_values]
3088 check_all = [v for v in check_all if (can_esd and v == None) or \
3089 (not can_esd and v != None)]
3090 if len(check_all)>0: return {"result":False,"bad_values":check_all}
3091 return {"result":True}
3092
3093 # Enumeration ranges. Our dictionary has been prepared as for a DDL2
3094 # dictionary, where loops are used to specify closed or open ranges: if
3095 # an entry exists where maximum and minimum values are equal, this means
3096 # that this value is included in the range; otherwise, ranges are open.
3097 # Our value is already numerical.
3098 #
3099 #
3100 # <Validate enumeration range>=
3101 def validate_enum_range(self,item_name,item_value):
3102 if "_item_range.minimum" not in self[item_name] and \
3103 "_item_range.maximum" not in self[item_name]:
3104 return {"result":None}
3105 minvals = self[item_name].get("_item_range.minimum",default = ["."])
3106 maxvals = self[item_name].get("_item_range.maximum",default = ["."])
3107 def makefloat(a):
3108 if a == ".": return a
3109 else: return float(a)
3110 maxvals = map(makefloat, maxvals)
3111 minvals = map(makefloat, minvals)
3112 rangelist = list(zip(minvals,maxvals))
3113 item_values = listify(item_value)
3114 def map_check(rangelist,item_value):
3115 if item_value == "?" or item_value == ".": return True
3116 iv,esd = get_number_with_esd(item_value)
3117 if iv==None: return None #shouldn't happen as is numb type
3118 for lower,upper in rangelist:
3119 #check the minima
3120 if lower == ".": lower = iv - 1
3121 if upper == ".": upper = iv + 1
3122 if iv > lower and iv < upper: return True
3123 if upper == lower and iv == upper: return True
3124 # debug
3125 # print("Value %s fails range check %d < x < %d" % (item_value,lower,upper))
3126 return False
3127 check_all = [a for a in item_values if map_check(rangelist,a) != True]
3128 if len(check_all)>0: return {"result":False,"bad_values":check_all}
3129 else: return {"result":True}
3130
3131 # Note that we must make a copy of the enum list, otherwise when we
3132 # add in our ? and . they will modify the Cif in place, very sneakily,
3133 # and next time we have a loop length check, e.g. in writing out, we
3134 # will probably have a mismatch.
3135 #
3136 #
3137 # <Validate an enumeration>=
3138 def validate_item_enum(self,item_name,item_value):
3139 try:
3140 enum_list = self[item_name][self.enum_spec][:]
3141 except KeyError:
3142 return {"result":None}
3143 enum_list = [value.lower() for value in enum_list]
3144 enum_list.append(".") #default value
3145 enum_list.append("?") #unknown
3146 item_values = listify(item_value)
3147 #print("Enum check: {!r} in {!r}".format(item_values, enum_list))
3148 check_all = [a for a in item_values if a.lower() not in enum_list]
3149 if len(check_all)>0: return {"result":False,"bad_values":check_all}
3150 else: return {"result":True}
3151
3152 # Check that something can be looped. For DDL1 we have yes, no and both,
3153 # For DDL2 there is no explicit restriction on looping beyond membership in
3154 # a category. Note that the DDL1 language specifies a default value of 'no'
3155 # for this item, so when not explicitly allowed by the dictionary, listing
3156 # is prohibited. In DDLm, only members of 'Loop' categories allow looping.
3157 # As we transition the whole setup to DDLm-type data structures, the two
3158 # calls below will merge and move to the looping checks rather than the single item
3159 # checks.
3160 #
3161 #
3162 # <Validate looping properties>=
3163 def validate_looping(self,item_name,item_value):
3164 try:
3165 must_loop = self[item_name][self.must_loop_spec]
3166 except KeyError:
3167 return {"result":None}
3168 if must_loop == 'yes' and isinstance(item_value,(unicode,str)): # not looped
3169 return {"result":False} #this could be triggered
3170 if must_loop == 'no' and not isinstance(item_value,(unicode,str)):
3171 return {"result":False}
3172 return {"result":True}
3173
3174 def validate_looping_ddlm(self,loop_names):
3175 """Check that all names are loopable"""
3176 truly_loopy = self.get_final_cats(loop_names)
3177 if len(truly_loopy)<len(loop_names): #some are bad
3178 categories = [(a,self[a][self.cat_spec].lower()) for a in loop_names]
3179 not_looped = [a[0] for a in categories if a[1] not in self.parent_lookup.keys()]
3180 return {"result":False,"bad_items":not_looped}
3181 return {"result":True}
3182
3183
3184 # And some things are related to the group structure. Note that these
3185 # functions do not require knowledge of the item values.
3186 #
3187 #
3188 # <Loop-level validation>=
3189 # Loop membership.
3190 # The most common constraints on a loop are that all items are from the same
3191 # category, and that loops of a certain category must contain a certain key to
3192 # be valid. The latter test should be performed after the former test.
3193 #
3194 # DDLm allows nested loop categories, so an item from a child category can appear
3195 # in a parent category loop if both are from 'Loop' categories.
3196 #
3197 #
3198 # <Validate loop membership>=
3199 def validate_loop_membership(self,loop_names):
3200 final_cat = self.get_final_cats(loop_names)
3201 bad_items = [a for a in final_cat if a != final_cat[0]]
3202 if len(bad_items)>0:
3203 return {"result":False,"bad_items":bad_items}
3204 else: return {"result":True}
3205
3206 def get_final_cats(self,loop_names):
3207 """Return a list of the uppermost parent categories for the loop_names. Names
3208 that are not from loopable categories are ignored."""
3209 try:
3210 categories = [self[a][self.cat_spec].lower() for a in loop_names]
3211 except KeyError: #category_id is mandatory
3212 raise ValidCifError( "{} missing from dictionary {} for item in loop containing {}".format(self.cat_spec,self.dicname,loop_names[0]))
3213 truly_looped = [a for a in categories if a in self.parent_lookup.keys()]
3214 return [self.parent_lookup[a] for a in truly_looped]
3215
3216 # The items specified by [[_list_mandatory]] (DDL1) must be present in a loop
3217 # containing items of a given category (and it follows that only one loop
3218 # in a given data block is available for any category containing such an
3219 # item). This has been explicitly described as a key in DDL2. In DDLm, any
3220 # key from a parent looped category is acceptable as well as the key of
3221 # the given category itself.
3222 #
3223 #
3224 # <Validate loop key>=
3225 def validate_loop_key(self,loop_names):
3226 category = self[loop_names[0]][self.cat_spec]
3227 # find any unique values which must be present
3228 key_spec = self[category].get(self.key_spec,[])
3229 for names_to_check in key_spec:
3230 if isinstance(names_to_check,unicode): #only one
3231 names_to_check = [names_to_check]
3232 for loop_key in names_to_check:
3233 if loop_key not in loop_names:
3234 #is this one of those dang implicit items?
3235 if self[loop_key].get(self.must_exist_spec,None) == "implicit":
3236 continue #it is virtually there...
3237 alternates = self.get_alternates(loop_key)
3238 if alternates == []:
3239 return {"result":False,"bad_items":loop_key}
3240 for alt_names in alternates:
3241 alt = [a for a in alt_names if a in loop_names]
3242 if len(alt) == 0:
3243 return {"result":False,"bad_items":loop_key} # no alternates
3244 return {"result":True}
3245
3246 # Validating keys in DDLm. We move everything to the uppermost parent category, and
3247 # then lookup what keys can be used. If any of these are present, we are happy. This
3248 # might miss some subtleties in mixed or unmixed loops?
3249 #
3250 #
3251 # <Validate loop key DDLm>=
3252 def validate_loop_key_uniqueness(self, loop_names, block):
3253 '''
3254 Function to validate if the id tags of a loop are unique. Function for the DDL1 dictionaries.
3255 Tags that have a category in self.black_list_categories are ignored.
3256 '''
3257
3258 loop_names_to_check = []
3259 for loop_name in loop_names:
3260 # Get the _list_mandatory tag value (empty if the loop does not have it)
3261 list_mandatory = self[loop_name].get(self.must_exist_spec, "")
3262
3263 # Get the tag's category to check if has to be avoided or not
3264 category = self[loop_name].get(self.cat_spec, "")
3265
3266 # Check if the tag actually is mandatory
3267 list_mandatory = list_mandatory == 'yes'
3268
3269 # Only check the categories that ARE NOT in self.black_list_categories
3270 if list_mandatory and category not in self.black_list_categories:
3271 loop_names_to_check.append(loop_name)
3272
3273 # No loop ids to check, the loop is valid
3274 if not loop_names_to_check:
3275 return {"result": True}
3276
3277 # Group the tag values by the number of ids in the loop
3278 if len(loop_names_to_check) > 1:
3279 values_list = [block[loop_name] for loop_name in loop_names_to_check]
3280 values = list(zip(*values_list))
3281
3282 else:
3283 loop_name = loop_names_to_check[0]
3284
3285 values = block[loop_name]
3286
3287 # The set only allows unique values
3288 set_values = set(values)
3289
3290 # If the lengths are different, it means that there are repeated values
3291 if len(values) != len(set_values):
3292 repeated_values = [item for item, count in collections.Counter(values).items() if count > 1]
3293 return {"result":False, "bad_items":repeated_values}
3294
3295 return {"result":True}
3296
3297 def validate_loop_key_uniqueness_ddlm(self, loop_names, block):
3298 '''
3299 Function to validate if the id tags of a loop are unique. Function for the DDLm dictionaries.
3300 Tags that have a category in self.black_list_categories are ignored.
3301 '''
3302 # Get the final categories
3303 final_cats = self.get_final_cats(loop_names)
3304
3305 # Get the category ids
3306 cat_keys = []
3307 for cat in final_cats:
3308 temp_cat_key = self[cat].get(self.unique_spec, "")
3309 if temp_cat_key not in cat_keys:
3310 cat_keys.append(temp_cat_key)
3311
3312 # Only take into account the loop ids from our loop tags
3313 loop_names_to_check = [loop_name for loop_name in loop_names if loop_name in cat_keys]
3314
3315 # There are no tags to check
3316 if not loop_names_to_check:
3317 return {"result":True}
3318
3319 # Group the tag values by the number of ids in the group
3320 if len(loop_names_to_check) > 1:
3321 values_list = [block[loop_name] for loop_name in loop_names_to_check]
3322 values = list(zip(*values_list))
3323
3324 else:
3325 loop_name = loop_names_to_check[0]
3326 values = block[loop_name]
3327
3328 # The set only allows unique values
3329 set_values = set(values)
3330
3331 # If the lengths are different, it means that there are repeated values
3332 if len(values) != len(set_values):
3333 repeated_values = [item for item, count in collections.Counter(values).items() if count > 1]
3334 return {"result":False, "bad_items":repeated_values}
3335
3336 return {"result":True}
3337
3338 def validate_loop_key_ddlm(self, loop_names):
3339 '''
3340 New version of the validation of the loop keys for the DDLm dictionaries.
3341 It checks if the _category_key.name of a given looped category appears.
3342 '''
3343
3344 # Get the parent categories of the input loop names
3345 temp_final_cats = self.get_final_cats(loop_names)
3346 final_cats = [final_cat for final_cat in temp_final_cats if final_cat not in self.black_list_categories]
3347
3348 if not final_cats:
3349 return {"result":True}
3350
3351 poss_keys = self.cat_key_table[final_cats[0]]
3352
3353 poss_keys_set = set()
3354
3355 # As we want to validate CIF1.0 against DDLm dictionaries,
3356 # we have to take into account that the category keys may have
3357 # alias.
3358 # The input loop tags may also be CIF1.0 tags.
3359 # Retrieve those alias to make a more complete validation
3360 for poss_key in poss_keys:
3361 for temp in poss_key:
3362 if temp is None: continue
3363 key = temp
3364 key_alias = self[key].get(self.alias_spec, [])
3365
3366 poss_keys_set.add(key.lower())
3367
3368 if isinstance(key_alias, list):
3369 for alias in key_alias:
3370 poss_keys_set.add(alias.lower())
3371
3372 else:
3373 poss_keys_set.add(key_alias.lower())
3374
3375 # If one of the tags exists, the loop is valid
3376 for loop_name in loop_names:
3377 if loop_name.lower() in poss_keys_set:
3378 return {"result":True}
3379
3380 return {"result":False, "bad_items":poss_keys_set}
3381
3382 # The [[_list_reference]] value specifies data names which must co-occur with the
3383 # defined data name. We check that this is indeed the case for all items in the
3384 # loop. We trace through alternate values as well. In DDL1 dictionaries, a
3385 # name terminating with an underscore indicates that any(?) corresponding name
3386 # is suitable.
3387 #
3388 #
3389 # <Validate loop mandatory items>=
3390 # Get the category keys
3391
3392 def validate_loop_references(self,loop_names):
3393 must_haves = [self[a].get(self.list_ref_spec,None) for a in loop_names]
3394 must_haves = [a for a in must_haves if a != None]
3395 # build a flat list. For efficiency we don't remove duplicates,as
3396 # we expect no more than the order of 10 or 20 looped names.
3397 def flat_func(a,b):
3398 if isinstance(b,unicode):
3399 a.append(b.lower()) #single name
3400 else:
3401 a.extend([a.lower() for a in b]) #list of names
3402 return a
3403 flat_mh = []
3404 [flat_func(flat_mh,a) for a in must_haves]
3405 group_mh = list(filter(lambda a:a[-1]=="_",flat_mh))
3406 single_mh = list(filter(lambda a:a[-1]!="_",flat_mh))
3407 res = [a for a in single_mh if a not in loop_names]
3408 def check_gr(s_item, name_list):
3409 nl = map(lambda a:a[:len(s_item)],name_list)
3410 if s_item in nl: return True
3411 return False
3412 res_g = [a for a in group_mh if check_gr(a,loop_names)]
3413 if len(res) == 0 and len(res_g) == 0: return {"result":True}
3414 # construct alternate list
3415 alternates = [(a,self.get_alternates(a)) for a in res]
3416 real_alternates = [a for a in alternates if len(a[1]) != 0]
3417 # next line purely for error reporting
3418 missing_alts = [a[0] for a in alternates if len(a[1]) == 0]
3419 if len(real_alternates) != len(res):
3420 return {"result":False,"bad_items":set(missing_alts)} #short cut; at least one
3421 #doesn't have an altern
3422 #loop over alternates
3423 for orig_name,alt_names in alternates:
3424 alt = [a for a in alt_names if a in loop_names]
3425 if len(alt) == 0: return {"result":False,"bad_items":orig_name}# no alternates
3426 return {"result":True} #found alternates
3427
3428 # A utility function to return a list of alternate names given a main name.
3429 # In DDL2 we have to deal with aliases. Each aliased item appears in
3430 # our normalised dictionary independently, so there is no need to resolve
3431 # aliases when looking up a data name. However, the original
3432 # definition using DDL2-type names is simply copied to this aliased
3433 # name during normalisation, so all references to other item names
3434 # (e.g. _item_dependent) have to be resolved using the present function.
3435 #
3436 # These aliases are returned in any case, so if we had a data file
3437 # which mixed DDL1 and DDL2 style names, it may turn out to be
3438 # valid, and what's more, we wouldn't necessarily detect an error
3439 # if a data name and its alias were present - need to ponder this.
3440 #
3441 # The exclusive_only option will only return items which must not
3442 # co-exist with the item name in the same datablock. This includes
3443 # aliases, and allows us to do a check that items and their aliases
3444 # are not present at the same time in a data file.
3445 #
3446 #
3447 # <Get alternative item names>=
3448 def get_alternates(self,main_name,exclusive_only=False):
3449 if self.get(main_name, None) is None:
3450 return []
3451 alternates = self[main_name].get(self.related_func,None)
3452 alt_names = []
3453 if alternates != None:
3454 alt_names = self[main_name].get(self.related_item,None)
3455 if isinstance(alt_names,unicode):
3456 alt_names = [alt_names]
3457 alternates = [alternates]
3458 together = zip(alt_names,alternates)
3459 if exclusive_only:
3460 alt_names = [a for a in together if a[1]=="alternate_exclusive" \
3461 or a[1]=="replace"]
3462 else:
3463 alt_names = [a for a in together if a[1]=="alternate" or a[1]=="replace"]
3464 alt_names = list([a[0] for a in alt_names])
3465 # now do the alias thing
3466 alias_names = listify(self[main_name].get("_item_aliases.alias_name",[]))
3467 alt_names.extend(alias_names)
3468 # print("Alternates for {}: {!r}".format(main_name, alt_names))
3469 return alt_names
3470
3471
3472 # Some checks require access to the entire data block. These functions
3473 # take both a provisional dictionary and a global dictionary; the
3474 # provisional dictionary includes items which will go into the
3475 # dictionary together with the current item, and the global
3476 # dictionary includes items which apply to all data blocks (this is
3477 # for validation of DDL1/2 dictionaries).
3478 #
3479 #
3480 # <Cross-item validation>=
3481 # DDL2 dictionaries introduce the "alternate exclusive" category for
3482 # related items. We also unilaterally include items listed in aliases
3483 # as acting in this way.
3484 #
3485 #
3486 # <Validate exclusion rules>=
3487 def validate_exclusion(self,item_name,item_value,whole_block,provisional_items={},globals={}):
3488 alternates = [a.lower() for a in self.get_alternates(item_name,exclusive_only=True)]
3489 item_name_list = [a.lower() for a in whole_block.keys()]
3490 item_name_list.extend([a.lower() for a in provisional_items.keys()])
3491 bad = [a for a in alternates if a in item_name_list]
3492 if len(bad)>0:
3493 if self.verbose_validation:
3494 print("Bad: {}, alternates {}".format(repr(bad),repr(alternates)))
3495 return {"result":False,"bad_items":bad}
3496 else: return {"result":True}
3497
3498 # When validating parent/child relations, we check the parent link to the
3499 # children, and separately check that parents exist for any children present.
3500 # Switching on optimisation will remove the redundancy in this procedure, but
3501 # only if no changes are made to the relevant data items between the two
3502 # checks.
3503 #
3504 # It appears that DDL2 dictionaries allow parents to be absent if children
3505 # take only unspecified values (i.e. dot or question mark). We catch this
3506 # case.
3507 #
3508 # The provisional items dictionary includes items that are going to be
3509 # included with the present item (in a single loop structure) so the
3510 # philosophy of inclusion must be all or nothing.
3511 #
3512 # When validating DDL2 dictionaries themselves, we are allowed access to
3513 # other definition blocks in order to resolve parent-child pointers.
3514 # We will be able to find
3515 # these save frames inside the globals dictionary (they will in this case
3516 # be collected inside a CifBlock object).
3517 #
3518 # When removing, we look at the item to make sure that no child items require
3519 # it to be present.
3520 #
3521 #
3522 # <Validate parent child relations>=
3523 # validate that parent exists and contains matching values
3524 def validate_parent(self,item_name,item_value,whole_block,provisional_items={},globals={}):
3525 parent_item = self[item_name].get(self.parent_spec)
3526 if not parent_item: return {"result":None} #no parent specified
3527 if isinstance(parent_item,list):
3528 parent_item = parent_item[0]
3529 if self.optimize:
3530 if parent_item in self.done_parents:
3531 return {"result":None}
3532 else:
3533 self.done_parents.append(parent_item)
3534 print("Done parents {}".format(repr(self.done_parents)))
3535 # initialise parent/child values
3536 if isinstance(item_value,unicode):
3537 child_values = [item_value]
3538 else: child_values = item_value[:] #copy for safety
3539 # track down the parent
3540 # print("Looking for {} parent item {} in {!r}".format(item_name, parent_item, whole_block))
3541 # if globals contains the parent values, we are doing a DDL2 dictionary, and so
3542 # we have collected all parent values into the global block - so no need to search
3543 # for them elsewhere.
3544 # print("Looking for {!r}".format(parent_item))
3545 parent_values = globals.get(parent_item)
3546 if not parent_values:
3547 parent_values = provisional_items.get(parent_item,whole_block.get(parent_item))
3548 if not parent_values:
3549 # go for alternates
3550 namespace = whole_block.keys()
3551 namespace.extend(provisional_items.keys())
3552 namespace.extend(globals.keys())
3553 alt_names = filter_present(self.get_alternates(parent_item),namespace)
3554 if len(alt_names) == 0:
3555 if len([a for a in child_values if a != "." and a != "?"])>0:
3556 return {"result":False,"parent":parent_item}#no parent available -> error
3557 else:
3558 return {"result":None} #maybe True is more appropriate??
3559 parent_item = alt_names[0] #should never be more than one??
3560 parent_values = provisional_items.get(parent_item,whole_block.get(parent_item))
3561 if not parent_values: # check global block
3562 parent_values = globals.get(parent_item)
3563 if isinstance(parent_values,unicode):
3564 parent_values = [parent_values]
3565 #print("Checking parent %s against %s, values %r/%r" % (parent_item,
3566 # item_name, parent_values, child_values))
3567 missing = self.check_parent_child(parent_values,child_values)
3568 if len(missing) > 0:
3569 return {"result":False,"bad_values":missing,"parent":parent_item}
3570 return {"result":True}
3571
3572 def validate_child(self,item_name,item_value,whole_block,provisional_items={},globals={}):
3573 try:
3574 child_items = self[item_name][self.child_spec][:] #copy
3575 except KeyError:
3576 return {"result":None} #not relevant
3577 # special case for dictionaries -> we check parents of children only
3578 if item_name in globals: #dictionary so skip
3579 return {"result":None}
3580 if isinstance(child_items,unicode): # only one child
3581 child_items = [child_items]
3582 if isinstance(item_value,unicode): # single value
3583 parent_values = [item_value]
3584 else: parent_values = item_value[:]
3585 # expand child list with list of alternates
3586 for child_item in child_items[:]:
3587 child_items.extend(self.get_alternates(child_item))
3588 # now loop over the children
3589 for child_item in child_items:
3590 if self.optimize:
3591 if child_item in self.done_children:
3592 return {"result":None}
3593 else:
3594 self.done_children.append(child_item)
3595 if self.verbose_validation:
3596 print("Done children {}".format(repr(self.done_children)))
3597 if child_item in provisional_items:
3598 child_values = provisional_items[child_item][:]
3599 elif child_item in whole_block:
3600 child_values = whole_block[child_item][:]
3601 else: continue
3602 if isinstance(child_values,unicode):
3603 child_values = [child_values]
3604 # print("Checking child %s against %s, values %r/%r" % (child_item,
3605 # item_name, child_values, parent_values))
3606 missing = self.check_parent_child(parent_values,child_values)
3607 if len(missing)>0:
3608 return {"result":False,"bad_values":missing,"child":child_item}
3609 return {"result":True} #could mean that no child items present
3610
3611 #a generic checker: all child vals should appear in parent_vals
3612 def check_parent_child(self,parent_vals,child_vals):
3613 # shield ourselves from dots and question marks
3614 pv = parent_vals[:]
3615 pv.extend([".","?"])
3616 res = [a for a in child_vals if a not in pv]
3617 #print("Missing: %s" % res)
3618 return res
3619
3620 def validate_remove_parent_child(self,item_name,whole_block):
3621 try:
3622 child_items = self[item_name][self.child_spec]
3623 except KeyError:
3624 return {"result":None}
3625 if isinstance(child_items,unicode): # only one child
3626 child_items = [child_items]
3627 for child_item in child_items:
3628 if child_item in whole_block:
3629 return {"result":False,"child":child_item}
3630 return {"result":True}
3631
3632 # The DDL2 [[_item_dependent]] attribute at first glance appears to be the
3633 # same as [[_list_reference]], however the dependent item does not have to appear
3634 # in a loop at all, and neither does the other item name. Perhaps this
3635 # behaviour was intended to be implied by having looped [[_names]] in DDL1
3636 # dictionaries, but we can't be sure and so don't implement this yet.
3637 #
3638 #
3639 # <Validate presence of dependents>=
3640 def validate_dependents(self,item_name,item_value,whole_block,prov={},globals={}):
3641 try:
3642 dep_items = self[item_name][self.dep_spec][:]
3643 except KeyError:
3644 return {"result":None} #not relevant
3645 if isinstance(dep_items,unicode):
3646 dep_items = [dep_items]
3647 actual_names = whole_block.keys()
3648 actual_names.extend(prov.keys())
3649 actual_names.extend(globals.keys())
3650 missing = [a for a in dep_items if a not in actual_names]
3651 if len(missing) > 0:
3652 alternates = map(lambda a:[self.get_alternates(a),a],missing)
3653 # compact way to get a list of alternative items which are
3654 # present
3655 have_check = [(filter_present(b[0],actual_names),
3656 b[1]) for b in alternates]
3657 have_check = list([a for a in have_check if len(a[0])==0])
3658 if len(have_check) > 0:
3659 have_check = [a[1] for a in have_check]
3660 return {"result":False,"bad_items":have_check}
3661 return {"result":True}
3662
3663 # The [[_list_uniqueness]] attribute permits specification of a single or
3664 # multiple items which must have a unique combined value. Currently it is only
3665 # used in the powder dictionary to indicate that peaks must have a unique
3666 # index and in the core dictionary to indicate the a publication section name
3667 # with its label must be unique; however it would appear to implicitly apply
3668 # to any index-type value in any dictionary. This is used precisely once
3669 # in the cif_core dictionary in a non-intuitive manner, but we code for
3670 # this here. The value of the [[_list_uniqueness]] attribute can actually
3671 # refer to another data name, which together with the defined name must
3672 # be unique.
3673 #
3674 # DDL2 dictionaries do away with separate [[_list_mandatory]] and [[_list_uniqueness]]
3675 # attributes, instead using a [[_category_key]]. If multiple keys are specified,
3676 # they must be unique in combination, in accordance with standard relational
3677 # database behaviour.
3678 #
3679 #
3680 # <Validate list uniqueness>=
3681 def validate_uniqueness(self,item_name,item_value,whole_block,provisional_items={},
3682 globals={}):
3683 category = self[item_name].get(self.cat_spec)
3684 if category == None:
3685 if self.verbose_validation:
3686 print("No category found for {}".format(item_name))
3687 return {"result":None}
3688 # print("Category {!r} for item {}".format(category, item_name))
3689 # we make a copy in the following as we will be removing stuff later!
3690 unique_i = self[category].get("_category_key.name",[])[:]
3691 if isinstance(unique_i,unicode):
3692 unique_i = [unique_i]
3693 if item_name not in unique_i: #no need to verify
3694 return {"result":None}
3695 if isinstance(item_value,unicode): #not looped
3696 return {"result":None}
3697 # print("Checking %s -> %s -> %s ->Unique: %r" % (item_name,category,catentry, unique_i))
3698 # check that we can't optimize by not doing this check
3699 if self.optimize:
3700 if unique_i in self.done_keys:
3701 return {"result":None}
3702 else:
3703 self.done_keys.append(unique_i)
3704 val_list = []
3705 # get the matching data from any other data items
3706 unique_i.remove(item_name)
3707 other_data = []
3708 if len(unique_i) > 0: # i.e. do have others to think about
3709 for other_name in unique_i:
3710 # we look for the value first in the provisional dict, then the main block
3711 # the logic being that anything in the provisional dict overrides the
3712 # main block
3713 if other_name in provisional_items:
3714 other_data.append(provisional_items[other_name])
3715 elif other_name in whole_block:
3716 other_data.append(whole_block[other_name])
3717 elif self[other_name].get(self.must_exist_spec)=="implicit":
3718 other_data.append([item_name]*len(item_value)) #placeholder
3719 else:
3720 return {"result":False,"bad_items":other_name}#missing data name
3721 # ok, so we go through all of our values
3722 # this works by comparing lists of strings to one other, and
3723 # so could be fooled if you think that '1.' and '1' are
3724 # identical
3725 for i in range(len(item_value)):
3726 #print("Value no. %d" % i, end=" ")
3727 this_entry = item_value[i]
3728 for j in range(len(other_data)):
3729 this_entry = " ".join([this_entry,other_data[j][i]])
3730 #print("Looking for {!r} in {!r}: ".format(this_entry, val_list))
3731 if this_entry in val_list:
3732 return {"result":False,"bad_values":this_entry}
3733 val_list.append(this_entry)
3734 return {"result":True}
3735
3736
3737 # <Block-level validation>=
3738 # DDL2 introduces a new idea, that of a mandatory category, items of
3739 # which must be present. We check only this particular fact, and
3740 # leave the checks for mandatory items within the category, keys etc.
3741 # to the relevant routines. This would appear to be applicable to
3742 # dictionaries only.
3743 #
3744 # Also, although the natural meaning for a DDL2 dictionary would be that
3745 # items from these categories must appear in every definition block, this is not what
3746 # happens in practice, as category definitions do not have anything from the
3747 # (mandatory) _item_description category. We therefore adopt the supremely
3748 # useless meaning that mandatory categories in a dictionary context mean only
3749 # that somewhere, maybe in only one save frame, an item from this category
3750 # exists. This interpretation is forced by using the "fake_mand" argument,
3751 # which then assumes that the alternative routine will be used to set the
3752 # error information on a dictionary-wide basis.
3753 #
3754 #
3755 # <Validate category presence>=
3756 def validate_mandatory_category(self,whole_block):
3757 mand_cats = [self[a]['_category.id'] for a in self.keys() if self[a].get("_category.mandatory_code","no")=="yes"]
3758 if len(mand_cats) == 0:
3759 return {"result":True}
3760 # print("Mandatory categories - {!r}".format(mand_cats)
3761 # find which categories each of our datanames belongs to
3762 all_cats = [self[a].get(self.cat_spec) for a in whole_block.keys()]
3763 missing = set(mand_cats) - set(all_cats)
3764 if len(missing) > 0:
3765 return {"result":False,"bad_items":repr(missing)}
3766 return {"result":True}
3767
3768 # Processing DDLm mandatory categories/items
3769 #
3770 # DDLm manages mandatory items by providing a table in the DDLm
3771 # dictionary which classifies datanames into
3772 # mandatory/recommended/prohibited for dictionary, category or item
3773 # scopes. Note that the following check might fail for categories and
3774 # dictionaries if '_definition.scope' or '_dictionary.title' is missing.
3775 #
3776 #
3777 # <Process DDLm mandatory information>=
3778 def check_mandatory_items(self,whole_block,default_scope='Item'):
3779 """Return an error if any mandatory items are missing"""
3780 if len(self.scopes_mandatory)== 0: return {"result":True}
3781 if default_scope == 'Datablock':
3782 return {"result":True} #is a data file
3783 scope = whole_block.get('_definition.scope',default_scope)
3784 if '_dictionary.title' in whole_block:
3785 scope = 'Dictionary'
3786 missing = list([a for a in self.scopes_mandatory[scope] if a not in whole_block])
3787 if len(missing)==0:
3788 return {"result":True}
3789 else:
3790 return {"result":False,"bad_items":missing}
3791
3792 # <Process DDLm prohibited information>=
3793 def check_prohibited_items(self,whole_block,default_scope='Item'):
3794 """Return an error if any prohibited items are present"""
3795 if len(self.scopes_naughty)== 0: return {"result":True}
3796 if default_scope == 'Datablock':
3797 return {"result":True} #is a data file
3798 scope = whole_block.get('_definition.scope',default_scope)
3799 if '_dictionary.title' in whole_block:
3800 scope = 'Dictionary'
3801 present = list([a for a in self.scopes_naughty[scope] if a in whole_block])
3802 if len(present)==0:
3803 return {"result":True}
3804 else:
3805 return {"result":False,"bad_items":present}
3806
3807
3808 # These validation checks are intended to be called externally. They return
3809 # a dictionary keyed by item name with value being a list of the
3810 # results of the check functions. The individual functions return a
3811 # dictionary which contains at least the key "result", and in case of error
3812 # relevant keys relating to the error.
3813 #
3814 #
3815 # <Run validation tests>=
3816 def run_item_validation(self,item_name,item_value):
3817 return {item_name:list([(f.__name__,f(item_name,item_value)) for f in self.item_validation_funs])}
3818
3819 def run_loop_validation(self,loop_names):
3820 return {loop_names[0]:list([(f.__name__,f(loop_names)) for f in self.loop_validation_funs])}
3821
3822 def run_loop_id_uniqueness(self, loop_names, block):
3823 return {loop_names[0]:list([(f.__name__, f(loop_names, block)) for f in self.loop_id_uniqueness_funs])}
3824
3825 def run_global_validation(self,item_name,item_value,data_block,provisional_items={},globals={}):
3826 results = list([(f.__name__,f(item_name,item_value,data_block,provisional_items,globals)) for f in self.global_validation_funs])
3827 return {item_name:results}
3828
3829 def run_block_validation(self,whole_block,block_scope='Item'):
3830 results = list([(f.__name__,f(whole_block)) for f in self.block_validation_funs])
3831 # fix up the return values
3832 return {"whole_block":results}
3833
3834 # Optimization: the dictionary validation routines normally retain no history
3835 # of what has been checked, as they are executed on a per-item basis. This
3836 # leads to duplication of the uniqueness check, when there is more than one
3837 # key, and duplication of the parent-child check, once for the parent and
3838 # once for the child. By switching on optimisation, a record is kept and
3839 # these checks will not be repeated. This is safe only if none of the
3840 # relevant items is altered while optimisation is on, and optimisation
3841 # should be switched off as soon as all the checks are finished.
3842 #
3843 #
3844 # <Optimisation on/off>=
3845 def optimize_on(self):
3846 self.optimize = True
3847 self.done_keys = []
3848 self.done_children = []
3849 self.done_parents = []
3850
3851 def optimize_off(self):
3852 self.optimize = False
3853 self.done_keys = []
3854 self.done_children = []
3855 self.done_parents = []
3856
3857
3858
3859 # We provide some functions for straight validation. These serve as an
3860 # example of the use of the CifDic class with the CifFile class.
3861 #
3862 #
3863 # <Top-level functions>=
3864 # A convenient wrapper class for dealing with the structure returned by
3865 # validation. Perhaps a more elegant approach would be to return one of
3866 # these objects from validation rather than wrap the validation routines inside.
3867 #
3868 #
3869 # <ValidationResult class>=
3870 class ValidationResult:
3871 """Represents validation result. It is initialised with """
3872 def __init__(self,results):
3873 """results is return value of validate function"""
3874 self.valid_result, self.no_matches = results
3875
3876 def report(self,use_html):
3877 """Return string with human-readable description of validation result"""
3878 return validate_report((self.valid_result, self.no_matches),use_html)
3879
3880 def is_valid(self,block_name=None):
3881 """Return True for valid CIF file, otherwise False"""
3882 if block_name is not None:
3883 block_names = [block_name]
3884 else:
3885 block_names = self.valid_result.keys()
3886 for block_name in block_names:
3887 if not self.valid_result[block_name] == (True,{}):
3888 valid = False
3889 break
3890 else:
3891 valid = True
3892 return valid
3893
3894 def has_no_match_items(self,block_name=None):
3895 """Return true if some items are not found in dictionary"""
3896 if block_name is not None:
3897 block_names = [block_name]
3898 else:
3899 block_names = self.no_matches.iter_keys()
3900 for block_name in block_names:
3901 if self.no_matches[block_name]:
3902 has_no_match_items = True
3903 break
3904 else:
3905 has_no_match_items = False
3906 return has_no_match_items
3907
3908 def get_no_matches_warning(checkfile, block, fulldic):
3909 no_matches = [a for a in checkfile[block].keys() if a not in fulldic]
3910 return no_matches
3911
3912 def get_obsolete_tags_warning_ddl1(checkfile, block, fulldic):
3913 result = {}
3914 for tag, tag_value in checkfile[block].items():
3915 dict_tag_entry = fulldic.get(tag, None)
3916 if dict_tag_entry is None:
3917 continue
3918
3919 if dict_tag_entry.get(fulldic.related_func, "") == "replace":
3920 related_tag = fulldic.get(tag, None).get(fulldic.related_item)
3921 result[tag] = related_tag
3922
3923 return result
3924
3925 def get_obsolete_tags_warning_ddlm(checkfile, block, fulldic):
3926 result = {}
3927 for tag, tag_value in checkfile[block].items():
3928 dict_tag_entry = fulldic.get(tag, None)
3929 if dict_tag_entry is None:
3930 continue
3931
3932 new_tags = dict_tag_entry.get(fulldic.related_func, [])
3933 if new_tags:
3934 result[tag] = new_tags
3935
3936 return result
3937
3938 def get_case_sensitive_warning(checkfile, block, fulldic):
3939 result = {}
3940 for tag, tag_value in checkfile[block].items():
3941 dict_tag_entry = fulldic.get(tag, None)
3942 # The tag is not found in the dictionary
3943 if dict_tag_entry is None:
3944 continue
3945
3946 enum_values = dict_tag_entry.get(fulldic.enum_spec, [])
3947 temp_result = []
3948
3949 # The tag has not any enumeration values
3950 if enum_values is None or not enum_values:
3951 continue
3952
3953 if isinstance(tag_value, list):
3954 for temp_tag_value in tag_value:
3955 if temp_tag_value not in enum_values and temp_tag_value.lower() in enum_values:
3956 temp_result.append(temp_tag_value)
3957
3958 else:
3959 if tag_value not in enum_values and tag_value.lower() in enum_values:
3960 temp_result.append(tag_value)
3961
3962 if temp_result:
3963 result[tag] = temp_result
3964
3965 return result
3966
3967 def get_blacklist_warning(checkfile, block, fulldic):
3968 result = []
3969 for tag, tag_value in checkfile[block].items():
3970 if tag in fulldic.black_list_categories:
3971 result.append(tag)
3972
3973 return result
3974
3975 def get_warnings(checkfile, block, fulldic):
3976 warnings = {}
3977 warnings["no_matches"] = get_no_matches_warning(checkfile, block, fulldic)
3978 warnings["blacklist"] = get_blacklist_warning(checkfile, block, fulldic)
3979 warnings["case_sensitive"] = get_case_sensitive_warning(checkfile, block, fulldic)
3980
3981 if fulldic.diclang == "DDL1":
3982 warnings["obsolete"] = get_obsolete_tags_warning_ddl1(checkfile, block, fulldic)
3983
3984 else:
3985 warnings["obsolete"] = get_obsolete_tags_warning_ddlm(checkfile, block, fulldic)
3986
3987 return warnings
3988
3989
3990 # We provide a function to do straight validation, using the built-in
3991 # methods of the dictionary type. We need to create a single dictionary
3992 # from the multiple dictionaries we are passed, before doing our
3993 # check. Also, we allow validation of dictionaries themselves, by
3994 # passing a special flag [[isdic]]. This should only be used for
3995 # DDL2/DDLm dictionaries, and simply makes save frames visible as
3996 # ordinary blocks. DDL1 dictionaries validate OK if (any) global block
3997 # is deleted.
3998 #
3999 #
4000 # <Validate against the given dictionaries>=
4001 def Validate(ciffile,dic = "", diclist=[],mergemode="replace",isdic=False):
4002 """Validate the `ciffile` conforms to the definitions in `CifDic` object `dic`, or if `dic` is missing,
4003 to the results of merging the `CifDic` objects in `diclist` according to `mergemode`. Flag
4004 `isdic` indicates that `ciffile` is a CIF dictionary meaning that save frames should be
4005 accessed for validation and that mandatory_category should be interpreted differently for DDL2."""
4006 if not isinstance(ciffile,CifFile):
4007 check_file = CifFile(ciffile)
4008 else:
4009 check_file = ciffile
4010 if not dic:
4011 fulldic = merge_dic(diclist,mergemode)
4012 else:
4013 fulldic = dic
4014
4015 no_matches = {}
4016 warnings = {}
4017 valid_result = {}
4018
4019 if isdic: #assume one block only
4020 check_file.scoping = 'instance' #only data blocks visible
4021 top_level = check_file.keys()[0]
4022 check_file.scoping = 'dictionary' #all blocks visible
4023 # collect a list of parents for speed
4024 if fulldic.diclang == 'DDL2':
4025 poss_parents = fulldic.get_all("_item_linked.parent_name")
4026 for parent in poss_parents:
4027 curr_parent = listify(check_file.get(parent,[]))
4028 new_vals = check_file.get_all(parent)
4029 new_vals.extend(curr_parent)
4030 if len(new_vals)>0:
4031 check_file[parent] = new_vals
4032 print("Added {} (len {})".format(parent,len(check_file[parent])))
4033 # now run the validations
4034 for block in check_file.keys():
4035 if isdic and block == top_level:
4036 block_scope = 'Dictionary'
4037 elif isdic:
4038 block_scope = 'Item'
4039 else:
4040 block_scope = 'Datablock'
4041 warnings[block] = get_warnings(check_file, block, fulldic)
4042 # remove non-matching items
4043 if fulldic.verbose_validation:
4044 print()
4045 print("The following tags were not found in the dictionary: " + str(warnings[block]["no_matches"]))
4046 print("The following tags are obsolete: " + str(warnings[block]["obsolete"]))
4047 print("The following tags have not been taken into account for validation: " + str(warnings[block]["blacklist"]))
4048 print("The followings tags' values have a case-sensitive match failure: " + str(warnings[block]["case_sensitive"]))
4049 print()
4050 for nogood in warnings[block]["no_matches"]:
4051 del check_file[block][nogood]
4052 if fulldic.verbose_validation:
4053 print("Validating block {}, scope {}".format(block,block_scope))
4054 valid_result[block] = run_data_checks(check_file[block],fulldic,block_scope=block_scope)
4055 return valid_result, warnings
4056
4057 def validate_report(val_result,use_html=False):
4058 valid_result,warnings = val_result
4059 outstr = StringIO()
4060 if use_html:
4061 outstr.write("<h2>Validation results</h2>")
4062 else:
4063 outstr.write( "\nValidation results\n")
4064 outstr.write( "------------------\n")
4065 if len(valid_result) > 10:
4066 suppress_valid = True #don't clutter with valid messages
4067 if use_html:
4068 outstr.write("<p>For brevity, valid blocks are not reported in the output.</p>")
4069 else:
4070 suppress_valid = False
4071
4072 dict_summary = {}
4073 dict_summary['blocks'] = {}
4074 cif_is_valid = True
4075 cif_has_warnings = False
4076 for block in valid_result.keys():
4077 block_result = valid_result[block]
4078
4079 dict_summary['blocks'][block] = {}
4080 dict_summary['blocks'][block]['is_valid'] = block_result[0]
4081 dict_summary['blocks'][block]['warnings'] = {}
4082 dict_summary['blocks'][block]['has_warnings'] = False
4083 dict_summary['blocks'][block]['errors'] = {}
4084
4085 dict_summary['blocks'][block]['output_str'] = ""
4086 dict_summary['blocks'][block]['error_str'] = ""
4087 dict_summary['blocks'][block]['warning_str'] = ""
4088
4089 if not dict_summary['blocks'][block]['is_valid']:
4090 cif_is_valid = False
4091
4092 if block_result[0]:
4093 out_line = "Block '{}' is VALID".format(block)
4094 else:
4095 out_line = "Block '{}' is INVALID".format(block)
4096 if use_html:
4097 if (block_result[0] and (not suppress_valid or len(warnings[block])>0)) or not block_result[0]:
4098 outstr.write( "<h3>{}</h3><p>".format(out_line))
4099 else:
4100 outstr.write( "\n{} \n".format(out_line))
4101
4102 warning_table = {
4103 'no_matches':'Warning: The following items were not found in the dictionary.',
4104 'obsolete':'Warning: Obsolete definitions found. Obsolete tags should be replaced by their related tags.',
4105 'case_sensitive':'Warning: Case-sensitive match failure for enumeration values.',
4106 'blacklist':'Warning: The following tags can cause validation problems so they have not been taken into account for validation.'
4107 }
4108
4109 warnings_str, warning_dict = get_warning_report(warnings.get(block), warning_table)
4110
4111 if warnings_str:
4112 outstr.write(warnings_str)
4113 cif_has_warnings = True
4114 dict_summary['blocks'][block]['warnings'] = warning_dict
4115 dict_summary['blocks'][block]['has_warnings'] = True
4116
4117 # now organise our results by type of error, not data item...
4118 error_type_dic = {}
4119 for error_item, error_list in block_result[1].items():
4120 for func_name,bad_result in error_list:
4121 bad_result.update({"item_name":error_item})
4122 try:
4123 error_type_dic[func_name].append(bad_result)
4124 except KeyError:
4125 error_type_dic[func_name] = [bad_result]
4126 # make a table of test name, test message
4127 info_table = {\
4128 'validate_item_type':\
4129 "Error: The following data items had badly formed values",
4130 'validate_item_esd':\
4131 "Error: The following data items should not have esds appended",
4132 'validate_enum_range':\
4133 "Error: The following data items have values outside permitted range",
4134 'validate_item_enum':\
4135 "Error: The following data items have values outside permitted set",
4136 'validate_looping':\
4137 "Error: The following data items violate looping constraints",
4138 'validate_loop_membership':\
4139 "Error: The following looped data names are of different categories to the first looped data name",
4140 'validate_loop_key':\
4141 "Error: A required dataname for this category is missing from the loop\n containing the dataname",
4142 'validate_loop_key_ddlm':\
4143 "Error: A loop key is missing for the category containing the dataname",
4144 'validate_loop_key_uniqueness':\
4145 "Error: There are repeated values for a _list_mandatory type tag",
4146 'validate_loop_references':\
4147 "Error: A dataname required by the item is missing from the loop",
4148 'validate_parent':\
4149 "Error: A parent dataname is missing or contains different values",
4150 'validate_child':\
4151 "Error: A child dataname contains different values to the parent",
4152 'validate_uniqueness':\
4153 "Error: One or more data items do not take unique values",
4154 'validate_dependents':\
4155 "Error: A dataname required by the item is missing from the data block",
4156 'validate_exclusion': \
4157 "Error: Both dataname and exclusive alternates or aliases are present in data block",
4158 'validate_mandatory_category':\
4159 "Error: A required category is missing from this block",
4160 'check_mandatory_items':\
4161 "Error: A required data attribute is missing from this block",
4162 'check_prohibited_items':\
4163 "Error: A prohibited data attribute is present in this block"}
4164
4165 block_validation_str = "\n" + out_line + " \n" + warnings_str + "\n"
4166 block_warning_str = "\n" + out_line + "\n" + warnings_str + "\n"
4167 block_error_str = "\n" + out_line + "\n"
4168 for test_name,test_results in error_type_dic.items():
4169 if use_html:
4170 outstr.write(html_error_report(test_name,info_table[test_name],test_results))
4171 else:
4172 temp_str = error_report(test_name,info_table[test_name],test_results)
4173 outstr.write(temp_str)
4174 outstr.write("\n\n")
4175
4176 block_error_str += temp_str + "\n\n"
4177 block_validation_str += temp_str + "\n\n"
4178 dict_summary['blocks'][block]['errors'][test_name] = temp_str
4179
4180 #outstr.write(error_report(test_name,info_table[test_name],test_results))
4181 #outstr.write("\n\n")
4182
4183 dict_summary['blocks'][block]["error_str"] = block_error_str
4184 dict_summary['blocks'][block]["warning_str"] = block_warning_str
4185 dict_summary['blocks'][block]["output_str"] = block_validation_str
4186
4187 dict_summary['cif_has_warnings'] = cif_has_warnings
4188 dict_summary['cif_is_valid'] = cif_is_valid
4189
4190 return outstr.getvalue(), dict_summary
4191
4192 def warning_report_no_matches(no_matches_warnings, warning_table):
4193 if not no_matches_warnings:
4194 return ""
4195
4196 warning_header = "\n" + warning_table.get('no_matches')
4197 table = PrettyTable()
4198
4199 field_names = ["Tags not found in the dictionaries"]
4200
4201 table.field_names = field_names
4202 table.align["Tags not found in the dictionaries"] = "l"
4203
4204 for idx, tag_name in enumerate(no_matches_warnings):
4205 table.add_row([tag_name])
4206
4207 table_str = table.get_string() + "\n"
4208
4209 return "\n".join((warning_header, table_str))
4210
4211
4212 def warning_report_obsolete(obsolete_tags, warning_table):
4213 if not obsolete_tags:
4214 return ""
4215
4216 warning_header = "\n" + warning_table.get('obsolete')
4217 table = PrettyTable()
4218
4219 field_names = ["Obsolete tags", "Related tags"]
4220
4221 table.field_names = field_names
4222 table.align["Obsolete tags"] = "l"
4223 table.align["Related tags"] = "l"
4224
4225 for obsolete_tag, related_tag in obsolete_tags.items():
4226 row = [obsolete_tag, related_tag]
4227 table.add_row(row)
4228
4229 table_str = table.get_string() + "\n"
4230
4231 return "\n".join((warning_header, table_str))
4232
4233 def warning_report_case_sensitive(case_sensitive_tags, warning_table):
4234 if not case_sensitive_tags:
4235 return ""
4236
4237 warning_header = "\n" + warning_table.get('case_sensitive')
4238 table = PrettyTable()
4239
4240 field_names = ["Tag name", "Case sensitive value"]
4241
4242 table.field_names = field_names
4243 table.align["Tag name"] = "l"
4244 table.align["Case sensitive value"] = "l"
4245
4246 for tag, wrong_values in case_sensitive_tags.items():
4247 row = [tag, wrong_values]
4248 table.add_row(row)
4249
4250 table_str = table.get_string() + "\n"
4251
4252 return "\n".join((warning_header, table_str))
4253
4254 def warning_report_blacklist(blacklist_tags, warning_table):
4255 if not blacklist_tags:
4256 return ""
4257
4258 warning_header = warning_table.get('blacklist') + "\n"
4259 table = PrettyTable()
4260
4261 field_names = ["Tags in the black list"]
4262
4263 table.field_names = field_names
4264 table.align["Tags in the black list"] = "l"
4265
4266 for idx, blacklist_tag in enumerate(blacklist_tags):
4267 table.add_row([blacklist_tag])
4268
4269 table_str = table.get_string() + "\n"
4270
4271 return "\n".join((warning_header, table_str))
4272
4273 def get_warning_report(warnings, warning_table):
4274 out_str = ""
4275 out_dict = {}
4276
4277 no_matches_str = warning_report_no_matches(warnings.get('no_matches'), warning_table)
4278 obsolete_str = warning_report_obsolete(warnings.get('obsolete'), warning_table)
4279 case_sensitive_str = warning_report_case_sensitive(warnings.get('case_sensitive'), warning_table)
4280 blacklist_str = warning_report_blacklist(warnings.get('blacklist'), warning_table)
4281
4282 out_dict['no_matches'] = no_matches_str
4283 out_dict['obsolete'] = obsolete_str
4284 out_dict['case_sensitive_str'] = case_sensitive_str
4285 out_dict['blacklist_str'] = blacklist_str
4286
4287 out_str = "".join((
4288 no_matches_str, obsolete_str,
4289 case_sensitive_str, blacklist_str
4290 ))
4291
4292 return out_str, out_dict
4293
4294 # A function to lay out a single error report. We are passed
4295 # the name of the error (one of our validation functions), the
4296 # explanation to print out, and a dictionary with the error
4297 # information. We print no more than 50 characters of the item
4298
4299 def error_report(error_name,error_explanation,error_dics):
4300 retstring = "\n\n" + error_explanation + ":\n\n"
4301 headstring = "{}".format("Item name, ")
4302 bodystring = ""
4303
4304 table = PrettyTable()
4305 field_names = ["Wrong item name"]
4306
4307 if "bad_values" in error_dics[0]:
4308 headstring += "{}".format("Bad value(s)")
4309 field_names.append("Wrong value(s)")
4310 if "bad_items" in error_dics[0]:
4311 headstring += "{}".format("Bad dataname(s)")
4312 field_names.append("Bad dataname(s)")
4313 if "child" in error_dics[0]:
4314 headstring += "{}".format("Child")
4315 field_names.append("Child")
4316 if "parent" in error_dics[0]:
4317 headstring += "{}".format("Parent")
4318 field_names.append("Parent")
4319 headstring +="\n"
4320
4321 table.field_names = field_names
4322
4323 for field_name in table.field_names:
4324 table.align[field_name] = "l"
4325
4326 for error in error_dics:
4327 bodystring += "\n{}".format(error["item_name"])
4328 row = [error["item_name"]]
4329 if "bad_values" in error:
4330 max_items = 8
4331 if len(error["bad_values"]) > max_items:
4332 out_vals = []
4333 for i in range(max_items):
4334 out_vals.append(error["bad_values"][i])
4335
4336 out_vals.append("...")
4337 else:
4338 out_vals = [repr(a)[:50] for a in error["bad_values"]]
4339 row.append(out_vals)
4340 bodystring += "{}".format(out_vals)
4341 if "bad_items" in error:
4342 bodystring += "{}".format(repr(error["bad_items"]))
4343 row.append(repr(error["bad_items"]))
4344 if "child" in error:
4345 bodystring += "{}".format(repr(error["child"]))
4346 row.append(repr(error["child"]))
4347 if "parent" in error:
4348 bodystring += "{}".format(repr(error["parent"]))
4349 row.append(repr(error["parent"]))
4350
4351 table.add_row(row)
4352
4353 bodystring = table.get_string()
4354 return retstring + bodystring
4355
4356 # This lays out an HTML error report
4357
4358 def html_error_report(error_name,error_explanation,error_dics,annotate=[]):
4359 retstring = "<h4>" + error_explanation + ":</h4>"
4360 retstring = retstring + "<table cellpadding=5><tr>"
4361 headstring = "<th>Item name</th>"
4362 bodystring = ""
4363 if "bad_values" in error_dics[0]:
4364 headstring += "<th>Bad value(s)</th>"
4365 if "bad_items" in error_dics[0]:
4366 headstring += "<th>Bad dataname(s)</th>"
4367 if "child" in error_dics[0]:
4368 headstring += "<th>Child</th>"
4369 if "parent" in error_dics[0]:
4370 headstring += "<th>Parent</th>"
4371 headstring +="</tr>\n"
4372 for error in error_dics:
4373 bodystring += "<tr><td><tt>{}</tt></td>".format(error["item_name"])
4374 if "bad_values" in error:
4375 bodystring += "<td>{}</td>".format(error["bad_values"])
4376 if "bad_items" in error:
4377 bodystring += "<td><tt>{}</tt></td>".format(error["bad_items"])
4378 if "child" in error:
4379 bodystring += "<td><tt>{}</tt></td>".format(error["child"])
4380 if "parent" in error:
4381 bodystring += "<td><tt>{}</tt></td>".format(error["parent"])
4382 bodystring += "</tr>\n"
4383 return retstring + headstring + bodystring + "</table>\n"
4384
4385 # This function executes validation checks provided in the CifDic. The
4386 # validation calls create a dictionary containing the test results for each
4387 # item name. Each item has a list of (test name,result) tuples. After running
4388 # the tests, we contract these lists to contain only false results, and then
4389 # remove all items containing no false results.
4390 #
4391 #
4392 # <Run dictionary validation checks>=
4393 def run_data_checks(check_block,fulldic,block_scope='Item'):
4394 v_result = {}
4395 for key in check_block.keys():
4396 update_value(v_result, fulldic.run_item_validation(key,check_block[key]))
4397 update_value(v_result, fulldic.run_global_validation(key,check_block[key],check_block))
4398 for loopnames in check_block.loops.values():
4399 update_value(v_result, fulldic.run_loop_validation(loopnames))
4400 update_value(v_result, fulldic.run_loop_id_uniqueness(loopnames, check_block))
4401 update_value(v_result,fulldic.run_block_validation(check_block,block_scope=block_scope))
4402 # return false and list of baddies if anything didn't match
4403 all_keys = list(v_result.keys())
4404 for test_key in all_keys:
4405 v_result[test_key] = [a for a in v_result[test_key] if a[1]["result"]==False]
4406 if len(v_result[test_key]) == 0:
4407 del v_result[test_key]
4408 # if even one false one is found, this should trigger
4409 # print("Baddies: {!r}".format(v_result))
4410 isvalid = len(v_result)==0
4411 return isvalid,v_result
4412
4413
4414 # <Utility functions>=
4415 # This support function uses re capturing to work out the number's value. The
4416 # re contains 7 groups: group 0 is the entire expression; group 1 is the overall
4417 # match in the part prior to esd brackets; group 2 is the match with a decimal
4418 # point, group 3 is the digits after the decimal point, group 4 is the match
4419 # without a decimal point. Group 5 is the esd bracket contents, and
4420 # group 6 is the exponent.
4421 #
4422 # The esd should be returned as an independent number. We count the number
4423 # of digits after the decimal point, create the esd in terms of this, and then,
4424 # if necessary, apply the exponent.
4425 #
4426 #
4427 # <Extract number and esd>=
4428 def get_number_with_esd(numstring):
4429 numb_re = '((-?(([0-9]*[.]([0-9]+))|([0-9]+)[.]?))([(][0-9]+[)])?([eEdD][+-]?[0-9]+)?)|(\\?)|(\\.)'
4430 our_match = re.match(numb_re,numstring)
4431 if our_match:
4432 a,base_num,b,c,dad,dbd,esd,exp,q,dot = our_match.groups()
4433 # print("Debug: {} -> {!r}".format(numstring, our_match.groups()))
4434 else:
4435 return None,None
4436 if dot or q: return None,None #a dot or question mark
4437 if exp: #has exponent
4438 exp = exp.replace("d","e") # mop up old fashioned numbers
4439 exp = exp.replace("D","e")
4440 base_num = base_num + exp
4441 # print("Debug: have %s for base_num from %s" % (base_num,numstring))
4442 base_num = float(base_num)
4443 # work out esd, if present.
4444 if esd:
4445 esd = float(esd[1:-1]) # no brackets
4446 if dad: # decimal point + digits
4447 esd = esd * (10 ** (-1* len(dad)))
4448 if exp:
4449 esd = esd * (10 ** (float(exp[1:])))
4450 return base_num,esd
4451
4452 # We may be passed float values which have esds appended. We catch this case
4453 # by searching for an opening round bracket
4454 #
4455 # <Convert value to float, ignore esd>=
4456 def float_with_esd(inval):
4457 if isinstance(inval,unicode):
4458 j = inval.find("(")
4459 if j>=0: return float(inval[:j])
4460 return float(inval)
4461
4462
4463
4464 # For dREl operations we require that all numerical types actually appear
4465 # as numerical types rather than strings. This function takes a datablock
4466 # and a dictionary and converts all the datablock contents to numerical
4467 # values according to the dictionary specifications.
4468 #
4469 # Note that as written we are happy to interpret a floating point string as
4470 # an integer. We are therefore assuming that the value has been validated.
4471 #
4472 #
4473 # <Conversions to dictionary types>=
4474 # Instead of returning a value, we return a function that can be used
4475 # to convert the values. This saves time reconstructing the conversion
4476 # function for every value in a loop.
4477 #
4478 #
4479 # <Overall conversion>=
4480 def convert_type(definition):
4481 """Convert value to have the type given by definition"""
4482 #extract the actual required type information
4483 container = definition['_type.container']
4484 dimension = definition.get('_type.dimension','[]')
4485 dimension = ast.literal_eval(dimension)
4486 structure = interpret_structure(definition['_type.contents'])
4487 if container == 'Single': #a single value to convert
4488 return convert_single_value(structure)
4489 elif container == 'List': #lots of the same value
4490 return convert_list_values(structure,dimension)
4491 elif container == 'Multiple': #no idea
4492 return None
4493 elif container in ('Array','Matrix'): #numpy array
4494 return convert_matrix_values(structure)
4495 return lambda a:a #unable to convert
4496
4497 # <Convert a single value>=
4498 def convert_single_value(type_spec):
4499 """Convert a single item according to type_spec"""
4500 if type_spec == 'Real':
4501 return float_with_esd
4502 if type_spec in ('Count','Integer','Index','Binary','Hexadecimal','Octal'):
4503 return int
4504 if type_spec == 'Complex':
4505 return complex
4506 if type_spec == 'Imag':
4507 return lambda a:complex(0,a)
4508 if type_spec in ('Code','Name','Tag'): #case-insensitive -> lowercase
4509 return lambda a:a.lower()
4510 return lambda a:a #can't do anything numeric
4511
4512 # Convert a whole DDLm list. A 'List' type implies a repetition of
4513 # the types given in the 'type.contents' entry. We get all fancy and
4514 # build a function to decode each entry in our input list. This
4515 # function is then mapped over the List, and in the case of looped List
4516 # values, it can be mapped over the dataname value as well. However, in
4517 # the case of a single repetition, files are allowed to drop one level
4518 # of enclosing brackets. We account for that here by detecting a
4519 # one-element list and *not* mapping the conversion function. TODO:
4520 # Note that we do not yet handle the case that we are supposed to
4521 # convert to a Matrix, rather than a list. TODO: handle arbitrary
4522 # dimension lists, rather than special-casing the character sequence
4523 # '[1]'.
4524 #
4525 #
4526 # <Convert a list value>=
4527 class convert_simple_list(object):
4528
4529 """\
4530 Callable object that converts values in a simple list according
4531 to the specified element structure.
4532 """
4533
4534 def __init__(self, structure):
4535 self.converters = [convert_single_value(tp) for tp in structure]
4536 return
4537
4538 def __call__(self, element):
4539 if len(element) != len(self.converters):
4540 emsg = "Expected iterable of {} values, got {}.".format(
4541 (len(self.converters), len(element)))
4542 raise ValueError(emsg)
4543 rv = [f(e) for f, e in zip(self.converters, element)]
4544 return rv
4545
4546 # End of class convert_single_value
4547
4548 def convert_list_values(structure, dimension):
4549 """Convert the values according to the element
4550 structure given in [[structure]]"""
4551 # simple repetition
4552 print("Converting {} of dimensions {}".format(structure, dimension))
4553 if isinstance(structure, (unicode, str)):
4554 fcnv = convert_single_value(structure)
4555 # assume structure is a list of types
4556 else:
4557 fcnv = convert_simple_list(structure)
4558 rv = fcnv
4559 # setup nested conversion function when dimension differs from 1.
4560 if len(dimension) > 0 and int(dimension[0]) != 1:
4561 rv = lambda args : [fcnv(a) for a in args]
4562 return rv
4563
4564 # When storing a matrix/array value as a result of a calculation, we remove the
4565 # numpy information and instead store as a StarList. The following routine will
4566 # work transparently for either string or number-valued Star Lists, so we do not
4567 # have to worry.
4568 #
4569 #
4570 # <Convert a matrix value>=
4571 def convert_matrix_values(valtype):
4572 """Convert a dREL String or Float valued List structure to a numpy matrix structure"""
4573 # first convert to numpy array, then let numpy do the work
4574 try:
4575 import numpy
4576 except ImportError:
4577 return lambda a:a #cannot do it
4578 if valtype == 'Real':
4579 dtype = float
4580 elif valtype == 'Integer':
4581 dtype = int
4582 elif valtype == 'Complex':
4583 dtype = complex
4584 else:
4585 raise ValueError('Unknown matrix value type')
4586 fcnv = lambda a : numpy.asarray(a, dtype=dtype)
4587 return fcnv
4588
4589 # DDLm specifies List element composition using a notation of form 'cont(el,el,el...)'
4590 # where 'cont' refers to a container constructor (list or matrix so far) and 'el' is a simple
4591 # element type. If 'cont' is missing, the sequence of elements is a sequence of elements in
4592 # a simple list. We have written a simple parser to interpret this.
4593 #
4594 #
4595 # <Parse the structure specification>=
4596 def interpret_structure(struc_spec):
4597 """Interpret a DDLm structure specification"""
4598 from . import TypeContentsParser as t
4599 p = t.TypeParser(t.TypeParserScanner(struc_spec))
4600 return getattr(p,"input")()
4601
4602
4603 # <Append update>=
4604 # A utility function to append to item values rather than replace them
4605 def update_value(base_dict,new_items):
4606 for new_key in new_items.keys():
4607 if new_key in base_dict:
4608 base_dict[new_key].extend(new_items[new_key])
4609 else:
4610 base_dict[new_key] = new_items[new_key]
4611
4612 # <Transpose data>=
4613 #Transpose the list of lists passed to us
4614 def transpose(base_list):
4615 new_lofl = []
4616 full_length = len(base_list)
4617 opt_range = range(full_length)
4618 for i in range(len(base_list[0])):
4619 new_packet = []
4620 for j in opt_range:
4621 new_packet.append(base_list[j][i])
4622 new_lofl.append(new_packet)
4623 return new_lofl
4624
4625 # listify strings - used surprisingly often
4626 def listify(item):
4627 if isinstance(item,(unicode,str)): return [item]
4628 else: return item
4629
4630 # given a list of search items, return a list of items
4631 # actually contained in the given data block
4632 def filter_present(namelist,datablocknames):
4633 return [a for a in namelist if a in datablocknames]
4634
4635 # Make an item immutable, used if we want a list to be a key
4636 def make_immutable(values):
4637 """Turn list of StarList values into a list of immutable items"""
4638 if not isinstance(values[0],StarList):
4639 return values
4640 else:
4641 return [tuple(a) for a in values]
4642
4643 # This uses the [[CifFile]] merge method to merge a list of filenames,
4644 # with an initial check to determine DDL1/DDL2 merge style. In one
4645 # case we merge save frames in a single block, in another case we
4646 # merge data blocks. These are different levels.
4647 #
4648 # Note that the data block name is passed to specify the parts of each object
4649 # to be merged, rather than the objects themselves (not doing this was a bug
4650 # that was caught a while ago).
4651 #
4652 #
4653 # <Merge dictionaries as CIFs>=
4654 # merge ddl dictionaries. We should be passed filenames or CifFile
4655 # objects
4656 def merge_dic(diclist,mergemode="replace",ddlspec=None, verbose_import=True, verbose_validation=True):
4657 dic_as_cif_list = []
4658 for dic in diclist:
4659 if not isinstance(dic,CifFile) and \
4660 not isinstance(dic,(unicode,str)):
4661 raise TypeError("Require list of CifFile names/objects for dictionary merging")
4662 if not isinstance(dic,CifFile): dic_as_cif_list.append(CifFile(dic))
4663 else: dic_as_cif_list.append(dic)
4664 # we now merge left to right
4665 basedic = dic_as_cif_list[0]
4666 if "on_this_dictionary" in basedic: #DDL1 style only
4667 for dic in dic_as_cif_list[1:]:
4668 basedic.merge(dic,mode=mergemode,match_att=[], idblock="on_this_dictionary")
4669 elif len(basedic.keys()) == 1: #One block: DDL2/m style
4670 old_block = basedic[basedic.keys()[0]]
4671 for dic in dic_as_cif_list[1:]:
4672 new_block = dic[dic.keys()[0]]
4673 basedic.merge(dic,mode=mergemode,
4674 single_block=[basedic.keys()[0],dic.keys()[0]],
4675 match_att=["_item.name"],match_function=find_parent)
4676 final_dic = CifDic(basedic, do_dREL=False, verbose_import=verbose_import, verbose_validation=verbose_validation)
4677
4678 # Add all the alias blocks once the dictionary is fully formed
4679 if final_dic.diclang == "DDLm":
4680 final_dic = final_dic.add_alias_blocks()
4681
4682 return final_dic
4683
4684 # Find the main item from a parent-child list. We are asked to find the
4685 # topmost parent in a ddl2 definition block containing multiple item.names.
4686 # We use the insight that the parent item will be that item which is not in
4687 # the list of children as well. If there are no item names, that means
4688 # that we are dealing with something like a category -can they be merged??
4689 #
4690 #
4691 # <Get topmost parent>=
4692 def find_parent(ddl2_def):
4693 if "_item.name" not in ddl2_def:
4694 return None
4695 if isinstance(ddl2_def["_item.name"],unicode):
4696 return ddl2_def["_item.name"]
4697 if "_item_linked.child_name" not in ddl2_def:
4698 raise CifError("Asked to find parent in block with no child_names")
4699 if "_item_linked.parent_name" not in ddl2_def:
4700 raise CifError("Asked to find parent in block with no parent_names")
4701 result = list([a for a in ddl2_def["_item.name"] if a not in ddl2_def["_item_linked.child_name"]])
4702 if len(result)>1 or len(result)==0:
4703 raise CifError("Unable to find single unique parent data item")
4704 return result[0]
4705
4706 # Utility routine for use by callers who have captured parsing results instead
4707 # of raising an error immediately.
4708
4709 import CifFile.yapps3_compiled_rt as yappsrt
4710
4711 def print_cif_syntax_error(parsing_result, cif_file_name):
4712 """ For use when parsing results have been captured instead of raising an error
4713 immediately. See ReadStarWithError."""
4714
4715 error = parsing_result[1]
4716
4717 # parsing_result[0] == -1
4718 if isinstance(error, yappsrt.YappsSyntaxError):
4719 parser = parsing_result[2]
4720 Y = parsing_result[3]
4721
4722 scanner = parser._scanner
4723 input = parser._scanner.input
4724 pos = error.charpos
4725
4726 line_number = scanner.get_line_number_with_pos(pos)
4727
4728 out_str = "\n"
4729 out_str += "======================================================================\n"
4730 out_str += "\n"
4731 out_str += "SYNTAX ERROR AT LINE " + str(line_number) + " WHEN PARSING INPUT FILE:" + str(cif_file_name) + ":\n"
4732 out_str += str(error.msg) + "\n"
4733 out_str += "\n"
4734 out_str += "ERROR NEAR THE FOLLOWING INPUT TEXT:\n"
4735
4736 text_error = Y.yappsrt.print_line_with_pointer(input, pos)
4737
4738 out_str += text_error
4739 print(out_str)
4740
4741 return out_str
4742
4743 # parsing_result[0] == -2
4744 if isinstance(error, CifSyntaxError):
4745 print(error.value)
4746
4747 return error.value
4748
4749 # Reading in a file. We use the STAR grammar parser. Note that the blocks returned
4750 # will be locked for changing ([[overwrite=False]]) and can be unlocked by setting
4751 # block.overwrite to True.
4752 #
4753 # Provide access to rich error information with alternate function that makes use
4754 # of the ReadStarWithError function.
4755 #
4756 # <Read in a CIF file>=
4757 def ReadCifWithErrors(filename,grammar='auto',scantype='standard',scoping='instance',standard='CIF',
4758 permissive=False):
4759 """ Read in a CIF file, returning a (`CifFile`, error_result) tuple. `error_result`
4760 is a list [error_val, Exception, Parser, ParserModule] which can be used for
4761 detailed error reporting. If `error_val` is less than 0, an error has occurred
4762 and the contents of `CifFile` will be incomplete and/or incorrect.
4763
4764 * `filename` may be a URL, a file
4765 path on the local system, or any object with a `read` method.
4766
4767 Keyword meanings are as for `ReadCif`"""
4768
4769 finalcif = CifFile(scoping=scoping,standard=standard)
4770 return StarFile.ReadStarWithErrors(filename,prepared=finalcif,grammar=grammar,scantype=scantype,
4771 permissive=permissive)
4772
4773 def ReadCif(filename, grammar='auto', scantype='standard', scoping='instance', standard='CIF',
4774 permissive = False):
4775 """ Read in a CIF file, returning a `CifFile` object and raising an exception
4776 on failure.
4777
4778 * `filename` may be a URL, a file
4779 path on the local system, or any object with a `read` method.
4780
4781 * `grammar` chooses the CIF grammar variant. `1.0` is the original 1992 grammar and `1.1`
4782 is identical except for the exclusion of square brackets as the first characters in
4783 undelimited datanames. `2.0` will read files in the CIF2.0 standard, and `STAR2` will
4784 read files according to the STAR2 publication. If grammar is `None`, autodetection
4785 will be attempted in the order `2.0`, `1.1` and `1.0`. This will always succeed for
4786 properly-formed CIF2.0 files. Note that only Unicode characters in the basic multilingual
4787 plane are recognised (this will be fixed when PyCIFRW is ported to Python 3).
4788
4789 * `scantype` can be `standard` or `flex`. `standard` provides pure Python parsing at the
4790 cost of a factor of 10 or so in speed. `flex` will tokenise the input CIF file using
4791 fast C routines, but is not available for CIF2/STAR2 files. Note that running PyCIFRW in
4792 Jython uses native Java regular expressions
4793 to provide a speedup regardless of this argument (and does not yet support CIF2).
4794
4795 * `scoping` is only relevant where nested save frames are expected (STAR2 only).
4796 `instance` scoping makes nested save frames
4797 invisible outside their hierarchy, allowing duplicate save frame names in separate
4798 hierarchies. `dictionary` scoping makes all save frames within a data block visible to each
4799 other, thereby restricting all save frames to have unique names.
4800 Currently the only recognised value for `standard` is `CIF`, which when set enforces a
4801 maximum length of 75 characters for datanames and has no other effect.
4802 """
4803
4804 finalcif = CifFile(scoping=scoping,standard=standard)
4805 return StarFile.ReadStar(filename, prepared=finalcif, grammar=grammar, scantype=scantype,
4806 permissive = permissive)
4807
4808 # \section{Cif Loop block class}
4809 #
4810 # With the removal (by PyCIFRW) of nested loops, this class is now unnecessary. It is now
4811 # simply a pointer to StarFile.LoopBlock.
4812 #
4813 #
4814 # <CifLoopBlock class>=
4815 class CifLoopBlock(StarFile.LoopBlock):
4816 def __init__(self,data=(),**kwargs):
4817 super(CifLoopBlock,self).__init__(data,**kwargs)
4818
4819 # <API documentation flags>=
4820 #No documentation flags
4821