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
/
Copy pathGSASIIconstrGUI.py
4340 lines (4094 loc) · 190 KB
/
GSASIIconstrGUI.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
# -*- coding: utf-8 -*-
#GSASIIconstrGUI - constraint GUI routines
########### SVN repository information ###################
# $Date: 2024-03-17 12:50:24 -0500 (Sun, 17 Mar 2024) $
# $Author: toby $
# $Revision: 5767 $
# $URL: https://subversion.xray.aps.anl.gov/pyGSAS/trunk/GSASIIconstrGUI.py $
# $Id: GSASIIconstrGUI.py 5767 2024-03-17 17:50:24Z toby $
########### SVN repository information ###################
'''
Constraints and rigid bodies GUI routines follow.
'''
from __future__ import division, print_function
import platform
import sys
import copy
import os.path
import wx
import wx.grid as wg
import wx.lib.scrolledpanel as wxscroll
import wx.lib.gridmovers as gridmovers
import random as ran
import numpy as np
import numpy.ma as ma
import numpy.linalg as nl
import GSASIIpath
GSASIIpath.SetVersionNumber("$Revision: 5767 $")
import GSASIIElem as G2elem
import GSASIIElemGUI as G2elemGUI
import GSASIIstrIO as G2stIO
import GSASIImapvars as G2mv
import GSASIImath as G2mth
import GSASIIlattice as G2lat
import GSASIIdataGUI as G2gd
import GSASIIctrlGUI as G2G
import GSASIIfiles as G2fl
import GSASIIplot as G2plt
import GSASIIobj as G2obj
import GSASIIspc as G2spc
import GSASIIphsGUI as G2phG
import GSASIIIO as G2IO
import GSASIIscriptable as G2sc
VERY_LIGHT_GREY = wx.Colour(235,235,235)
WACV = wx.ALIGN_CENTER_VERTICAL
class G2BoolEditor(wg.GridCellBoolEditor):
'''Substitute for wx.grid.GridCellBoolEditor except toggles
grid items immediately when opened, updates grid & table contents after every
item change
'''
def __init__(self):
self.saveVals = None
wx.grid.GridCellBoolEditor.__init__(self)
def Create(self, parent, id, evtHandler):
'''Create the editing control (wx.CheckBox) when cell is opened
for edit
'''
self._tc = wx.CheckBox(parent, -1, "")
self._tc.Bind(wx.EVT_CHECKBOX, self.onCheckSet)
self.SetControl(self._tc)
if evtHandler:
self._tc.PushEventHandler(evtHandler)
def onCheckSet(self, event):
'''Callback used when checkbox is toggled.
Makes change to table immediately (creating event)
'''
if self.saveVals:
self.ApplyEdit(*self.saveVals)
def SetSize(self, rect):
'''Set position/size the edit control within the cell's rectangle.
'''
# self._tc.SetDimensions(rect.x, rect.y, rect.width+2, rect.height+2, # older
self._tc.SetSize(rect.x, rect.y, rect.width+2, rect.height+2,
wx.SIZE_ALLOW_MINUS_ONE)
def BeginEdit(self, row, col, grid):
'''Prepares the edit control by loading the initial
value from the table (toggles it since you would not
click on it if you were not planning to change it),
buts saves the original, pre-change value.
Makes change to table immediately.
Saves the info needed to make updates in self.saveVals.
Sets the focus.
'''
if grid.GetTable().GetValue(row,col) not in [True,False]:
return
self.startValue = int(grid.GetTable().GetValue(row, col))
self.saveVals = row, col, grid
# invert state and set in editor
if self.startValue:
grid.GetTable().SetValue(row, col, 0)
self._tc.SetValue(0)
else:
grid.GetTable().SetValue(row, col, 1)
self._tc.SetValue(1)
self._tc.SetFocus()
self.ApplyEdit(*self.saveVals)
def EndEdit(self, row, col, grid, oldVal=None):
'''End editing the cell. This is supposed to
return None if the value has not changed, but I am not
sure that actually works.
'''
val = int(self._tc.GetValue())
if val != oldVal: #self.startValue:?
return val
else:
return None
def ApplyEdit(self, row, col, grid):
'''Save the value into the table, and create event.
Called after EndEdit(), BeginEdit and onCheckSet.
'''
val = int(self._tc.GetValue())
grid.GetTable().SetValue(row, col, val) # update the table
def Reset(self):
'''Reset the value in the control back to its starting value.
'''
self._tc.SetValue(self.startValue)
def StartingClick(self):
'''This seems to be needed for BeginEdit to work properly'''
pass
def Destroy(self):
"final cleanup"
super(G2BoolEditor, self).Destroy()
def Clone(self):
'required'
return G2BoolEditor()
class DragableRBGrid(wg.Grid):
'''Simple grid implentation for display of rigid body positions.
:param parent: frame or panel where grid will be placed
:param dict rb: dict with atom labels, types and positions
:param function onChange: a callback used every time a value in
rb is changed.
'''
def __init__(self, parent, rb, onChange=None):
#wg.Grid.__init__(self, parent, wx.ID_ANY,size=(-1,200))
wg.Grid.__init__(self, parent, wx.ID_ANY)
self.SetTable(RBDataTable(rb,onChange), True)
# Enable Row moving
gridmovers.GridRowMover(self)
self.Bind(gridmovers.EVT_GRID_ROW_MOVE, self.OnRowMove, self)
self.SetColSize(0, 60)
self.SetColSize(1, 40)
self.SetColSize(2, 35)
for r in range(len(rb['RBlbls'])):
self.SetReadOnly(r,0,isReadOnly=True)
self.SetCellEditor(r, 1, G2BoolEditor())
self.SetCellRenderer(r, 1, wg.GridCellBoolRenderer())
self.SetReadOnly(r,2,isReadOnly=True)
self.SetCellEditor(r,3, wg.GridCellFloatEditor())
self.SetCellEditor(r,4, wg.GridCellFloatEditor())
self.SetCellEditor(r,6, wg.GridCellFloatEditor())
def OnRowMove(self,evt):
'called when a row move needs to take place'
frm = evt.GetMoveRow() # Row being moved
to = evt.GetBeforeRow() # Before which row to insert
self.GetTable().MoveRow(frm,to)
def completeEdits(self):
'complete any outstanding edits'
if self.IsCellEditControlEnabled(): # complete any grid edits in progress
#if GSASIIpath.GetConfigValue('debug'): print ('Completing grid edit')
self.SaveEditControlValue()
self.HideCellEditControl()
self.DisableCellEditControl()
class RBDataTable(wg.GridTableBase):
'''A Table to support :class:`DragableRBGrid`
'''
def __init__(self,rb,onChange):
wg.GridTableBase.__init__(self)
self.colLabels = ['Label','Select','Type','x','y','z']
self.coords = rb['RBcoords']
self.labels = rb['RBlbls']
self.types = rb['RBtypes']
self.index = rb['RBindex']
self.select = rb['RBselection']
self.onChange = onChange
# required methods
def GetNumberRows(self):
return len(self.labels)
def GetNumberCols(self):
return len(self.colLabels)
def IsEmptyCell(self, row, col):
return False
def GetValue(self, row, col):
row = self.index[row]
if col == 0:
return self.labels[row]
elif col == 1:
if self.select[row]:
return '1'
else:
return ''
elif col == 2:
return self.types[row]
else:
return '{:.5f}'.format(self.coords[row][col-3])
def SetValue(self, row, col, value):
row = self.index[row]
try:
if col == 0:
self.labels[row] = value
elif col == 1:
self.select[row] = bool(value)
elif col == 2:
self.types[row] = value
else:
self.coords[row][col-3] = float(value)
except:
pass
if self.onChange:
self.onChange()
# Display column & row labels
def GetColLabelValue(self, col):
return self.colLabels[col]
def GetRowLabelValue(self,row):
return str(row)
# Implement "row movement" by updating the pointer array
def MoveRow(self,frm,to):
grid = self.GetView()
if grid:
move = self.index[frm]
del self.index[frm]
if frm > to:
self.index.insert(to,move)
else:
self.index.insert(to-1,move)
# Notify the grid
grid.BeginBatch()
msg = wg.GridTableMessage(
self, wg.GRIDTABLE_NOTIFY_ROWS_DELETED, frm, 1
)
grid.ProcessTableMessage(msg)
msg = wg.GridTableMessage(
self, wg.GRIDTABLE_NOTIFY_ROWS_INSERTED, to, 1
)
grid.ProcessTableMessage(msg)
grid.EndBatch()
if self.onChange:
self.onChange()
# def MakeDrawAtom(data,atom):
# 'Convert atom to format needed to draw it'
# generalData = data['General']
# deftype = G2obj.validateAtomDrawType(
# GSASIIpath.GetConfigValue('DrawAtoms_default'),generalData)
# if generalData['Type'] in ['nuclear','faulted',]:
# atomInfo = [atom[:2]+atom[3:6]+['1']+[deftype]+
# ['']+[[255,255,255]]+atom[9:]+[[],[]]][0]
# ct,cs = [1,8] #type & color
# atNum = generalData['AtomTypes'].index(atom[ct])
# atomInfo[cs] = list(generalData['Color'][atNum])
# return atomInfo
class ConstraintDialog(wx.Dialog):
'''Window to edit Constraint values
'''
def __init__(self,parent,title,text,data,separator='*',varname="",varyflag=False):
wx.Dialog.__init__(self,parent,-1,'Edit '+title,
pos=wx.DefaultPosition,style=wx.DEFAULT_DIALOG_STYLE)
self.data = data[:]
self.newvar = [varname,varyflag]
panel = wx.Panel(self)
mainSizer = wx.BoxSizer(wx.VERTICAL)
topLabl = wx.StaticText(panel,-1,text)
mainSizer.Add((10,10),1)
mainSizer.Add(topLabl,0,wx.LEFT,10)
mainSizer.Add((10,10),1)
dataGridSizer = wx.FlexGridSizer(cols=3,hgap=2,vgap=2)
self.OkBtn = wx.Button(panel,wx.ID_OK)
for id in range(len(self.data)):
lbl1 = lbl = str(self.data[id][1])
if lbl[-1] != '=': lbl1 = lbl + ' ' + separator + ' '
name = wx.StaticText(panel,wx.ID_ANY,lbl1,style=wx.ALIGN_RIGHT)
scale = G2G.ValidatedTxtCtrl(panel,self.data[id],0,OKcontrol=self.DisableOK)
dataGridSizer.Add(name,0,wx.LEFT|wx.RIGHT|WACV,5)
dataGridSizer.Add(scale,0,wx.RIGHT,3)
if ':' in lbl:
dataGridSizer.Add(
wx.StaticText(panel,-1,G2obj.fmtVarDescr(lbl)),
0,wx.RIGHT|WACV,3)
else:
dataGridSizer.Add((-1,-1))
if title == 'New Variable':
name = wx.StaticText(panel,wx.ID_ANY,"New variable's\nname (optional)",
style=wx.ALIGN_CENTER)
scale = G2G.ValidatedTxtCtrl(panel,self.newvar,0,notBlank=False)
dataGridSizer.Add(name,0,wx.LEFT|wx.RIGHT|WACV,5)
dataGridSizer.Add(scale,0,wx.RIGHT|WACV,3)
self.refine = wx.CheckBox(panel,label='Refine?')
self.refine.SetValue(self.newvar[1]==True)
self.refine.Bind(wx.EVT_CHECKBOX, self.OnCheckBox)
dataGridSizer.Add(self.refine,0,wx.RIGHT|WACV,3)
mainSizer.Add(dataGridSizer,0,wx.EXPAND)
self.OkBtn.Bind(wx.EVT_BUTTON, self.OnOk)
self.OkBtn.SetDefault()
cancelBtn = wx.Button(panel,wx.ID_CANCEL)
cancelBtn.Bind(wx.EVT_BUTTON, self.OnCancel)
btnSizer = wx.BoxSizer(wx.HORIZONTAL)
btnSizer.Add((20,20),1)
btnSizer.Add(self.OkBtn)
btnSizer.Add((20,20),1)
btnSizer.Add(cancelBtn)
btnSizer.Add((20,20),1)
mainSizer.Add(btnSizer,0,wx.EXPAND, 10)
panel.SetSizer(mainSizer)
panel.Fit()
self.Fit()
self.CenterOnParent()
def DisableOK(self,setting):
for id in range(len(self.data)): # coefficient cannot be zero
try:
if abs(self.data[id][0]) < 1.e-20:
setting = False
break
except:
pass
if setting:
self.OkBtn.Enable()
else:
self.OkBtn.Disable()
def OnCheckBox(self,event):
self.newvar[1] = self.refine.GetValue()
def OnOk(self,event):
parent = self.GetParent()
parent.Raise()
self.EndModal(wx.ID_OK)
def OnCancel(self,event):
parent = self.GetParent()
parent.Raise()
self.EndModal(wx.ID_CANCEL)
def GetData(self):
return self.data
##### Constraints ################################################################################
def CheckConstraints(G2frame,Phases,Histograms,data,newcons=[],reqVaryList=None,seqhst=None,seqmode='use-all'):
'''Load constraints & check them for errors.
N.B. Equivalences based on symmetry (etc.)
are generated by running :func:`GSASIIstrIO.GetPhaseData`.
When reqVaryList is included (see WarnConstraintLimit) then
parameters with limits are checked against constraints and a
warning is shown.
'''
G2mv.InitVars()
#Find all constraints
constrDict = []
for key in data:
if key.startswith('_'): continue
constrDict += data[key]
if newcons:
constrDict = constrDict + newcons
constrDict, fixedList, ignored = G2mv.ProcessConstraints(constrDict, seqhst=seqhst, seqmode=seqmode)
parmDict = {}
# generate symmetry constraints to check for conflicts
rigidbodyDict = G2frame.GPXtree.GetItemPyData(
G2gd.GetGPXtreeItemId(G2frame, G2frame.root, 'Rigid bodies'))
rbIds = rigidbodyDict.get('RBIds', {'Vector': [], 'Residue': [],'Spin':[]})
rbVary, rbDict = G2stIO.GetRigidBodyModels(rigidbodyDict, Print=False)
parmDict.update(rbDict)
(Natoms,atomIndx,phaseVary,phaseDict,pawleyLookup,FFtables,EFtables,ORBtables,BLtables,MFtables,maxSSwave) = \
G2stIO.GetPhaseData(Phases,RestraintDict=None,rbIds=rbIds,Print=False) # generates atom symmetry constraints
parmDict.update(phaseDict)
# get Hist and HAP info
hapVary, hapDict, controlDict = G2stIO.GetHistogramPhaseData(Phases, Histograms, Print=False, resetRefList=False)
parmDict.update(hapDict)
histVary, histDict, controlDict = G2stIO.GetHistogramData(Histograms, Print=False)
parmDict.update(histDict)
# TODO: twining info needed?
#TwConstr,TwFixed = G2stIO.makeTwinFrConstr(Phases,Histograms,hapVary)
#constrDict += TwConstr
#fixedList += TwFixed
varyList = rbVary+phaseVary+hapVary+histVary
msg = G2mv.EvaluateMultipliers(constrDict,parmDict)
if msg:
return 'Unable to interpret multiplier(s): '+msg,''
if reqVaryList:
varyList = reqVaryList[:]
errmsg,warnmsg,groups,parmlist = G2mv.GenerateConstraints(varyList,constrDict,fixedList,parmDict) # changes varyList
impossible = []
if reqVaryList:
Controls = G2frame.GPXtree.GetItemPyData(G2gd.GetGPXtreeItemId(G2frame,G2frame.root, 'Controls'))
for key in ('parmMinDict','parmMaxDict','parmFrozen'):
if key not in Controls: Controls[key] = {}
G2mv.Map2Dict(parmDict,varyList) # changes parmDict & varyList
# check for limits on dependent vars
consVars = [i for i in reqVaryList if i not in varyList]
impossible = set(
[str(i) for i in Controls['parmMinDict'] if i in consVars] +
[str(i) for i in Controls['parmMaxDict'] if i in consVars])
if impossible:
msg = ''
for i in sorted(impossible):
if msg: msg += ', '
msg += i
msg = ' &'.join(msg.rsplit(',',1))
msg = ('Note: limits on variable(s) '+msg+
' will be ignored because they are constrained.')
G2G.G2MessageBox(G2frame,msg,'Limits ignored for constrained vars')
else:
G2mv.Map2Dict(parmDict,varyList) # changes varyList
return errmsg,warnmsg
def UpdateConstraints(G2frame, data, selectTab=None, Clear=False):
'''Called when Constraints tree item is selected.
Displays the constraints in the data window
'''
def FindEquivVarb(name,nameList):
'Creates a list of variables appropriate to constrain with name'
outList = []
#phlist = []
items = name.split(':')
namelist = [items[2],]
if 'dA' in name:
namelist = ['dAx','dAy','dAz']
elif 'AU' in name:
namelist = ['AUiso','AU11','AU22','AU33','AU12','AU13','AU23']
elif 'Akappa' in name:
namelist = ['Akappa%d'%i for i in range(6)]
elif 'ANe' in name:
namelist = ['ANe0','ANe1']
elif 'AD(1' in name:
orb = name.split(':')[2][-1]
namelist = ['AD(1,0)'+orb,'AD(1,1)'+orb,'AD(1,-1)'+orb]
elif 'AD(2' in name:
orb = name.split(':')[2][-1]
namelist = ['AD(2,0)'+orb,'AD(2,1)'+orb,'AD(2,-1)'+orb,'AD(2,2)'+orb,'AD(2,-2)'+orb]
elif 'AD(4' in name:
orb = name.split(':')[2][-1]
namelist = ['AD(4,0)'+orb,'AD(4,1)'+orb,'AD(4,-1)'+orb,'AD(4,2)'+orb,'AD(4,-2)'+orb,
'AD(4,3)'+orb,'AD(4,-3)'+orb,'AD(4,4)'+orb,'AD(4,-4)'+orb]
elif 'AM' in name:
namelist = ['AMx','AMy','AMz']
elif items[-1] in ['A0','A1','A2','A3','A4','A5']:
namelist = ['A0','A1','A2','A3','A4','A5']
elif items[-1] in ['D11','D22','D33','D12','D13','D23']:
namelist = ['D11','D22','D33','D12','D13','D23']
elif 'Tm' in name:
namelist = ['Tmin','Tmax']
elif 'MX' in name or 'MY' in name or 'MZ' in name:
namelist = ['MXcos','MYcos','MZcos','MXsin','MYsin','MZsin']
elif 'mV' in name:
namelist = ['mV0','mV1','mV2']
elif 'Debye' in name or 'BkPk' in name: #special cases for Background fxns
dbname = name.split(';')[0].split(':')[2]
return [item for item in nameList if dbname in item]
elif 'RB' in name:
rbfx = 'RB'+items[2][2]
if 'T' in name and 'Tr' not in name:
namelist = [rbfx+'T11',rbfx+'T22',rbfx+'T33',rbfx+'T12',rbfx+'T13',rbfx+'T23']
if 'L' in name:
namelist = [rbfx+'L11',rbfx+'L22',rbfx+'L33',rbfx+'L12',rbfx+'L13',rbfx+'L23']
if 'S' in name:
namelist = [rbfx+'S12',rbfx+'S13',rbfx+'S21',rbfx+'S23',rbfx+'S31',rbfx+'S32',rbfx+'SAA',rbfx+'SBB']
if 'U' in name:
namelist = [rbfx+'U',]
if 'Tr' in name:
namelist = [rbfx+'Tr',]
for item in nameList:
keys = item.split(':')
#if keys[0] not in phlist:
# phlist.append(keys[0])
if items[1] == '*' and keys[2] in namelist: # wildcard -- select only sequential options
keys[1] = '*'
mitem = ':'.join(keys)
if mitem == name: continue
if mitem not in outList: outList.append(mitem)
elif (keys[2] in namelist or keys[2].split(';')[0] in namelist) and item != name:
outList.append(item)
return outList
def SelectVarbs(page,FrstVarb,varList,legend,constType):
'''Select variables used in constraints after one variable has
been selected. This routine determines the appropriate variables to be
used based on the one that has been selected and asks for more to be added.
It then creates the constraint and adds it to the constraints list.
Called from OnAddEquivalence, OnAddFunction & OnAddConstraint (all but
OnAddHold)
:param list page: defines calling page -- type of variables to be used
:parm GSASIIobj.G2VarObj FrstVarb: reference to first selected variable
:param list varList: list of other appropriate variables to select from
:param str legend: header for selection dialog
:param str constType: type of constraint to be generated
:returns: a constraint, as defined in
:ref:`GSASIIobj <Constraint_definitions_table>`
'''
choices = [[i]+list(G2obj.VarDescr(i)) for i in varList]
meaning = G2obj.getDescr(FrstVarb.name)
if not meaning:
meaning = "(no definition found!)"
l = str(FrstVarb).split(':')
# make lists of phases & histograms to iterate over
phaselist = [l[0]]
if l[0]:
phaselbl = ['phase #'+l[0]]
if len(Phases) > 1:
phaselist += ['all']
phaselbl += ['all phases']
else:
phaselbl = ['']
histlist = [l[1]]
if l[1] == '*':
pass
elif l[1]:
histlbl = ['histogram #'+l[1]]
if len(Histograms) > 1:
histlist += ['all']
histlbl += ['all histograms']
typ = Histograms[G2obj.LookupHistName(l[1])[0]]['Instrument Parameters'][0]['Type'][1]
i = 0
for hist in Histograms:
if Histograms[hist]['Instrument Parameters'][0]['Type'][1] == typ: i += 1
if i > 1:
histlist += ['all='+typ]
histlbl += ['all '+typ+' histograms']
else:
histlbl = ['']
# make a list of equivalent parameter names
nameList = [FrstVarb.name]
for var in varList:
nam = var.split(":")[2]
if nam not in nameList: nameList += [nam]
# add "wild-card" names to the list of variables
if l[1] == '*':
pass
elif page[1] == 'phs':
if 'RB' in FrstVarb.name:
pass
elif FrstVarb.atom is None:
for nam in nameList:
for ph,plbl in zip(phaselist,phaselbl):
if plbl: plbl = 'For ' + plbl
var = ph+"::"+nam
if var == str(FrstVarb) or var in varList: continue
varList += [var]
choices.append([var,plbl,meaning])
else:
for nam in nameList:
for ph,plbl in zip(phaselist,phaselbl):
if plbl: plbl = ' in ' + plbl
for atype in ['']+TypeList:
if atype:
albl = "For "+atype+" atoms"
akey = "all="+atype
else:
albl = "For all atoms"
akey = "all"
var = ph+"::"+nam+":"+akey
if var == str(FrstVarb) or var in varList: continue
varList += [var]
choices.append([var,albl+plbl,meaning])
elif page[1] == 'hap':
if FrstVarb.name == "Scale":
meaning = "Phase fraction"
for nam in nameList:
for ph,plbl in zip(phaselist,phaselbl):
if plbl: plbl = 'For ' + plbl
for hst,hlbl in zip(histlist,histlbl):
if hlbl:
if plbl:
hlbl = ' in ' + hlbl
else:
hlbl = 'For ' + hlbl
var = ph+":"+hst+":"+nam
if var == str(FrstVarb) or var in varList: continue
varList += [var]
choices.append([var,plbl+hlbl,meaning])
elif page[1] == 'hst':
if FrstVarb.name == "Scale":
meaning = "Scale factor"
for nam in nameList:
for hst,hlbl in zip(histlist,histlbl):
if hlbl:
hlbl = 'For ' + hlbl
var = ":"+hst+":"+nam
if var == str(FrstVarb) or var in varList: continue
varList += [var]
choices.append([var,hlbl,meaning])
elif page[1] == 'glb' or page[1] == 'sym':
pass
else:
raise Exception('Unknown constraint page '+ page[1])
if len(choices):
l1 = l2 = 1
for i1,i2,i3 in choices:
l1 = max(l1,len(i1))
l2 = max(l2,len(i2))
fmt = "{:"+str(l1)+"s} {:"+str(l2)+"s} {:s}"
atchoices = [fmt.format(*i1) for i1 in choices] # reformat list as str with columns
dlg = G2G.G2MultiChoiceDialog(
G2frame,legend,
'Constrain '+str(FrstVarb)+' with...',atchoices,
toggle=False,size=(625,400),monoFont=True)
dlg.CenterOnParent()
res = dlg.ShowModal()
Selections = dlg.GetSelections()[:]
dlg.Destroy()
if res != wx.ID_OK: return []
if len(Selections) == 0:
dlg = wx.MessageDialog(
G2frame,
'No variables were selected to include with '+str(FrstVarb),
'No variables')
dlg.CenterOnParent()
dlg.ShowModal()
dlg.Destroy()
return []
else:
dlg = wx.MessageDialog(
G2frame,
'There are no appropriate variables to include with '+str(FrstVarb),
'No variables')
dlg.CenterOnParent()
dlg.ShowModal()
dlg.Destroy()
return []
# now process the variables provided by the user
varbs = [str(FrstVarb),] # list of selected variables
for sel in Selections:
var = varList[sel]
# phase(s) included
l = var.split(':')
if l[0] == "all":
phlist = [str(Phases[phase]['pId']) for phase in Phases]
else:
phlist = [l[0]]
# histogram(s) included
if l[1] == "all":
hstlist = [str(Histograms[hist]['hId']) for hist in Histograms]
elif '=' in l[1]:
htyp = l[1].split('=')[1]
hstlist = [str(Histograms[hist]['hId']) for hist in Histograms if
Histograms[hist]['Instrument Parameters'][0]['Type'][1] == htyp]
else:
hstlist = [l[1]]
if len(l) == 3:
for ph in phlist:
for hst in hstlist:
var = ph + ":" + hst + ":" + l[2]
if var in varbs: continue
varbs.append(var)
else: # constraints with atoms or rigid bodies
if len(l) == 5: # rigid body parameter
var = ':'.join(l)
if var in varbs: continue
varbs.append(var)
elif l[3] == "all":
for ph in phlist:
key = G2obj.LookupPhaseName(ph)[0]
for hst in hstlist: # should be blank
for iatm,at in enumerate(Phases[key]['Atoms']):
var = ph + ":" + hst + ":" + l[2] + ":" + str(iatm)
if var in varbs: continue
varbs.append(var)
elif '=' in l[3]:
for ph in phlist:
key = G2obj.LookupPhaseName(ph)[0]
cx,ct,cs,cia = Phases[key]['General']['AtomPtrs']
for hst in hstlist: # should be blank
atyp = l[3].split('=')[1]
for iatm,at in enumerate(Phases[key]['Atoms']):
if at[ct] != atyp: continue
var = ph + ":" + hst + ":" + l[2] + ":" + str(iatm)
if var in varbs: continue
varbs.append(var)
else:
for ph in phlist:
key = G2obj.LookupPhaseName(ph)[0]
for hst in hstlist: # should be blank
var = ph + ":" + hst + ":" + l[2] + ":" + l[3]
if var in varbs: continue
varbs.append(var)
if len(varbs) >= 1 or 'constraint' in constType:
constr = [[1.0,FrstVarb]]
for item in varbs[1:]:
constr += [[1.0,G2obj.G2VarObj(item)]]
if 'equivalence' in constType:
return [constr+[None,None,'e']]
elif 'function' in constType:
return [constr+[None,False,'f']]
elif 'constraint' in constType:
return [constr+[1.0,None,'c']]
else:
raise Exception('Unknown constraint type: '+str(constType))
else:
dlg = wx.MessageDialog(
G2frame,
'There are no selected variables to include with '+str(FrstVarb),
'No variables')
dlg.CenterOnParent()
dlg.ShowModal()
dlg.Destroy()
return []
def CheckAddedConstraint(newcons):
'''Check a new constraint that has just been input.
If there is an error display a message and discard the last entry
Since the varylist is not available, no warning messages
should be generated here
:returns: True if constraint should be added
'''
errmsg,warnmsg = CheckConstraints(G2frame,Phases,Histograms,data,newcons,seqhst=seqhistnum,seqmode=seqmode)
if errmsg:
G2frame.ErrorDialog('Constraint Error',
'Error with newly added constraint:\n'+errmsg+
'\nIgnoring newly added constraint',parent=G2frame)
# reset error status
errmsg,warnmsg = CheckConstraints(G2frame,Phases,Histograms,data,seqhst=seqhistnum,seqmode=seqmode)
if errmsg:
print (errmsg)
print (G2mv.VarRemapShow([],True))
return False
elif warnmsg:
print ('Warning after constraint addition:\n'+warnmsg)
ans = G2G.ShowScrolledInfo(header='Constraint Warning',
txt='Warning noted after adding constraint:\n'+warnmsg+
'\n\nKeep this addition?',
buttonlist=[wx.ID_YES,wx.ID_NO],parent=G2frame,height=250)
if ans == wx.ID_NO: return False
return True
def WarnConstraintLimit():
'''Check if constraints reference variables with limits.
Displays a warning message, but does nothing
'''
parmDict,reqVaryList = G2frame.MakeLSParmDict()
try:
errmsg,warnmsg = CheckConstraints(G2frame,Phases,Histograms,data,[],reqVaryList,seqhst=seqhistnum,seqmode=seqmode)
except Exception as msg:
if GSASIIpath.GetConfigValue('debug'):
import traceback
print (traceback.format_exc())
return 'CheckConstraints error retrieving parameter\nError='+str(msg),''
return errmsg,warnmsg
def CheckChangedConstraint():
'''Check all constraints after an edit has been made.
If there is an error display a message and reject the change.
Since the varylist is not available, no warning messages
should be generated.
:returns: True if the edit should be retained
'''
errmsg,warnmsg = CheckConstraints(G2frame,Phases,Histograms,data,seqhst=seqhistnum,seqmode=seqmode)
if errmsg:
G2frame.ErrorDialog('Constraint Error',
'Error after editing constraint:\n'+errmsg+
'\nDiscarding last constraint edit',parent=G2frame)
# reset error status
errmsg,warnmsg = CheckConstraints(G2frame,Phases,Histograms,data,seqhst=seqhistnum,seqmode=seqmode)
if errmsg:
print (errmsg)
print (G2mv.VarRemapShow([],True))
return False
elif warnmsg:
print ('Warning after constraint edit:\n'+warnmsg)
ans = G2G.ShowScrolledInfo(header='Constraint Warning',
txt='Warning noted after last constraint edit:\n'+warnmsg+
'\n\nKeep this change?',
buttonlist=[wx.ID_YES,wx.ID_NO],parent=G2frame,height=250)
if ans == wx.ID_NO: return False
return True
def PageSelection(page):
'Decode page reference'
if page[1] == "phs":
vartype = "phase"
varList = G2obj.removeNonRefined(phaseList) # remove any non-refinable prms from list
constrDictEnt = 'Phase'
elif page[1] == "hap":
vartype = "Histogram*Phase"
varList = G2obj.removeNonRefined(hapList) # remove any non-refinable prms from list
constrDictEnt = 'HAP'
elif page[1] == "hst":
vartype = "Histogram"
varList = G2obj.removeNonRefined(histList) # remove any non-refinable prms from list
constrDictEnt = 'Hist'
elif page[1] == "glb":
vartype = "Global"
varList = G2obj.removeNonRefined(globalList) # remove any non-refinable prms from list
constrDictEnt = 'Global'
elif page[1] == "sym":
return None,None,None
else:
raise Exception('Should not happen!')
return vartype,varList,constrDictEnt
def OnAddHold(event):
'''Create a new Hold constraint
Hold constraints allows the user to select one variable (the list of available
variables depends on which tab is currently active).
'''
page = G2frame.Page
vartype,varList,constrDictEnt = PageSelection(page)
if vartype is None: return
varList = G2obj.SortVariables(varList)
title1 = "Hold "+vartype+" variable"
if not varList:
G2frame.ErrorDialog('No variables','There are no variables of type '+vartype,
parent=G2frame)
return
l2 = l1 = 1
for i in varList:
l1 = max(l1,len(i))
loc,desc = G2obj.VarDescr(i)
l2 = max(l2,len(loc))
fmt = "{:"+str(l1)+"s} {:"+str(l2)+"s} {:s}"
varListlbl = [fmt.format(i,*G2obj.VarDescr(i)) for i in varList]
#varListlbl = ["("+i+") "+G2obj.fmtVarDescr(i) for i in varList]
legend = "Select variables to hold (Will not be varied, even if vary flag is set)"
dlg = G2G.G2MultiChoiceDialog(G2frame,
legend,title1,varListlbl,toggle=False,size=(625,400),monoFont=True)
dlg.CenterOnParent()
if dlg.ShowModal() == wx.ID_OK:
for sel in dlg.GetSelections():
Varb = varList[sel]
VarObj = G2obj.G2VarObj(Varb)
newcons = [[[0.0,VarObj],None,None,'h']]
if CheckAddedConstraint(newcons):
data[constrDictEnt] += newcons
dlg.Destroy()
#wx.CallAfter(OnPageChanged,None)
wx.CallAfter(UpdateConstraints, G2frame, data, G2frame.constr.GetSelection(), True)
def OnAddEquivalence(event):
'''add an Equivalence constraint'''
page = G2frame.Page
vartype,varList,constrDictEnt = PageSelection(page)
if vartype is None: return
title1 = "Create equivalence constraint between "+vartype+" variables"
title2 = "Select additional "+vartype+" variable(s) to be equivalent with "
if not varList:
G2frame.ErrorDialog('No variables','There are no variables of type '+vartype,
parent=G2frame)
return
# legend = "Select variables to make equivalent (only one of the variables will be varied when all are set to be varied)"
GetAddVars(page,title1,title2,varList,constrDictEnt,'equivalence')
def OnAddAtomEquiv(event):
''' Add equivalences between all parameters on atoms '''
page = G2frame.Page
vartype,varList,constrDictEnt = PageSelection(page)
if vartype is None: return
title1 = "Setup equivalent atom variables"
title2 = "Select additional atoms(s) to be equivalent with "
if not varList:
G2frame.ErrorDialog('No variables','There are no variables of type '+vartype,
parent=G2frame)
return
# legend = "Select atoms to make equivalent (only one of the atom variables will be varied when all are set to be varied)"
GetAddAtomVars(page,title1,title2,varList,constrDictEnt,'equivalence')
def OnAddRiding(event):
''' Add riding equivalences between all parameters on atoms - not currently used'''
page = G2frame.Page
vartype,varList,constrDictEnt = PageSelection(page)
if vartype is None: return
title1 = "Setup riding atoms "
title2 = "Select additional atoms(s) to ride on "
if not varList:
G2frame.ErrorDialog('No variables','There are no variables of type '+vartype,
parent=G2frame)
return
# legend = "Select atoms to ride (only one of the atom variables will be varied when all are set to be varied)"
GetAddAtomVars(page,title1,title2,varList,constrDictEnt,'riding')
def OnAddFunction(event):
'''add a Function (new variable) constraint'''
page = G2frame.Page
vartype,varList,constrDictEnt = PageSelection(page)
if vartype is None: return
title1 = "Setup new variable based on "+vartype+" variables"
title2 = "Include additional "+vartype+" variable(s) to be included with "
if not varList:
G2frame.ErrorDialog('No variables','There are no variables of type '+vartype,
parent=G2frame)
return
# legend = "Select variables to include in a new variable (the new variable will be varied when all included variables are varied)"
GetAddVars(page,title1,title2,varList,constrDictEnt,'function')
def OnAddConstraint(event):
'''add a constraint equation to the constraints list'''
page = G2frame.Page
vartype,varList,constrDictEnt = PageSelection(page)
if vartype is None: return
title1 = "Creating constraint on "+vartype+" variables"
title2 = "Select additional "+vartype+" variable(s) to include in constraint with "
if not varList:
G2frame.ErrorDialog('No variables','There are no variables of type '+vartype,
parent=G2frame)
return
# legend = "Select variables to include in a constraint equation (the values will be constrainted to equal a specified constant)"
GetAddVars(page,title1,title2,varList,constrDictEnt,'constraint')
def GetAddVars(page,title1,title2,varList,constrDictEnt,constType):
'''Get the variables to be added for OnAddEquivalence, OnAddFunction,
and OnAddConstraint. Then create and check the constraint.
'''
#varListlbl = ["("+i+") "+G2obj.fmtVarDescr(i) for i in varList]
if constType == 'equivalence':
omitVars = G2mv.GetDependentVars()
else:
omitVars = []
varList = G2obj.SortVariables([i for i in varList if i not in omitVars])
l2 = l1 = 1
for i in varList:
l1 = max(l1,len(i))
loc,desc = G2obj.VarDescr(i)
l2 = max(l2,len(loc))
fmt = "{:"+str(l1)+"s} {:"+str(l2)+"s} {:s}"
varListlbl = [fmt.format(i,*G2obj.VarDescr(i)) for i in varList]
dlg = G2G.G2SingleChoiceDialog(G2frame,'Select 1st variable:',
title1,varListlbl,monoFont=True,size=(625,400))
dlg.CenterOnParent()
if dlg.ShowModal() == wx.ID_OK:
if constType == 'equivalence':
omitVars = G2mv.GetDependentVars() + G2mv.GetIndependentVars()
sel = dlg.GetSelection()
FrstVarb = varList[sel]
VarObj = G2obj.G2VarObj(FrstVarb)
moreVarb = G2obj.SortVariables(FindEquivVarb(FrstVarb,[i for i in varList if i not in omitVars]))
newcons = SelectVarbs(page,VarObj,moreVarb,title2+FrstVarb,constType)
if len(newcons) > 0:
if CheckAddedConstraint(newcons):
data[constrDictEnt] += newcons
dlg.Destroy()
WarnConstraintLimit()
# wx.CallAfter(OnPageChanged,None)
wx.CallAfter(UpdateConstraints, G2frame, data, G2frame.constr.GetSelection(), True)
def FindNeighbors(phase,FrstName,AtNames):
General = phase['General']
cx,ct,cs,cia = General['AtomPtrs']
Atoms = phase['Atoms']
atNames = [atom[ct-1] for atom in Atoms]
Cell = General['Cell'][1:7]
Amat,Bmat = G2lat.cell2AB(Cell)
atTypes = General['AtomTypes']
Radii = np.array(General['BondRadii'])
AtInfo = dict(zip(atTypes,Radii)) #or General['BondRadii']
Orig = atNames.index(FrstName.split()[1])
OType = Atoms[Orig][ct]
XYZ = G2mth.getAtomXYZ(Atoms,cx)
Neigh = []
Dx = np.inner(Amat,XYZ-XYZ[Orig]).T
dist = np.sqrt(np.sum(Dx**2,axis=1))
sumR = AtInfo[OType]+0.5 #H-atoms only!
IndB = ma.nonzero(ma.masked_greater(dist-0.85*sumR,0.))
for j in IndB[0]:
if j != Orig:
Neigh.append(AtNames[j])
return Neigh
def GetAddAtomVars(page,title1,title2,varList,constrDictEnt,constType):
'''Get the atom variables to be added for OnAddAtomEquiv. Then create and
check the constraints. Riding for H atoms only.
'''
Atoms = {G2obj.VarDescr(i)[0]:[] for i in varList if 'Atom' in G2obj.VarDescr(i)[0]}
for item in varList:
atName = G2obj.VarDescr(item)[0]