This repository was 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
Expand file tree
/
Copy pathGSASIIpwdGUI.py
More file actions
8988 lines (8498 loc) · 435 KB
/
GSASIIpwdGUI.py
File metadata and controls
8988 lines (8498 loc) · 435 KB
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 -*-
#GSASIIpwdGUI - powder data display routines
########### SVN repository information ###################
# $Date: 2024-02-21 22:58:44 -0600 (Wed, 21 Feb 2024) $
# $Author: toby $
# $Revision: 5737 $
# $URL: https://subversion.xray.aps.anl.gov/pyGSAS/trunk/GSASIIpwdGUI.py $
# $Id: GSASIIpwdGUI.py 5737 2024-02-22 04:58:44Z toby $
########### SVN repository information ###################
'''GUI routines for PWDR datadree subitems follow.
'''
from __future__ import division, print_function
import platform
import sys
import os.path
# Don't depend on graphics for scriptable
try:
import wx
import wx.grid as wg
except ImportError:
pass
import numpy as np
import numpy.linalg as nl
import numpy.ma as ma
import math
import copy
import random as ran
if '2' in platform.python_version_tuple()[0]:
import cPickle
else:
import pickle as cPickle
import scipy.interpolate as si
import GSASIIpath
GSASIIpath.SetVersionNumber("$Revision: 5737 $")
import GSASIImath as G2mth
import GSASIIpwd as G2pwd
import GSASIIfiles as G2fil
import GSASIIobj as G2obj
import GSASIIlattice as G2lat
import GSASIIspc as G2spc
import GSASIIindex as G2indx
import GSASIIplot as G2plt
import GSASIIdataGUI as G2gd
import GSASIIphsGUI as G2phsG
import GSASIIctrlGUI as G2G
import GSASIIElemGUI as G2elemGUI
import GSASIIElem as G2elem
import GSASIIsasd as G2sasd
import G2shapes
import SUBGROUPS as kSUB
try:
VERY_LIGHT_GREY = wx.SystemSettings.GetColour(wx.SYS_COLOUR_BTNFACE)
WACV = wx.ALIGN_CENTER_VERTICAL
except:
pass
if '2' not in platform.python_version_tuple()[0]:
unichr = chr
GkDelta = unichr(0x0394)
GkSigma = unichr(0x03a3)
GkTheta = unichr(0x03f4)
Gklambda = unichr(0x03bb)
Pwr10 = unichr(0x0b9)+unichr(0x2070)
Pwr20 = unichr(0x0b2)+unichr(0x2070)
Pwrm1 = unichr(0x207b)+unichr(0x0b9)
Pwrm2 = unichr(0x207b)+unichr(0x0b2)
Pwrm6 = unichr(0x207b)+unichr(0x2076)
Pwrm4 = unichr(0x207b)+unichr(0x2074)
Angstr = unichr(0x00c5)
superMinusOne = unichr(0xaf)+unichr(0xb9)
notEq0 = unichr(0x2260)+'0'
# trig functions in degrees
sind = lambda x: math.sin(x*math.pi/180.)
tand = lambda x: math.tan(x*math.pi/180.)
cosd = lambda x: math.cos(x*math.pi/180.)
asind = lambda x: 180.*math.asin(x)/math.pi
################################################################################
###### class definitions
################################################################################
class SubCellsDialog(wx.Dialog):
'Display magnetic subcell space group information from selection in Unit Cells table of results from k-SUBGROUPSMAG'
def __init__(self,parent,title,controls,SGData,items,phaseDict):
wx.Dialog.__init__(self,parent,-1,title,
pos=wx.DefaultPosition,style=wx.DEFAULT_DIALOG_STYLE)
self.panel = None
self.controls = controls
self.SGData = SGData #for parent phase
self.items = items
self.phaseDict = phaseDict
self.Draw()
def Draw(self):
def RefreshGrid(event):
r,c = event.GetRow(),event.GetCol()
br = self.items[r]
phase = self.phaseDict[br]
rLab = magDisplay.GetRowLabelValue(r)
pname = '(%s) %s'%(rLab,phase['Name'])
if c == 0:
mSGData = phase['SGData']
text,table = G2spc.SGPrint(mSGData,AddInv=True)
if 'magAtms' in phase:
msg = 'Magnetic space group information'
text[0] = ' Magnetic Space Group: '+mSGData['MagSpGrp']
text[3] = ' The magnetic lattice point group is '+mSGData['MagPtGp']
OprNames,SpnFlp = G2spc.GenMagOps(mSGData)
G2G.SGMagSpinBox(self.panel,msg,text,table,mSGData['SGCen'],OprNames,
mSGData['SpnFlp'],False).Show()
else:
msg = 'Space Group Information'
G2G.SGMessageBox(self.panel,msg,text,table).Show()
elif c == 1:
maxequiv = phase['maxequiv']
mSGData = phase['SGData']
Uvec = phase['Uvec']
Trans = phase['Trans']
ifMag = False
if 'magAtms' in phase:
ifMag = True
allmom = phase.get('allmom',False)
magAtms = phase.get('magAtms','')
mAtoms = TestMagAtoms(phase,magAtms,self.SGData,Uvec,Trans,allmom,maxequiv)
else:
mAtoms = TestAtoms(phase,self.controls[15],self.SGData,Uvec,Trans,maxequiv)
Atms = []
AtCods = []
atMxyz = []
for ia,atom in enumerate(mAtoms):
atom[0] += '_%d'%ia
SytSym,Mul,Nop,dupDir = G2spc.SytSym(atom[2:5],mSGData)
Atms.append(atom[:2]+['',]+atom[2:5])
AtCods.append('1')
if 'magAtms' in phase:
MagSytSym = G2spc.MagSytSym(SytSym,dupDir,mSGData)
CSI = G2spc.GetCSpqinel(mSGData['SpnFlp'],dupDir)
atMxyz.append([MagSytSym,CSI[0]])
else:
CSI = G2spc.GetCSxinel(SytSym)
atMxyz.append([SytSym,CSI[0]])
G2phsG.UseMagAtomDialog(self.panel,pname,Atms,AtCods,atMxyz,ifMag=ifMag,ifOK=True).Show()
elif c in [2,3]:
if c == 2:
title = 'Conjugacy list for '+pname
items = phase['altList']
elif c == 3:
title = 'Super groups list list for '+pname
items = phase['supList']
if not items[0]:
wx.MessageBox(pname+' is a maximal subgroup',caption='Super group is parent',style=wx.ICON_INFORMATION)
return
SubCellsDialog(self.panel,title,self.controls,self.SGData,items,self.phaseDict).Show()
if self.panel: self.panel.Destroy()
self.panel = wx.Panel(self)
rowLabels = [str(i+1) for i in range(len(self.items))]
colLabels = ['Space Gp','Uniq','nConj','nSup','Trans','Vec','a','b','c','alpha','beta','gamma','Volume']
Types = [wg.GRID_VALUE_STRING,]+3*[wg.GRID_VALUE_LONG,]+2*[wg.GRID_VALUE_STRING,]+ \
3*[wg.GRID_VALUE_FLOAT+':10,5',]+3*[wg.GRID_VALUE_FLOAT+':10,3',]+[wg.GRID_VALUE_FLOAT+':10,2']
table = []
for ip in self.items:
phase = self.phaseDict[ip]
natms = phase.get('nAtoms',1)
try:
nConj = len(phase['altList'])
nSup = len(phase['supList'])
except KeyError:
nConj = 0
nSup = 0
cell = list(phase['Cell'])
trans = G2spc.Trans2Text(phase['Trans'])
vec = G2spc.Latt2text([phase['Uvec'],])
row = [phase['Name'],natms,nConj,nSup,trans,vec]+cell
table.append(row)
CellsTable = G2G.Table(table,rowLabels=rowLabels,colLabels=colLabels,types=Types)
mainSizer = wx.BoxSizer(wx.VERTICAL)
magDisplay = G2G.GSGrid(self.panel)
magDisplay.SetTable(CellsTable, True)
magDisplay.Bind(wg.EVT_GRID_CELL_LEFT_CLICK,RefreshGrid)
magDisplay.AutoSizeColumns(False)
mainSizer.Add(magDisplay,0)
OkBtn = wx.Button(self.panel,-1,"Ok")
OkBtn.Bind(wx.EVT_BUTTON, self.OnOk)
btnSizer = wx.BoxSizer(wx.HORIZONTAL)
btnSizer.Add((20,20),1)
btnSizer.Add(OkBtn)
btnSizer.Add((20,20),1)
mainSizer.Add(btnSizer,0,wx.EXPAND|wx.BOTTOM|wx.TOP, 10)
self.panel.SetSizer(mainSizer)
self.panel.Fit()
self.Fit()
def OnOk(self,event):
parent = self.GetParent()
parent.Raise()
self.Destroy()
# self.EndModal(wx.ID_OK)
class RDFDialog(wx.Dialog):
'Display controls for generating RDF plot in Background'
def __init__(self,parent):
wx.Dialog.__init__(self,parent,-1,'Background radial distribution function',
pos=wx.DefaultPosition,style=wx.DEFAULT_DIALOG_STYLE)
self.panel = None
self.result = {'UseObsCalc':'obs-calc','maxR':20.0,'Smooth':'linear'}
self.Draw()
def Draw(self):
def OnUseOC(event):
self.result['UseObsCalc'] = useOC.GetValue()
def OnSmCombo(event):
self.result['Smooth'] = smCombo.GetValue()
if self.panel: self.panel.Destroy()
self.panel = wx.Panel(self)
mainSizer = wx.BoxSizer(wx.VERTICAL)
mainSizer.Add(wx.StaticText(self.panel,label='Background RDF controls:'),0)
plotType = wx.BoxSizer(wx.HORIZONTAL)
plotType.Add(wx.StaticText(self.panel,label=' Select plot type:'),0,WACV)
Choices = ['obs-back','calc-back','obs-calc','auto-back']
useOC = wx.ComboBox(self.panel,value=Choices[2],choices=Choices,
style=wx.CB_READONLY|wx.CB_DROPDOWN)
useOC.SetValue(self.result['UseObsCalc'])
useOC.Bind(wx.EVT_COMBOBOX,OnUseOC)
plotType.Add(useOC,0,WACV)
mainSizer.Add(plotType,0)
dataSizer = wx.BoxSizer(wx.HORIZONTAL)
dataSizer.Add(wx.StaticText(self.panel,label=' Smoothing type: '),0,WACV)
smChoice = ['linear','nearest',]
smCombo = wx.ComboBox(self.panel,value=self.result['Smooth'],choices=smChoice,
style=wx.CB_READONLY|wx.CB_DROPDOWN)
smCombo.Bind(wx.EVT_COMBOBOX, OnSmCombo)
dataSizer.Add(smCombo,0,WACV)
dataSizer.Add(wx.StaticText(self.panel,label=' Maximum radial dist.: '),0,WACV)
maxR = G2G.ValidatedTxtCtrl(self.panel,self.result,'maxR',nDig=(10,1),xmin=10.,xmax=50.,
typeHint=float)
dataSizer.Add(maxR,0,WACV)
mainSizer.Add(dataSizer,0)
OkBtn = wx.Button(self.panel,-1,"Ok")
OkBtn.Bind(wx.EVT_BUTTON, self.OnOk)
cancelBtn = wx.Button(self.panel,-1,"Cancel")
cancelBtn.Bind(wx.EVT_BUTTON, self.OnCancel)
btnSizer = wx.BoxSizer(wx.HORIZONTAL)
btnSizer.Add((20,20),1)
btnSizer.Add(OkBtn)
btnSizer.Add((20,20),1)
btnSizer.Add(cancelBtn)
btnSizer.Add((20,20),1)
mainSizer.Add(btnSizer,0,wx.EXPAND|wx.BOTTOM|wx.TOP, 10)
self.panel.SetSizer(mainSizer)
self.panel.Fit()
self.Fit()
def GetSelection(self):
return self.result
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)
################################################################################
##### Setup routines
################################################################################
def GetFileBackground(G2frame,xye,background,scale=True):
''' Select a background file to subtract from PWDR pattern
param: xye list [npts,6] of PWDR pattern
param: background PWDR file to be used as background
param: scale bool:=True if scale mult included in background & apply it
returns: list background to subtract
'''
bxye = np.zeros(len(xye[1]))
mult = 1.0
if 'background PWDR' in background[1]:
backfile,mult = background[1]['background PWDR'][:2]
if backfile:
bId = G2gd.GetGPXtreeItemId(G2frame,G2frame.root,backfile)
if bId:
bxye = G2frame.GPXtree.GetItemPyData(bId)[1][1]
else:
print('Error: background PWDR {} not found'.format(backfile))
background[1]['background PWDR'] = ['',1.0,False]
if scale:
return bxye*mult
else:
return bxye
def IsHistogramInAnyPhase(G2frame,histoName):
'''Tests a Histogram to see if it is linked to any phases.
Returns the name of the first phase where the histogram is used.
'''
phases = G2gd.GetGPXtreeItemId(G2frame,G2frame.root,'Phases')
if phases:
item, cookie = G2frame.GPXtree.GetFirstChild(phases)
while item:
data = G2frame.GPXtree.GetItemPyData(item)
histoList = data['Histograms'].keys()
if histoName in histoList:
return G2frame.GPXtree.GetItemText(item)
item, cookie = G2frame.GPXtree.GetNextChild(phases, cookie)
return False
else:
return False
def GetPhasesforHistogram(G2frame,histoName):
'''Returns phases (if any) associated with provided Histogram
Returns a list of phase dicts
'''
phList = []
Histograms,Phases = G2frame.GetUsedHistogramsAndPhasesfromTree()
for ph in Phases:
if histoName in Phases[ph]['Histograms']:
phList.append(Phases[ph])
return phList
def SetupSampleLabels(histName,dataType,histType):
'''Setup a list of labels and number formatting for use in
labeling sample parameters.
:param str histName: Name of histogram, ("PWDR ...")
:param str dataType:
'''
parms = []
parms.append(['Scale','Histogram scale factor: ',[10,7]])
if 'C' in histType or 'B' in histType:
parms.append(['Gonio. radius','Goniometer radius (mm): ',[10,3]])
if 'PWDR' in histName:
if dataType == 'Debye-Scherrer':
if 'T' in histType:
parms += [['Absorption',u'Sample absorption (\xb5r/'+Gklambda+'): ',[10,4]],]
else:
parms += [['DisplaceX',u'Sample X displ. perp. to beam (\xb5m): ',[10,3]],
['DisplaceY',u'Sample Y displ. || to beam (\xb5m): ',[10,3]],
['Absorption',u'Sample absorption (\xb5\xb7r): ',[10,4]],]
elif dataType == 'Bragg-Brentano':
parms += [['Shift',u'Sample displacement(\xb5m): ',[10,4]],
['Transparency',u'Sample transparency(1/\xb5eff, cm): ',[10,3]],
['SurfRoughA','Surface roughness A: ',[10,4]],
['SurfRoughB','Surface roughness B: ',[10,4]]]
elif 'SASD' in histName:
parms.append(['Thick','Sample thickness (mm)',[10,3]])
parms.append(['Trans','Transmission (meas)',[10,3]])
parms.append(['SlitLen',u'Slit length (Q,\xc5'+Pwrm1+')',[10,3]])
parms.append(['Omega','Goniometer omega:',[10,3]])
parms.append(['Chi','Goniometer chi:',[10,3]])
parms.append(['Phi','Goniometer phi:',[10,3]])
parms.append(['Azimuth','Detector azimuth:',[10,3]])
parms.append(['Time','Clock time (s):',[12,3]])
parms.append(['Temperature','Sample temperature (K): ',[10,3]])
parms.append(['Pressure','Sample pressure (MPa): ',[10,3]])
return parms
def SetDefaultSASDModel():
'Fills in default items for the SASD Models dictionary'
return {'Back':[0.0,False],
'Size':{'MinDiam':50,'MaxDiam':10000,'Nbins':100,'logBins':True,'Method':'MaxEnt',
'Distribution':[],'Shape':['Spheroid',1.0],
'MaxEnt':{'Niter':100,'Precision':0.01,'Sky':-3},
'IPG':{'Niter':100,'Approach':0.8,'Power':-1},'Reg':{},},
'Pair':{'Method':'Moore','MaxRadius':100.,'NBins':100,'Errors':'User',
'Percent error':2.5,'Background':[0,False],'Distribution':[],
'Moore':10,'Dist G':100.,'Result':[],},
'Particle':{'Matrix':{'Name':'vacuum','VolFrac':[0.0,False]},'Levels':[],},
'Shapes':{'outName':'run','NumAA':100,'Niter':1,'AAscale':1.0,'Symm':1,'bias-z':0.0,
'inflateV':1.0,'AAglue':0.0,'pdbOut':False,'boxStep':4.0},
'Current':'Size dist.','BackFile':'',
}
def SetDefaultREFDModel():
'''Fills in default items for the REFD Models dictionary which are
defined as follows for each layer:
* Name: name of substance
* Thick: thickness of layer in Angstroms (not present for top & bottom layers)
* Rough: upper surface roughness for layer (not present for toplayer)
* Penetration: mixing of layer substance into layer above-is this needed?
* DenMul: multiplier for layer scattering density (default = 1.0)
Top layer defaults to vacuum (or air/any gas); can be substituted for some other substance.
Bottom layer default: infinitely thisck Silicon; can be substituted for some other substance.
'''
return {'Layers':[{'Name':'vacuum','DenMul':[1.0,False],}, #top layer
{'Name':'vacuum','Rough':[0.,False],'Penetration':[0.,False],'DenMul':[1.0,False],}], #bottom layer
'Scale':[1.0,False],'FltBack':[0.0,False],'Zero':'Top','dQ type':'None','Layer Seq':[], #globals
'Minimizer':'LMLS','Resolution':[0.,'Const dq/q'],'Recomb':0.5,'Toler':0.5, #minimizer controls
'DualFitFiles':['',],'DualFltBacks':[[0.0,False],],'DualScales':[[1.0,False],]} #optional stuff for multidat fits?
def SetDefaultSubstances():
'Fills in default items for the SASD Substances dictionary'
return {'Substances':{'vacuum':{'Elements':{},'Volume':1.0,'Density':0.0,'Scatt density':0.0,'XImag density':0.0},
'unit scatter':{'Elements':None,'Volume':None,'Density':None,'Scatt density':1.0,'XImag density':1.0}}}
def GetFileList(G2frame,fileType):
''' Get list of file names containing a particular string
param: fileType str: any string within a file name
returns: list of file names from GSAS-II tree
Note routine of same name in GSASIIdataGUI; it has a skip option
'''
fileList = []
Id, cookie = G2frame.GPXtree.GetFirstChild(G2frame.root)
while Id:
name = G2frame.GPXtree.GetItemText(Id)
if fileType in name.split()[0]:
fileList.append(name)
Id, cookie = G2frame.GPXtree.GetNextChild(G2frame.root, cookie)
return fileList
def GetHistsLikeSelected(G2frame):
'''Get the histograms that match the current selected one:
The histogram prefix and data type (PXC etc.), the number of
wavelengths and the instrument geometry (Debye-Scherrer etc.)
must all match. The current histogram is not included in the list.
:param wx.Frame G2frame: pointer to main GSAS-II data tree
'''
histList = []
inst,inst2 = G2frame.GPXtree.GetItemPyData(G2gd.GetGPXtreeItemId(G2frame,G2frame.PatternId, 'Instrument Parameters'))
hType = inst['Type'][0]
if 'Lam1' in inst:
hLam = 2
elif 'Lam' in inst:
hLam = 1
else:
hLam = 0
# sample = G2frame.GPXtree.GetItemPyData(G2gd.GetGPXtreeItemId(G2frame,G2frame.PatternId,'Sample Parameters'))
# hGeom = sample.get('Type')
hstName = G2frame.GPXtree.GetItemText(G2frame.PatternId)
hPrefix = hstName.split()[0]+' '
# cycle through tree looking for items that match the above
item, cookie = G2frame.GPXtree.GetFirstChild(G2frame.root)
while item:
name = G2frame.GPXtree.GetItemText(item)
if name.startswith(hPrefix) and name != hstName:
cType,cLam, = '?',-1
subitem, subcookie = G2frame.GPXtree.GetFirstChild(item)
while subitem:
subname = G2frame.GPXtree.GetItemText(subitem)
if subname == 'Sample Parameters':
# sample = G2frame.GPXtree.GetItemPyData(subitem)
# cGeom = sample.get('Type')
pass
elif subname == 'Instrument Parameters':
inst,inst2 = G2frame.GPXtree.GetItemPyData(subitem)
cType = inst['Type'][0]
if 'Lam1' in inst:
cLam = 2
elif 'Lam' in inst:
cLam = 1
else:
cLam = 0
subitem, subcookie = G2frame.GPXtree.GetNextChild(item, subcookie)
if cLam == hLam and cType == hType: # and cGeom == hGeom:
if name not in histList: histList.append(name)
item, cookie = G2frame.GPXtree.GetNextChild(G2frame.root, cookie)
return histList
def SetCopyNames(histName,dataType,addNames=[]):
'''Determine the items in the sample parameters that should be copied,
depending on the histogram type and the instrument type.
'''
copyNames = ['Scale',]
histType = 'HKLF'
if 'PWDR' in histName:
histType = 'PWDR'
if 'Debye' in dataType:
copyNames += ['DisplaceX','DisplaceY','Absorption']
else: #Bragg-Brentano
copyNames += ['Shift','Transparency','SurfRoughA','SurfRoughB']
elif 'SASD' in histName:
histType = 'SASD'
copyNames += ['Materials','Thick',]
if len(addNames):
copyNames += addNames
return histType,copyNames
def CopyPlotCtrls(G2frame):
'''Global copy: Copy plot controls from current histogram to others.
'''
hst = G2frame.GPXtree.GetItemText(G2frame.PatternId)
histList = GetHistsLikeSelected(G2frame)
if not histList:
G2frame.ErrorDialog('No match','No other histograms match '+hst,G2frame)
return
sourceData = G2frame.GPXtree.GetItemPyData(G2frame.PatternId)
if 'Offset' not in sourceData[0]: #patch for old data
sourceData[0].update({'Offset':[0.0,0.0],'delOffset':0.02,'refOffset':-1.0,
'refDelt':0.01,})
G2frame.GPXtree.SetItemPyData(G2frame.PatternId,sourceData)
dlg = G2G.G2MultiChoiceDialog(G2frame,'Copy plot controls from\n'+str(hst[5:])+' to...',
'Copy plot controls', histList)
results = []
try:
if dlg.ShowModal() == wx.ID_OK:
results = dlg.GetSelections()
finally:
dlg.Destroy()
copyList = []
for i in results:
copyList.append(histList[i])
keys = ['Offset','delOffset','refOffset','refDelt']
source = dict(zip(keys,[sourceData[0][item] for item in keys]))
for hist in copyList:
Id = G2gd.GetGPXtreeItemId(G2frame,G2frame.root,hist)
data = G2frame.GPXtree.GetItemPyData(Id)
data[0].update(source)
G2frame.GPXtree.SetItemPyData(Id,data)
print ('Copy of plot controls successful')
def CopySelectedHistItems(G2frame):
'''Global copy: Copy items from current histogram to others.
'''
hst = G2frame.GPXtree.GetItemText(G2frame.PatternId)
histList = GetHistsLikeSelected(G2frame)
if not histList:
G2frame.ErrorDialog('No match','No other histograms match '+hst,G2frame)
return
choices = ['Limits','Background','Instrument Parameters','Sample Parameters']
dlg = G2G.G2MultiChoiceDialog(G2frame,'Copy which histogram sections from\n'+str(hst[5:]),
'Select copy sections', choices, filterBox=False)
dlg.SetSelections(range(len(choices)))
choiceList = []
if dlg.ShowModal() == wx.ID_OK:
choiceList = [choices[i] for i in dlg.GetSelections()]
if not choiceList: return
dlg = G2G.G2MultiChoiceDialog(G2frame,'Copy parameters from\n'+str(hst[5:])+' to...',
'Copy parameters', histList)
results = []
try:
if dlg.ShowModal() == wx.ID_OK:
results = dlg.GetSelections()
finally:
dlg.Destroy()
copyList = []
for i in results:
copyList.append(histList[i])
if 'Limits' in choiceList: # Limits
data = G2frame.GPXtree.GetItemPyData(
G2gd.GetGPXtreeItemId(G2frame,G2frame.PatternId,'Limits'))
for item in copyList:
Id = G2gd.GetGPXtreeItemId(G2frame,G2frame.root,item)
G2frame.GPXtree.SetItemPyData(
G2gd.GetGPXtreeItemId(G2frame,Id,'Limits'),
copy.deepcopy(data))
if 'Background' in choiceList: # Background
data = G2frame.GPXtree.GetItemPyData(
G2gd.GetGPXtreeItemId(G2frame,G2frame.PatternId,'Background'))
for item in copyList:
Id = G2gd.GetGPXtreeItemId(G2frame,G2frame.root,item)
G2frame.GPXtree.SetItemPyData(
G2gd.GetGPXtreeItemId(G2frame,Id,'Background'),
copy.deepcopy(data))
if 'Instrument Parameters' in choiceList: # Instrument Parameters
# for now all items in Inst. parms are copied
data,data1 = G2frame.GPXtree.GetItemPyData(
G2gd.GetGPXtreeItemId(
G2frame,G2frame.PatternId,'Instrument Parameters'))
for item in copyList:
Id = G2gd.GetGPXtreeItemId(G2frame,G2frame.root,item)
G2frame.GPXtree.GetItemPyData(
G2gd.GetGPXtreeItemId(G2frame,Id,'Instrument Parameters')
)[0].update(copy.deepcopy(data))
G2frame.GPXtree.GetItemPyData(
G2gd.GetGPXtreeItemId(G2frame,Id,'Instrument Parameters')
)[1].update(copy.deepcopy(data1))
if 'Sample Parameters' in choiceList: # Sample Parameters
data = G2frame.GPXtree.GetItemPyData(
G2gd.GetGPXtreeItemId(
G2frame,G2frame.PatternId,'Sample Parameters'))
# selects items to be copied
histType,copyNames = SetCopyNames(hst,data['Type'],
addNames = ['Omega','Chi','Phi','Gonio. radius','InstrName'])
copyDict = {parm:data[parm] for parm in copyNames}
for item in copyList:
Id = G2gd.GetGPXtreeItemId(G2frame,G2frame.root,item)
G2frame.GPXtree.GetItemPyData(
G2gd.GetGPXtreeItemId(G2frame,Id,'Sample Parameters')
).update(copy.deepcopy(copyDict))
def TestMagAtoms(phase,magAtms,SGData,Uvec,Trans,allmom,maxequiv=100,maximal=False):
''' Tests substructure magnetic atoms for magnetic site symmetry
param: phase GSAS-II phase object
param: magAtms list:magnetic atom objects
param: SGData dict: GSAS-II space group object
param: Uvec array: Translation U vector
param: Trans array: Transformation matrix
param: allmom bool: =True if all atoms must have moments allowed
params: maxequiv int:maximum number of atoms with moments to consider
param: maximal bool:=True if maximal subgroups only are allowed
returns: unique magnetic atoms (if any)
'''
found = False
anymom = False
phase['Keep'] = False
if not magAtms:
phase['Keep'] = True
return []
invTrans = nl.inv(Trans)
atCodes = []
Phase = {'General':{'AtomPtrs':[2,1],'SGData':copy.deepcopy(phase['SGData'])},'Atoms':[]}
for matm in magAtms:
XYZ = G2spc.GenAtom(matm[3:6],SGData,False,Move=True)
xyzs = [xyz[0] for xyz in XYZ]
atCodes += len(xyzs)*['1',]
xyzs,atCodes = G2lat.ExpandCell(xyzs,atCodes,0,Trans)
for ix,x in enumerate(xyzs):
xyz = G2lat.TransformXYZ(x-Uvec,invTrans.T,np.zeros(3))%1.
Phase['Atoms'].append(matm[:2]+list(xyz))
SytSym,Mul,Nop,dupDir = G2spc.SytSym(xyz,phase['SGData'])
CSI = G2spc.GetCSpqinel(phase['SGData']['SpnFlp'],dupDir)
if any(CSI[0]):
anymom = True
if allmom:
if not any(CSI[0]):
phase['Keep'] = False
found = True
uAtms = G2lat.GetUnique(Phase,atCodes)[0]
natm = len(uAtms)
if anymom and natm <= maxequiv and not found:
phase['Keep'] = True
if maximal and phase['supList'][0]:
phase['Keep'] = False
return uAtms
def TestAtoms(phase,magAtms,SGData,Uvec,Trans,maxequiv=100,maximal=False):
'''Tests atoms for substructure equivalents
param: phase GSAS-II phase object
param: magAtms list: atom objects
param: SGData dict: GSAS-II space group object
param: Uvec array: Translation U vector
param: Trans array: Transformation matrix
params: maxequiv int:maximum number of atoms with moments to consider
param: maximal bool:=True if maximal subgroups only are allowed
returns: unique atoms (if any)
'''
phase['Keep'] = True
invTrans = nl.inv(Trans)
atCodes = []
Phase = {'General':{'AtomPtrs':[2,1],'SGData':copy.deepcopy(phase['SGData'])},'Atoms':[]}
for matm in magAtms:
XYZ = G2spc.GenAtom(matm[3:6],SGData,False,Move=True)
xyzs = [xyz[0] for xyz in XYZ]
atCodes += len(xyzs)*['1',]
xyzs,atCodes = G2lat.ExpandCell(xyzs,atCodes,0,Trans)
for ix,x in enumerate(xyzs):
xyz = G2lat.TransformXYZ(x-Uvec,invTrans.T,np.zeros(3))%1.
Phase['Atoms'].append(matm[:2]+list(xyz))
uAtms = G2lat.GetUnique(Phase,atCodes)[0]
natm = len(uAtms)
if natm > maxequiv: #too many allowed atoms found
phase['Keep'] = False
if maximal and phase['supList'][0]:
phase['Keep'] = False
return uAtms
################################################################################
##### Powder Peaks
################################################################################
def UpdatePeakGrid(G2frame, data):
'''respond to selection of PWDR powder peaks data tree item.
'''
def OnAutoSearch(event):
'Search pattern for possible peak positions'
PatternId = G2frame.PatternId
limits = G2frame.GPXtree.GetItemPyData(G2gd.GetGPXtreeItemId(G2frame,PatternId, 'Limits'))[1]
background = G2frame.GPXtree.GetItemPyData(G2gd.GetGPXtreeItemId(G2frame,PatternId, 'Background'))
inst,inst2 = G2frame.GPXtree.GetItemPyData(G2gd.GetGPXtreeItemId(G2frame,PatternId, 'Instrument Parameters'))
Pattern = G2frame.GPXtree.GetItemPyData(PatternId)
profile = Pattern[1]
bxye = GetFileBackground(G2frame,profile,background)
x0 = profile[0]
iBeg = np.searchsorted(x0,limits[0])
iFin = np.searchsorted(x0,limits[1])
x = x0[iBeg:iFin]
y0 = (profile[1]-bxye)[iBeg:iFin]
ysig = 1.0*np.std(y0)
offset = [-1,1]
ymask = ma.array(y0,mask=(y0<ysig))
for off in offset:
ymask = ma.array(ymask,mask=(ymask-np.roll(y0,off)<=0.))
indx = ymask.nonzero()
mags = ymask[indx]
poss = x[indx]
refs = list(zip(poss,mags))
if 'T' in Inst['Type'][0]:
refs = G2mth.sortArray(refs,0,reverse=True) #big TOFs first
else: #'C', 'E' or 'B'
refs = G2mth.sortArray(refs,0,reverse=False) #small 2-Thetas or energies first
for i,ref1 in enumerate(refs): #reject picks closer than 1 FWHM
for ref2 in refs[i+1:]:
if abs(ref2[0]-ref1[0]) < 2.*G2pwd.getFWHM(ref1[0],inst):
del(refs[i])
if 'T' in Inst['Type'][0]:
refs = G2mth.sortArray(refs,1,reverse=False)
else: #'C', 'E' or 'B'
refs = G2mth.sortArray(refs,1,reverse=True)
for pos,mag in refs:
data['peaks'].append(G2mth.setPeakparms(inst,inst2,pos,mag))
UpdatePeakGrid(G2frame,data)
G2plt.PlotPatterns(G2frame,plotType='PWDR')
def OnCopyPeaks(event):
'Copy peaks to other histograms'
hst = G2frame.GPXtree.GetItemText(G2frame.PatternId)
histList = GetHistsLikeSelected(G2frame)
if not histList:
G2frame.ErrorDialog('No match','No histograms match '+hst,G2frame)
return
copyList = []
dlg = G2G.G2MultiChoiceDialog(G2frame,'Copy peak list from\n'+str(hst[5:])+' to...',
'Copy peaks', histList)
try:
if dlg.ShowModal() == wx.ID_OK:
for i in dlg.GetSelections():
copyList.append(histList[i])
finally:
dlg.Destroy()
for item in copyList:
Id = G2gd.GetGPXtreeItemId(G2frame,G2frame.root,item)
G2frame.GPXtree.SetItemPyData(
G2gd.GetGPXtreeItemId(G2frame,Id,'Peak List'),copy.deepcopy(data))
def OnLoadPeaks(event):
'Load peak list from file'
pth = G2G.GetExportPath(G2frame)
dlg = wx.FileDialog(G2frame, 'Choose GSAS-II PWDR peaks list file', pth, '',
'PWDR peak list files (*.pkslst)|*.pkslst',wx.FD_OPEN)
try:
if dlg.ShowModal() == wx.ID_OK:
peaks = []
filename = dlg.GetPath()
File = open(filename,'r')
S = File.readline()
while S:
if '#' in S:
S = File.readline()
continue
try:
peaks.append(eval(S))
except:
break
S = File.readline()
File.close()
finally:
dlg.Destroy()
data = {'peaks':peaks,'sigDict':{}}
UpdatePeakGrid(G2frame,data)
G2plt.PlotPatterns(G2frame,plotType='PWDR')
def OnSavePeaks(event):
'Save peak to file suitable for OnLoadPeaks'
pth = G2G.GetExportPath(G2frame)
dlg = wx.FileDialog(G2frame, 'Choose GSAS-II PWDR peaks list file', pth, '',
'PWDR peak list files (*.pkslst)|*.pkslst',wx.FD_SAVE|wx.FD_OVERWRITE_PROMPT)
try:
if dlg.ShowModal() == wx.ID_OK:
filename = dlg.GetPath()
# make sure extension is .pkslst
filename = os.path.splitext(filename)[0]+'.pkslst'
File = open(filename,'w')
File.write("#GSAS-II PWDR peaks list file; do not add/delete items!\n")
for item in data:
if item == 'peaks':
for pk in data[item]:
File.write(str(pk)+'\n')
File.close()
print ('PWDR peaks list saved to: '+filename)
finally:
dlg.Destroy()
def OnUnDo(event):
'Undo a peak fit - reads a saved file from PeakFit'
file = open(G2frame.undofile,'rb')
PatternId = G2frame.PatternId
for item in ['Background','Instrument Parameters','Peak List']:
Id = G2gd.GetGPXtreeItemId(G2frame,PatternId, item)
oldvals = cPickle.load(file)
G2frame.GPXtree.SetItemPyData(Id,oldvals)
if item == 'Peak List':
data.update(G2frame.GPXtree.GetItemPyData(Id))
print (item+' recovered')
file.close()
G2frame.dataWindow.UnDo.Enable(False)
wx.CallAfter(UpdatePeakGrid,G2frame,data)
G2plt.PlotPatterns(G2frame,plotType='PWDR')
def SaveState():
'Saves result of a peaak fit for possible UnDo'
G2frame.undofile = os.path.join(G2frame.dirname,'GSASII.save')
file = open(G2frame.undofile,'wb')
PatternId = G2frame.PatternId
for item in ['Background','Instrument Parameters','Peak List']:
cPickle.dump(G2frame.GPXtree.GetItemPyData(G2gd.GetGPXtreeItemId(G2frame,PatternId,item)),file,1)
file.close()
G2frame.dataWindow.UnDo.Enable(True)
def OnLSQPeakFit(event):
'Do a sequential peak fit across multiple histograms - peaks must be present in all'
if reflGrid.IsCellEditControlEnabled(): # complete any grid edits in progress
reflGrid.HideCellEditControl()
reflGrid.DisableCellEditControl()
if not G2frame.GSASprojectfile: #force a save of the gpx file so SaveState can write in the same directory
G2frame.OnFileSaveas(event)
wx.CallAfter(OnPeakFit)
def OnOneCycle(event):
'Do a single cycle of peak fit refinement'
if reflGrid.IsCellEditControlEnabled(): # complete any grid edits in progress
reflGrid.HideCellEditControl()
reflGrid.DisableCellEditControl()
wx.CallAfter(OnPeakFit,oneCycle=True)
def OnSeqPeakFit(event):
''''Do a sequential peak fit across multiple histograms - peaks must be present in all.
results saved in Sequential peak fit results'''
histList = G2gd.GetGPXtreeDataNames(G2frame,['PWDR',])
od = {'label_1':'Copy to next','value_1':False,'label_2':'Reverse order','value_2':False}
dlg = G2G.G2MultiChoiceDialog(G2frame, 'Sequential peak fits',
'Select dataset to include',histList,extraOpts=od)
names = []
if dlg.ShowModal() == wx.ID_OK:
for sel in dlg.GetSelections():
names.append(histList[sel])
dlg.Destroy()
if not names:
return
Id = G2gd.GetGPXtreeItemId(G2frame,G2frame.root,'Sequential peak fit results')
if Id:
SeqResult = G2frame.GPXtree.GetItemPyData(Id)
else:
SeqResult = {}
Id = G2frame.GPXtree.AppendItem(parent=G2frame.root,text='Sequential peak fit results')
SeqResult = {'SeqPseudoVars':{},'SeqParFitEqList':[]}
SeqResult['histNames'] = names
dlg = wx.ProgressDialog('Sequential peak fit','Data set name = '+names[0],len(names),
style = wx.PD_ELAPSED_TIME|wx.PD_AUTO_HIDE|wx.PD_REMAINING_TIME|wx.PD_CAN_ABORT)
controls = {'deriv type':'analytic','min dM/M':0.001,}
print ('Peak Fitting with '+controls['deriv type']+' derivatives:')
oneCycle = False
prevVaryList = []
peaks = None
varyList = None
if od['value_2']:
names.reverse()
try:
for i,name in enumerate(names):
print (' Sequential fit for '+name)
dlg.Raise()
GoOn = dlg.Update(i,newmsg='Data set name = '+name)[0]
if not GoOn:
dlg.Destroy()
break
PatternId = G2gd.GetGPXtreeItemId(G2frame,G2frame.root,name)
if i and od['value_1']:
G2frame.GPXtree.SetItemPyData(G2gd.GetGPXtreeItemId(G2frame,PatternId, 'Peak List'),copy.deepcopy(peaks))
prevVaryList = varyList[:]
peaks = G2frame.GPXtree.GetItemPyData(G2gd.GetGPXtreeItemId(G2frame,PatternId, 'Peak List'))
background = G2frame.GPXtree.GetItemPyData(G2gd.GetGPXtreeItemId(G2frame,PatternId, 'Background'))
limits = G2frame.GPXtree.GetItemPyData(G2gd.GetGPXtreeItemId(G2frame,PatternId, 'Limits'))[1]
inst,inst2 = G2frame.GPXtree.GetItemPyData(G2gd.GetGPXtreeItemId(G2frame,PatternId, 'Instrument Parameters'))
Pattern = G2frame.GPXtree.GetItemPyData(PatternId)
data = Pattern[1]
fixback = GetFileBackground(G2frame,data,background,scale=False)
peaks['sigDict'],result,sig,Rvals,varyList,parmDict,fullvaryList,badVary = G2pwd.DoPeakFit(None,peaks['peaks'],
background,limits,inst,inst2,data,fixback,prevVaryList,oneCycle,controls) #needs wtFactor after controls?
if len(result[0]) != len(fullvaryList):
dlg.Destroy()
print (' ***** Sequential peak fit stopped at '+name+' *****')
break
else:
G2frame.GPXtree.SetItemPyData(G2gd.GetGPXtreeItemId(G2frame,PatternId, 'Peak List'),copy.deepcopy(peaks))
SeqResult[name] = {'variables':result[0],'varyList':varyList,'sig':sig,'Rvals':Rvals,
'covMatrix':np.eye(len(result[0])),'title':name,'parmDict':parmDict,
'fullVary':fullvaryList,'badVary':badVary}
print (' ***** Sequential peak fit successful *****')
finally:
dlg.Destroy()
SeqResult['histNames'] = histList
G2frame.GPXtree.SetItemPyData(Id,SeqResult)
G2frame.G2plotNB.Delete('Sequential refinement') #clear away probably invalid plot
G2frame.GPXtree.SelectItem(Id)
def OnDelPeaks(event):
'Delete selected peaks from the Peak fit table'
if G2frame.dataWindow.XtraPeakMode.IsChecked(): # which table?
tbl = data['xtraPeaks']
else:
tbl = data['peaks']
choices = [f"{i[0]:.2f}" for i in tbl]
if not choices: return
sel = []
dlg = G2G.G2MultiChoiceDialog(G2frame,'Select peaks to delete',
'Delete peaks',choices)
try:
if dlg.ShowModal() == wx.ID_OK:
sel = dlg.GetSelections()
finally:
dlg.Destroy()
for i in sorted(sel,reverse=True):
del tbl[i]
UpdatePeakGrid(G2frame,data)
G2plt.PlotPatterns(G2frame,plotType='PWDR')
def OnClearPeaks(event):
'Clear the Peak fit table'
dlg = wx.MessageDialog(G2frame,'Delete all peaks?','Clear peak list',wx.OK|wx.CANCEL)
try:
if dlg.ShowModal() == wx.ID_OK:
peaks = {'peaks':[],'sigDict':{}}
finally:
dlg.Destroy()
UpdatePeakGrid(G2frame,peaks)
G2plt.PlotPatterns(G2frame,plotType='PWDR')
def OnPeakFit(oneCycle=False,noFit=False):
'Do peak fitting by least squares'
SaveState()
controls = G2frame.GPXtree.GetItemPyData(G2gd.GetGPXtreeItemId(G2frame,G2frame.root, 'Controls'))
if not controls:
controls = {'deriv type':'analytic','min dM/M':0.001,} #fill in defaults if needed
#print ('Peak Fitting with '+controls['deriv type']+' derivatives:')
PatternId = G2frame.PatternId
peaks = G2frame.GPXtree.GetItemPyData(G2gd.GetGPXtreeItemId(G2frame,PatternId, 'Peak List'))
if not peaks:
G2frame.ErrorDialog('No peaks!','Nothing to fit!')
return
background = G2frame.GPXtree.GetItemPyData(G2gd.GetGPXtreeItemId(G2frame,PatternId, 'Background'))
limits = G2frame.GPXtree.GetItemPyData(G2gd.GetGPXtreeItemId(G2frame,PatternId, 'Limits'))[1]
inst,inst2 = G2frame.GPXtree.GetItemPyData(G2gd.GetGPXtreeItemId(G2frame,PatternId, 'Instrument Parameters'))
Pattern = G2frame.GPXtree.GetItemPyData(PatternId)
data = Pattern[1]
wtFactor = Pattern[0]['wtFactor']
overallInfo = {}
peaks['LaueFringe'] = peaks.get('LaueFringe',{})
peaks['LaueFringe']['satellites'] = []
lines = peaks['LaueFringe'].get('Show')
if 'LF' in inst['Type'][0]:
wave = G2mth.getWave(inst)
overallInfo = {'ncell':peaks['LaueFringe']['ncell'],
'clat': peaks['LaueFringe']['clat'],
'clat-ref': peaks['LaueFringe']['clat-ref'],
'fitRange': peaks['LaueFringe'].get('fitRange',8.0),
'fitPowerM': peaks['LaueFringe'].get('fitPowerM',2.0),
'fitPowerP': peaks['LaueFringe'].get('fitPowerP',2.0),
} # add overall info here
if lines:
for i in peaks['peaks']:
pks = list(range(-lines,0)) + list(range(1,lines+1))
peaks['LaueFringe']['satellites'].extend(
G2pwd.LaueSatellite(i[0],wave,peaks['LaueFringe']['clat'],peaks['LaueFringe']['ncell'],pks))
if G2frame.dataWindow.XtraPeakMode.IsChecked(): # adding peaks to computed pattern
histoName = G2frame.GPXtree.GetItemText(G2frame.PatternId)
# do zero cycle refinement
import GSASIIstrMain as G2stMn
# recompute current pattern for current histogram, set as fixed background
bxye = G2stMn.DoNoFit(G2frame.GSASprojectfile,histoName)
peaksplus = peaks['xtraPeaks'] + [{}]
# dummy out background parameters (are not used so can't be refined)
background = [['chebyschev-1', False, 1, 0.0], {
'nDebye': 0,'debyeTerms': [],'nPeaks': 0,'peaksList': [],
'background PWDR': ['', 1.0, False],
'FixedPoints': [],'autoPrms': {}}]
#breakpoint() ##################################################
else:
peaksplus = peaks['peaks'] + [overallInfo]
bxye = GetFileBackground(G2frame,data,background,scale=False)
if noFit:
results = G2pwd.DoPeakFit(None,peaksplus,background,limits,inst,inst2,data,bxye,[],oneCycle,controls,wtFactor,noFit=True)
G2plt.PlotPatterns(G2frame,plotType='PWDR')
return
# try:
dlg = wx.ProgressDialog('Residual','Peak fit Rwp = ',101,parent=G2frame,
style = wx.PD_ELAPSED_TIME|wx.PD_AUTO_HIDE|wx.PD_REMAINING_TIME|wx.PD_CAN_ABORT)
results = G2pwd.DoPeakFit(None,peaksplus,background,limits,inst,inst2,data,bxye,[],oneCycle,controls,wtFactor,dlg)
# finally:
# dlg.Destroy()