| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
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 |
| 32 |
|
| 33 |
try: |
| 34 |
from cStringIO import StringIO |
| 35 |
except ImportError: |
| 36 |
from io import StringIO |
| 37 |
|
| 38 |
|
| 39 |
try: |
| 40 |
from urllib import urlopen |
| 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 |
|
| 49 |
|
| 50 |
|
| 51 |
|
| 52 |
|
| 53 |
|
| 54 |
if isinstance(u"abc",str): |
| 55 |
unicode = str |
| 56 |
long = int |
| 57 |
|
| 58 |
|
| 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 |
| 113 |
from . import CifSyntaxError |
| 114 |
try: |
| 115 |
import numpy |
| 116 |
from .drel import drel_runtime |
| 117 |
except ImportError: |
| 118 |
pass |
| 119 |
from copy import copy |
| 120 |
import json |
| 121 |
|
| 122 |
|
| 123 |
|
| 124 |
|
| 125 |
|
| 126 |
|
| 127 |
|
| 128 |
|
| 129 |
|
| 130 |
|
| 131 |
|
| 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[:]) |
| 140 |
if len(wrapper.called_list) == 0: |
| 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: |
| 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 |
|
| 163 |
|
| 164 |
|
| 165 |
|
| 166 |
|
| 167 |
|
| 168 |
|
| 169 |
|
| 170 |
|
| 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 |
|
| 197 |
|
| 198 |
|
| 199 |
|
| 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 |
| 222 |
self.compat_mode = compat_mode |
| 223 |
|
| 224 |
def RemoveCifItem(self,itemname): |
| 225 |
"""Remove `itemname` from the CifBlock""" |
| 226 |
self.RemoveItem(itemname) |
| 227 |
|
| 228 |
|
| 229 |
|
| 230 |
|
| 231 |
|
| 232 |
|
| 233 |
def __setitem__(self,key,value): |
| 234 |
self.AddItem(key,value) |
| 235 |
|
| 236 |
if self.compat_mode: |
| 237 |
if isinstance(value,(tuple,list)) and not isinstance(value,StarFile.StarList): |
| 238 |
|
| 239 |
self.CreateLoop([key]) |
| 240 |
|
| 241 |
def copy(self): |
| 242 |
newblock = super(CifBlock,self).copy() |
| 243 |
return self.copy.im_class(newblock) |
| 244 |
|
| 245 |
|
| 246 |
|
| 247 |
|
| 248 |
|
| 249 |
|
| 250 |
|
| 251 |
def loopnames(self): |
| 252 |
return [self.loops[a] for a in self.loops] |
| 253 |
|
| 254 |
|
| 255 |
|
| 256 |
|
| 257 |
|
| 258 |
|
| 259 |
|
| 260 |
|
| 261 |
|
| 262 |
|
| 263 |
|
| 264 |
|
| 265 |
|
| 266 |
|
| 267 |
|
| 268 |
|
| 269 |
|
| 270 |
|
| 271 |
|
| 272 |
|
| 273 |
|
| 274 |
|
| 275 |
|
| 276 |
|
| 277 |
|
| 278 |
|
| 279 |
class CifFile(StarFile.StarFile): |
| 280 |
|
| 281 |
|
| 282 |
|
| 283 |
|
| 284 |
|
| 285 |
|
| 286 |
|
| 287 |
|
| 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: |
| 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 |
|
| 315 |
|
| 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 |
|
| 330 |
|
| 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 |
|
| 340 |
|
| 341 |
if tag_name_ddlm != tag: |
| 342 |
|
| 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 |
|
| 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 |
|
| 371 |
|
| 372 |
|
| 373 |
|
| 374 |
|
| 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 |
|
| 397 |
|
| 398 |
|
| 399 |
|
| 400 |
|
| 401 |
|
| 402 |
|
| 403 |
|
| 404 |
|
| 405 |
|
| 406 |
|
| 407 |
|
| 408 |
|
| 409 |
|
| 410 |
|
| 411 |
|
| 412 |
|
| 413 |
|
| 414 |
|
| 415 |
|
| 416 |
|
| 417 |
|
| 418 |
|
| 419 |
|
| 420 |
|
| 421 |
|
| 422 |
|
| 423 |
|
| 424 |
|
| 425 |
|
| 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: |
| 441 |
final_value = value |
| 442 |
if final_value is None: |
| 443 |
raise KeyError("{} not found".format(dataname)) |
| 444 |
return final_value |
| 445 |
|
| 446 |
|
| 447 |
|
| 448 |
|
| 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 |
|
| 479 |
mode = import_ref.get("mode",'Contents').lower() |
| 480 |
if mode == "contents": |
| 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 |
|
| 505 |
|
| 506 |
|
| 507 |
|
| 508 |
|
| 509 |
|
| 510 |
|
| 511 |
|
| 512 |
|
| 513 |
|
| 514 |
|
| 515 |
|
| 516 |
|
| 517 |
|
| 518 |
|
| 519 |
|
| 520 |
|
| 521 |
|
| 522 |
|
| 523 |
|
| 524 |
|
| 525 |
|
| 526 |
|
| 527 |
|
| 528 |
|
| 529 |
|
| 530 |
|
| 531 |
|
| 532 |
|
| 533 |
|
| 534 |
|
| 535 |
|
| 536 |
|
| 537 |
|
| 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 = {} |
| 548 |
self.ddlm_functions = {} |
| 549 |
self.switch_numpy(False) |
| 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' |
| 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 = [] |
| 561 |
|
| 562 |
if self.diclang == "DDL1": |
| 563 |
self.DDL1_normalise() |
| 564 |
self.create_def_block_table() |
| 565 |
if self.diclang == "DDL1": |
| 566 |
self.ddl1_cat_load() |
| 567 |
elif self.diclang == "DDL2": |
| 568 |
self.DDL2_normalise() |
| 569 |
elif self.diclang == "DDLm": |
| 570 |
self.scoping = 'dictionary' |
| 571 |
self._import_dics = self.get_dictionaries_to_import() |
| 572 |
if do_imports != 'No': |
| 573 |
self.obtain_imports(import_mode=do_imports,heavy=heavy) |
| 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 |
|
| 582 |
self.typedic={} |
| 583 |
self.primdic = {} |
| 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 |
|
| 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 |
|
| 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 |
|
| 608 |
|
| 609 |
|
| 610 |
if isinstance(alias_temp, list): |
| 611 |
for alias in alias_temp: |
| 612 |
|
| 613 |
|
| 614 |
self.NewBlock(alias.lower(), contents) |
| 615 |
self.block_id_table[alias.lower()] = alias.lower() |
| 616 |
|
| 617 |
else: |
| 618 |
|
| 619 |
|
| 620 |
|
| 621 |
self.NewBlock(alias_temp.lower(), contents) |
| 622 |
self.block_id_table[alias_temp.lower()] = alias_temp.lower() |
| 623 |
|
| 624 |
return self |
| 625 |
|
| 626 |
|
| 627 |
|
| 628 |
|
| 629 |
|
| 630 |
|
| 631 |
|
| 632 |
|
| 633 |
|
| 634 |
|
| 635 |
|
| 636 |
|
| 637 |
|
| 638 |
|
| 639 |
|
| 640 |
|
| 641 |
|
| 642 |
|
| 643 |
|
| 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" |
| 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 = [] |
| 666 |
|
| 667 |
|
| 668 |
|
| 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: |
| 684 |
self.master_block = super(CifDic,self).__getitem__(self.get_roots()[0][0]) |
| 685 |
|
| 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"): |
| 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 |
|
| 701 |
|
| 702 |
self.black_list_categories = { |
| 703 |
'publ_author' |
| 704 |
} |
| 705 |
return(name,version,"DDLm") |
| 706 |
else: |
| 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 |
|
| 731 |
|
| 732 |
|
| 733 |
|
| 734 |
|
| 735 |
|
| 736 |
|
| 737 |
|
| 738 |
|
| 739 |
|
| 740 |
|
| 741 |
|
| 742 |
|
| 743 |
|
| 744 |
|
| 745 |
|
| 746 |
|
| 747 |
|
| 748 |
|
| 749 |
|
| 750 |
|
| 751 |
|
| 752 |
|
| 753 |
|
| 754 |
|
| 755 |
|
| 756 |
|
| 757 |
|
| 758 |
|
| 759 |
|
| 760 |
|
| 761 |
|
| 762 |
|
| 763 |
|
| 764 |
|
| 765 |
|
| 766 |
|
| 767 |
|
| 768 |
def DDL1_normalise(self): |
| 769 |
|
| 770 |
self.standard = None |
| 771 |
|
| 772 |
|
| 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] |
| 780 |
if "_name" in value: |
| 781 |
real_name = value["_name"] |
| 782 |
if isinstance(real_name,list): |
| 783 |
for looped_name in real_name: |
| 784 |
new_value = value.copy() |
| 785 |
new_value["_name"] = looped_name |
| 786 |
self[looped_name] = new_value |
| 787 |
newnames = real_name |
| 788 |
else: |
| 789 |
self[real_name] = value |
| 790 |
newnames = [real_name] |
| 791 |
|
| 792 |
if key not in newnames: |
| 793 |
del self[key] |
| 794 |
|
| 795 |
for key,value in self.items(): |
| 796 |
|
| 797 |
save_overwrite = value.overwrite |
| 798 |
value.overwrite = True |
| 799 |
|
| 800 |
if "_list" not in value: value["_list"] = 'no' |
| 801 |
if "_type_conditions" not in value: value["_type_conditions"] = 'none' |
| 802 |
|
| 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 |
|
| 812 |
if "_type_construct" in value: |
| 813 |
base_types.append(value["_name"]+"_type") |
| 814 |
base_constructs.append(value["_type_construct"]+"$") |
| 815 |
prim_types.append(value["_type"]) |
| 816 |
value["_type"] = base_types[-1] |
| 817 |
|
| 818 |
|
| 819 |
|
| 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 |
|
| 825 |
if "]" in value["_name"]: |
| 826 |
last_under = len(value["_name"]) |
| 827 |
|
| 828 |
catid = value["_name"][1:last_under] |
| 829 |
value["_category.id"] = catid |
| 830 |
if catid not in self.cat_list: self.cat_list.append(catid) |
| 831 |
value.overwrite = save_overwrite |
| 832 |
|
| 833 |
|
| 834 |
for key,value in self.items(): |
| 835 |
|
| 836 |
if "_category" in self[key]: |
| 837 |
if self[key]["_category"] not in self.cat_list: |
| 838 |
|
| 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 |
|
| 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 |
|
| 855 |
|
| 856 |
|
| 857 |
|
| 858 |
|
| 859 |
|
| 860 |
|
| 861 |
|
| 862 |
|
| 863 |
|
| 864 |
|
| 865 |
def ddl1_cat_load(self): |
| 866 |
deflist = self.keys() |
| 867 |
cat_mand_dic = {} |
| 868 |
cat_unique_dic = {} |
| 869 |
|
| 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 |
|
| 877 |
|
| 878 |
|
| 879 |
|
| 880 |
|
| 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] |
| 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 |
|
| 896 |
|
| 897 |
|
| 898 |
|
| 899 |
|
| 900 |
|
| 901 |
|
| 902 |
|
| 903 |
|
| 904 |
|
| 905 |
|
| 906 |
|
| 907 |
|
| 908 |
|
| 909 |
|
| 910 |
|
| 911 |
|
| 912 |
|
| 913 |
|
| 914 |
|
| 915 |
|
| 916 |
|
| 917 |
|
| 918 |
|
| 919 |
|
| 920 |
|
| 921 |
|
| 922 |
|
| 923 |
|
| 924 |
|
| 925 |
|
| 926 |
|
| 927 |
|
| 928 |
|
| 929 |
|
| 930 |
|
| 931 |
|
| 932 |
|
| 933 |
|
| 934 |
|
| 935 |
|
| 936 |
|
| 937 |
|
| 938 |
|
| 939 |
|
| 940 |
|
| 941 |
|
| 942 |
|
| 943 |
|
| 944 |
|
| 945 |
|
| 946 |
|
| 947 |
|
| 948 |
|
| 949 |
|
| 950 |
|
| 951 |
|
| 952 |
|
| 953 |
|
| 954 |
|
| 955 |
|
| 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 |
|
| 985 |
dodgy_defs = filter(lambda a:len(self[a]['_item.name']) > 1, listed_defs) |
| 986 |
for item_def in dodgy_defs: |
| 987 |
|
| 988 |
|
| 989 |
|
| 990 |
|
| 991 |
|
| 992 |
|
| 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 |
|
| 998 |
|
| 999 |
|
| 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 |
|
| 1015 |
|
| 1016 |
|
| 1017 |
|
| 1018 |
|
| 1019 |
|
| 1020 |
|
| 1021 |
|
| 1022 |
|
| 1023 |
|
| 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 |
|
| 1027 |
for item_def in dodgy_defs: self.create_pcloop(item_def) |
| 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 |
|
| 1034 |
family = list(zip(parents,child_list)) |
| 1035 |
notmychildren = family |
| 1036 |
|
| 1037 |
while len(notmychildren): |
| 1038 |
|
| 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: |
| 1042 |
|
| 1043 |
|
| 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 |
|
| 1054 |
|
| 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: |
| 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) |
| 1062 |
setattr(newpacket,'_item_linked.child_name',child) |
| 1063 |
setattr(newpacket,'_item_linked.parent_name',parent) |
| 1064 |
childloop.AddPacket(newpacket) |
| 1065 |
|
| 1066 |
|
| 1067 |
|
| 1068 |
|
| 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 |
|
| 1080 |
old_children.append(childname) |
| 1081 |
old_parents.append(parent_name) |
| 1082 |
|
| 1083 |
|
| 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 |
|
| 1092 |
notmychildren = [a for a in notmychildren if a[0]!=mychildren[0][0]] |
| 1093 |
|
| 1094 |
|
| 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 |
|
| 1100 |
|
| 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() |
| 1106 |
del self[alias]["_item_aliases.alias_name"] |
| 1107 |
|
| 1108 |
|
| 1109 |
|
| 1110 |
|
| 1111 |
|
| 1112 |
|
| 1113 |
|
| 1114 |
|
| 1115 |
|
| 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 |
|
| 1129 |
|
| 1130 |
|
| 1131 |
|
| 1132 |
|
| 1133 |
|
| 1134 |
|
| 1135 |
|
| 1136 |
|
| 1137 |
|
| 1138 |
|
| 1139 |
|
| 1140 |
|
| 1141 |
|
| 1142 |
|
| 1143 |
|
| 1144 |
|
| 1145 |
|
| 1146 |
|
| 1147 |
|
| 1148 |
|
| 1149 |
|
| 1150 |
|
| 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 |
|
| 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) |
| 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 |
|
| 1196 |
mode = import_ref.get("mode",'Contents').lower() |
| 1197 |
if target_key in self and mode=='full': |
| 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 |
|
| 1207 |
|
| 1208 |
|
| 1209 |
|
| 1210 |
|
| 1211 |
|
| 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': |
| 1223 |
self[parent_block].merge(import_target) |
| 1224 |
elif mode =="full": |
| 1225 |
|
| 1226 |
syntactic_head = self[self.get_parent(parent_block)] |
| 1227 |
from_cat_head = import_target['_name.object_id'] |
| 1228 |
child_frames = import_from.ddlm_all_children(from_cat_head) |
| 1229 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 1255 |
|
| 1256 |
self.create_def_block_table() |
| 1257 |
merging_cat = self[parent_block]['_name.object_id'] |
| 1258 |
if head_to_head: |
| 1259 |
child_frames = self.ddlm_immediate_children(from_cat_head) |
| 1260 |
|
| 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 |
|
| 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: |
| 1270 |
from_frame = import_from[target_key]['_definition.id'] |
| 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 |
|
| 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 |
|
| 1288 |
tag_name = double_def[0] |
| 1289 |
|
| 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 |
|
| 1299 |
|
| 1300 |
|
| 1301 |
|
| 1302 |
|
| 1303 |
|
| 1304 |
|
| 1305 |
|
| 1306 |
|
| 1307 |
|
| 1308 |
|
| 1309 |
|
| 1310 |
|
| 1311 |
|
| 1312 |
|
| 1313 |
|
| 1314 |
if len(duplicated_block_keys) == len(base_block_keys) \ |
| 1315 |
and duplicated_block_keys == base_block_keys: |
| 1316 |
continue |
| 1317 |
|
| 1318 |
|
| 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 |
| 1327 |
new_url = urljoin(self.my_uri,file_loc) |
| 1328 |
|
| 1329 |
return new_url |
| 1330 |
|
| 1331 |
|
| 1332 |
|
| 1333 |
|
| 1334 |
|
| 1335 |
|
| 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': |
| 1341 |
self[parent_block].add_dict_cache(file_loc,import_from) |
| 1342 |
elif mode =="full": |
| 1343 |
|
| 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 |
|
| 1350 |
head_id = import_target["_definition.id"] |
| 1351 |
|
| 1352 |
merging_cat = self[parent_block]['_name.object_id'] |
| 1353 |
from_cat_head = import_target['_name.object_id'] |
| 1354 |
if not head_to_head: |
| 1355 |
import_target["_name.category_id"]=merging_cat |
| 1356 |
self._import_dics = [(import_from,head_id)]+self._import_dics |
| 1357 |
|
| 1358 |
|
| 1359 |
|
| 1360 |
|
| 1361 |
|
| 1362 |
|
| 1363 |
|
| 1364 |
|
| 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 |
|
| 1377 |
|
| 1378 |
|
| 1379 |
|
| 1380 |
|
| 1381 |
|
| 1382 |
|
| 1383 |
|
| 1384 |
|
| 1385 |
|
| 1386 |
|
| 1387 |
|
| 1388 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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: |
| 1412 |
return super(CifDic,self).__getitem__(key) |
| 1413 |
except KeyError: |
| 1414 |
try: |
| 1415 |
return super(CifDic,self).__getitem__(key) |
| 1416 |
except KeyError: |
| 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: |
| 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: |
| 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): |
| 1440 |
super(CifDic,self).__delitem__(key) |
| 1441 |
return |
| 1442 |
|
| 1443 |
|
| 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 |
|
| 1466 |
|
| 1467 |
|
| 1468 |
|
| 1469 |
|
| 1470 |
|
| 1471 |
|
| 1472 |
|
| 1473 |
|
| 1474 |
|
| 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: |
| 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 |
|
| 1499 |
|
| 1500 |
|
| 1501 |
|
| 1502 |
|
| 1503 |
|
| 1504 |
|
| 1505 |
|
| 1506 |
|
| 1507 |
|
| 1508 |
|
| 1509 |
|
| 1510 |
|
| 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 == '': |
| 1553 |
raise CifError("{} has no parent".format(itemname)) |
| 1554 |
return parent |
| 1555 |
|
| 1556 |
|
| 1557 |
|
| 1558 |
|
| 1559 |
|
| 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 |
|
| 1577 |
|
| 1578 |
|
| 1579 |
|
| 1580 |
|
| 1581 |
|
| 1582 |
|
| 1583 |
|
| 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 |
|
| 1594 |
|
| 1595 |
|
| 1596 |
|
| 1597 |
|
| 1598 |
|
| 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 |
|
| 1605 |
|
| 1606 |
|
| 1607 |
|
| 1608 |
|
| 1609 |
|
| 1610 |
|
| 1611 |
|
| 1612 |
|
| 1613 |
|
| 1614 |
|
| 1615 |
|
| 1616 |
|
| 1617 |
|
| 1618 |
|
| 1619 |
|
| 1620 |
|
| 1621 |
|
| 1622 |
|
| 1623 |
|
| 1624 |
def create_cat_obj_table(self): |
| 1625 |
"""Populate a table indexed by (cat,obj) and returning the correct dataname""" |
| 1626 |
|
| 1627 |
|
| 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 |
|
| 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 = {} |
| 1647 |
|
| 1648 |
|
| 1649 |
|
| 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 |
|
| 1659 |
|
| 1660 |
for child_cat in child_cats: |
| 1661 |
nn = [] |
| 1662 |
|
| 1663 |
if child_cat in expand_list: |
| 1664 |
nn = expand_base_table(child_cat,expand_list[child_cat]) |
| 1665 |
|
| 1666 |
extra_names += nn |
| 1667 |
|
| 1668 |
|
| 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 |
|
| 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 |
|
| 1677 |
|
| 1678 |
child_names += extra_names |
| 1679 |
|
| 1680 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 1743 |
|
| 1744 |
|
| 1745 |
|
| 1746 |
|
| 1747 |
|
| 1748 |
|
| 1749 |
|
| 1750 |
|
| 1751 |
|
| 1752 |
|
| 1753 |
|
| 1754 |
|
| 1755 |
|
| 1756 |
|
| 1757 |
|
| 1758 |
|
| 1759 |
|
| 1760 |
|
| 1761 |
|
| 1762 |
|
| 1763 |
|
| 1764 |
|
| 1765 |
|
| 1766 |
|
| 1767 |
|
| 1768 |
|
| 1769 |
|
| 1770 |
|
| 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 |
|
| 1777 |
def regex_fiddle(mm_regex): |
| 1778 |
brack_match = r"((.*\[.+)(\\{)(.*\].*))" |
| 1779 |
ret_match = r"((.*\[.+)(\\n)(.*\].*))" |
| 1780 |
fixed_regexp = mm_regex[:] |
| 1781 |
|
| 1782 |
bm = re.match(brack_match,mm_regex) |
| 1783 |
if bm != None: |
| 1784 |
fixed_regexp = bm.expand(r"\2\\\\{\4") |
| 1785 |
|
| 1786 |
rm = re.match(ret_match,fixed_regexp) |
| 1787 |
if rm != None: |
| 1788 |
fixed_regexp = rm.expand(r"\2\3\\r\4") |
| 1789 |
|
| 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 |
|
| 1795 |
for typecode,primtype in zip(types,prim_types): |
| 1796 |
self.primdic[typecode] = primtype |
| 1797 |
|
| 1798 |
|
| 1799 |
|
| 1800 |
|
| 1801 |
|
| 1802 |
|
| 1803 |
|
| 1804 |
def add_category_info(self,full=True): |
| 1805 |
if self.diclang == "DDLm": |
| 1806 |
|
| 1807 |
|
| 1808 |
|
| 1809 |
|
| 1810 |
|
| 1811 |
|
| 1812 |
|
| 1813 |
|
| 1814 |
|
| 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 |
|
| 1830 |
|
| 1831 |
|
| 1832 |
|
| 1833 |
|
| 1834 |
|
| 1835 |
|
| 1836 |
|
| 1837 |
|
| 1838 |
|
| 1839 |
|
| 1840 |
|
| 1841 |
|
| 1842 |
|
| 1843 |
|
| 1844 |
|
| 1845 |
|
| 1846 |
self.key_equivs = {} |
| 1847 |
for one_cat in looped_cats: |
| 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 |
|
| 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 |
|
| 1874 |
if set(parent_keys) != set(linked_keys): |
| 1875 |
raise CifError("Parent keys and linked keys are different! {}/{}".format(parent_keys,linked_keys)) |
| 1876 |
|
| 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 |
| 1880 |
|
| 1881 |
else: |
| 1882 |
|
| 1883 |
lower_keys = [] |
| 1884 |
|
| 1885 |
else: |
| 1886 |
self.parent_lookup = {} |
| 1887 |
self.key_equivs = {} |
| 1888 |
|
| 1889 |
|
| 1890 |
|
| 1891 |
|
| 1892 |
|
| 1893 |
|
| 1894 |
|
| 1895 |
|
| 1896 |
|
| 1897 |
|
| 1898 |
|
| 1899 |
|
| 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) |
| 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:]) |
| 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: |
| 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 |
| 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]: |
| 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 |
|
| 1962 |
|
| 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) |
| 2014 |
|
| 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 |
|
| 2034 |
|
| 2035 |
|
| 2036 |
|
| 2037 |
|
| 2038 |
|
| 2039 |
|
| 2040 |
|
| 2041 |
|
| 2042 |
|
| 2043 |
|
| 2044 |
|
| 2045 |
|
| 2046 |
|
| 2047 |
|
| 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] == '_': |
| 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 |
|
| 2068 |
|
| 2069 |
|
| 2070 |
|
| 2071 |
|
| 2072 |
|
| 2073 |
|
| 2074 |
|
| 2075 |
|
| 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 |
|
| 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() |
| 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 |
|
| 2136 |
|
| 2137 |
|
| 2138 |
|
| 2139 |
|
| 2140 |
|
| 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 |
|
| 2147 |
|
| 2148 |
|
| 2149 |
|
| 2150 |
|
| 2151 |
|
| 2152 |
|
| 2153 |
|
| 2154 |
|
| 2155 |
|
| 2156 |
|
| 2157 |
|
| 2158 |
|
| 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 |
|
| 2165 |
else: |
| 2166 |
return None,None |
| 2167 |
if dot or q: return None,None |
| 2168 |
if exp: |
| 2169 |
exp = exp.replace("d","e") |
| 2170 |
exp = exp.replace("D","e") |
| 2171 |
base_num = base_num + exp |
| 2172 |
|
| 2173 |
base_num = float(base_num) |
| 2174 |
|
| 2175 |
if esd: |
| 2176 |
esd = float(esd[1:-1]) |
| 2177 |
if dad: |
| 2178 |
esd = esd * (10 ** (-1* len(dad))) |
| 2179 |
if exp: |
| 2180 |
esd = esd * (10 ** (float(exp[1:]))) |
| 2181 |
return base_num,esd |
| 2182 |
|
| 2183 |
|
| 2184 |
|
| 2185 |
|
| 2186 |
|
| 2187 |
|
| 2188 |
|
| 2189 |
|
| 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 |
|
| 2206 |
|
| 2207 |
|
| 2208 |
|
| 2209 |
|
| 2210 |
|
| 2211 |
|
| 2212 |
|
| 2213 |
|
| 2214 |
|
| 2215 |
|
| 2216 |
|
| 2217 |
|
| 2218 |
|
| 2219 |
|
| 2220 |
|
| 2221 |
|
| 2222 |
|
| 2223 |
|
| 2224 |
|
| 2225 |
|
| 2226 |
|
| 2227 |
|
| 2228 |
|
| 2229 |
|
| 2230 |
|
| 2231 |
|
| 2232 |
|
| 2233 |
def initialise_drel(self): |
| 2234 |
"""Parse drel functions and prepare data structures in dictionary""" |
| 2235 |
self.ddlm_parse_valid() |
| 2236 |
self.transform_drel() |
| 2237 |
self.add_drel_funcs() |
| 2238 |
|
| 2239 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 2273 |
|
| 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 |
|
| 2282 |
lexer.begin('INITIAL') |
| 2283 |
continue |
| 2284 |
|
| 2285 |
cat_meth = False |
| 2286 |
if self[derivable].get('_definition.scope','Item') == 'Category': |
| 2287 |
cat_meth = True |
| 2288 |
|
| 2289 |
|
| 2290 |
if drel_purpose == "Definition": |
| 2291 |
|
| 2292 |
|
| 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 |
|
| 2309 |
|
| 2310 |
|
| 2311 |
|
| 2312 |
|
| 2313 |
|
| 2314 |
|
| 2315 |
|
| 2316 |
|
| 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 |
|
| 2322 |
|
| 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 |
|
| 2332 |
parser = drel_ast_yacc.parser |
| 2333 |
|
| 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 |
|
| 2345 |
global_table = globals() |
| 2346 |
exec(py_function, global_table) |
| 2347 |
|
| 2348 |
self.ddlm_functions = globals() |
| 2349 |
|
| 2350 |
|
| 2351 |
|
| 2352 |
|
| 2353 |
|
| 2354 |
|
| 2355 |
|
| 2356 |
|
| 2357 |
|
| 2358 |
|
| 2359 |
|
| 2360 |
|
| 2361 |
|
| 2362 |
|
| 2363 |
|
| 2364 |
|
| 2365 |
|
| 2366 |
|
| 2367 |
|
| 2368 |
|
| 2369 |
|
| 2370 |
|
| 2371 |
|
| 2372 |
|
| 2373 |
|
| 2374 |
|
| 2375 |
@track_recursion |
| 2376 |
def derive_item(self,start_key,cifdata,store_value = False,allow_defaults=True): |
| 2377 |
key = start_key |
| 2378 |
result = None |
| 2379 |
default_result = False |
| 2380 |
|
| 2381 |
|
| 2382 |
|
| 2383 |
|
| 2384 |
|
| 2385 |
|
| 2386 |
|
| 2387 |
|
| 2388 |
|
| 2389 |
|
| 2390 |
|
| 2391 |
|
| 2392 |
|
| 2393 |
|
| 2394 |
|
| 2395 |
|
| 2396 |
|
| 2397 |
|
| 2398 |
|
| 2399 |
|
| 2400 |
|
| 2401 |
|
| 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 |
|
| 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] |
| 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 |
|
| 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: |
| 2425 |
|
| 2426 |
|
| 2427 |
|
| 2428 |
|
| 2429 |
|
| 2430 |
|
| 2431 |
|
| 2432 |
|
| 2433 |
|
| 2434 |
|
| 2435 |
|
| 2436 |
|
| 2437 |
|
| 2438 |
|
| 2439 |
|
| 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 |
|
| 2453 |
|
| 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 |
|
| 2465 |
if key in cat_result: |
| 2466 |
return cat_result[key] |
| 2467 |
|
| 2468 |
|
| 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: |
| 2472 |
|
| 2473 |
|
| 2474 |
|
| 2475 |
|
| 2476 |
|
| 2477 |
|
| 2478 |
|
| 2479 |
|
| 2480 |
|
| 2481 |
|
| 2482 |
|
| 2483 |
|
| 2484 |
for one_func in the_funcs: |
| 2485 |
print('Executing function for {}:'.format(key)) |
| 2486 |
|
| 2487 |
exec(one_func, globals()) |
| 2488 |
|
| 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 |
|
| 2504 |
|
| 2505 |
if result is None and allow_defaults: |
| 2506 |
|
| 2507 |
|
| 2508 |
|
| 2509 |
|
| 2510 |
|
| 2511 |
|
| 2512 |
|
| 2513 |
|
| 2514 |
|
| 2515 |
|
| 2516 |
|
| 2517 |
|
| 2518 |
|
| 2519 |
if def_val: |
| 2520 |
result = self.change_type(key,def_val) |
| 2521 |
default_result = True |
| 2522 |
elif def_index_val: |
| 2523 |
index_vals = self[key]["_enumeration_default.index"] |
| 2524 |
val_to_index = cifdata[def_index_val] |
| 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 |
|
| 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) |
| 2539 |
result = self[key]["_enumeration_default.value"][keypos] |
| 2540 |
default_result = True |
| 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 |
|
| 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 |
|
| 2550 |
exec(def_func[0], globals()) |
| 2551 |
|
| 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 |
|
| 2566 |
if result is None: |
| 2567 |
print('Warning: no way of deriving item {}, allow_defaults is {}'.format(key,repr(allow_defaults))) |
| 2568 |
raise StarFile.StarDerivationError(start_key) |
| 2569 |
|
| 2570 |
|
| 2571 |
|
| 2572 |
|
| 2573 |
|
| 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: |
| 2578 |
if result is None or default_result: |
| 2579 |
loop_len = len(cifdata[has_cat_names[0]]) |
| 2580 |
out_result = [result]*loop_len |
| 2581 |
result = out_result |
| 2582 |
else: |
| 2583 |
print('Resetting result {} for {} to null list as category is empty'.format(key,result)) |
| 2584 |
result = [] |
| 2585 |
|
| 2586 |
|
| 2587 |
|
| 2588 |
|
| 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 |
|
| 2601 |
|
| 2602 |
|
| 2603 |
|
| 2604 |
|
| 2605 |
|
| 2606 |
|
| 2607 |
|
| 2608 |
|
| 2609 |
|
| 2610 |
|
| 2611 |
|
| 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 |
|
| 2615 |
the_category = self[key]["_name.category_id"] |
| 2616 |
out_result = result |
| 2617 |
if result is not None and not default_result: |
| 2618 |
|
| 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: |
| 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 |
|
| 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: |
| 2637 |
cifdata[key] = out_result |
| 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 |
|
| 2658 |
|
| 2659 |
|
| 2660 |
|
| 2661 |
|
| 2662 |
|
| 2663 |
|
| 2664 |
|
| 2665 |
|
| 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] |
| 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] |
| 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 |
|
| 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 |
|
| 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': |
| 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 |
|
| 2705 |
|
| 2706 |
|
| 2707 |
|
| 2708 |
|
| 2709 |
|
| 2710 |
|
| 2711 |
|
| 2712 |
|
| 2713 |
|
| 2714 |
|
| 2715 |
|
| 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 |
|
| 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: |
| 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 |
|
| 2734 |
extra_result = self.duplicate_datanames(cifdata,sc,target_category,skip_names=new_ids+[target_key]) |
| 2735 |
|
| 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: |
| 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 |
|
| 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: |
| 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 |
|
| 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) |
| 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 |
|
| 2813 |
|
| 2814 |
|
| 2815 |
|
| 2816 |
|
| 2817 |
|
| 2818 |
|
| 2819 |
|
| 2820 |
|
| 2821 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 2846 |
print('Fixing item order for {}'.format(repr(the_key))) |
| 2847 |
for one_key in the_key: |
| 2848 |
cifdata.ChangeItemOrder(one_key,0) |
| 2849 |
|
| 2850 |
|
| 2851 |
|
| 2852 |
|
| 2853 |
|
| 2854 |
|
| 2855 |
|
| 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 |
|
| 2873 |
|
| 2874 |
|
| 2875 |
|
| 2876 |
|
| 2877 |
|
| 2878 |
|
| 2879 |
def switch_numpy(self,to_val): |
| 2880 |
pass |
| 2881 |
|
| 2882 |
|
| 2883 |
|
| 2884 |
|
| 2885 |
|
| 2886 |
|
| 2887 |
|
| 2888 |
|
| 2889 |
|
| 2890 |
|
| 2891 |
|
| 2892 |
|
| 2893 |
|
| 2894 |
|
| 2895 |
|
| 2896 |
|
| 2897 |
|
| 2898 |
|
| 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): |
| 2903 |
newval = list([change_function(a) for a in inval]) |
| 2904 |
else: |
| 2905 |
newval = change_function(inval) |
| 2906 |
return newval |
| 2907 |
|
| 2908 |
|
| 2909 |
|
| 2910 |
|
| 2911 |
|
| 2912 |
|
| 2913 |
|
| 2914 |
|
| 2915 |
|
| 2916 |
|
| 2917 |
|
| 2918 |
|
| 2919 |
|
| 2920 |
|
| 2921 |
|
| 2922 |
def install_validation_functions(self): |
| 2923 |
"""Install the DDL-appropriate validation checks""" |
| 2924 |
if self.diclang != 'DDLm': |
| 2925 |
|
| 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 |
|
| 2934 |
self.loop_validation_funs = [ |
| 2935 |
self.validate_loop_membership, |
| 2936 |
self.validate_loop_key, |
| 2937 |
self.validate_loop_references |
| 2938 |
] |
| 2939 |
|
| 2940 |
|
| 2941 |
|
| 2942 |
self.loop_id_uniqueness_funs = [ |
| 2943 |
self.validate_loop_key_uniqueness |
| 2944 |
] |
| 2945 |
|
| 2946 |
|
| 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 |
|
| 2955 |
self.block_validation_funs = [ |
| 2956 |
self.validate_mandatory_category |
| 2957 |
] |
| 2958 |
|
| 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 |
| 2982 |
self.done_parents = [] |
| 2983 |
self.done_children = [] |
| 2984 |
self.done_keys = [] |
| 2985 |
|
| 2986 |
|
| 2987 |
|
| 2988 |
|
| 2989 |
|
| 2990 |
|
| 2991 |
|
| 2992 |
|
| 2993 |
|
| 2994 |
|
| 2995 |
|
| 2996 |
|
| 2997 |
|
| 2998 |
|
| 2999 |
|
| 3000 |
|
| 3001 |
|
| 3002 |
|
| 3003 |
|
| 3004 |
|
| 3005 |
|
| 3006 |
|
| 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: |
| 3014 |
return {"result":True} |
| 3015 |
matchexpr = self.typedic[target_type] |
| 3016 |
item_values = listify(item_value) |
| 3017 |
|
| 3018 |
|
| 3019 |
|
| 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 |
|
| 3026 |
|
| 3027 |
|
| 3028 |
|
| 3029 |
|
| 3030 |
|
| 3031 |
|
| 3032 |
|
| 3033 |
|
| 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': |
| 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 |
|
| 3055 |
|
| 3056 |
|
| 3057 |
|
| 3058 |
|
| 3059 |
|
| 3060 |
|
| 3061 |
|
| 3062 |
|
| 3063 |
|
| 3064 |
|
| 3065 |
|
| 3066 |
|
| 3067 |
|
| 3068 |
|
| 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} |
| 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 |
|
| 3094 |
|
| 3095 |
|
| 3096 |
|
| 3097 |
|
| 3098 |
|
| 3099 |
|
| 3100 |
|
| 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 |
| 3118 |
for lower,upper in rangelist: |
| 3119 |
|
| 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 |
|
| 3125 |
|
| 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 |
|
| 3132 |
|
| 3133 |
|
| 3134 |
|
| 3135 |
|
| 3136 |
|
| 3137 |
|
| 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(".") |
| 3145 |
enum_list.append("?") |
| 3146 |
item_values = listify(item_value) |
| 3147 |
|
| 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 |
|
| 3153 |
|
| 3154 |
|
| 3155 |
|
| 3156 |
|
| 3157 |
|
| 3158 |
|
| 3159 |
|
| 3160 |
|
| 3161 |
|
| 3162 |
|
| 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)): |
| 3169 |
return {"result":False} |
| 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): |
| 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 |
|
| 3185 |
|
| 3186 |
|
| 3187 |
|
| 3188 |
|
| 3189 |
|
| 3190 |
|
| 3191 |
|
| 3192 |
|
| 3193 |
|
| 3194 |
|
| 3195 |
|
| 3196 |
|
| 3197 |
|
| 3198 |
|
| 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: |
| 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 |
|
| 3217 |
|
| 3218 |
|
| 3219 |
|
| 3220 |
|
| 3221 |
|
| 3222 |
|
| 3223 |
|
| 3224 |
|
| 3225 |
def validate_loop_key(self,loop_names): |
| 3226 |
category = self[loop_names[0]][self.cat_spec] |
| 3227 |
|
| 3228 |
key_spec = self[category].get(self.key_spec,[]) |
| 3229 |
for names_to_check in key_spec: |
| 3230 |
if isinstance(names_to_check,unicode): |
| 3231 |
names_to_check = [names_to_check] |
| 3232 |
for loop_key in names_to_check: |
| 3233 |
if loop_key not in loop_names: |
| 3234 |
|
| 3235 |
if self[loop_key].get(self.must_exist_spec,None) == "implicit": |
| 3236 |
continue |
| 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} |
| 3244 |
return {"result":True} |
| 3245 |
|
| 3246 |
|
| 3247 |
|
| 3248 |
|
| 3249 |
|
| 3250 |
|
| 3251 |
|
| 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 |
|
| 3261 |
list_mandatory = self[loop_name].get(self.must_exist_spec, "") |
| 3262 |
|
| 3263 |
|
| 3264 |
category = self[loop_name].get(self.cat_spec, "") |
| 3265 |
|
| 3266 |
|
| 3267 |
list_mandatory = list_mandatory == 'yes' |
| 3268 |
|
| 3269 |
|
| 3270 |
if list_mandatory and category not in self.black_list_categories: |
| 3271 |
loop_names_to_check.append(loop_name) |
| 3272 |
|
| 3273 |
|
| 3274 |
if not loop_names_to_check: |
| 3275 |
return {"result": True} |
| 3276 |
|
| 3277 |
|
| 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 |
|
| 3288 |
set_values = set(values) |
| 3289 |
|
| 3290 |
|
| 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 |
|
| 3303 |
final_cats = self.get_final_cats(loop_names) |
| 3304 |
|
| 3305 |
|
| 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 |
|
| 3313 |
loop_names_to_check = [loop_name for loop_name in loop_names if loop_name in cat_keys] |
| 3314 |
|
| 3315 |
|
| 3316 |
if not loop_names_to_check: |
| 3317 |
return {"result":True} |
| 3318 |
|
| 3319 |
|
| 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 |
|
| 3329 |
set_values = set(values) |
| 3330 |
|
| 3331 |
|
| 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 |
|
| 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 |
|
| 3356 |
|
| 3357 |
|
| 3358 |
|
| 3359 |
|
| 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 |
|
| 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 |
|
| 3383 |
|
| 3384 |
|
| 3385 |
|
| 3386 |
|
| 3387 |
|
| 3388 |
|
| 3389 |
|
| 3390 |
|
| 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 |
|
| 3396 |
|
| 3397 |
def flat_func(a,b): |
| 3398 |
if isinstance(b,unicode): |
| 3399 |
a.append(b.lower()) |
| 3400 |
else: |
| 3401 |
a.extend([a.lower() for a in b]) |
| 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 |
|
| 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 |
|
| 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)} |
| 3421 |
|
| 3422 |
|
| 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} |
| 3426 |
return {"result":True} |
| 3427 |
|
| 3428 |
|
| 3429 |
|
| 3430 |
|
| 3431 |
|
| 3432 |
|
| 3433 |
|
| 3434 |
|
| 3435 |
|
| 3436 |
|
| 3437 |
|
| 3438 |
|
| 3439 |
|
| 3440 |
|
| 3441 |
|
| 3442 |
|
| 3443 |
|
| 3444 |
|
| 3445 |
|
| 3446 |
|
| 3447 |
|
| 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 |
|
| 3466 |
alias_names = listify(self[main_name].get("_item_aliases.alias_name",[])) |
| 3467 |
alt_names.extend(alias_names) |
| 3468 |
|
| 3469 |
return alt_names |
| 3470 |
|
| 3471 |
|
| 3472 |
|
| 3473 |
|
| 3474 |
|
| 3475 |
|
| 3476 |
|
| 3477 |
|
| 3478 |
|
| 3479 |
|
| 3480 |
|
| 3481 |
|
| 3482 |
|
| 3483 |
|
| 3484 |
|
| 3485 |
|
| 3486 |
|
| 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 |
|
| 3499 |
|
| 3500 |
|
| 3501 |
|
| 3502 |
|
| 3503 |
|
| 3504 |
|
| 3505 |
|
| 3506 |
|
| 3507 |
|
| 3508 |
|
| 3509 |
|
| 3510 |
|
| 3511 |
|
| 3512 |
|
| 3513 |
|
| 3514 |
|
| 3515 |
|
| 3516 |
|
| 3517 |
|
| 3518 |
|
| 3519 |
|
| 3520 |
|
| 3521 |
|
| 3522 |
|
| 3523 |
|
| 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} |
| 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 |
|
| 3536 |
if isinstance(item_value,unicode): |
| 3537 |
child_values = [item_value] |
| 3538 |
else: child_values = item_value[:] |
| 3539 |
|
| 3540 |
|
| 3541 |
|
| 3542 |
|
| 3543 |
|
| 3544 |
|
| 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 |
|
| 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} |
| 3557 |
else: |
| 3558 |
return {"result":None} |
| 3559 |
parent_item = alt_names[0] |
| 3560 |
parent_values = provisional_items.get(parent_item,whole_block.get(parent_item)) |
| 3561 |
if not parent_values: |
| 3562 |
parent_values = globals.get(parent_item) |
| 3563 |
if isinstance(parent_values,unicode): |
| 3564 |
parent_values = [parent_values] |
| 3565 |
|
| 3566 |
|
| 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][:] |
| 3575 |
except KeyError: |
| 3576 |
return {"result":None} |
| 3577 |
|
| 3578 |
if item_name in globals: |
| 3579 |
return {"result":None} |
| 3580 |
if isinstance(child_items,unicode): |
| 3581 |
child_items = [child_items] |
| 3582 |
if isinstance(item_value,unicode): |
| 3583 |
parent_values = [item_value] |
| 3584 |
else: parent_values = item_value[:] |
| 3585 |
|
| 3586 |
for child_item in child_items[:]: |
| 3587 |
child_items.extend(self.get_alternates(child_item)) |
| 3588 |
|
| 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 |
|
| 3605 |
|
| 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} |
| 3610 |
|
| 3611 |
|
| 3612 |
def check_parent_child(self,parent_vals,child_vals): |
| 3613 |
|
| 3614 |
pv = parent_vals[:] |
| 3615 |
pv.extend([".","?"]) |
| 3616 |
res = [a for a in child_vals if a not in pv] |
| 3617 |
|
| 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): |
| 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 |
|
| 3633 |
|
| 3634 |
|
| 3635 |
|
| 3636 |
|
| 3637 |
|
| 3638 |
|
| 3639 |
|
| 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} |
| 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 |
|
| 3654 |
|
| 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 |
|
| 3664 |
|
| 3665 |
|
| 3666 |
|
| 3667 |
|
| 3668 |
|
| 3669 |
|
| 3670 |
|
| 3671 |
|
| 3672 |
|
| 3673 |
|
| 3674 |
|
| 3675 |
|
| 3676 |
|
| 3677 |
|
| 3678 |
|
| 3679 |
|
| 3680 |
|
| 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 |
|
| 3689 |
|
| 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: |
| 3694 |
return {"result":None} |
| 3695 |
if isinstance(item_value,unicode): |
| 3696 |
return {"result":None} |
| 3697 |
|
| 3698 |
|
| 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 |
|
| 3706 |
unique_i.remove(item_name) |
| 3707 |
other_data = [] |
| 3708 |
if len(unique_i) > 0: |
| 3709 |
for other_name in unique_i: |
| 3710 |
|
| 3711 |
|
| 3712 |
|
| 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)) |
| 3719 |
else: |
| 3720 |
return {"result":False,"bad_items":other_name} |
| 3721 |
|
| 3722 |
|
| 3723 |
|
| 3724 |
|
| 3725 |
for i in range(len(item_value)): |
| 3726 |
|
| 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 |
|
| 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 |
|
| 3738 |
|
| 3739 |
|
| 3740 |
|
| 3741 |
|
| 3742 |
|
| 3743 |
|
| 3744 |
|
| 3745 |
|
| 3746 |
|
| 3747 |
|
| 3748 |
|
| 3749 |
|
| 3750 |
|
| 3751 |
|
| 3752 |
|
| 3753 |
|
| 3754 |
|
| 3755 |
|
| 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 |
|
| 3761 |
|
| 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 |
|
| 3769 |
|
| 3770 |
|
| 3771 |
|
| 3772 |
|
| 3773 |
|
| 3774 |
|
| 3775 |
|
| 3776 |
|
| 3777 |
|
| 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} |
| 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 |
|
| 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} |
| 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 |
|
| 3809 |
|
| 3810 |
|
| 3811 |
|
| 3812 |
|
| 3813 |
|
| 3814 |
|
| 3815 |
|
| 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 |
|
| 3832 |
return {"whole_block":results} |
| 3833 |
|
| 3834 |
|
| 3835 |
|
| 3836 |
|
| 3837 |
|
| 3838 |
|
| 3839 |
|
| 3840 |
|
| 3841 |
|
| 3842 |
|
| 3843 |
|
| 3844 |
|
| 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 |
|
| 3860 |
|
| 3861 |
|
| 3862 |
|
| 3863 |
|
| 3864 |
|
| 3865 |
|
| 3866 |
|
| 3867 |
|
| 3868 |
|
| 3869 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 3991 |
|
| 3992 |
|
| 3993 |
|
| 3994 |
|
| 3995 |
|
| 3996 |
|
| 3997 |
|
| 3998 |
|
| 3999 |
|
| 4000 |
|
| 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: |
| 4020 |
check_file.scoping = 'instance' |
| 4021 |
top_level = check_file.keys()[0] |
| 4022 |
check_file.scoping = 'dictionary' |
| 4023 |
|
| 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 |
|
| 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 |
|
| 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 |
| 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 |
|
| 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 |
|
| 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 |
|
| 4181 |
|
| 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 |
|
| 4295 |
|
| 4296 |
|
| 4297 |
|
| 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 |
|
| 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 |
|
| 4386 |
|
| 4387 |
|
| 4388 |
|
| 4389 |
|
| 4390 |
|
| 4391 |
|
| 4392 |
|
| 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 |
|
| 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 |
|
| 4409 |
|
| 4410 |
isvalid = len(v_result)==0 |
| 4411 |
return isvalid,v_result |
| 4412 |
|
| 4413 |
|
| 4414 |
|
| 4415 |
|
| 4416 |
|
| 4417 |
|
| 4418 |
|
| 4419 |
|
| 4420 |
|
| 4421 |
|
| 4422 |
|
| 4423 |
|
| 4424 |
|
| 4425 |
|
| 4426 |
|
| 4427 |
|
| 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 |
|
| 4434 |
else: |
| 4435 |
return None,None |
| 4436 |
if dot or q: return None,None |
| 4437 |
if exp: |
| 4438 |
exp = exp.replace("d","e") |
| 4439 |
exp = exp.replace("D","e") |
| 4440 |
base_num = base_num + exp |
| 4441 |
|
| 4442 |
base_num = float(base_num) |
| 4443 |
|
| 4444 |
if esd: |
| 4445 |
esd = float(esd[1:-1]) |
| 4446 |
if dad: |
| 4447 |
esd = esd * (10 ** (-1* len(dad))) |
| 4448 |
if exp: |
| 4449 |
esd = esd * (10 ** (float(exp[1:]))) |
| 4450 |
return base_num,esd |
| 4451 |
|
| 4452 |
|
| 4453 |
|
| 4454 |
|
| 4455 |
|
| 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 |
|
| 4465 |
|
| 4466 |
|
| 4467 |
|
| 4468 |
|
| 4469 |
|
| 4470 |
|
| 4471 |
|
| 4472 |
|
| 4473 |
|
| 4474 |
|
| 4475 |
|
| 4476 |
|
| 4477 |
|
| 4478 |
|
| 4479 |
|
| 4480 |
def convert_type(definition): |
| 4481 |
"""Convert value to have the type given by definition""" |
| 4482 |
|
| 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': |
| 4488 |
return convert_single_value(structure) |
| 4489 |
elif container == 'List': |
| 4490 |
return convert_list_values(structure,dimension) |
| 4491 |
elif container == 'Multiple': |
| 4492 |
return None |
| 4493 |
elif container in ('Array','Matrix'): |
| 4494 |
return convert_matrix_values(structure) |
| 4495 |
return lambda a:a |
| 4496 |
|
| 4497 |
|
| 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'): |
| 4509 |
return lambda a:a.lower() |
| 4510 |
return lambda a:a |
| 4511 |
|
| 4512 |
|
| 4513 |
|
| 4514 |
|
| 4515 |
|
| 4516 |
|
| 4517 |
|
| 4518 |
|
| 4519 |
|
| 4520 |
|
| 4521 |
|
| 4522 |
|
| 4523 |
|
| 4524 |
|
| 4525 |
|
| 4526 |
|
| 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 |
|
| 4547 |
|
| 4548 |
def convert_list_values(structure, dimension): |
| 4549 |
"""Convert the values according to the element |
| 4550 |
structure given in [[structure]]""" |
| 4551 |
|
| 4552 |
print("Converting {} of dimensions {}".format(structure, dimension)) |
| 4553 |
if isinstance(structure, (unicode, str)): |
| 4554 |
fcnv = convert_single_value(structure) |
| 4555 |
|
| 4556 |
else: |
| 4557 |
fcnv = convert_simple_list(structure) |
| 4558 |
rv = fcnv |
| 4559 |
|
| 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 |
|
| 4565 |
|
| 4566 |
|
| 4567 |
|
| 4568 |
|
| 4569 |
|
| 4570 |
|
| 4571 |
def convert_matrix_values(valtype): |
| 4572 |
"""Convert a dREL String or Float valued List structure to a numpy matrix structure""" |
| 4573 |
|
| 4574 |
try: |
| 4575 |
import numpy |
| 4576 |
except ImportError: |
| 4577 |
return lambda a:a |
| 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 |
|
| 4590 |
|
| 4591 |
|
| 4592 |
|
| 4593 |
|
| 4594 |
|
| 4595 |
|
| 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 |
|
| 4604 |
|
| 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 |
|
| 4613 |
|
| 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 |
|
| 4626 |
def listify(item): |
| 4627 |
if isinstance(item,(unicode,str)): return [item] |
| 4628 |
else: return item |
| 4629 |
|
| 4630 |
|
| 4631 |
|
| 4632 |
def filter_present(namelist,datablocknames): |
| 4633 |
return [a for a in namelist if a in datablocknames] |
| 4634 |
|
| 4635 |
|
| 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 |
|
| 4644 |
|
| 4645 |
|
| 4646 |
|
| 4647 |
|
| 4648 |
|
| 4649 |
|
| 4650 |
|
| 4651 |
|
| 4652 |
|
| 4653 |
|
| 4654 |
|
| 4655 |
|
| 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 |
|
| 4665 |
basedic = dic_as_cif_list[0] |
| 4666 |
if "on_this_dictionary" in basedic: |
| 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: |
| 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 |
|
| 4679 |
if final_dic.diclang == "DDLm": |
| 4680 |
final_dic = final_dic.add_alias_blocks() |
| 4681 |
|
| 4682 |
return final_dic |
| 4683 |
|
| 4684 |
|
| 4685 |
|
| 4686 |
|
| 4687 |
|
| 4688 |
|
| 4689 |
|
| 4690 |
|
| 4691 |
|
| 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 |
|
| 4707 |
|
| 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 |
|
| 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 |
|
| 4744 |
if isinstance(error, CifSyntaxError): |
| 4745 |
print(error.value) |
| 4746 |
|
| 4747 |
return error.value |
| 4748 |
|
| 4749 |
|
| 4750 |
|
| 4751 |
|
| 4752 |
|
| 4753 |
|
| 4754 |
|
| 4755 |
|
| 4756 |
|
| 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 |
|
| 4809 |
|
| 4810 |
|
| 4811 |
|
| 4812 |
|
| 4813 |
|
| 4814 |
|
| 4815 |
class CifLoopBlock(StarFile.LoopBlock): |
| 4816 |
def __init__(self,data=(),**kwargs): |
| 4817 |
super(CifLoopBlock,self).__init__(data,**kwargs) |
| 4818 |
|
| 4819 |
|
| 4820 |
|
| 4821 |
|