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 pathGSASIIseqGUI.py
2119 lines (1991 loc) · 98.3 KB
/
GSASIIseqGUI.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 -*-
#GSASIIseqGUI - Sequential Results Display routines
########### SVN repository information ###################
# $Date: 2023-11-13 14:28:09 -0600 (Mon, 13 Nov 2023) $
# $Author: vondreele $
# $Revision: 5700 $
# $URL: https://subversion.xray.aps.anl.gov/pyGSAS/trunk/GSASIIseqGUI.py $
# $Id: GSASIIseqGUI.py 5700 2023-11-13 20:28:09Z vondreele $
########### SVN repository information ###################
'''
Routines for Sequential Results & Cluster Analysis dataframes follow.
'''
from __future__ import division, print_function
import platform
import copy
import re
import numpy as np
import numpy.ma as ma
import numpy.linalg as nl
import scipy.optimize as so
try:
import wx
import wx.grid as wg
except ImportError:
pass
import GSASIIpath
GSASIIpath.SetVersionNumber("$Revision: 5700 $")
import GSASIImath as G2mth
import GSASIIIO as G2IO
import GSASIIdataGUI as G2gd
import GSASIIstrIO as G2stIO
import GSASIIlattice as G2lat
import GSASIIplot as G2plt
import GSASIImapvars as G2mv
import GSASIIobj as G2obj
import GSASIIexprGUI as G2exG
import GSASIIctrlGUI as G2G
WACV = wx.ALIGN_CENTER_VERTICAL
##### Display of Sequential Results ##########################################
def UpdateSeqResults(G2frame,data,prevSize=None):
"""
Called when any data tree entry is selected that has 'Sequential' in the name
to show results from any sequential analysis.
:param wx.Frame G2frame: main GSAS-II data tree windows
:param dict data: a dictionary containing the following items:
* 'histNames' - list of histogram names in order as processed by Sequential Refinement
* 'varyList' - list of variables - identical over all refinements in sequence
note that this is the original list of variables, prior to processing
constraints.
* 'variableLabels' -- a dict of labels to be applied to each parameter
(this is created as an empty dict if not present in data).
* keyed by histName - dictionaries for all data sets processed, which contains:
* 'variables'- result[0] from leastsq call
* 'varyList' - list of variables passed to leastsq call (not same as above)
* 'sig' - esds for variables
* 'covMatrix' - covariance matrix from individual refinement
* 'title' - histogram name; same as dict item name
* 'newAtomDict' - new atom parameters after shifts applied
* 'newCellDict' - refined cell parameters after shifts to A0-A5 from Dij terms applied'
"""
def GetSampleParms():
'''Make a dictionary of the sample parameters that are not the same over the
refinement series. Controls here is local
'''
if 'IMG' in histNames[0]:
sampleParmDict = {'Sample load':[],}
elif 'PDF' in histNames[0]:
sampleParmDict = {'Temperature':[]}
else:
sampleParmDict = {'Temperature':[],'Pressure':[],'Time':[],
'FreePrm1':[],'FreePrm2':[],'FreePrm3':[],'Omega':[],
'Chi':[],'Phi':[],'Azimuth':[],}
Controls = G2frame.GPXtree.GetItemPyData(
G2gd.GetGPXtreeItemId(G2frame,G2frame.root, 'Controls'))
sampleParm = {}
for name in histNames:
if 'IMG' in name or 'PDF' in name:
if name not in data:
continue
for item in sampleParmDict:
sampleParmDict[item].append(data[name]['parmDict'].get(item,0))
else:
if 'PDF' in name:
name = 'PWDR' + name[4:]
Id = G2gd.GetGPXtreeItemId(G2frame,G2frame.root,name)
if Id:
sampleData = G2frame.GPXtree.GetItemPyData(G2gd.GetGPXtreeItemId(G2frame,Id,'Sample Parameters'))
else: # item missing from tree! stick in NaN's!
sampleData = {}
for item in sampleParmDict:
sampleParmDict[item].append(sampleData.get(item,np.NaN))
for item in sampleParmDict:
if sampleParmDict[item]:
frstValue = sampleParmDict[item][0]
if np.any(np.array(sampleParmDict[item])-frstValue):
if item.startswith('FreePrm'):
sampleParm[Controls[item]] = sampleParmDict[item]
else:
sampleParm[item] = sampleParmDict[item]
return sampleParm
def GetColumnInfo(col):
'''returns column label, lists of values and errors (or None) for each column in the table
for plotting. The column label is reformatted from Unicode to MatPlotLib encoding
'''
colName = G2frame.SeqTable.GetColLabelValue(col)
plotName = variableLabels.get(colName,colName)
plotName = plotSpCharFix(plotName)
return plotName,G2frame.colList[col],G2frame.colSigs[col]
def PlotSelectedColRow(calltyp='',event=None):
'''Called to plot a selected column or row by clicking
on a row or column label. N.B. This is called for LB click
after the event is processed so that the column or row has been
selected. For RB clicks, the event is processed here
:param str calltyp: ='left'/'right', specifies if this was
a left- or right-click, where a left click on row
plots histogram; Right click on row plots V-C matrix;
Left or right click on column: plots values in column
:param obj event: from wx.EVT_GRID_LABEL_RIGHT_CLICK
'''
rows = []
cols = []
if calltyp == 'left':
cols = G2frame.dataDisplay.GetSelectedCols()
rows = G2frame.dataDisplay.GetSelectedRows()
elif calltyp == 'right':
r,c = event.GetRow(),event.GetCol()
if r > -1:
rows = [r,]
elif c > -1:
cols = [c,]
if cols and calltyp == 'left':
G2plt.PlotSelectedSequence(G2frame,cols,GetColumnInfo,SelectXaxis)
elif cols and calltyp == 'right':
SetLabelString(cols[0]) #only the 1st one selected!
elif rows and calltyp == 'left':
name = histNames[rows[0]] #only does 1st one selected
if name.startswith('PWDR'):
pickId = G2frame.PickId
G2frame.PickId = G2frame.PatternId = G2gd.GetGPXtreeItemId(G2frame, G2frame.root, name)
G2plt.PlotPatterns(G2frame,newPlot=False,plotType='PWDR')
G2frame.PickId = pickId
elif name.startswith('PDF'):
pickId = G2frame.PickId
G2frame.PickId = G2frame.PatternId = G2gd.GetGPXtreeItemId(G2frame, G2frame.root, name)
PFdata = G2frame.GPXtree.GetItemPyData(G2gd.GetGPXtreeItemId(G2frame,G2frame.PickId,'PDF Controls'))
G2plt.PlotISFG(G2frame,PFdata,plotType='G(R)')
G2frame.PickId = pickId
else:
return
elif rows and calltyp == 'right':
name = histNames[rows[0]] #only does 1st one selected
if name.startswith('PWDR'):
if len(data[name].get('covMatrix',[])):
G2plt.PlotCovariance(G2frame,data[name])
elif name.startswith('PDF'):
print('make structure plot')
else:
G2frame.ErrorDialog(
'Select row or columns',
'Nothing selected in table. Click on column or row label(s) to plot. N.B. Grid selection can be a bit funky.'
)
def SetLabelString(col):
'''Define or edit the label for a column in the table, to be used
as a tooltip and for plotting
'''
if col < 0 or col > len(colLabels):
return
var = colLabels[col]
lbl = variableLabels.get(var,G2obj.fmtVarDescr(var))
head = u'Set a new name for variable {} (column {})'.format(var,col)
dlg = G2G.SingleStringDialog(G2frame,'Set variable label',
head,lbl,size=(400,-1))
if dlg.Show():
variableLabels[var] = dlg.GetValue()
dlg.Destroy()
wx.CallAfter(UpdateSeqResults,G2frame,data) # redisplay variables
else:
dlg.Destroy()
def PlotLeftSelect(event):
'Called by a left MB click on a row or column label. '
event.Skip()
wx.CallAfter(PlotSelectedColRow,'left')
def PlotRightSelect(event):
'Called by a right MB click on a row or column label'
PlotSelectedColRow('right',event)
def OnPlotSelSeq(event):
'plot the selected columns or row from menu command'
cols = sorted(G2frame.dataDisplay.GetSelectedCols()) # ignore selection order
rows = G2frame.dataDisplay.GetSelectedRows()
if cols:
G2plt.PlotSelectedSequence(G2frame,cols,GetColumnInfo,SelectXaxis)
elif rows:
name = histNames[rows[0]] #only does 1st one selected
G2plt.PlotCovariance(G2frame,data[name])
else:
G2frame.ErrorDialog('Select columns',
'No columns or rows selected in table. Click on row or column labels to select fields for plotting.')
def OnAveSelSeq(event):
'average the selected columns from menu command'
cols = sorted(G2frame.dataDisplay.GetSelectedCols()) # ignore selection order
useCol = ~np.array(G2frame.SeqTable.GetColValues(1),dtype=bool)
if cols:
for col in cols:
items = GetColumnInfo(col)[1]
noneMask = np.array([item is None for item in items])
info = ma.array(items,mask=useCol+noneMask)
ave = ma.mean(ma.compressed(info))
sig = ma.std(ma.compressed(info))
print (u' Average for '+G2frame.SeqTable.GetColLabelValue(col)+u': '+'%.6g'%(ave)+u' +/- '+u'%.6g'%(sig))
else:
G2frame.ErrorDialog('Select columns',
'No columns selected in table. Click on column labels to select fields for averaging.')
def OnSelectUse(event):
dlg = G2G.G2MultiChoiceDialog(G2frame, 'Select rows to use','Select rows',histNames)
sellist = [i for i,item in enumerate(G2frame.colList[1]) if item]
dlg.SetSelections(sellist)
if dlg.ShowModal() == wx.ID_OK:
sellist = dlg.GetSelections()
for row in range(G2frame.SeqTable.GetNumberRows()):
G2frame.SeqTable.SetValue(row,1,False)
G2frame.colList[1][row] = False
for row in sellist:
G2frame.SeqTable.SetValue(row,1,True)
G2frame.colList[1][row] = True
G2frame.dataDisplay.ForceRefresh()
dlg.Destroy()
def OnRenameSelSeq(event):
cols = sorted(G2frame.dataDisplay.GetSelectedCols()) # ignore selection order
colNames = [G2frame.SeqTable.GetColLabelValue(c) for c in cols]
newNames = colNames[:]
for i,name in enumerate(colNames):
if name in variableLabels:
newNames[i] = variableLabels[name]
if not cols:
G2frame.ErrorDialog('Select columns',
'No columns selected in table. Click on column labels to select fields for rename.')
return
dlg = G2G.MultiStringDialog(G2frame.dataDisplay,'Set column names',colNames,newNames)
if dlg.Show():
newNames = dlg.GetValues()
variableLabels.update(dict(zip(colNames,newNames)))
data['variableLabels'] = variableLabels
dlg.Destroy()
UpdateSeqResults(G2frame,data,G2frame.dataDisplay.GetSize()) # redisplay variables
G2plt.PlotSelectedSequence(G2frame,cols,GetColumnInfo,SelectXaxis)
def OnSaveSelSeqCSV(event):
'export the selected columns to a .csv file from menu command'
OnSaveSelSeq(event,csv=True)
def OnSaveSeqCSV(event):
'export all columns to a .csv file from menu command'
OnSaveSelSeq(event,csv=True,allcols=True)
def OnSaveSelSeq(event,csv=False,allcols=False):
'export the selected columns to a .txt or .csv file from menu command'
def WriteLine(line):
if '2' in platform.python_version_tuple()[0]:
SeqFile.write(G2obj.StripUnicode(line))
else:
SeqFile.write(line)
def WriteCSV():
def WriteList(headerItems):
line = ''
for lbl in headerItems:
if line: line += ','
line += '"'+lbl+'"'
return line
head = ['name']
for col in cols:
# Excel does not like unicode
item = G2obj.StripUnicode(G2frame.SeqTable.GetColLabelValue(col))
if col in havesig:
head += [item,'esd-'+item]
else:
head += [item]
WriteLine(WriteList(head)+'\n')
for row,name in enumerate(saveNames):
line = '"'+saveNames[row]+'"'
for col in cols:
if saveData[col][row] is None:
if col in havesig:
# line += ',0.0,0.0'
line += ',,'
else:
# line += ',0.0'
line += ','
else:
if col in havesig:
line += ','+str(saveData[col][row])+','+str(saveSigs[col][row])
else:
line += ','+str(saveData[col][row])
WriteLine(line+'\n')
def WriteSeq():
lenName = len(saveNames[0])
line = ' %s '%('name'.center(lenName))
for col in cols:
item = G2frame.SeqTable.GetColLabelValue(col)
if col in havesig:
line += ' %12s %12s '%(item.center(12),'esd'.center(12))
else:
line += ' %12s '%(item.center(12))
WriteLine(line+'\n')
for row,name in enumerate(saveNames):
line = " '%s' "%(saveNames[row])
for col in cols:
if col in havesig:
try:
line += ' %12.6f %12.6f '%(saveData[col][row],saveSigs[col][row])
except TypeError:
line += ' '
else:
try:
line += ' %12.6f '%saveData[col][row]
except TypeError:
line += ' '
WriteLine(line+'\n')
# start of OnSaveSelSeq code
if allcols:
cols = range(G2frame.SeqTable.GetNumberCols())
else:
cols = sorted(G2frame.dataDisplay.GetSelectedCols()) # ignore selection order
nrows = G2frame.SeqTable.GetNumberRows()
if not cols:
choices = [G2frame.SeqTable.GetColLabelValue(r) for r in range(G2frame.SeqTable.GetNumberCols())]
dlg = G2G.G2MultiChoiceDialog(G2frame, 'Select columns to write',
'select columns',choices)
#dlg.SetSelections()
if dlg.ShowModal() == wx.ID_OK:
cols = dlg.GetSelections()
dlg.Destroy()
else:
dlg.Destroy()
return
#G2frame.ErrorDialog('Select columns',
# 'No columns selected in table. Click on column labels to select fields for output.')
#return
saveNames = [G2frame.SeqTable.GetRowLabelValue(r) for r in range(nrows)]
saveData = {}
saveSigs = {}
havesig = []
for col in cols:
name,vals,sigs = GetColumnInfo(col)
saveData[col] = vals
if sigs:
havesig.append(col)
saveSigs[col] = sigs
if csv:
wild = 'CSV output file (*.csv)|*.csv'
else:
wild = 'Text output file (*.txt)|*.txt'
pth = G2G.GetExportPath(G2frame)
dlg = wx.FileDialog(
G2frame,
'Choose text output file for your selection', pth, '',
wild,wx.FD_SAVE|wx.FD_OVERWRITE_PROMPT)
try:
if dlg.ShowModal() == wx.ID_OK:
SeqTextFile = dlg.GetPath()
SeqTextFile = G2IO.FileDlgFixExt(dlg,SeqTextFile)
SeqFile = open(SeqTextFile,'w')
if csv:
WriteCSV()
else:
WriteSeq()
SeqFile.close()
finally:
dlg.Destroy()
def striphist(var,insChar=''):
'strip a histogram number from a var name'
sv = var.split(':')
if len(sv) <= 1: return var
if sv[1]:
sv[1] = insChar
return ':'.join(sv)
def plotSpCharFix(lbl):
'Change selected unicode characters to their matplotlib equivalent'
for u,p in [
(u'\u03B1',r'$\alpha$'),
(u'\u03B2',r'$\beta$'),
(u'\u03B3',r'$\gamma$'),
(u'\u0394\u03C7',r'$\Delta\chi$'),
]:
lbl = lbl.replace(u,p)
return lbl
def SelectXaxis():
'returns a selected column number (or None) as the X-axis selection'
ncols = G2frame.SeqTable.GetNumberCols()
colNames = [G2frame.SeqTable.GetColLabelValue(r) for r in range(ncols)]
dlg = G2G.G2SingleChoiceDialog(
G2frame.dataDisplay,
'Select x-axis parameter for\nplot (Cancel=sequence #)',
'Select X-axis',
colNames)
try:
if dlg.ShowModal() == wx.ID_OK:
col = dlg.GetSelection()
else:
col = None
finally:
dlg.Destroy()
return col
def EnablePseudoVarMenus():
'Enables or disables the PseudoVar menu items that require existing defs'
if data['SeqPseudoVars']:
val = True
else:
val = False
G2frame.dataWindow.SequentialPvars.Enable(G2G.wxID_DELSEQVAR,val)
G2frame.dataWindow.SequentialPvars.Enable(G2G.wxID_EDITSEQVAR,val)
def DelPseudoVar(event):
'Ask the user to select a pseudo var expression to delete'
choices = list(data['SeqPseudoVars'].keys())
selected = G2G.ItemSelector(
choices,G2frame,
multiple=True,
title='Select expressions to remove',
header='Delete expression')
if selected is None: return
for item in selected:
del data['SeqPseudoVars'][choices[item]]
if selected:
UpdateSeqResults(G2frame,data,G2frame.dataDisplay.GetSize()) # redisplay variables
def EditPseudoVar(event):
'Edit an existing pseudo var expression'
choices = list(data['SeqPseudoVars'].keys())
if len(choices) == 1:
selected = 0
else:
selected = G2G.ItemSelector(
choices,G2frame,
multiple=False,
title='Select an expression to edit',
header='Edit expression')
if selected is not None:
dlg = G2exG.ExpressionDialog(
G2frame.dataDisplay,PSvarDict,
data['SeqPseudoVars'][choices[selected]],
header="Edit the PseudoVar expression",
VarLabel="PseudoVar #"+str(selected+1),
fit=False)
newobj = dlg.Show(True)
if newobj:
calcobj = G2obj.ExpressionCalcObj(newobj)
del data['SeqPseudoVars'][choices[selected]]
data['SeqPseudoVars'][calcobj.eObj.expression] = newobj
UpdateSeqResults(G2frame,data,G2frame.dataDisplay.GetSize()) # redisplay variables
def AddNewPseudoVar(event):
'Create a new pseudo var expression'
dlg = G2exG.ExpressionDialog(G2frame.dataDisplay,PSvarDict,
header='Enter an expression for a PseudoVar here',
VarLabel = "New PseudoVar",fit=False)
obj = dlg.Show(True)
dlg.Destroy()
if obj:
calcobj = G2obj.ExpressionCalcObj(obj)
data['SeqPseudoVars'][calcobj.eObj.expression] = obj
UpdateSeqResults(G2frame,data,G2frame.dataDisplay.GetSize()) # redisplay variables
def AddNewDistPseudoVar(event):
obj = None
dlg = G2exG.BondDialog(
G2frame.dataDisplay,Phases,PSvarDict,
VarLabel = "New Bond")
if dlg.ShowModal() == wx.ID_OK:
pName,Oatom,Tatom = dlg.GetSelection()
if Tatom:
Phase = Phases[pName]
General = Phase['General']
cx,ct = General['AtomPtrs'][:2]
pId = Phase['pId']
SGData = General['SGData']
sB = Tatom.find('(')+1
symNo = 0
if sB:
sF = Tatom.find(')')
symNo = int(Tatom[sB:sF])
cellNo = [0,0,0]
cB = Tatom.find('[')
if cB>0:
cF = Tatom.find(']')+1
cellNo = eval(Tatom[cB:cF])
Atoms = Phase['Atoms']
aNames = [atom[ct-1] for atom in Atoms]
oId = aNames.index(Oatom)
tId = aNames.index(Tatom.split(' +')[0])
# create an expression object
obj = G2obj.ExpressionObj()
obj.expression = 'Dist(%s,\n%s)'%(Oatom,Tatom.split(' d=')[0].replace(' ',''))
obj.distance_dict = {'pId':pId,'SGData':SGData,'symNo':symNo,'cellNo':cellNo}
obj.distance_atoms = [oId,tId]
else:
dlg.Destroy()
return
dlg.Destroy()
if obj:
data['SeqPseudoVars'][obj.expression] = obj
UpdateSeqResults(G2frame,data,G2frame.dataDisplay.GetSize()) # redisplay variables
def AddNewAnglePseudoVar(event):
obj = None
dlg = G2exG.AngleDialog(
G2frame.dataDisplay,Phases,PSvarDict,
header='Enter an Angle here',
VarLabel = "New Angle")
if dlg.ShowModal() == wx.ID_OK:
pName,Oatom,Tatoms = dlg.GetSelection()
if Tatoms:
obj = G2obj.makeAngleObj(Phases[pName],Oatom,Tatoms)
else:
dlg.Destroy()
return
dlg.Destroy()
if obj:
data['SeqPseudoVars'][obj.expression] = obj
UpdateSeqResults(G2frame,data,G2frame.dataDisplay.GetSize()) # redisplay variables
def UpdateParmDict(parmDict):
'''generate the atom positions and the direct & reciprocal cell values,
because they might be needed to evaluate the pseudovar
#TODO - effect of ISO modes?
'''
Ddict = dict(zip(['D11','D22','D33','D12','D13','D23'],
['A'+str(i) for i in range(6)])
)
delList = []
phaselist = []
for item in parmDict:
if ':' not in item: continue
key = item.split(':')
if len(key) < 3: continue
# remove the dA[xyz] terms, they would only bring confusion
if key[0] and key[0] not in phaselist: phaselist.append(key[0])
if key[2].startswith('dA'):
delList.append(item)
# compute and update the corrected reciprocal cell terms using the Dij values
elif key[2] in Ddict:
akey = key[0]+'::'+Ddict[key[2]]
parmDict[akey] += parmDict[item]
delList.append(item)
for item in delList:
del parmDict[item]
for i in phaselist:
pId = int(i)
# apply cell symmetry
try:
A,zeros = G2stIO.cellFill(str(pId)+'::',SGdata[pId],parmDict,zeroDict[pId])
# convert to direct cell & add the unique terms to the dictionary
try:
dcell = G2lat.A2cell(A)
except:
print('phase',pId,'Invalid cell tensor',A)
raise ValueError('Invalid cell tensor in phase '+str(pId))
for i,val in enumerate(dcell):
if i in uniqCellIndx[pId]:
lbl = str(pId)+'::'+G2lat.cellUlbl[i]
parmDict[lbl] = val
lbl = str(pId)+'::'+'Vol'
parmDict[lbl] = G2lat.calc_V(A)
except KeyError:
pass
return parmDict
def EvalPSvarDeriv(calcobj,parmDict,sampleDict,var,ESD):
'''Evaluate an expression derivative with respect to a
GSAS-II variable name.
Note this likely could be faster if the loop over calcobjs were done
inside after the Dict was created.
'''
if not ESD:
return 0.
step = ESD/10
Ddict = dict(zip(['D11','D22','D33','D12','D13','D23'],
['A'+str(i) for i in range(6)])
)
results = []
phaselist = []
VparmDict = sampleDict.copy()
for incr in step,-step:
VparmDict.update(parmDict.copy())
# as saved, the parmDict has updated 'A[xyz]' values, but 'dA[xyz]'
# values are not zeroed: fix that!
VparmDict.update({item:0.0 for item in parmDict if 'dA' in item})
VparmDict[var] += incr
G2mv.Dict2Map(VparmDict) # apply constraints
# generate the atom positions and the direct & reciprocal cell values now, because they might
# needed to evaluate the pseudovar
for item in VparmDict:
if item in sampleDict:
continue
if ':' not in item: continue
key = item.split(':')
if len(key) < 3: continue
# apply any new shifts to atom positions
if key[2].startswith('dA'):
VparmDict[''.join(item.split('d'))] += VparmDict[item]
VparmDict[item] = 0.0
# compute and update the corrected reciprocal cell terms using the Dij values
if key[2] in Ddict:
if key[0] not in phaselist: phaselist.append(key[0])
akey = key[0]+'::'+Ddict[key[2]]
VparmDict[akey] += VparmDict[item]
for i in phaselist:
pId = int(i)
# apply cell symmetry
try:
A,zeros = G2stIO.cellFill(str(pId)+'::',SGdata[pId],VparmDict,zeroDict[pId])
# convert to direct cell & add the unique terms to the dictionary
for i,val in enumerate(G2lat.A2cell(A)):
if i in uniqCellIndx[pId]:
lbl = str(pId)+'::'+G2lat.cellUlbl[i]
VparmDict[lbl] = val
lbl = str(pId)+'::'+'Vol'
VparmDict[lbl] = G2lat.calc_V(A)
except KeyError:
pass
# dict should be fully updated, use it & calculate
calcobj.SetupCalc(VparmDict)
results.append(calcobj.EvalExpression())
if None in results:
return None
return (results[0] - results[1]) / (2.*step)
def EnableParFitEqMenus():
'Enables or disables the Parametric Fit menu items that require existing defs'
if data['SeqParFitEqList']:
val = True
else:
val = False
G2frame.dataWindow.SequentialPfit.Enable(G2G.wxID_DELPARFIT,val)
G2frame.dataWindow.SequentialPfit.Enable(G2G.wxID_EDITPARFIT,val)
G2frame.dataWindow.SequentialPfit.Enable(G2G.wxID_DOPARFIT,val)
def ParEqEval(Values,calcObjList,varyList):
'''Evaluate the parametric expression(s)
:param list Values: a list of values for each variable parameter
:param list calcObjList: a list of :class:`GSASIIobj.ExpressionCalcObj`
expression objects to evaluate
:param list varyList: a list of variable names for each value in Values
'''
result = []
for calcobj in calcObjList:
calcobj.UpdateVars(varyList,Values)
if calcobj.depSig:
result.append((calcobj.depVal-calcobj.EvalExpression())/calcobj.depSig)
else:
result.append(calcobj.depVal-calcobj.EvalExpression())
return result
def DoParEqFit(event,eqObj=None):
'Parametric fit minimizer'
varyValueDict = {} # dict of variables and their initial values
calcObjList = [] # expression objects, ready to go for each data point
if eqObj is not None:
eqObjList = [eqObj,]
else:
eqObjList = data['SeqParFitEqList']
UseFlags = G2frame.SeqTable.GetColValues(1)
for obj in eqObjList:
# assemble refined vars for this equation
varyValueDict.update({var:val for var,val in obj.GetVariedVarVal()})
# lookup dependent var position
depVar = obj.GetDepVar()
if depVar in colLabels:
indx = colLabels.index(depVar)
else:
raise Exception('Dependent variable '+depVar+' not found')
# assemble a list of the independent variables
indepVars = obj.GetIndependentVars()
# loop over each datapoint
for j,row in enumerate(zip(*G2frame.colList)):
if not UseFlags[j]: continue
# assemble equations to fit
calcobj = G2obj.ExpressionCalcObj(obj)
# prepare a dict of needed independent vars for this expression
indepVarDict = {var:row[i] for i,var in enumerate(colLabels) if var in indepVars}
calcobj.SetupCalc(indepVarDict)
# values and sigs for current value of dependent var
if row[indx] is None: continue
calcobj.depVal = row[indx]
if G2frame.colSigs[indx]:
calcobj.depSig = G2frame.colSigs[indx][j]
else:
calcobj.depSig = 1.
calcObjList.append(calcobj)
# varied parameters
varyList = varyValueDict.keys()
values = varyValues = [varyValueDict[key] for key in varyList]
if not varyList:
print ('no variables to refine!')
return
try:
result = so.leastsq(ParEqEval,varyValues,full_output=True, #ftol=Ftol,
args=(calcObjList,varyList))
values = result[0]
covar = result[1]
if covar is None:
raise Exception
chisq = np.sum(result[2]['fvec']**2)
GOF = np.sqrt(chisq/(len(calcObjList)-len(varyList)))
esdDict = {}
for i,avar in enumerate(varyList):
esdDict[avar] = np.sqrt(covar[i,i])
except:
print('====> Fit failed')
return
print('==== Fit Results ====')
print (' chisq = %.2f, GOF = %.2f'%(chisq,GOF))
for obj in eqObjList:
obj.UpdateVariedVars(varyList,values)
ind = ' '
print(u' '+obj.GetDepVar()+u' = '+obj.expression)
for var in obj.assgnVars:
print(ind+var+u' = '+obj.assgnVars[var])
for var in obj.freeVars:
avar = "::"+obj.freeVars[var][0]
val = obj.freeVars[var][1]
if obj.freeVars[var][2]:
print(ind+var+u' = '+avar + " = " + G2mth.ValEsd(val,esdDict[avar]))
else:
print(ind+var+u' = '+avar + u" =" + G2mth.ValEsd(val,0))
# create a plot for each parametric variable
for fitnum,obj in enumerate(eqObjList):
calcobj = G2obj.ExpressionCalcObj(obj)
# lookup dependent var position
indx = colLabels.index(obj.GetDepVar())
# assemble a list of the independent variables
indepVars = obj.GetIndependentVars()
# loop over each datapoint
fitvals = []
for j,row in enumerate(zip(*G2frame.colList)):
calcobj.SetupCalc({var:row[i] for i,var in enumerate(colLabels) if var in indepVars})
fitvals.append(calcobj.EvalExpression())
G2plt.PlotSelectedSequence(G2frame,[indx],GetColumnInfo,SelectXaxis,fitnum,fitvals)
def SingleParEqFit(eqObj):
DoParEqFit(None,eqObj)
def DelParFitEq(event):
'Ask the user to select function to delete'
txtlst = [obj.GetDepVar()+' = '+obj.expression for obj in data['SeqParFitEqList']]
selected = G2G.ItemSelector(
txtlst,G2frame,
multiple=True,
title='Select a parametric equation(s) to remove',
header='Delete equation')
if selected is None: return
data['SeqParFitEqList'] = [obj for i,obj in enumerate(data['SeqParFitEqList']) if i not in selected]
EnableParFitEqMenus()
if data['SeqParFitEqList']: DoParEqFit(event)
def EditParFitEq(event):
'Edit an existing parametric equation'
txtlst = [obj.GetDepVar()+' = '+obj.expression for obj in data['SeqParFitEqList']]
if len(txtlst) == 1:
selected = 0
else:
selected = G2G.ItemSelector(
txtlst,G2frame,
multiple=False,
title='Select a parametric equation to edit',
header='Edit equation')
if selected is not None:
dlg = G2exG.ExpressionDialog(G2frame.dataDisplay,VarDict,
data['SeqParFitEqList'][selected],depVarDict=VarDict,
header="Edit the formula for this minimization function",
ExtraButton=['Fit',SingleParEqFit],wildCard=False)
newobj = dlg.Show(True)
if newobj:
data['SeqParFitEqList'][selected] = newobj
EnableParFitEqMenus()
if data['SeqParFitEqList']: DoParEqFit(event)
def AddNewParFitEq(event):
'Create a new parametric equation to be fit to sequential results'
# compile the variable names used in previous freevars to avoid accidental name collisions
usedvarlist = []
for obj in data['SeqParFitEqList']:
for var in obj.freeVars:
if obj.freeVars[var][0] not in usedvarlist: usedvarlist.append(obj.freeVars[var][0])
dlg = G2exG.ExpressionDialog(G2frame.dataDisplay,VarDict,depVarDict=VarDict,
header='Define an equation to minimize in the parametric fit',
ExtraButton=['Fit',SingleParEqFit],usedVars=usedvarlist,wildCard=False)
obj = dlg.Show(True)
dlg.Destroy()
if obj:
data['SeqParFitEqList'].append(obj)
EnableParFitEqMenus()
if data['SeqParFitEqList']: DoParEqFit(event)
def CopyParFitEq(event):
'Copy an existing parametric equation to be fit to sequential results'
# compile the variable names used in previous freevars to avoid accidental name collisions
usedvarlist = []
for obj in data['SeqParFitEqList']:
for var in obj.freeVars:
if obj.freeVars[var][0] not in usedvarlist: usedvarlist.append(obj.freeVars[var][0])
txtlst = [obj.GetDepVar()+' = '+obj.expression for obj in data['SeqParFitEqList']]
if len(txtlst) == 1:
selected = 0
else:
selected = G2G.ItemSelector(
txtlst,G2frame,
multiple=False,
title='Select a parametric equation to copy',
header='Copy equation')
if selected is not None:
newEqn = copy.deepcopy(data['SeqParFitEqList'][selected])
for var in newEqn.freeVars:
newEqn.freeVars[var][0] = G2obj.MakeUniqueLabel(newEqn.freeVars[var][0],usedvarlist)
dlg = G2exG.ExpressionDialog(
G2frame.dataDisplay,VarDict,newEqn,depVarDict=VarDict,
header="Edit the formula for this minimization function",
ExtraButton=['Fit',SingleParEqFit],wildCard=False)
newobj = dlg.Show(True)
if newobj:
data['SeqParFitEqList'].append(newobj)
EnableParFitEqMenus()
if data['SeqParFitEqList']: DoParEqFit(event)
def GridSetToolTip(row,col):
'''Routine to show standard uncertainties for each element in table
as a tooltip
'''
if G2frame.colSigs[col]:
if G2frame.colSigs[col][row] == -0.1: return 'frozen'
return u'\u03c3 = '+str(G2frame.colSigs[col][row])
return ''
def GridColLblToolTip(col):
'''Define a tooltip for a column. This will be the user-entered value
(from data['variableLabels']) or the default name
'''
if col < 0 or col > len(colLabels):
print ('Illegal column #%d'%col)
return
var = colLabels[col]
return variableLabels.get(var,G2obj.fmtVarDescr(var))
def DoSequentialExport(event):
'''Event handler for all Sequential Export menu items
'''
if event.GetId() == G2G.wxID_XPORTSEQFCIF:
G2IO.ExportSequentialFullCIF(G2frame,data,Controls)
return
vals = G2frame.dataWindow.SeqExportLookup.get(event.GetId())
if vals is None:
print('Error: Id not found. This should not happen!')
return
G2IO.ExportSequential(G2frame,data,*vals)
def onSelectSeqVars(event):
'''Select which variables will be shown in table'''
hides = [saveColLabels[2:].index(item) for item in G2frame.SeqTblHideList if
item in saveColLabels[2:]]
dlg = G2G.G2MultiChoiceDialog(G2frame, 'Select columns to hide',
'Hide columns',saveColLabels[2:])
dlg.SetSelections(hides)
if dlg.ShowModal() == wx.ID_OK:
G2frame.SeqTblHideList = [saveColLabels[2:][sel] for sel in dlg.GetSelections()]
dlg.Destroy()
UpdateSeqResults(G2frame,data,G2frame.dataDisplay.GetSize()) # redisplay variables
else:
dlg.Destroy()
def OnCellChange(event):
c = event.GetCol()
if c != 1: return
r = event.GetRow()
val = G2frame.SeqTable.GetValue(r,c)
data['Use'][r] = val
G2frame.SeqTable.SetValue(r,c, val)
def OnSelectUpdate(event):
'''Update all phase parameters from a selected column in the Sequential Table.
If no histogram is selected (or more than one), ask the user to make a selection.
Loosely based on :func:`GSASIIstrIO.SetPhaseData`
#TODO effect of ISO modes?
'''
rows = G2frame.dataDisplay.GetSelectedRows()
if len(rows) == 1:
sel = rows[0]
else:
dlg = G2G.G2SingleChoiceDialog(G2frame, 'Select a histogram to\nupdate phase from',
'Select row',histNames)
if dlg.ShowModal() == wx.ID_OK:
sel = dlg.GetSelection()
dlg.Destroy()
else:
dlg.Destroy()
return
parmDict = data[histNames[sel]]['parmDict']
Histograms,Phases = G2frame.GetUsedHistogramsAndPhasesfromTree()
for phase in Phases:
print('Updating {} from Seq. Ref. row {}'.format(phase,histNames[sel]))
Phase = Phases[phase]
General = Phase['General']
SGData = General['SGData']
Atoms = Phase['Atoms']
cell = General['Cell']
pId = Phase['pId']
pfx = str(pId)+'::'
# there should not be any changes to the cell because those terms are not refined
A,sigA = G2stIO.cellFill(pfx,SGData,parmDict,{})
cell[1:7] = G2lat.A2cell(A)
cell[7] = G2lat.calc_V(A)
textureData = General['SH Texture']
if textureData['Order']:
for name in ['omega','chi','phi']:
aname = pfx+'SH '+name
textureData['Sample '+name][1] = parmDict[aname]
for name in textureData['SH Coeff'][1]:
aname = pfx+name
textureData['SH Coeff'][1][name] = parmDict[aname]
ik = 6 #for Pawley stuff below
if General.get('Modulated',False):
ik = 7
# how are these updated?
#General['SuperVec']
#RBModels = Phase['RBModels']
if Phase['General'].get('doPawley'):
pawleyRef = Phase['Pawley ref']
for i,refl in enumerate(pawleyRef):
key = pfx+'PWLref:'+str(i)
refl[ik] = parmDict[key]
# if key in sigDict: #TODO: error here sigDict not defined. What was intended?
# refl[ik+1] = sigDict[key]
# else:
# refl[ik+1] = 0
continue
cx,ct,cs,cia = General['AtomPtrs']
for i,at in enumerate(Atoms):
names = {cx:pfx+'Ax:'+str(i),cx+1:pfx+'Ay:'+str(i),cx+2:pfx+'Az:'+str(i),cx+3:pfx+'Afrac:'+str(i),
cia+1:pfx+'AUiso:'+str(i),cia+2:pfx+'AU11:'+str(i),cia+3:pfx+'AU22:'+str(i),cia+4:pfx+'AU33:'+str(i),
cia+5:pfx+'AU12:'+str(i),cia+6:pfx+'AU13:'+str(i),cia+7:pfx+'AU23:'+str(i),
cx+4:pfx+'AMx:'+str(i),cx+5:pfx+'AMy:'+str(i),cx+6:pfx+'AMz:'+str(i)}
for ind in range(cx,cx+4):
at[ind] = parmDict[names[ind]]
if at[cia] == 'I':
at[cia+1] = parmDict[names[cia+1]]
else:
for ind in range(cia+2,cia+8):
at[ind] = parmDict[names[ind]]
if General['Type'] == 'magnetic':
for ind in range(cx+4,cx+7):
at[ind] = parmDict[names[ind]]
ind = General['AtomTypes'].index(at[ct])
if General.get('Modulated',False):
AtomSS = at[-1]['SS1']
waveType = AtomSS['waveType']
for Stype in ['Sfrac','Spos','Sadp','Smag']:
Waves = AtomSS[Stype]
for iw,wave in enumerate(Waves):
stiw = str(i)+':'+str(iw)
if Stype == 'Spos':
if waveType in ['ZigZag','Block',] and not iw:
names = ['Tmin:'+stiw,'Tmax:'+stiw,'Xmax:'+stiw,'Ymax:'+stiw,'Zmax:'+stiw]
else:
names = ['Xsin:'+stiw,'Ysin:'+stiw,'Zsin:'+stiw,
'Xcos:'+stiw,'Ycos:'+stiw,'Zcos:'+stiw]
elif Stype == 'Sadp':
names = ['U11sin:'+stiw,'U22sin:'+stiw,'U33sin:'+stiw,
'U12sin:'+stiw,'U13sin:'+stiw,'U23sin:'+stiw,
'U11cos:'+stiw,'U22cos:'+stiw,'U33cos:'+stiw,
'U12cos:'+stiw,'U13cos:'+stiw,'U23cos:'+stiw]
elif Stype == 'Sfrac':
if 'Crenel' in waveType and not iw:
names = ['Fzero:'+stiw,'Fwid:'+stiw]
else:
names = ['Fsin:'+stiw,'Fcos:'+stiw]
elif Stype == 'Smag':
names = ['MXsin:'+stiw,'MYsin:'+stiw,'MZsin:'+stiw,