This repository has been archived by the owner on Sep 16, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
GSASIImapvars.py
2059 lines (1902 loc) · 86.3 KB
/
GSASIImapvars.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
# TODO: revisit SeqRefine and :meth:`GSASIIdataGUI.GSASII.OnSeqRefine` and :func:`GSASIIseqGUI.UpdateSeqResults`
# -*- coding: utf-8 -*-
########### SVN repository information ###################
# $Date: 2024-02-07 14:07:07 -0600 (Wed, 07 Feb 2024) $
# $Author: toby $
# $Revision: 5723 $
# $URL: https://subversion.xray.aps.anl.gov/pyGSAS/trunk/GSASIImapvars.py $
# $Id: GSASIImapvars.py 5723 2024-02-07 20:07:07Z toby $
########### SVN repository information ###################
"""
Classes and routines defined in :mod:`GSASIImapvars` follow.
Note that parameter names in GSAS-II are strings of form ``<ph#>:<hst#>:<nam>`` or ``<ph#>::<nam>:<at#>``
where ``<ph#>`` is a phase number, ``<hst#>`` is a histogram number and ``<at#>`` is an atom number.
``<nam>`` is a name that determines the parameter type (see :func:`GSASIIobj.CompileVarDesc`). When
stored in the data tree, parameters are saved as :class:`GSASIIobj.G2VarObj` objects
so that they can be resolved if the phase/histogram order changes.
"""
# Note that documentation for GSASIImapvars.py has been moved
# to file docs/source/GSASIImapvars.rst
from __future__ import division, print_function
import copy
import numpy as np
import GSASIIpath
GSASIIpath.SetVersionNumber("$Revision: 5723 $")
import GSASIIobj as G2obj
# data used for constraints;
debug = False # turns on printing as constraint input is processed
#------------------------------------------------------------------------------------
# Global vars used for storing constraints and equivalences after processing
# note that new var and constraint equations are stored together in groups,
# where each constraint group contains those parameters that must be handled
# together. Equivalences are also stored in these
dependentParmList = []
'''a list of lists where each item contains a list of parameters in each constraint group.
note that parameters listed in dependentParmList should not be refined directly.'''
indParmList = [] # a list of names for the new parameters
'''a list of lists where each item contains a list for each constraint group with
fixed values for constraint equations and names of generated/New Var parameters.
In the case of equivalences, the name of a single independent parameter is stored.
'''
arrayList = []
'''a list of of relationship matrices that map model parameters in each
constraint group (in :data:`dependentParmList`) to
generated (New Var) parameters.
'''
invarrayList = []
'''a list of of inverse-relationship matrices that map constrained values and
generated (New Var) parameters (in :data:`indParmList`) to model parameters
(in :data:`dependentParmList`).
'''
symGenList = []
'''A list of flags that if True indicates a constraint was generated by symmetry
'''
holdParmList = []
'''List of parameters that should not be refined ("Hold"s).
Set in :func:`StoreHold`. Initialized in :func:`InitVars`.
'''
holdParmType = {}
'''The reason why a parameter has been marked as "Hold".
Initialized in :func:`InitVars`; set in :func:`StoreHold`.
'''
constrParms = {'indep-equiv':[], 'indep-constr':[], 'dep-equiv':[], 'dep-constr':[]}
'''A dict with parameters in equivalences, compiled from
(:data:`dependentParmList`) and (:data:`indParmList`).
Used within :func:`GetIndependentVars` and :func:`GetDependentVars`.
'''
saveVaryList = []
'''A list of the varied parameters that was last supplied when constraints were
processed. This is set in :func:`GenerateConstraints` and updated in
:func:`Map2Dict`. Used in :func:`VarRemapShow`
'''
droppedSym = []
'''A list of symmetry generated equivalences that have been converted to
constraint equations in :func:`CheckEquivalences`
'''
#------------------------------------------------------------------------------------
# Global vars set in :func:`GenerateConstraints`. Used for intermediate processing of
# constraints.
constrVarList = []
'List of parameters used in "Constr" and "New Var" constraints'
indepVarList = []
'A list of all independent parameters in equivalences'
depVarList = []
'A list of all dependent parameters in equivalences'
#------------------------------------------------------------------------------------
# global variables used in :func:`getConstrError` to store error and warning information.
# set in CheckEquivalences and in GenerateConstraints
convVarList = []
'parameters in equivalences that were converted to "Const" constraints'
multdepVarList = []
'parameters used as dependents multiple times in equivalences'
unvariedParmsList = []
'parameters used in equivalences that are not varied'
undefinedVars = []
'parameters used in equivalences that are not defined in the parameter dict'
groupErrors = []
'parameters in constraints where parameter grouping and matrix inversion fails'
#------------------------------------------------------------------------------------
paramPrefix = "::constr"
'A prefix for generated parameter names'
consNum = 0
'The number to be assigned to the next constraint to be created'
#------------------------------------------------------------------------------------
class ConstraintException(Exception):
'''Defines an Exception that is used when an exception is raised processing constraints.
Raised in :func:`GenerateConstraints` during sequential fits. Possible (but highly unlikely)
to be raised in :func:`CheckEquivalences` (called by :func:`GenerateConstraints`) if an
infinite loop is detected.
Also raised in :func:`GramSchmidtOrtho` and :func:`_SwapColumns` but caught
within :func:`GenerateConstraints`.
'''
pass
def InitVars():
'''Initializes all constraint information'''
global dependentParmList,arrayList,invarrayList,indParmList,consNum,symGenList
dependentParmList = [] # contains a list of parameters in each group
arrayList = [] # a list of of relationship matrices
invarrayList = [] # a list of inverse relationship matrices
indParmList = [] # a list of names for the new parameters
consNum = 0 # number of the next constraint to be created
symGenList = [] # Flag if constraint is generated by symmetry
global holdParmList,holdParmType
holdParmList = []
holdParmType = {}
global droppedSym
droppedSym = []
global constrVarList,indepVarList,depVarList
constrVarList = []
indepVarList = []
depVarList = []
def VarKeys(constr):
"""Finds the keys in a constraint that represent parameters
e.g. eliminates any that start with '_'
:param dict constr: a single constraint entry of form::
{'var1': mult1, 'var2': mult2,... '_notVar': val,...}
(see :func:`GroupConstraints`)
:returns: a list of keys where any keys beginning with '_' are
removed.
"""
return [i for i in constr.keys() if not i.startswith('_')]
def GroupConstraints(constrDict):
"""Divide the constraints into groups that share no parameters.
:param dict constrDict: a list of dicts defining relationships/constraints
::
constrDict = [{<constr1>}, {<constr2>}, ...]
where {<constr1>} is {'var1': mult1, 'var2': mult2,... }
:returns: two lists of lists:
* a list of grouped contraints where each constraint grouped containts a list
of indices for constraint constrDict entries
* a list containing lists of parameter names contained in each group
"""
assignedlist = [] # relationships that have been used
groups = [] # contains a list of grouplists
ParmList = []
for i,constrI in enumerate(constrDict):
if i in assignedlist: continue # already in a group, skip
# starting a new group
grouplist = [i,]
assignedlist.append(i)
groupset = set(VarKeys(constrI))
changes = True # always loop at least once
while(changes): # loop until we can't find anything to add to the current group
changes = False # but don't loop again unless we find something
for j,constrJ in enumerate(constrDict):
if j in assignedlist: continue # already in a group, skip
if len(set(VarKeys(constrJ)) & groupset) > 0: # true if this needs to be added
changes = True
grouplist.append(j)
assignedlist.append(j)
groupset = groupset | set(VarKeys(constrJ))
group = sorted(grouplist)
varlist = sorted(list(groupset))
groups.append(group)
ParmList.append(varlist)
return groups,ParmList
def GenerateConstraints(varyList,constrDict,fixedList,parmDict=None,
seqHistNum=None,raiseException=False):
'''Takes a list of relationship entries that have been stored by
:func:`ProcessConstraints` into lists ``constrDict`` and ``fixedList``
This routine then calls :func:`CheckEquivalences` for internal
consistency. This includes converting equivalenced variables into
constraints when a variable is used in both.
Once checked, parameters are grouped so that any parameters that are used in
more than one constraint are grouped together. This allows checking for incompatible
logic (for example, when four constraints are specified for three variables).
If parmDict is not None, the parameter groups are checked for constraints where
some parameters are varied, but not others. If so, the value for that unvaried
parameter is subtracted from the constant in the constraint.
Once all checks are complete, the constraints are then
converted to the form used to apply them, saving them as global variables within
this module.
:param list varyList: a list of parameters names (strings of form
``<ph>:<hst>:<nam>``) that will be varied. Note that this is changed
here unless set to None. None is used to indicate that all constraints
should be generated.
:param dict constrDict: a list of dicts defining relationships/constraints
(as described in :func:`GroupConstraints`)
:param list fixedList: a list of values specifying a fixed value for each
dict in constrDict. Values are either strings that can be converted to
floats, float values or None if the constraint defines a new parameter.
:param dict parmDict: a dict containing all parameters defined in current
refinement.
:param int seqHistNum: the hId number of the current histogram in a sequential
fit. None (default) otherwise.
:param bool raiseException: When True, generation of an error causes
an exception to be raised (used in sequential fits)
:returns: errmsg,warning,groups,parmlist
**errmsg**
Is an error message or empty if no errors were found
**warning**
Is a warning message about constraints that have been ignored or changed
**groups**
Lists parameter groups
**parmlist**
Lists parameters in each parameter groups
'''
warninfo = {'msg':'', 'shown':{}}
def warn(msg,cdict=None,val=None):
if cdict is not None and cdict != warninfo['shown']:
warninfo['shown'] = cdict
if warninfo['msg']: warninfo['msg'] += '\n'
if '_vary' in cdict:
warninfo['msg'] += '\nProblem with new var expression: ' + _FormatConstraint(cdict,cdict.get('_name','New Var'))
else:
warninfo['msg'] += '\nProblem with constraint equation: ' + _FormatConstraint(cdict,val)
if warninfo['msg']: warninfo['msg'] += '\n'
warninfo['msg'] += ' ' + msg
global dependentParmList,arrayList,invarrayList,indParmList,consNum
# lists of parameters used for error reporting
global undefinedVars # parameters that are used in equivalences but are not defined
undefinedVars = []
global groupErrors # parameters in constraints that cause grouping errors
groupErrors = []
global saveVaryList
saveVaryList = copy.copy(varyList)
errmsg = '' # save error messages here. If non-blank, constraints cannot be used.
warning = '' # save informational text messages here.
# find parameters used in constraint equations & new var assignments (all are dependent)
global constrVarList
constrVarList = []
for cnum,(cdict,fixVal) in enumerate(zip(constrDict,fixedList)):
constrVarList += [i for i in cdict if i not in constrVarList and not i.startswith('_')]
# Process the equivalences; If there are conflicting parameters, move them into constraints
warning = CheckEquivalences(constrDict,varyList,fixedList,parmDict,seqHistNum=seqHistNum)
# look through "Constr" and "New Var" constraints looking for zero multipliers and
# Hold, Unvaried & Undefined parameters
skipList = []
invalidParms = []
for cnum,(cdict,fixVal) in enumerate(zip(constrDict,fixedList)):
#constrVarList += [i for i in cdict if i not in constrVarList and not i.startswith('_')]
valid = 0 # count of good parameters
# error reporting
zeroList = [] # parameters with zero multipliers
holdList = [] # parameters with "Hold"'s
noVaryList = [] # parameters not varied
noWildcardList = [] # wildcard parameters in non-sequential fit
notDefList = [] # parameters not defined
# processing to be done
problem = False # constraint must be dropped
dropList = [] # parameters to remove
for var in VarKeys(cdict): # assemble warning info
if cdict[var] == 0: # zero multiplier
if var not in zeroList: zeroList.append(var)
if var not in dropList: dropList.append(var)
elif var in holdParmList: # hold invalid in New Var, drop from constraint eqn
holdList.append(var)
if fixVal is None: # hold in a newvar is not allowed
problem = True
else:
if var not in dropList: dropList.append(var)
elif ':*:' in var : # wildcard still present should be treated as undefined
if var not in undefinedVars: undefinedVars.append(var)
noWildcardList.append(var)
problem = True
elif parmDict is not None and var not in parmDict: # not defined, constraint will not be used
if var not in undefinedVars: undefinedVars.append(var)
notDefList.append(var)
if seqHistNum is None:
if ':dAx:' in var or ':dAy:' in var or ':dAz:' in var: # coordinates from undefined atoms
if fixVal is None:
problem = True # invalid in New Var
else:
if var not in dropList: dropList.append(var) # ignore in constraint eqn
else:
problem = True
elif varyList is None:
valid += 1
elif var not in varyList and fixVal is not None: # unvaried, constraint eq. only
if var not in unvariedParmsList: unvariedParmsList.append(var)
noVaryList.append(var)
dropList.append(var)
else:
valid += 1
if seqHistNum is not None and len(notDefList) > 0 and valid == 0:
# for sequential ref can quietly ignore constraints with all undefined vars
notDefList = []
for l,m in ((zeroList,"have zero multipliers"), # show warning
(holdList,'set as "Hold"'),
(noVaryList,"not varied"),
(noWildcardList,"wildcard in non-sequential fit"),
(notDefList,"not defined")):
if l and cdict.get('_vary',True): # true for constr eq & varied New Var
msg = "parameter(s) " + m + ': '
for i,v in enumerate(l):
if i != 0: msg += ', '
msg += v
warn(msg,cdict,fixVal)
if valid == 0: # no valid entries
if seqHistNum is None: warn('Ignoring constraint, no valid entries',cdict)
skipList.append(cnum)
elif problem: # mix of valid & refined and undefined items, cannot use this
if cdict.get('_vary',True): # true for constr eq & varied New Var
warn('New Var constraint will be ignored',cdict)
skipList.append(cnum)
invalidParms += VarKeys(cdict)
elif len(dropList) > 0: # mix of valid and problematic items, drop problem vars, but keep rest
if GSASIIpath.GetConfigValue('debug'):
msg = ''
for v in dropList:
if msg: msg += ' ,'
msg += v
warn('removing: '+msg,cdict)
value = fixedList[cnum]
for var in dropList: # do cleanup
# NB expressions in constraint multipliers have already been evaluated
if ':dAx:' in var or ':dAy:' in var or ':dAz:' in var:
pass # treat delta coords as 0; no change in total is needed
elif cdict[var] != 0:
value = float(value) - cdict[var]*parmDict[var]
del cdict[var]
if float(value) != float(fixedList[cnum]): fixedList[cnum] = float(np.round(value,12))
if GSASIIpath.GetConfigValue('debug'):
warn('revised as: '+_FormatConstraint(constrDict[cnum],fixedList[cnum]))
for i in list(range(len(constrDict)-1,-1,-1)): # remove the dropped constraints
if i in skipList:
del constrDict[i]
del fixedList[i]
for i in invalidParms: StoreHold(i,"Used in invalid constraint")
if warning: warning += '\n'
warning += warninfo['msg']
groups,parmlist = GroupConstraints(constrDict)
# now process each group and create the relations that are needed to form
# a non-singular square matrix
# Now check that all parameters are varied (probably do not need to do this
# any more). For constraint equations, if all are varied, set VaryFree to True
# and all newly created relationships will be varied. For NewVar constraints,
# vary if the vary flag was set.
for group,depPrmList in zip(groups,parmlist):
if len(depPrmList) < len(group): # too many relationships -- no can do
if errmsg: errmsg += '\n'
errmsg += "Over-constrained input. "
errmsg += "There are more constraints (" + str(len(group))
errmsg += ") than parameters (" + str(len(depPrmList)) + ")\nin these constraints:"
for rel in group:
errmsg += '\n\t'+ _FormatConstraint(constrDict[rel],fixedList[rel])
groupErrors += depPrmList
continue # go on to next group
try:
constrArr = _FillArray(group,constrDict,depPrmList)
except Exception as err:
if errmsg: errmsg += '\n'
if 'Initial' in str(err):
errmsg += "\nSingular input. "
errmsg += "There are internal inconsistencies in these constraints:"
else:
errmsg += "\nError expanding matrix with these constraints:"
for rel in group:
errmsg += '\n\t' + _FormatConstraint(constrDict[rel],fixedList[rel])
groupErrors += depPrmList
continue
try:
GramSchmidtOrtho(constrArr,len(group))
except:
if errmsg: errmsg += '\n'
errmsg += "\nUnexpected singularity with constraints group (in Gram-Schmidt)"
for rel in group:
errmsg += '\n\t' + _FormatConstraint(constrDict[rel],fixedList[rel])
groupErrors += depPrmList
continue
try:
invConstrArr = np.linalg.inv(constrArr)
except:
if errmsg: errmsg += '\n'
errmsg += "\nSingular input. "
errmsg += "The following constraints are not "
errmsg += "linearly independent\nor do not "
errmsg += "allow for generation of a non-singular set.\n"
errmsg += 'This is unexpected. Please report this (toby@anl.gov)'
for rel in group:
errmsg += '\n\t' + _FormatConstraint(constrDict[rel],fixedList[rel])
groupErrors += depPrmList
continue
# scan through current group looking for new var assignments
hasNewVar = False
for rel in group:
if fixedList[rel] is None:
hasNewVar = True # there a New Var relationship in this group
break
else: # only constraint equations, check for unvaried parameters in one
unvaried = False
# this should not happen as they should have been removed
for var in depPrmList:
if varyList is not None and var not in varyList:
unvaried = True
break
if unvaried: # something is not varied: skip group & remove all parameters from varyList
for var in depPrmList: StoreHold(var,'Unexpected: mixed use')
if GSASIIpath.GetConfigValue('debug'):
print('Unexpected: Constraint group ignored (some parameters unvaried)')
for rel in group:
print (' '+_FormatConstraint(constrDict[rel],fixedList[rel]))
continue
maplist = [] # value or param name mapped to each row in expression matrix
if not hasNewVar: # constraint equations; all remaining entries varied, vary generated
for i in range(len(depPrmList)):
if i >= len(group): # tag generated degrees of freedom with names and vary them
varname = paramPrefix + str(consNum) # assign a unique name
consNum += 1
maplist.append(varname)
if varyList is not None: varyList.append(varname)
else:
rel = group[i]
maplist.append(fixedList[rel])
else: # ------------------------- groups with new var assignments, vary only NV's w/flags set
for i,rel in enumerate(group):
if fixedList[rel] is None:
varname = constrDict[rel].get('_name','::?????')
maplist.append(varname)
if constrDict[rel].get('_vary',False):
if varyList is not None: varyList.append(varname)
else:
maplist.append(fixedList[rel]) # constraint equation
for i in range(len(depPrmList)):
if i >= len(group): # name generated degrees of freedom
varname = paramPrefix + str(consNum) # assign a unique name
consNum += 1
maplist.append(varname)
for var in depPrmList: StoreHold(var,'New Var use')
# keep this group
dependentParmList.append(depPrmList)
arrayList.append(constrArr)
invarrayList.append(invConstrArr)
indParmList.append(maplist)
symGenList.append(False)
if errmsg and raiseException:
print (' *** ERROR in constraint definitions! ***')
print (errmsg)
if warning:
print (' also note warnings in constraint processing:')
print (warning)
raise ConstraintException
elif errmsg:
return errmsg,warning,None,None
# Make list of dependent and independent variables for all constraints
constrParms['dep-equiv'] = []
constrParms['dep-constr'] = []
constrParms['indep-equiv'] = []
constrParms['indep-constr'] = []
for varlist,mapvars,multarr in zip(dependentParmList,indParmList,arrayList): # process all constraints
for mv in mapvars:
if type(mv) is float or type(mv) is int: continue
if multarr is None and mv not in constrParms['indep-equiv']:
constrParms['indep-equiv'].append(mv)
elif mv not in constrParms['indep-constr']:
constrParms['indep-constr'].append(mv)
for mv in varlist:
if multarr is None and mv not in constrParms['dep-equiv']:
constrParms['dep-equiv'].append(mv)
elif mv not in constrParms['dep-constr']:
constrParms['dep-constr'].append(mv)
StoreHold(mv,'dependent param')
saveVaryList = copy.copy(varyList) # save varyList so it can be used within module
if varyList is None: saveVaryList = []
# if equivMoved:
# print(60*'=')
# print('Constraints were reclassified to avoid conflicts, as below:')
# print(mvMsg)
# print('New constraints are:')
# print (VarRemapShow(varyList,True))
# print(60*'=')
return errmsg,warning,groups,parmlist # saved for sequential fits
def CheckEquivalences(constrDict,varyList,fixedList,parmDict=None,seqHistNum=None):
'''Process equivalence constraints, looking for conflicts such as
where a parameter is used in both an equivalence and a constraint expression
or where chaining is done (A->B and B->C).
Removes equivalences or parameters from equivalences or converts equivalences to
constraints as described for :ref:`Equivalence Checking and Reorganization <CheckEquivalences>`.
:param dict constrDict: a list of dicts defining relationships/constraints
:param list varyList: list of varied parameters (defined during refinements only)
:param list fixedList: a list of values specifying a fixed value for each
dict in constrDict. Values are either strings that can be converted to
floats or ``None`` if the constraint defines a new parameter rather
than a constant.
:param dict parmDict: a dict containing defined parameters and their values. Used to find
equivalences where a parameter is has been removed from a refinement.
:param int seqHistNum: the hId number of the current histogram in a sequential
fit. None (default) otherwise.
:returns: warning messages about changes that need to be made to equivalences
'''
warninfo = {'msg':'', 'shown':-1}
def warnEqv(msg,cnum=None):
if cnum is not None and cnum != warninfo['shown']:
warninfo['shown'] = cnum
if warninfo['msg']: warninfo['msg'] += '\n'
warninfo['msg'] += '\nProblem with equivalence: ' + _showEquiv(
dependentParmList[cnum],indParmList[cnum],invarrayList[cnum])
if warninfo['msg']: warninfo['msg'] += '\n'
warninfo['msg'] += ' ' + msg
global depVarList # parameters used in equivalences as dependent parameters
global indepVarList # parameters used in equivalences as independent parameters
global constrVarList # parameters used in other constraints
# lists of parameters used for error reporting
global undefinedVars # parameters that are used in equivalences but are not defined
global convVarList # parameters in equivalences that will be converted to constraints
convVarList = [] # parameters in equivalences to be made into constraints
global multdepVarList
multdepVarList = [] # list of dependent parameters used in more than one equivalence
# local vars
dropVarList = [] # parameters that can be removed from equivalences
removeList = [] # equivalences that are not needed
convertList = [] # equivalences that should be converted to "Const" constraints
# tabulate parameters used in equivalences by type
depVarList = [] # list of all dependent parameters in equivalences
indepVarList = [] # list of all independent parameters in equivalences
for cnum,(varlist,mapvars,multarr,invmultarr) in enumerate(zip(
dependentParmList,indParmList,arrayList,invarrayList)):
#if multarr is not None: continue # equivalence
indepVarList += [mv for mv in mapvars if mv not in indepVarList]
depVarList += [v for v in varlist if v not in depVarList]
# process equivalences: make a list of dependent and independent vars
# and check for repeated uses (repetition of a parameter as an
# independent var is OK)
# look for parameters in equivalences that are used more than once as dependent parameters
seenOnce = []
for cnum,(varlist,multarr) in enumerate(zip(dependentParmList,arrayList)):
if multarr is not None: continue # equivalences only
for v in varlist:
if v not in seenOnce:
seenOnce.append(v)
elif v not in multdepVarList:
multdepVarList.append(v)
# scan through equivalences looking for other "dual uses". Stop when no new ones are found
changed = True
count = 0
while changed:
changed = False
count += 1
if count > 1000:
raise ConstraintException("Too many loops in CheckEquivalences")
# look for repeated dependent vars
convVarList = [] # parameters in equivalences to be made into constraints
for cnum,(varlist,mapvars,multarr,invmultarr) in enumerate(zip(
dependentParmList,indParmList,arrayList,invarrayList)):
if multarr is not None: continue # equivalences only
if cnum in convertList:
convVarList += [v for v in mapvars+varlist if v not in convVarList and type(v) is not float]
continue
# identify equivalences that need to be converted to constraints.
# Where parameters:
# are used both in equivalences & constraints,
# are used as dependent multiple times or
# where are used as both dependent and independent (chained)
msg = False
for v in mapvars:
if v in constrVarList+convVarList:
changed = True
msg = True
warnEqv("Independent parameter "+str(v)+' used in constraint',cnum)
if cnum not in convertList: convertList.append(cnum)
for v in varlist:
if v in multdepVarList:
changed = True
msg = True
warnEqv("Dependent parameter "+str(v)+' repeated',cnum)
if cnum not in convertList: convertList.append(cnum)
elif v in indepVarList:
changed = True
msg = True
warnEqv("Dependent parameter "+str(v)+' used elsewhere as independent',cnum)
if cnum not in convertList: convertList.append(cnum)
elif v in constrVarList+convVarList:
changed = True
msg = True
warnEqv("Dependent parameter "+str(v)+' used in constraint',cnum)
if cnum not in convertList: convertList.append(cnum)
if msg:
warnEqv('Converting to "Constr"',cnum)
if warninfo['msg'] and seqHistNum is not None:
# sequential fit -- print the recasts but don't stop with a warning
print(warninfo['msg'])
warninfo = {'msg':'', 'shown':-1}
global unvariedParmsList
unvariedParmsList = [] # parameters in equivalences that are not varied
# scan equivalences: look for holds
for cnum,(varlist,mapvars,multarr,invmultarr) in enumerate(zip(
dependentParmList,indParmList,arrayList,invarrayList)):
if multarr is not None: continue # not an equivalence
if cnum in convertList: continue
# look for holds
gotHold = False
holdList = []
for v in varlist+mapvars:
if v in holdParmList:
gotHold = True
elif type(v) is not float:
holdList.append(v)
if gotHold:
if holdList:
msg = ' Some parameters set as "Hold"; setting remainder as "Hold": '
for i,var in enumerate(holdList):
if i != 0: msg += ", "
msg += var
StoreHold(var,'Equiv fixed')
else:
msg = ' All parameters set as "Hold" '
msg += "\n Will ignore equivalence"
warnEqv(msg,cnum)
removeList.append(cnum)
continue
# look for unvaried parameters
gotVary = False
gotNotVary = False
holdList = []
for v in varlist+mapvars:
if varyList is None or v in varyList:
gotVary = True
holdList.append(v)
elif type(v) is not float:
gotNotVary = True
if v not in unvariedParmsList: unvariedParmsList.append(v)
if gotNotVary: # at least some unvaried parameters
if gotVary: # mix of varied and unvaried parameters
msg = '\nSome parameters not varied; setting remainder as "Hold": '
for i,var in enumerate(holdList):
if i != 0: msg += ", "
msg += var
StoreHold(var,'Equiv fixed')
elif seqHistNum is not None: # don't need to warn for sequential fit
removeList.append(cnum)
continue
else:
msg = 'No parameters varied '
msg += "\n Will ignore equivalence"
warnEqv(msg,cnum)
removeList.append(cnum)
continue
# look for undefined or zero multipliers
holdList = []
drop = 0
for v,m in zip(varlist,invmultarr):
if parmDict is not None and v not in parmDict:
if v not in undefinedVars: undefinedVars.append(v)
if v not in dropVarList: dropVarList.append(v)
drop += 1
elif m == 0:
warnEqv("Parameter "+str(v)+" has a zero multiplier, dropping",cnum)
if v not in dropVarList: dropVarList.append(v)
drop += 1
else:
holdList.append(v)
if drop == len(varlist):
warnEqv("No dependent parameters defined, ignoring equivalence",cnum)
removeList.append(cnum)
continue
for mv in mapvars:
if type(mv) is float: continue
if parmDict is not None and mv not in parmDict:
# independent parameter is undefined, but some dependent parameters are defined
# hold them
if mv not in undefinedVars: undefinedVars.append(mv)
msg = "Parameter(s) "+str(mv)
for v in varlist:
if v in dropVarList:
msg += ', ' + v
msg += "not defined in this refinement\n"
msg = "Setting holds for: "
for i,var in enumerate(holdList):
if i != 0: msg += ", "
msg += var
warnEqv(msg,cnum)
drop += 1
if drop: # independent var and at least one dependent variable is defined
msg = "Dropping undefined parameter(s) "
i = 0
for v in varlist:
if v in dropVarList:
if i != 0: msg += ', '
i += 1
msg += v
warnEqv(msg,cnum)
msg = "Some parameters not defined. Setting holds for: "
for i,var in enumerate(holdList):
if i != 0: msg += ", "
msg += var
StoreHold(var,'Equiv fixed')
warnEqv(msg,cnum)
# Convert equivalences where noted
for cnum,varlist in enumerate(dependentParmList):
if cnum not in convertList: continue
indvar = indParmList[cnum][0]
# msg = '\nChanging equivalence:\n ' + _showEquiv(
# dependentParmList[cnum],indParmList[cnum],invarrayList[cnum])
for dep,mult in zip(dependentParmList[cnum],invarrayList[cnum]):
constrDict += [{indvar:-1.,dep:1./mult[0]}]
fixedList += ['0.0']
#msg += '\n to constraint(s):'
#msg += '\n ' + _FormatConstraint(constrDict[-1],fixedList[-1])
removeList.append(cnum)
# Drop equivalences where noted
global droppedSym
droppedSym = []
if removeList:
for i in set(removeList):
if symGenList[i]:
droppedSym.append((dependentParmList[i],indParmList[i],arrayList[i],invarrayList[i]))
for i in sorted(set(removeList),reverse=True):
del dependentParmList[i],indParmList[i],arrayList[i],invarrayList[i],symGenList[i]
# Drop variables from remaining equivalences
for cnum,varlist in enumerate(dependentParmList):
for j,v in enumerate(varlist):
drop = []
if v in dropVarList:
drop.append(j)
if drop:
for j in sorted(drop,reverse=True):
del indParmList[cnum][j]
return warninfo['msg']
def ProcessConstraints(constList,seqmode='use-all',seqhst=None):
"""Interpret the constraints in the constList input into a dictionary, etc.
All :class:`GSASIIobj.G2VarObj` objects are mapped to the appropriate
phase/hist/atoms based on the object internals (random Ids). If this can't be
done (if a phase has been deleted, etc.), the variable is ignored.
If the constraint cannot be used due to too many dropped variables,
it is counted as ignored. In the case of sequential refinements,
the current histogram number is substituted for a histogram number of "*".
NB: this processing does not include symmetry imposed constraints
:param list constList: a list of lists where each item in the outer list
specifies a constraint of some form, as described in the :mod:`GSASIIobj`
:ref:`Constraint definitions <Constraint_definitions_table>`.
:param str seqmode: one of 'use-all', 'wildcards-only' or 'auto-wildcard'.
When seqmode=='wildcards-only' then any constraint with a numerical
histogram number is skipped. With seqmode=='auto-wildcard',
any non-null constraint number is set to the selected histogram.
:param int seqhst: number for current histogram (used for
'wildcards-only' or 'auto-wildcard' only). Should be None for
non-sequential fits.
:returns: a tuple of (constrDict,fixedList,ignored) where:
* constrDict (list of dicts) contains the constraint relationships
* fixedList (list) contains the fixed values for each type
of constraint.
* ignored (int) counts the number of invalid constraint items
(should always be zero!)
"""
constrDict = []
fixedList = []
ignored = 0
namedVarList = []
for constr in constList:
terms = copy.deepcopy(constr[:-3]) # don't change the tree contents
# deal with wildcards in sequential fits
if seqmode == 'wildcards-only' and seqhst is not None:
skip = False
for term in terms:
if term[1].histogram == '*':
term[1] = term[1].varname(seqhst)
elif term[1].histogram:
skip = True
if skip: continue
elif seqmode == 'auto-wildcard' and seqhst is not None:
for term in terms:
term[1] = term[1].varname(seqhst)
elif seqhst is not None:
for term in terms:
if term[1].histogram == '*':
term[1] = term[1].varname(seqhst)
# else:
# term[1] = term[1].varname() # does this change anything???
# separate processing by constraint type
if constr[-1] == 'h':
# process a hold
var = str(terms[0][1])
if '?' not in var:
StoreHold(var,'User supplied')
else:
ignored += 1
elif constr[-1] == 'f':
# process a new variable
fixedList.append(None)
D = {}
varyFlag = constr[-2]
varname = constr[-3]
for term in terms:
var = str(term[1])
if '?' not in var:
D[var] = term[0]
# add extra dict terms for input variable name and vary flag
if varname is None: # no assigned name, create one
global consNum
varname = str(consNum)
consNum += 1
else:
varname = str(varname) # in case this is a G2VarObj
if '::' in varname:
D['_name'] = varname.replace('::','::nv-')
else:
D['_name'] = '::nv-' + varname
D['_name'] = G2obj.MakeUniqueLabel(D['_name'],namedVarList)
D['_vary'] = varyFlag == True # force to bool
constrDict.append(D)
elif constr[-1] == 'c':
# process a constraint equation
D = {}
for term in terms:
var = str(term[1])
if '?' not in var:
D[var] = term[0]
if len(D) >= 1:
fixedList.append(float(constr[-3]))
constrDict.append(D)
else:
ignored += 1
elif constr[-1] == 'e':
# process an equivalence
firstmult = None
eqlist = []
for term in terms:
if term[0] == 0: term[0] = 1.0
var = str(term[1])
if '?' in var: continue
if firstmult is None:
firstmult = term[0]
firstvar = var
else:
eqlist.append([var,firstmult/term[0]])
if len(eqlist) > 0:
StoreEquivalence(firstvar,eqlist,False)
else:
ignored += 1
else:
ignored += 1
return constrDict,fixedList,ignored
def StoreHold(var,holdType=None):
'''Takes a variable name and prepares it to be removed from the
refined variables.
Called with user-supplied constraints by :func:`ProcessConstraints`.
At present symGen is not used, but could be set up to track Holds generated
by symmetry.
'''
global holdParmList,holdParmType
if var not in holdParmList:
holdParmList.append(var)
if holdType: holdParmType[var] = holdType
def StoreEquivalence(independentVar,dependentList,symGen=True):
'''Takes a list of dependent parameter(s) and stores their
relationship to a single independent parameter (independentVar).
Called with user-supplied constraints by :func:`ProcessConstraints`,
with Pawley constraints from :func:`GSASIIstrIO.GetPawleyConstr`,
with Unit Cell constraints from :func:`GSASIIstrIO.cellVary`
with symmetry-generated atom constraints from :func:`GSASIIstrIO.GetPhaseData`
There is no harm in using StoreEquivalence with the same independent variable::
StoreEquivalence('x',('y',))
StoreEquivalence('x',('z',))
but the same outcome can be obtained with a single call::
StoreEquivalence('x',('y','z'))
The latter will run more efficiently.
Note that mixing independent and dependent variables, such as::
StoreEquivalence('x',('y',))
StoreEquivalence('y',('z',))
is a poor choice. The module will attempt to fix this by transforming the equivalence to a
"Const" constraint.
:param str independentVar: name of master parameter that will be used to determine the value
to set the dependent variables
:param list dependentList: a list of parameters that will set from
independentVar. Each item in the list can be a string with the parameter
name or a tuple containing a name and multiplier:
``['::parm1',('::parm2',.5),]``
'''
global dependentParmList,arrayList,invarrayList,indParmList,symGenList
mapList = []
multlist = []
allfloat = True
for var in dependentList:
if isinstance(var, str):
mult = 1.0
elif len(var) == 2:
var,mult = var
else:
raise Exception("Cannot parse "+repr(var) + " as var or (var,multiplier)")
mapList.append(var)
try:
multlist.append(tuple((float(mult),)))
except:
allfloat = False
multlist.append(tuple((mult,)))
# added relationships to stored values
arrayList.append(None)
if allfloat:
invarrayList.append(np.array(multlist))
else:
invarrayList.append(multlist)
indParmList.append(list((independentVar,)))
dependentParmList.append(mapList)
symGenList.append(symGen)
return
def SubfromParmDict(s,prmDict):
'''Process a string as a multiplier and convert it to a float value. This
is done by subsituting any GSAS-II parameter names that appear in the