-
Notifications
You must be signed in to change notification settings - Fork 135
/
qmcpack_input.py
8670 lines (7897 loc) · 300 KB
/
qmcpack_input.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
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
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
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
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
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
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
##################################################################
## (c) Copyright 2015- by Jaron T. Krogel ##
##################################################################
#====================================================================#
# qmcpack_input.py #
# Supports I/O and manipulation of QMCPACK's xml input file. #
# #
# Content summary: #
# QmcpackInput #
# SimulationInput class for QMCPACK. #
# Represents the QMCPACK input file as a nested collection of #
# objects mirroring the structure of the XML input. #
# XML attributes and <parameter/> elements are joined into #
# a common keyword representation. #
# Full tranlations of test QMCPACK input files into executable #
# Python code can be found at the end of this file for #
# reference. #
# #
# BundledQmcpackInput #
# Class represents QMCPACK input when provided in 'bundled' #
# form, i.e. an input file containing a list of XML input #
# files. #
# A BundledQmcpackInput object contains many QmcpackInput #
# objects. #
# #
# QmcpackInputTemplate #
# Class supports Nexus interaction with text input files #
# provided by users as 'templates'. #
# Users can mark keywords in a template input file, generate #
# variations on that input file through this class, and #
# then use the resulting input files in Nexus workflows. #
# #
# generate_qmcpack_input #
# User-facing function to compose specific QMCPACK input files. #
# Though any QMCPACK input file can be composed directly with #
# Python code, only a more limited selection can be #
# generated directly. #
# Calls many other functions to generate specific XML elements: #
# generate_simulationcell #
# generate_particlesets #
# generate_sposets #
# generate_sposet_builder #
# generate_bspline_builder #
# generate_heg_builder #
# generate_determinantset #
# generate_determinantset_old #
# generate_hamiltonian #
# generate_jastrows #
# generate_jastrow #
# generate_jastrow1 #
# generate_bspline_jastrow2 #
# generate_pade_jastrow2 #
# generate_jastrow2 #
# generate_jastrow3 #
# generate_kspace_jastrow #
# generate_opt #
# generate_opts #
# #
# QIxml, Names #
# Class represents a generic XML element. #
# Supports read/write and setting default values. #
# Derived classes represent specific elements and contain #
# a keyword specification for each element. #
# Support for new XML elements is enabled by creating #
# a corresponding class with the allowed keywords, etc., #
# and then adding it to the global 'classes' list below. #
# See classes simulation, project, application, random, include, #
# mcwalkerset, qmcsystem, simulationcell, particleset, group, #
# sposet, bspline_builder, heg_builder, composite_builder, #
# wavefunction, determinantset, basisset, grid, atomicbasisset,#
# basisgroup, radfunc, slaterdeterminant, determinant, #
# occupation, multideterminant, detlist, ci, jastrow1, #
# jastrow2, jastrow3, correlation, var, coefficients, #
# coefficient, hamiltonian, coulomb, constant, pseudopotential,#
# pseudo, mpc, localenergy, energydensity, reference_points, #
# spacegrid, origin, axis, chiesa, density, nearestneighbors, #
# neighbor_trace, dm1b, spindensity, structurefactor, init, #
# scalar_traces, array_traces, particle_traces, traces, loop, #
# linear, cslinear, vmc, dmc. #
# #
# QIxmlFactory #
# Class supports comprehension of XML elements that share the #
# same XML tag (e.g. <pairpot/>), but have many different #
# and distinct realizations (e.g. coulomb, mpc, etc.). #
# See QIxmlFactory instances pairpot, estimator, #
# sposet_builder, jastrow, and qmc. #
# #
# collection #
# Container class representing an ordered set of plural XML #
# elements named according to an XML attribute (e.g. named #
# particlesets). #
# XML elements are listed by name in the collection to allow #
# intuitive interactive navigation by the user. #
# #
# Param (single global instance is param) #
# Handles all reads/writes of attributes and text contents #
# of XML elements. #
# Automatically distinguishes string, int, float, and array #
# data of any of these types. #
# #
# Note: those seeking to add new XML elements should be aware #
# of the global data structures described below. #
# #
# classes #
# Global list of QIxml classes. #
# Each new QIxml class must be added here. #
# #
# types #
# Global dict of elements that are actually simple types (to be #
# interpreted the same way as <parameter/> elements) and also #
# factory instances. #
# #
# plurals #
# Global obj of elements that can be plural (i.e. multiple can #
# be present with the same tag. A QmcpackInput object will #
# contain collection instances containing the related XML #
# elements. Each collection is named according to the keys in #
# plurals. #
# #
# Names.set_expanded_names #
# Function to specify mappings from all-lowercase names used #
# in QmcpackInput objects to the names expected by QMCPACK in #
# the actual XML input file. QMCPACK does not follow any #
# consistent naming convention (camel-case, hyphenation, and #
# separation via underscore are all present in names) and some #
# names are case-sensitive while others are not. This function #
# allows developers to cope with this diversity upon write, #
# while preserving a uniform representation (all lowercase) in #
# QmcpackInput objects. #
# #
#====================================================================#
import os
import inspect
import keyword
import numpy as np
from numpy import fromstring,empty,array,float64,\
loadtxt,ndarray,dtype,sqrt,pi,arange,exp,eye,\
ceil,mod,dot,abs,identity,floor,linalg,where,isclose
from io import StringIO
from superstring import string2val
from generic import obj,hidden
from xmlreader import XMLreader,XMLelement
from developer import DevBase,error
from periodic_table import is_element
from structure import Structure,Jellium,get_kpath
from physical_system import PhysicalSystem
from simulation import SimulationInput,SimulationInputTemplate
from pwscf_input import array_to_string as pwscf_array_string
from debug import ci as interact
yesno_dict = {True:'yes' ,False:'no'}
truefalse_dict = {True:'true',False:'false'}
onezero_dict = {True:'1' ,False:'0'}
boolmap={'yes':True,'no':False,'true':True,'false':False,'1':True,'0':False}
def is_int(var):
try:
int(var)
return True
except ValueError:
return False
#end try
#end def is_int
def is_float(var):
try:
float(var)
return True
except ValueError:
return False
#end try
#end def is_float
def is_array(var,type):
try:
if isinstance(var,str):
array(var.split(),type)
else:
array(var,type)
#end if
return True
except ValueError:
return False
#end try
#end def is_float_array
def attribute_to_value(attr):
if is_int(attr):
val = int(attr)
elif is_float(attr):
val = float(attr)
elif is_array(attr,int):
val = array(attr.split(),int)
if val.size==9:
val.shape = 3,3
#end if
elif is_array(attr,float):
val = array(attr.split(),float)
else:
val = attr
#end if
return val
#end def attribute_to_value
#local write types
def yesno(var):
return render_bool(var,'yes','no')
#end def yesno
def yesnostr(var):
if isinstance(var,str):
return var
else:
return yesno(var)
#end if
#end def yesnostr
def onezero(var):
return render_bool(var,'1','0')
#end def onezero
def truefalse(var):
return render_bool(var,'true','false')
#end def onezero
def render_bool(var,T,F):
if isinstance(var,bool) or var in (1,0):
if var:
return T
else:
return F
#end if
elif var in (T,F):
return var
else:
error('Invalid QMCPACK input encountered.\nUser provided an invalid value of "{}" when yes/no was expected.\nValid options are: "{}", "{}", True, False, 1, 0'.format(var,T,F))
#end if
#end def render_bool
bool_write_types = set([yesno,onezero,truefalse])
class QIobj(DevBase):
afqmc_mode = False
# user settings
permissive_read = False
permissive_write = False
permissive_init = False
@staticmethod
def settings(
permissive_read = False,
permissive_write = False,
permissive_init = False,
):
QIobj.permissive_read = permissive_read
QIobj.permissive_write = permissive_write
QIobj.permissive_init = permissive_init
#end def settings
#end class QIobj
class meta(obj):
None
#end class meta
class section(QIobj):
def __init__(self,*args,**kwargs):
self.args = args
self.kwargs = kwargs
#end def __init__
#end class section
class collection(hidden):
def __init__(self,*elements):
hidden.__init__(self)
if len(elements)==1 and isinstance(elements[0],list):
elements = elements[0]
elif len(elements)==1 and isinstance(elements[0],collection):
elements = elements[0].__dict__.values()
#end if
self.hidden().order = []
for element in elements:
self.add(element)
#end for
#end def __init__
def __setitem__(self,name,value):
#self.error('elements can only be set via the add function')
self.add(value,key=name)
#end def __setitem__
def __delitem__(self,name):
#self.error('elements can only be deleted via the remove function')
self.remove(name)
#end def __delitem__
def __setattr__(self,name,value):
#self.error('elements can only be set via the add function')
self.add(value,key=name)
#end def __setattr__
def __delattr__(self,name):
#self.error('elements can only be deleted via the remove function')
self.remove(name)
#end def __delattr__
def add(self,element,strict=True,key=None):
if not isinstance(element,QIxml):
self.error('collection cannot be formed\nadd attempted for non QIxml element\ntype received: {0}'.format(element.__class__.__name__))
#end if
keyin = key
key = None
public = self.public()
identifier = element.identifier
missing_identifier = False
if not element.tag in plurals_inv and element.collection_id is None:
self.error('collection cannot be formed\n encountered non-plural element\n element class: {0}\n element tag: {1}\n tags allowed in a collection: {2}'.format(element.__class__.__name__,element.tag,sorted(plurals_inv.keys())))
elif identifier is None:
key = len(public)
elif isinstance(identifier,str):
if identifier in element:
key = element[identifier]
else:
missing_identifier = True
#end if
else:
key = ''
for ident in identifier:
if ident in element:
key+=element[ident]
#end if
#end for
missing_identifier = key==''
#end if
if missing_identifier:
key = len(public)
#end if
if keyin is not None and not isinstance(key,int) and keyin.lower()!=key.lower():
self.error('attempted to add key with incorrect name\nrequested key: {0}\ncorrect key: {1}'.format(keyin,key))
#end if
#if key in public:
# self.error('attempted to add duplicate key to collection: {0}\n keys present: {1}'.format(key,sorted(public.keys())))
##end if
public[key] = element
self.hidden().order.append(key)
return True
#end def add
def remove(self,key):
public = self.public()
if key in public:
del public[key]
self.hidden().order.remove(key)
else:
raise KeyError
#end if
#end def remove
def get_single(self,preference=None):
if len(self)>0:
if preference!=None and preference in self:
return self[preference]
else:
return self.list()[0]
#end if
else:
#return self
return None
#end if
#end def get_single
def list(self):
lst = []
for key in self.hidden().order:
lst.append(self[key])
#end for
return lst
#end def list
def pairlist(self):
pairs = []
for key in self.hidden().order:
pairs.append((key,self[key]))
#end for
return pairs
#end def pairlist
#end class collection
def make_collection(elements):
return collection(*elements)
#end def make_collection
class classcollection(QIobj):
def __init__(self,*classes):
if len(classes)==1 and isinstance(classes[0],list):
classes = classes[0]
#end if
self.classes = classes
#end def __init__
#end class classcollection
class QmcpackInputCollections(QIobj):
def add(self,element):
if element.tag in plurals_inv:
cname = plurals_inv[element.tag]
if not cname in self:
coll = collection()
success = coll.add(element,strict=False)
if success:
self[cname] = coll
#end if
else:
self[cname].add(element,strict=False)
#end if
#end if
#end def add
def get(self,cname,label=None):
v = None
if cname in self:
if label is None:
v = self[cname]
elif label in self[cname]:
v = self[cname][label]
#end if
#end if
return v
#end def get
#end class QmcpackInputCollections
QIcollections = QmcpackInputCollections()
class Names(QIobj):
condensed_names = obj()
expanded_names = None
rsqmc_expanded_names = None
afqmc_expanded_names = None
escape_names = set(keyword.kwlist+['write'])
escaped_names = list(escape_names)
for i in range(len(escaped_names)):
escaped_names[i]+='_'
#end for
escaped_names = set(escaped_names)
@staticmethod
def set_expanded_names(**kwargs):
exnames = obj(**kwargs)
Names.expanded_names = exnames
Names.rsqmc_expanded_names = exnames
#end def set_expanded_names
@staticmethod
def set_afqmc_expanded_names(**kwargs):
Names.afqmc_expanded_names = obj(**kwargs)
#end def set_afqmc_expanded_names
@staticmethod
def use_rsqmc_expanded_names():
Names.expanded_names = Names.rsqmc_expanded_names
#end def use_rsqmc_expanded_names
@staticmethod
def use_afqmc_expanded_names():
Names.expanded_names = Names.afqmc_expanded_names
#end def use_afqmc_expanded_names
def expand_name(self,condensed):
expanded = condensed
cname = self.condense_name(condensed)
if cname in self.escaped_names:
cname = cname[:-1]
expanded = cname
#end if
if cname in self.expanded_names:
expanded = self.expanded_names[cname]
#end if
return expanded
#end def expand_name
def condense_name(self,expanded):
condensed = expanded
condensed = condensed.replace('___','_').replace('__','_')
condensed = condensed.replace('-','_').replace(' ','_')
condensed = condensed.lower()
if condensed in self.escape_names:
condensed += '_'
#end if
self.condensed_names[expanded]=condensed
return condensed
#end def condense_name
def condense_names(self,*namelists):
out = []
for namelist in namelists:
exp = obj()
for expanded in namelist:
condensed = self.condense_name(expanded)
exp[condensed]=expanded
#end for
out.append(exp)
#end for
return out
#end def condense_names
def condensed_name_report(self):
print()
print('Condensed Name Report:')
print('----------------------')
keylist = array(list(self.condensed_names.keys()))
order = array(list(self.condensed_names.values())).argsort()
keylist = keylist[order]
for expanded in keylist:
condensed = self.condensed_names[expanded]
if expanded!=condensed:
print(" {0:15} = '{1}'".format(condensed,expanded))
#end if
#end for
print()
print()
#end def condensed_name_report
#end class Names
class QIxml(Names):
def init_from_args(self,args):
print()
print('In init from args (not implemented).')
print('Possible reasons for incorrect entry: ')
print(' Is xml element {0} meant to be plural?'.format(self.__class__.__name__))
print(' If so, add it to the plurals object.')
print()
print('Arguments received:')
print(args)
print()
self.not_implemented()
#end def init_from_args
@classmethod
def init_class(cls):
cls.class_set_optional(
tag = cls.__name__,
identifier = None,
attributes = [],
elements = [],
text = None,
parameters = [],
attribs = [],
costs = [],
h5tags = [],
types = obj(),
write_types = obj(),
attr_types = None,
precision = None,
defaults = obj(),
collection_id = None,
exp_names = None,
)
for v in ['attributes','elements','parameters','attribs','costs','h5tags']:
names = cls.class_get(v)
for i in range(len(names)):
if names[i] in cls.escape_names:
names[i]+='_'
#end if
#end for
#end for
cls.params = cls.parameters + cls.attribs + cls.costs + cls.h5tags
cls.plurals_inv = obj()
for e in cls.elements:
if e in plurals_inv:
cls.plurals_inv[e] = plurals_inv[e]
#end if
#end for
cls.plurals = cls.plurals_inv.inverse()
if cls.exp_names is not None:
cls.expanded_names = obj(Names.expanded_names,cls.exp_names)
#end if
#end def init_class
def write(self,indent_level=0,pad=' ',first=False):
param.set_precision(self.get_precision())
if not QIobj.permissive_write:
self.check_junk(exit=True)
#end if
indent = indent_level*pad
ip = indent+pad
ipp= ip+pad
expanded_tag = self.expand_name(self.tag)
c = indent+'<'+expanded_tag
for a in self.attributes:
if a in self:
val = self[a]
if isinstance(val,str):
val = self.expand_name(val)
#end if
c += ' '+self.expand_name(a)+'='
if a in self.write_types:
c += '"'+self.write_types[a](val)+'"'
else:
c += '"'+param.write(val)+'"'
#end if
#end if
#end for
#if first:
# c+=' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://www.mcc.uiuc.edu/qmc/schema/molecu.xsd"'
##end if
#no_contents = len(set(self.keys())-set(self.elements)-set(self.plurals.keys()))==0
no_contents = len(set(self.keys())-set(self.attributes))==0
if no_contents:
c += '/>\n'
else:
c += '>\n'
for v in self.h5tags:
if v in self:
if v in self.write_types:
write_type = self.write_types[v]
else:
write_type = None
#end if
c += param.write(self[v],name=self.expand_name(v),tag='h5tag',mode='elem',pad=ip,write_type=write_type)
#end if
#end for
for v in self.costs:
if v in self:
c += param.write(self[v],name=self.expand_name(v),tag='cost',mode='elem',pad=ip)
#end if
#end for
for p in self.parameters:
if p in self:
if p in self.write_types:
write_type = self.write_types[p]
else:
write_type = None
#end if
c += param.write(self[p],name=self.expand_name(p),mode='elem',pad=ip,write_type=write_type)
#end if
#end for
for a in self.attribs:
if a in self:
if a in self.write_types:
write_type = self.write_types[a]
else:
write_type = None
#end if
c += param.write(self[a],name=self.expand_name(a),tag='attrib',mode='elem',pad=ip,write_type=write_type)
#end if
#end for
elements = self.elements
if self.afqmc_mode and 'afqmc_order' in self.__class__.__dict__:
elements = self.afqmc_order
#end if
for e in elements:
if e in self:
elem = self[e]
if isinstance(elem,QIxml):
c += elem.write(indent_level+1)
else:
begin = '<'+e+'>'
contents = param.write(elem)
end = '</'+e+'>'
if contents.strip()=='':
c += ip+begin+end+'\n'
else:
c += ip+begin+'\n'
c += ipp+contents+'\n'
c += ip+end+'\n'
#end if
#end if
elif e in plurals_inv and plurals_inv[e] in self:
coll = self[plurals_inv[e]]
if not isinstance(coll,collection):
self.error('write failed\n element {0} is not a collection\n contents of element {0}:\n{1}'.format(plurals_inv[e],str(coll)))
#end if
for instance in coll.list():
c += instance.write(indent_level+1)
#end for
#end if
#end for
if self.text!=None:
c = c.rstrip('\n')
c+=param.write(self[self.text],mode='elem',pad=ip,tag=None,normal_elem=True)
#end if
c+=indent+'</'+expanded_tag+'>\n'
#end if
param.reset_precision()
return c
#end def write
def __init__(self,*args,**kwargs):
if Param.metadata==None:
Param.metadata = meta()
#end if
if len(args)==1:
a = args[0]
if isinstance(a,XMLelement):
self.init_from_xml(a)
elif isinstance(a,section):
self.init_from_inputs(a.args,a.kwargs)
elif isinstance(a,self.__class__):
self.transfer_from(a)
else:
self.init_from_inputs(args,kwargs)
#end if
else:
self.init_from_inputs(args,kwargs)
#end if
QIcollections.add(self)
#end def __init__
def init_from_xml(self,xml):
al,el = self.condense_names(xml._attributes.keys(),xml._elements.keys())
xa,sa = set(al.keys()) , set(self.attributes)
attr = xa & sa
junk = xa-attr
junk_elem = []
for e,ecap in el.items():
value = xml._elements[ecap]
if (isinstance(value,list) or isinstance(value,tuple)) and e in self.plurals_inv.keys():
if e not in types:
self.error('input element "{}" is unknown'.format(e))
#end if
p = self.plurals_inv[e]
plist = []
for instance in value:
plist.append(types[e](instance))
#end for
self[p] = make_collection(plist)
elif e in self.elements:
if e not in types:
self.error('input element "{}" is unknown'.format(e))
#end if
self[e] = types[e](value)
elif e in ['parameter','attrib','cost','h5tag']:
if isinstance(value,XMLelement):
value = [value]
#end if
for p in value:
name = self.condense_name(p.name)
if name in self.params:
self[name] = param(p)
else:
junk_elem.append(name)
#end if
#end for
else:
junk_elem.append(e)
#end if
#end for
junk = junk | set(junk_elem)
if QmcpackInput.profile_collection!=None:
self.collect_profile(xml,al,el,junk)
#end for
if not QIobj.permissive_read:
self.check_junk(junk)
#end if
if self.attr_types!=None:
typed_attr = attr & set(self.attr_types.keys())
attr -= typed_attr
for a in typed_attr:
self[a] = self.attr_types[a](xml._attributes[al[a]])
#end for
#end if
for a in attr:
if a in self.write_types and self.write_types[a] in bool_write_types:
aval = xml._attributes[al[a]]
if aval in boolmap:
self[a] = boolmap[aval]
else:
self.error('{0} is not a valid value for boolean attribute {1}\n valid values are: {2}'.format(aval,a,boolmap.keys()))
#end if
else:
self[a] = attribute_to_value(xml._attributes[al[a]])
#end if
#end for
if self.text!=None:
self[self.text] = param(xml)
#end if
#end def init_from_xml
def init_from_inputs(self,args,kwargs):
if len(args)>0:
if len(args)==1 and isinstance(args[0],self.__class__):
self.transfer_from(args[0])
elif len(args)==1 and isinstance(args[0],dict):
self.init_from_kwargs(args[0])
else:
self.init_from_args(args)
#end if
#end if
self.init_from_kwargs(kwargs)
#end def init_from_inputs
def init_from_kwargs(self,kwargs):
ks=[]
kmap = dict()
for key,val in kwargs.items():
ckey = self.condense_name(key)
ks.append(ckey)
kmap[ckey] = val
#end for
ks = set(ks)
kwargs = kmap
h5tags = ks & set(self.h5tags)
costs = ks & set(self.costs)
parameters = ks & set(self.parameters)
attribs = ks & set(self.attribs)
attr = ks & set(self.attributes)
elem = ks & set(self.elements)
plur = ks & set(self.plurals.keys())
if self.text!=None:
text = ks & set([self.text])
else:
text = set()
#end if
if not QIobj.permissive_init:
junk = ks -attr -elem -plur -h5tags -costs -parameters -attribs -text
self.check_junk(junk,exit=True)
#end if
for v in h5tags:
self[v] = param(kwargs[v])
#end for
for v in costs:
self[v] = param(kwargs[v])
#end for
for v in parameters:
self[v] = param(kwargs[v])
#end for
for v in attribs:
self[v] = param(kwargs[v])
#end for
for a in attr:
self[a] = kwargs[a]
#end for
for e in elem:
self[e] = types[e](kwargs[e])
#end for
for p in plur:
e = self.plurals[p]
kwcoll = kwargs[p]
if isinstance(kwcoll,collection):
plist = kwcoll.list()
elif isinstance(kwcoll,(list,tuple)):
plist = kwcoll
else:
self.error('init failed\n encountered non-list collection')
#end if
ilist = []
for instance in plist:
ilist.append(types[e](instance))
#end for
self[p] = make_collection(ilist)
#end for
for t in text:
self[t] = kwargs[t]
#end for
#end def init_from_kwargs
def incorporate_defaults(self,elements=False,overwrite=False,propagate=True):
for name,value in self.defaults.items():
defval=None
if isinstance(value,classcollection):
if elements:
coll=[]
for cls in value.classes:
ins = cls()
ins.incorporate_defaults()
coll.append(ins)
#end for
defval = make_collection(coll)
#end if
elif inspect.isclass(value):
if elements:
defval = value()
#end if
elif inspect.isfunction(value):
defval = value()
else:
defval = value
#end if
if defval!=None:
if overwrite or not name in self:
self[name] = defval
#end if
#end if
#end for
if propagate:
for name,value in self.items():
if isinstance(value,QIxml):
value.incorporate_defaults(elements,overwrite)
elif isinstance(value,collection):
for v in value:
if isinstance(v,QIxml):
v.incorporate_defaults(elements,overwrite)
#end if
#end for
#end if
#end for
#end if
#end def incorporate_defaults
def check_junk(self,junk=None,exit=False):
if junk is None:
ks = set(self.keys())
h5tags = ks & set(self.h5tags)
costs = ks & set(self.costs)
parameters = ks & set(self.parameters)
attribs = ks & set(self.attribs)
attr = ks & set(self.attributes)
elem = ks & set(self.elements)
plur = ks & set(self.plurals.keys())
if self.text is not None:
text = ks & set([self.text])
else:
text = set()
#end if
junk = ks -attr -elem -plur -h5tags -costs -parameters -attribs -text
#end if
if len(junk)>0:
oname = ''
if self.tag!=self.__class__.__name__:
oname = ' ('+self.__class__.__name__+')'
#end if
msg = '{0}{1} does not have the following attributes/elements:\n'.format(self.tag,oname)
for jname in junk:
msg+=' '+jname+'\n'
#end for
#if QmcpackInput.profile_collection is None:
# self.error(msg,'QmcpackInput',exit=exit,trace=exit)
##end if
print(obj(dict(self.__class__.__dict__)))
self.error(msg,'QmcpackInput',exit=exit,trace=exit)
#end if
#end def check_junk
def collect_profile(self,xml,al,el,junk):
attributes = obj(**al)
parameters = obj()
elements = obj()
for e,ecap in el.items():
if e=='parameter':
parameters[e]=ecap
else:
elements[e]=ecap
#end if
#end for
profile = obj(
attributes = attributes,
parameters = parameters,
elements = elements,
xml = xml,
junk = junk
)
#xml = xml.copy()
xname = xml._name
if xname[-1:].isdigit():
xname = xname[:-1]
elif xname[-2:].isdigit():
xname = xname[:-2]
#end if
#xml._name = xname
if len(profile.junk)>0:
print(' '+xname+' (found '+str(junk)+')')