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 pathGSASIIpwd.py
5772 lines (5464 loc) · 239 KB
/
GSASIIpwd.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
#/usr/bin/env python
# -*- coding: utf-8 -*-
########### SVN repository information ###################
# $Date: 2024-01-30 14:19:34 -0600 (Tue, 30 Jan 2024) $
# $Author: toby $
# $Revision: 5721 $
# $URL: https://subversion.xray.aps.anl.gov/pyGSAS/trunk/GSASIIpwd.py $
# $Id: GSASIIpwd.py 5721 2024-01-30 20:19:34Z toby $
########### SVN repository information ###################
'''
Classes and routines defined in :mod:`GSASIIpwd` follow.
'''
from __future__ import division, print_function
import sys
import math
import time
import os
import os.path
import subprocess as subp
import datetime as dt
import copy
import numpy as np
import numpy.linalg as nl
import numpy.ma as ma
import random as rand
import numpy.fft as fft
import scipy.interpolate as si
import scipy.stats as st
import scipy.optimize as so
import scipy.special as sp
import scipy.signal as signal
import GSASIIpath
filversion = "$Revision: 5721 $"
GSASIIpath.SetVersionNumber("$Revision: 5721 $")
import GSASIIlattice as G2lat
import GSASIIspc as G2spc
import GSASIIElem as G2elem
import GSASIImath as G2mth
try:
import pypowder as pyd
except ImportError:
print ('pypowder is not available - profile calcs. not allowed')
try:
import pydiffax as pyx
except ImportError:
print ('pydiffax is not available for this platform')
import GSASIIfiles as G2fil
# trig functions in degrees
tand = lambda x: math.tan(x*math.pi/180.)
atand = lambda x: 180.*math.atan(x)/math.pi
atan2d = lambda y,x: 180.*math.atan2(y,x)/math.pi
cosd = lambda x: math.cos(x*math.pi/180.)
acosd = lambda x: 180.*math.acos(x)/math.pi
rdsq2d = lambda x,p: round(1.0/math.sqrt(x),p)
#numpy versions
npsind = lambda x: np.sin(x*np.pi/180.)
npasind = lambda x: 180.*np.arcsin(x)/math.pi
npcosd = lambda x: np.cos(x*math.pi/180.)
npacosd = lambda x: 180.*np.arccos(x)/math.pi
nptand = lambda x: np.tan(x*math.pi/180.)
npatand = lambda x: 180.*np.arctan(x)/np.pi
npatan2d = lambda y,x: 180.*np.arctan2(y,x)/np.pi
npT2stl = lambda tth, wave: 2.0*npsind(tth/2.0)/wave #=d*
npT2q = lambda tth,wave: 2.0*np.pi*npT2stl(tth,wave) #=2pi*d*
npq2T = lambda Q,wave: 2.0*npasind(0.25*Q*wave/np.pi)
ateln2 = 8.0*math.log(2.0)
sateln2 = np.sqrt(ateln2)
nxs = np.newaxis
is_exe = lambda fpath: os.path.isfile(fpath) and os.access(fpath, os.X_OK)
#### Powder utilities ################################################################################
def PhaseWtSum(G2frame,histo):
'''
Calculate sum of phase mass*phase fraction for PWDR data (exclude magnetic phases)
:param G2frame: GSASII main frame structure
:param str histo: histogram name
:returns: sum(scale*mass) for phases in histo
'''
Histograms,Phases = G2frame.GetUsedHistogramsAndPhasesfromTree()
wtSum = 0.0
for phase in Phases:
if Phases[phase]['General']['Type'] != 'magnetic':
if histo in Phases[phase]['Histograms']:
if not Phases[phase]['Histograms'][histo]['Use']: continue
mass = Phases[phase]['General']['Mass']
phFr = Phases[phase]['Histograms'][histo]['Scale'][0]
wtSum += mass*phFr
return wtSum
#### GSASII pwdr & pdf calculation routines ################################################################################
def Transmission(Geometry,Abs,Diam):
'''
Calculate sample transmission
:param str Geometry: one of 'Cylinder','Bragg-Brentano','Tilting flat plate in transmission','Fixed flat plate'
:param float Abs: absorption coeff in cm-1
:param float Diam: sample thickness/diameter in mm
'''
if 'Cylinder' in Geometry: #Lobanov & Alte da Veiga for 2-theta = 0; beam fully illuminates sample
MuR = Abs*Diam/20.0
if MuR <= 3.0:
T0 = 16/(3.*math.pi)
T1 = -0.045780
T2 = -0.02489
T3 = 0.003045
T = -T0*MuR-T1*MuR**2-T2*MuR**3-T3*MuR**4
if T < -20.:
return 2.06e-9
else:
return math.exp(T)
else:
T1 = 1.433902
T2 = 0.013869+0.337894
T3 = 1.933433+1.163198
T4 = 0.044365-0.04259
T = (T1-T4)/(1.0+T2*(MuR-3.0))**T3+T4
return T/100.
elif 'plate' in Geometry:
MuR = Abs*Diam/10.
return math.exp(-MuR)
elif 'Bragg' in Geometry:
return 0.0
def SurfaceRough(SRA,SRB,Tth):
''' Suortti (J. Appl. Cryst, 5,325-331, 1972) surface roughness correction
:param float SRA: Suortti surface roughness parameter
:param float SRB: Suortti surface roughness parameter
:param float Tth: 2-theta(deg) - can be numpy array
'''
sth = npsind(Tth/2.)
T1 = np.exp(-SRB/sth)
T2 = SRA+(1.-SRA)*np.exp(-SRB)
return (SRA+(1.-SRA)*T1)/T2
def SurfaceRoughDerv(SRA,SRB,Tth):
''' Suortti surface roughness correction derivatives
:param float SRA: Suortti surface roughness parameter (dimensionless)
:param float SRB: Suortti surface roughness parameter (dimensionless)
:param float Tth: 2-theta(deg) - can be numpy array
:return list: [dydSRA,dydSRB] derivatives to be used for intensity derivative
'''
sth = npsind(Tth/2.)
T1 = np.exp(-SRB/sth)
T2 = SRA+(1.-SRA)*np.exp(-SRB)
Trans = (SRA+(1.-SRA)*T1)/T2
dydSRA = ((1.-T1)*T2-(1.-np.exp(-SRB))*Trans)/T2**2
dydSRB = ((SRA-1.)*T1*T2/sth-Trans*(SRA-T2))/T2**2
return [dydSRA,dydSRB]
def Absorb(Geometry,MuR,Tth,Phi=0,Psi=0):
'''Calculate sample absorption
:param str Geometry: one of 'Cylinder','Bragg-Brentano','Tilting Flat Plate in transmission','Fixed flat plate'
:param float MuR: absorption coeff * sample thickness/2 or radius
:param Tth: 2-theta scattering angle - can be numpy array
:param float Phi: flat plate tilt angle - future
:param float Psi: flat plate tilt axis - future
'''
def muRunder3(MuR,Sth2):
T0 = 16.0/(3.*np.pi)
T1 = (25.99978-0.01911*Sth2**0.25)*np.exp(-0.024551*Sth2)+ \
0.109561*np.sqrt(Sth2)-26.04556
T2 = -0.02489-0.39499*Sth2+1.219077*Sth2**1.5- \
1.31268*Sth2**2+0.871081*Sth2**2.5-0.2327*Sth2**3
T3 = 0.003045+0.018167*Sth2-0.03305*Sth2**2
Trns = -T0*MuR-T1*MuR**2-T2*MuR**3-T3*MuR**4
return np.exp(Trns)
def muRover3(MuR,Sth2):
T1 = 1.433902+11.07504*Sth2-8.77629*Sth2*Sth2+ \
10.02088*Sth2**3-3.36778*Sth2**4
T2 = (0.013869-0.01249*Sth2)*np.exp(3.27094*Sth2)+ \
(0.337894+13.77317*Sth2)/(1.0+11.53544*Sth2)**1.555039
T3 = 1.933433/(1.0+23.12967*Sth2)**1.686715- \
0.13576*np.sqrt(Sth2)+1.163198
T4 = 0.044365-0.04259/(1.0+0.41051*Sth2)**148.4202
Trns = (T1-T4)/(1.0+T2*(MuR-3.0))**T3+T4
return Trns/100.
Sth2 = npsind(Tth/2.0)**2
if 'Cylinder' in Geometry: #Lobanov & Alte da Veiga for 2-theta = 0; beam fully illuminates sample
if 'array' in str(type(MuR)):
MuRSTh2 = np.vstack((MuR,Sth2))
AbsCr = np.where(MuRSTh2[0]<=3.0,muRunder3(MuRSTh2[0],MuRSTh2[1]),muRover3(MuRSTh2[0],MuRSTh2[1]))
return AbsCr
else:
if MuR <= 3.0:
return muRunder3(MuR,Sth2)
else:
return muRover3(MuR,Sth2)
elif 'Bragg' in Geometry:
return 1.0
elif 'Fixed' in Geometry: #assumes sample plane is perpendicular to incident beam
# and only defined for 2theta < 90
MuT = 2.*MuR
T1 = np.exp(-MuT)
T2 = np.exp(-MuT/npcosd(Tth))
Tb = MuT-MuT/npcosd(Tth)
return (T2-T1)/Tb
elif 'Tilting' in Geometry: #assumes symmetric tilt so sample plane is parallel to diffraction vector
MuT = 2.*MuR
cth = npcosd(Tth/2.0)
return np.exp(-MuT/cth)/cth
def AbsorbDerv(Geometry,MuR,Tth,Phi=0,Psi=0):
'needs a doc string'
dA = 0.001
AbsP = Absorb(Geometry,MuR+dA,Tth,Phi,Psi)
if MuR:
AbsM = Absorb(Geometry,MuR-dA,Tth,Phi,Psi)
return (AbsP-AbsM)/(2.0*dA)
else:
return (AbsP-1.)/dA
def Polarization(Pola,Tth,Azm=0.0):
""" Calculate angle dependent x-ray polarization correction (not scaled correctly!)
:param Pola: polarization coefficient e.g 1.0 fully polarized, 0.5 unpolarized
:param Azm: azimuthal angle e.g. 0.0 in plane of polarization - can be numpy array
:param Tth: 2-theta scattering angle - can be numpy array
which (if either) of these is "right"?
:return: (pola, dpdPola) - both 2-d arrays
* pola = ((1-Pola)*npcosd(Azm)**2+Pola*npsind(Azm)**2)*npcosd(Tth)**2+ \
(1-Pola)*npsind(Azm)**2+Pola*npcosd(Azm)**2
* dpdPola: derivative needed for least squares
"""
cazm = npcosd(Azm)**2
sazm = npsind(Azm)**2
pola = ((1.0-Pola)*cazm+Pola*sazm)*npcosd(Tth)**2+(1.0-Pola)*sazm+Pola*cazm
dpdPola = -npsind(Tth)**2*(sazm-cazm)
return pola,dpdPola
def Oblique(ObCoeff,Tth):
'currently assumes detector is normal to beam'
if ObCoeff:
K = (1.-ObCoeff)/(1.0-np.exp(np.log(ObCoeff)/npcosd(Tth)))
return K
else:
return 1.0
def Ruland(RulCoff,wave,Q,Compton):
'needs a doc string'
C = 2.9978e8
D = 1.5e-3
hmc = 0.024262734687 #Compton wavelength in A
sinth2 = (Q*wave/(4.0*np.pi))**2
dlam = (wave**2)*Compton*Q/C
dlam_c = 2.0*hmc*sinth2-D*wave**2
return 1.0/((1.0+dlam/RulCoff)*(1.0+(np.pi*dlam_c/(dlam+RulCoff))**2))
def KleinNishina(wave,Q):
hmc = 0.024262734687 #Compton wavelength in A
TTh = npq2T(Q,wave)
P = 1./(1.+(1.-npcosd(TTh)*(hmc/wave)))
KN = (P**3-(P*npsind(TTh))**2+P)/(1.+npcosd(TTh)**2)
return KN
def LorchWeight(Q):
'needs a doc string'
return np.sin(np.pi*(Q[-1]-Q)/(2.0*Q[-1]))
def GetAsfMean(ElList,Sthl2):
'''Calculate various scattering factor terms for PDF calcs
:param dict ElList: element dictionary contains scattering factor coefficients, etc.
:param np.array Sthl2: numpy array of sin theta/lambda squared values
:returns: mean(f^2), mean(f)^2, mean(compton)
'''
sumNoAtoms = 0.0
FF = np.zeros_like(Sthl2)
FF2 = np.zeros_like(Sthl2)
CF = np.zeros_like(Sthl2)
for El in ElList:
sumNoAtoms += ElList[El]['FormulaNo']
for El in ElList:
el = ElList[El]
ff2 = (G2elem.ScatFac(el,Sthl2)+el['fp'])**2+el['fpp']**2
cf = G2elem.ComptonFac(el,Sthl2)
FF += np.sqrt(ff2)*el['FormulaNo']/sumNoAtoms
FF2 += ff2*el['FormulaNo']/sumNoAtoms
CF += cf*el['FormulaNo']/sumNoAtoms
return FF2,FF**2,CF
def GetNumDensity(ElList,Vol):
'needs a doc string'
sumNoAtoms = 0.0
for El in ElList:
sumNoAtoms += ElList[El]['FormulaNo']
return sumNoAtoms/Vol
def CalcPDF(data,inst,limits,xydata):
'''Computes I(Q), S(Q) & G(r) from Sample, Bkg, etc. diffraction patterns loaded into
dict xydata; results are placed in xydata.
Calculation parameters are found in dicts data and inst and list limits.
The return value is at present an empty list.
'''
auxPlot = []
if 'T' in inst['Type'][0]:
Ibeg = 0
Ifin = len(xydata['Sample'][1][0])
else:
Ibeg = np.searchsorted(xydata['Sample'][1][0],limits[0])
Ifin = np.searchsorted(xydata['Sample'][1][0],limits[1])+1
#subtract backgrounds - if any & use PWDR limits
IofQ = copy.deepcopy(xydata['Sample'])
IofQ[1] = np.array([I[Ibeg:Ifin] for I in IofQ[1]])
if data['Sample Bkg.']['Name']:
try: # fails if background differs in number of points
IofQ[1][1] += xydata['Sample Bkg.'][1][1][Ibeg:Ifin]*data['Sample Bkg.']['Mult']
except ValueError:
print("Interpolating Sample background since points don't match")
interpF = si.interp1d(xydata['Sample Bkg.'][1][0],xydata['Sample Bkg.'][1][1],
fill_value='extrapolate')
IofQ[1][1] += interpF(IofQ[1][0]) * data['Sample Bkg.']['Mult']
if data['Container']['Name']:
xycontainer = xydata['Container'][1][1]*data['Container']['Mult']
if data['Container Bkg.']['Name']:
try:
xycontainer += xydata['Container Bkg.'][1][1][Ibeg:Ifin]*data['Container Bkg.']['Mult']
except ValueError:
print('Number of points do not agree between Container and Container Bkg.')
return
try: # fails if background differs in number of points
IofQ[1][1] += xycontainer[Ibeg:Ifin]
except ValueError:
print("Interpolating Container background since points don't match")
interpF = si.interp1d(xydata['Container'][1][0],xycontainer,fill_value='extrapolate')
IofQ[1][1] += interpF(IofQ[1][0])
data['IofQmin'] = IofQ[1][1][-1]
IofQ[1][1] -= data.get('Flat Bkg',0.)
#get element data & absorption coeff.
ElList = data['ElList']
Tth = IofQ[1][0] #2-theta or TOF!
if 'X' in inst['Type'][0]:
Abs = G2lat.CellAbsorption(ElList,data['Form Vol'])
#Apply angle dependent corrections
MuR = Abs*data['Diam']/20.0
IofQ[1][1] /= Absorb(data['Geometry'],MuR,Tth)
IofQ[1][1] /= Polarization(inst['Polariz.'][1],Tth,Azm=inst['Azimuth'][1])[0]
if data['DetType'] == 'Area detector':
IofQ[1][1] *= Oblique(data['ObliqCoeff'],Tth)
elif 'T' in inst['Type'][0]: #neutron TOF normalized data - needs wavelength dependent absorption
wave = 2.*G2lat.TOF2dsp(inst,IofQ[1][0])*npsind(inst['2-theta'][1]/2.)
Els = ElList.keys()
Isotope = {El:'Nat. abund.' for El in Els}
GD = {'AtomTypes':ElList,'Isotope':Isotope}
BLtables = G2elem.GetBLtable(GD)
FP,FPP = G2elem.BlenResTOF(Els,BLtables,wave)
Abs = np.zeros(len(wave))
for iel,El in enumerate(Els):
BL = BLtables[El][1]
SA = BL['SA']*wave/1.798197+4.0*np.pi*FPP[iel]**2 #+BL['SL'][1]?
SA *= ElList[El]['FormulaNo']/data['Form Vol']
Abs += SA
MuR = Abs*data['Diam']/2.
IofQ[1][1] /= Absorb(data['Geometry'],MuR,inst['2-theta'][1]*np.ones(len(wave)))
# improves look of F(Q) but no impact on G(R)
# bBut,aBut = signal.butter(8,.5,"lowpass")
# IofQ[1][1] = signal.filtfilt(bBut,aBut,IofQ[1][1])
XY = IofQ[1]
#convert to Q
nQpoints = 5000
if 'C' in inst['Type'][0]:
wave = G2mth.getWave(inst)
minQ = npT2q(Tth[0],wave)
maxQ = npT2q(Tth[-1],wave)
Qpoints = np.linspace(0.,maxQ,nQpoints,endpoint=True)
dq = Qpoints[1]-Qpoints[0]
XY[0] = npT2q(XY[0],wave)
Qdata = si.griddata(XY[0],XY[1],Qpoints,method='linear',fill_value=XY[1][0]) #interpolate I(Q)
elif 'T' in inst['Type'][0]:
difC = inst['difC'][1]
minQ = 2.*np.pi*difC/Tth[-1]
maxQ = 2.*np.pi*difC/Tth[0]
Qpoints = np.linspace(0.,maxQ,nQpoints,endpoint=True)
dq = Qpoints[1]-Qpoints[0]
XY[0] = 2.*np.pi*difC/XY[0]
Qdata = si.griddata(XY[0],XY[1],Qpoints,method='linear',fill_value=XY[1][-1]) #interpolate I(Q)
Qdata -= np.min(Qdata)*data['BackRatio']
qLimits = data['QScaleLim']
maxQ = np.searchsorted(Qpoints,min(Qpoints[-1],qLimits[1]))+1
minQ = np.searchsorted(Qpoints,min(qLimits[0],0.90*Qpoints[-1]))
qLimits = [Qpoints[minQ],Qpoints[maxQ-1]]
newdata = []
if len(IofQ) < 3:
xydata['IofQ'] = [IofQ[0],[Qpoints,Qdata],'']
else:
xydata['IofQ'] = [IofQ[0],[Qpoints,Qdata],IofQ[2]]
for item in xydata['IofQ'][1]:
newdata.append(item[:maxQ])
xydata['IofQ'][1] = newdata
xydata['SofQ'] = copy.deepcopy(xydata['IofQ'])
if 'XC' in inst['Type'][0]:
FFSq,SqFF,CF = GetAsfMean(ElList,(xydata['SofQ'][1][0]/(4.0*np.pi))**2) #these are <f^2>,<f>^2,Cf
else: #TOF
CF = np.zeros(len(xydata['SofQ'][1][0]))
FFSq = np.ones(len(xydata['SofQ'][1][0]))
SqFF = np.ones(len(xydata['SofQ'][1][0]))
Q = xydata['SofQ'][1][0]
# auxPlot.append([Q,np.copy(CF),'CF-unCorr'])
if 'XC' in inst['Type'][0]:
# CF *= KleinNishina(wave,Q)
ruland = Ruland(data['Ruland'],wave,Q,CF)
# auxPlot.append([Q,ruland,'Ruland'])
CF *= ruland
# auxPlot.append([Q,CF,'CF-Corr'])
scale = np.sum((FFSq+CF)[minQ:maxQ])/np.sum(xydata['SofQ'][1][1][minQ:maxQ])
xydata['SofQ'][1][1] *= scale
if 'XC' in inst['Type'][0]:
xydata['SofQ'][1][1] -= CF
xydata['SofQ'][1][1] = xydata['SofQ'][1][1]/SqFF
scale = len(xydata['SofQ'][1][1][minQ:maxQ])/np.sum(xydata['SofQ'][1][1][minQ:maxQ])
xydata['SofQ'][1][1] *= scale
xydata['FofQ'] = copy.deepcopy(xydata['SofQ'])
xydata['FofQ'][1][1] = xydata['FofQ'][1][0]*(xydata['SofQ'][1][1]-1.0)
if data['Lorch']:
xydata['FofQ'][1][1] *= LorchWeight(Q)
xydata['GofR'] = copy.deepcopy(xydata['FofQ'])
xydata['gofr'] = copy.deepcopy(xydata['FofQ'])
nR = len(xydata['GofR'][1][1])
Rmax = GSASIIpath.GetConfigValue('PDF_Rmax',100.)
mul = int(round(2.*np.pi*nR/(Rmax*qLimits[1])))
# mul = int(round(2.*np.pi*nR/(data.get('Rmax',100.)*qLimits[1])))
R = 2.*np.pi*np.linspace(0,nR,nR,endpoint=True)/(mul*qLimits[1])
xydata['GofR'][1][0] = R
xydata['gofr'][1][0] = R
GR = -(2./np.pi)*dq*np.imag(fft.fft(xydata['FofQ'][1][1],mul*nR)[:nR])*data.get('GR Scale',1.0)
# GR = -dq*np.imag(fft.fft(xydata['FofQ'][1][1],mul*nR)[:nR])*data.get('GR Scale',1.0)
xydata['GofR'][1][1] = GR
numbDen = 0.
if 'ElList' in data:
numbDen = GetNumDensity(data['ElList'],data['Form Vol'])
gr = GR/(4.*np.pi*numbDen*R)+1.
# gr = GR/(np.pi*R) ##mising numberdensity
xydata['gofr'][1][1] = gr
if data.get('noRing',True):
Rmin = data['Rmin']
xydata['gofr'][1][1] = np.where(R<Rmin,-4.*numbDen,xydata['gofr'][1][1])
xydata['GofR'][1][1] = np.where(R<Rmin,-4.*R*np.pi*numbDen,xydata['GofR'][1][1])
return auxPlot
def PDFPeakFit(peaks,data):
rs2pi = 1./np.sqrt(2*np.pi)
def MakeParms(peaks):
varyList = []
parmDict = {'slope':peaks['Background'][1][1]}
if peaks['Background'][2]:
varyList.append('slope')
for i,peak in enumerate(peaks['Peaks']):
parmDict['PDFpos;'+str(i)] = peak[0]
parmDict['PDFmag;'+str(i)] = peak[1]
parmDict['PDFsig;'+str(i)] = peak[2]
if 'P' in peak[3]:
varyList.append('PDFpos;'+str(i))
if 'M' in peak[3]:
varyList.append('PDFmag;'+str(i))
if 'S' in peak[3]:
varyList.append('PDFsig;'+str(i))
return parmDict,varyList
def SetParms(peaks,parmDict,varyList):
if 'slope' in varyList:
peaks['Background'][1][1] = parmDict['slope']
for i,peak in enumerate(peaks['Peaks']):
if 'PDFpos;'+str(i) in varyList:
peak[0] = parmDict['PDFpos;'+str(i)]
if 'PDFmag;'+str(i) in varyList:
peak[1] = parmDict['PDFmag;'+str(i)]
if 'PDFsig;'+str(i) in varyList:
peak[2] = parmDict['PDFsig;'+str(i)]
def CalcPDFpeaks(parmdict,Xdata):
Z = parmDict['slope']*Xdata
ipeak = 0
while True:
try:
pos = parmdict['PDFpos;'+str(ipeak)]
mag = parmdict['PDFmag;'+str(ipeak)]
wid = parmdict['PDFsig;'+str(ipeak)]
wid2 = 2.*wid**2
Z += mag*rs2pi*np.exp(-(Xdata-pos)**2/wid2)/wid
ipeak += 1
except KeyError: #no more peaks to process
return Z
def errPDFProfile(values,xdata,ydata,parmdict,varylist):
parmdict.update(zip(varylist,values))
M = CalcPDFpeaks(parmdict,xdata)-ydata
return M
newpeaks = copy.copy(peaks)
iBeg = np.searchsorted(data[1][0],newpeaks['Limits'][0])
iFin = np.searchsorted(data[1][0],newpeaks['Limits'][1])+1
X = data[1][0][iBeg:iFin]
Y = data[1][1][iBeg:iFin]
parmDict,varyList = MakeParms(peaks)
if not len(varyList):
G2fil.G2Print (' Nothing varied')
return newpeaks,None,None,None,None,None
Rvals = {}
values = np.array(Dict2Values(parmDict, varyList))
result = so.leastsq(errPDFProfile,values,full_output=True,ftol=0.0001,
args=(X,Y,parmDict,varyList))
chisq = np.sum(result[2]['fvec']**2)
Values2Dict(parmDict, varyList, result[0])
SetParms(peaks,parmDict,varyList)
Rvals['Rwp'] = np.sqrt(chisq/np.sum(Y**2))*100. #to %
chisq = np.sum(result[2]['fvec']**2)/(len(X)-len(values)) #reduced chi^2 = M/(Nobs-Nvar)
sigList = list(np.sqrt(chisq*np.diag(result[1])))
Z = CalcPDFpeaks(parmDict,X)
newpeaks['calc'] = [X,Z]
return newpeaks,result[0],varyList,sigList,parmDict,Rvals
def MakeRDF(RDFcontrols,background,inst,pwddata):
auxPlot = []
if 'C' in inst['Type'][0] or 'B' in inst['Type'][0]:
Tth = pwddata[0]
wave = G2mth.getWave(inst)
minQ = npT2q(Tth[0],wave)
maxQ = npT2q(Tth[-1],wave)
powQ = npT2q(Tth,wave)
elif 'T' in inst['Type'][0]:
TOF = pwddata[0]
difC = inst['difC'][1]
minQ = 2.*np.pi*difC/TOF[-1]
maxQ = 2.*np.pi*difC/TOF[0]
powQ = 2.*np.pi*difC/TOF
piDQ = np.pi/(maxQ-minQ)
Qpoints = np.linspace(minQ,maxQ,len(pwddata[0]),endpoint=True)
if RDFcontrols['UseObsCalc'] == 'obs-calc':
Qdata = si.griddata(powQ,pwddata[1]-pwddata[3],Qpoints,method=RDFcontrols['Smooth'],fill_value=0.)
elif RDFcontrols['UseObsCalc'] == 'obs-back':
Qdata = si.griddata(powQ,pwddata[1]-pwddata[4],Qpoints,method=RDFcontrols['Smooth'],fill_value=pwddata[1][0])
elif RDFcontrols['UseObsCalc'] == 'calc-back':
Qdata = si.griddata(powQ,pwddata[3]-pwddata[4],Qpoints,method=RDFcontrols['Smooth'],fill_value=pwddata[1][0])
elif RDFcontrols['UseObsCalc'] == 'auto-back':
auto = autoBkgCalc(background[1],pwddata[1])
Qdata = si.griddata(powQ,auto-pwddata[4],Qpoints,method=RDFcontrols['Smooth'],fill_value=0.)
Qdata *= np.sin((Qpoints-minQ)*piDQ)/piDQ
Qdata *= 0.5*np.sqrt(Qpoints) #Qbin normalization
dq = Qpoints[1]-Qpoints[0]
nR = len(Qdata)
R = 0.5*np.pi*np.linspace(0,nR,nR)/(4.*maxQ)
iFin = np.searchsorted(R,RDFcontrols['maxR'])+1
bBut,aBut = signal.butter(4,0.01)
Qsmooth = signal.filtfilt(bBut,aBut,Qdata)
# auxPlot.append([Qpoints,Qdata,'interpolate:'+RDFcontrols['Smooth']])
# auxPlot.append([Qpoints,Qsmooth,'interpolate:'+RDFcontrols['Smooth']])
DofR = dq*np.imag(fft.fft(Qsmooth,16*nR)[:nR])
auxPlot.append([R[:iFin],DofR[:iFin],'D(R) for '+RDFcontrols['UseObsCalc']])
return auxPlot
# PDF optimization =============================================================
def OptimizePDF(data,xydata,limits,inst,showFit=True,maxCycles=25):
import scipy.optimize as opt
numbDen = GetNumDensity(data['ElList'],data['Form Vol'])
Min,Init,Done = SetupPDFEval(data,xydata,limits,inst,numbDen)
xstart = Init()
bakMul = data['Sample Bkg.']['Mult']
if showFit:
rms = Min(xstart)
G2fil.G2Print(' Optimizing corrections to improve G(r) at low r')
if data['Sample Bkg.'].get('Refine',False):
# data['Flat Bkg'] = 0.
G2fil.G2Print(' start: Ruland={:.3f}, Sample Bkg mult={:.3f} (RMS:{:.4f})'.format(
data['Ruland'],data['Sample Bkg.']['Mult'],rms))
else:
G2fil.G2Print(' start: Flat Bkg={:.1f}, BackRatio={:.3f}, Ruland={:.3f} (RMS:{:.4f})'.format(
data['Flat Bkg'],data['BackRatio'],data['Ruland'],rms))
if data['Sample Bkg.'].get('Refine',False):
res = opt.minimize(Min,xstart,bounds=([0.01,1.],[1.2*bakMul,0.8*bakMul]),
method='L-BFGS-B',options={'maxiter':maxCycles},tol=0.001)
else:
res = opt.minimize(Min,xstart,bounds=([0.,None],[0,1],[0.01,1.]),
method='L-BFGS-B',options={'maxiter':maxCycles},tol=0.001)
Done(res['x'])
if showFit:
if res['success']:
msg = 'Converged'
else:
msg = 'Not Converged'
if data['Sample Bkg.'].get('Refine',False):
G2fil.G2Print(' end: Ruland={:.3f}, Sample Bkg mult={:.3f} (RMS:{:.4f}) *** {} ***\n'.format(
data['Ruland'],data['Sample Bkg.']['Mult'],res['fun'],msg))
else:
G2fil.G2Print(' end: Flat Bkg={:.1f}, BackRatio={:.3f}, Ruland={:.3f} RMS:{:.4f}) *** {} ***\n'.format(
data['Flat Bkg'],data['BackRatio'],data['Ruland'],res['fun'],msg))
return res
def SetupPDFEval(data,xydata,limits,inst,numbDen):
Data = copy.deepcopy(data)
BkgMax = 1.
def EvalLowPDF(arg):
'''Objective routine -- evaluates the RMS deviations in G(r)
from -4(pi)*#density*r for for r<Rmin
arguments are ['Flat Bkg','BackRatio','Ruland'] scaled so that
the min & max values are between 0 and 1.
'''
if Data['Sample Bkg.'].get('Refine',False):
R,S = arg
Data['Sample Bkg.']['Mult'] = S
else:
F,B,R = arg
Data['Flat Bkg'] = BkgMax*(2.*F-1.)
Data['BackRatio'] = B
Data['Ruland'] = R
CalcPDF(Data,inst,limits,xydata)
# test low r computation
g = xydata['GofR'][1][1]
r = xydata['GofR'][1][0]
g0 = g[r < Data['Rmin']] + 4*np.pi*r[r < Data['Rmin']]*numbDen
M = sum(g0**2)/len(g0)
return M
def GetCurrentVals():
'''Get the current ['Flat Bkg','BackRatio','Ruland'] with scaling
'''
if data['Sample Bkg.'].get('Refine',False):
return [max(data['Ruland'],.05),data['Sample']['Mult']]
try:
F = 0.5+0.5*data['Flat Bkg']/BkgMax
except:
F = 0
return [F,data['BackRatio'],max(data['Ruland'],.05)]
def SetFinalVals(arg):
'''Set the 'Flat Bkg', 'BackRatio' & 'Ruland' values from the
scaled, refined values and plot corrected region of G(r)
'''
if data['Sample Bkg.'].get('Refine',False):
R,S = arg
data['Sample Bkg.']['Mult'] = S
else:
F,B,R = arg
data['Flat Bkg'] = BkgMax*(2.*F-1.)
data['BackRatio'] = B
data['Ruland'] = R
CalcPDF(data,inst,limits,xydata)
EvalLowPDF(GetCurrentVals())
BkgMax = max(xydata['IofQ'][1][1])/50.
return EvalLowPDF,GetCurrentVals,SetFinalVals
#### GSASII convolution peak fitting routines: Finger, Cox & Jephcoat model
def factorize(num):
''' Provide prime number factors for integer num
:returns: dictionary of prime factors (keys) & power for each (data)
'''
factors = {}
orig = num
# we take advantage of the fact that (i +1)**2 = i**2 + 2*i +1
i, sqi = 2, 4
while sqi <= num:
while not num%i:
num /= i
factors[i] = factors.get(i, 0) + 1
sqi += 2*i + 1
i += 1
if num != 1 and num != orig:
factors[num] = factors.get(num, 0) + 1
if factors:
return factors
else:
return {num:1} #a prime number!
def makeFFTsizeList(nmin=1,nmax=1023,thresh=15):
''' Provide list of optimal data sizes for FFT calculations
:param int nmin: minimum data size >= 1
:param int nmax: maximum data size > nmin
:param int thresh: maximum prime factor allowed
:Returns: list of data sizes where the maximum prime factor is < thresh
'''
plist = []
nmin = max(1,nmin)
nmax = max(nmin+1,nmax)
for p in range(nmin,nmax):
if max(list(factorize(p).keys())) < thresh:
plist.append(p)
return plist
np.seterr(divide='ignore')
# Normal distribution
# loc = mu, scale = std
_norm_pdf_C = 1./math.sqrt(2*math.pi)
class norm_gen(st.rv_continuous):
'''
Normal distribution
The location (loc) keyword specifies the mean.
The scale (scale) keyword specifies the standard deviation.
normal.pdf(x) = exp(-x**2/2)/sqrt(2*pi)
'''
def pdf(self,x,*args,**kwds):
loc,scale=kwds['loc'],kwds['scale']
x = (x-loc)/scale
return np.exp(-x**2/2.0) * _norm_pdf_C / scale
norm = norm_gen(name='norm')
## Cauchy
# median = loc
class cauchy_gen(st.rv_continuous):
'''
Cauchy distribution
cauchy.pdf(x) = 1/(pi*(1+x**2))
This is the t distribution with one degree of freedom.
'''
def pdf(self,x,*args,**kwds):
loc,scale=kwds['loc'],kwds['scale']
x = (x-loc)/scale
return 1.0/np.pi/(1.0+x*x) / scale
cauchy = cauchy_gen(name='cauchy')
class fcjde_gen(st.rv_continuous):
"""
Finger-Cox-Jephcoat D(2phi,2th) function for S/L = H/L
Ref: J. Appl. Cryst. (1994) 27, 892-900.
:param x: array -1 to 1
:param t: 2-theta position of peak
:param s: sum(S/L,H/L); S: sample height, H: detector opening,
L: sample to detector opening distance
:param dx: 2-theta step size in deg
:returns: for fcj.pdf
* T = x*dx+t
* s = S/L+H/L
* if x < 0::
fcj.pdf = [1/sqrt({cos(T)**2/cos(t)**2}-1) - 1/s]/|cos(T)|
* if x >= 0: fcj.pdf = 0
"""
def _pdf(self,x,t,s,dx):
T = dx*x+t
ax2 = abs(npcosd(T))
ax = ax2**2
bx = npcosd(t)**2
bx = np.where(ax>bx,bx,ax)
fx = np.where(ax>bx,(np.sqrt(bx/(ax-bx))-1./s)/ax2,0.0)
fx = np.where(fx > 0.,fx,0.0)
return fx
def pdf(self,x,*args,**kwds):
loc=kwds['loc']
return self._pdf(x-loc,*args)
fcjde = fcjde_gen(name='fcjde',shapes='t,s,dx')
def getFCJVoigt(pos,intens,sig,gam,shl,xdata):
'''Compute the Finger-Cox-Jepcoat modified Voigt function for a
CW powder peak by direct convolution. This version is not used.
'''
DX = xdata[1]-xdata[0]
widths,fmin,fmax = getWidthsCW(pos,sig,gam,shl)
x = np.linspace(pos-fmin,pos+fmin,256)
dx = x[1]-x[0]
Norm = norm.pdf(x,loc=pos,scale=widths[0])
Cauchy = cauchy.pdf(x,loc=pos,scale=widths[1])
arg = [pos,shl/57.2958,dx,]
FCJ = fcjde.pdf(x,*arg,loc=pos)
if len(np.nonzero(FCJ)[0])>5:
z = np.column_stack([Norm,Cauchy,FCJ]).T
Z = fft.fft(z)
Df = fft.ifft(Z.prod(axis=0)).real
else:
z = np.column_stack([Norm,Cauchy]).T
Z = fft.fft(z)
Df = fft.fftshift(fft.ifft(Z.prod(axis=0))).real
Df /= np.sum(Df)
Df = si.interp1d(x,Df,bounds_error=False,fill_value=0.0)
return intens*Df(xdata)*DX/dx
#### GSASII peak fitting routine: Finger, Cox & Jephcoat model
def getWidthsCW(pos,sig,gam,shl):
'''Compute the peak widths used for computing the range of a peak
for constant wavelength data. On low-angle side, 50 FWHM are used,
on high-angle side 75 are used, high angle side extended for axial divergence
(for peaks above 90 deg, these are reversed.)
:param pos: peak position; 2-theta in degrees
:param sig: Gaussian peak variance in centideg^2
:param gam: Lorentzian peak width in centidegrees
:param shl: axial divergence parameter (S+H)/L
:returns: widths; [Gaussian sigma, Lorentzian gamma] in degrees, and
low angle, high angle ends of peak; 20 FWHM & 50 FWHM from position
reversed for 2-theta > 90 deg.
'''
widths = [np.sqrt(sig)/100.,gam/100.]
fwhm = 2.355*widths[0]+widths[1]
fmin = 50.*(fwhm+shl*abs(npcosd(pos)))
fmax = 75.0*fwhm
if pos > 90:
fmin,fmax = [fmax,fmin]
return widths,fmin,fmax
def getWidthsED(pos,sig,gam):
'''Compute the peak widths used for computing the range of a peak
for energy dispersive data. On low-energy side, 20 FWHM are used,
on high-energy side 20 are used
:param pos: peak position; energy in keV (not used)
:param sig: Gaussian peak variance in keV^2
:param gam: Lorentzian peak width in keV
:returns: widths; [Gaussian sigma, Lorentzian gamma] in keV, and
low angle, high angle ends of peak; 5 FWHM & 5 FWHM from position
'''
widths = [np.sqrt(sig),gam]
fwhm = 2.355*widths[0]+widths[1]
fmin = 5.*fwhm
fmax = 5.*fwhm
return widths,fmin,fmax
def getWidthsTOF(pos,alp,bet,sig,gam):
'''Compute the peak widths used for computing the range of a peak
for constant wavelength data. 50 FWHM are used on both sides each
extended by exponential coeff.
param pos: peak position; TOF in musec (not used)
param alp,bet: TOF peak exponential rise & decay parameters
param sig: Gaussian peak variance in musec^2
param gam: Lorentzian peak width in musec
returns: widths; [Gaussian sigma, Lornetzian gamma] in musec
returns: low TOF, high TOF ends of peak; 50FWHM from position
'''
widths = [np.sqrt(sig),gam]
fwhm = 2.355*widths[0]+2.*widths[1]
fmin = 50.*fwhm*(1.+1./alp)
fmax = 50.*fwhm*(1.+1./bet)
return widths,fmin,fmax
def getFWHM(pos,Inst,N=1):
'''Compute total FWHM from Thompson, Cox & Hastings (1987) , J. Appl. Cryst. 20, 79-83
via getgamFW(g,s).
:param pos: float peak position in deg 2-theta or tof in musec
:param Inst: dict instrument parameters
:param N: int Inst index (0 for input, 1 for fitted)
:returns float: total FWHM of pseudoVoigt in deg or musec
'''
sig = lambda Th,U,V,W: np.sqrt(max(0.001,U*tand(Th)**2+V*tand(Th)+W))
sigED = lambda E,A,B,C: np.sqrt(max(0.001,A*E**2+B*E+C))
sigTOF = lambda dsp,S0,S1,S2,Sq: np.sqrt(S0+S1*dsp**2+S2*dsp**4+Sq*dsp)
gam = lambda Th,X,Y,Z: Z+X/cosd(Th)+Y*tand(Th)
gamED = lambda E,X,Y,Z: max(0.001,X*E**2+Y*E+Z)
gamTOF = lambda dsp,X,Y,Z: Z+X*dsp+Y*dsp**2
alpTOF = lambda dsp,alp: alp/dsp
betTOF = lambda dsp,bet0,bet1,betq: bet0+bet1/dsp**4+betq/dsp**2
alpPinkX = lambda pos,alp0,alp1: alp0+alp1*nptand(pos/2.)
betPinkX = lambda pos,bet0,bet1: bet0+bet1*nptand(pos/2.)
alpPinkN = lambda pos,alp0,alp1: alp0+alp1*npsind(pos/2.)
betPinkN = lambda pos,bet0,bet1: bet0+bet1*npsind(pos/2.)
if 'LF' in Inst['Type'][0]:
return 3
elif 'T' in Inst['Type'][0]:
dsp = pos/Inst['difC'][N]
alp = alpTOF(dsp,Inst['alpha'][N])
bet = betTOF(dsp,Inst['beta-0'][1],Inst['beta-1'][N],Inst['beta-q'][N])
s = sigTOF(dsp,Inst['sig-0'][N],Inst['sig-1'][N],Inst['sig-2'][N],Inst['sig-q'][N])
g = gamTOF(dsp,Inst['X'][N],Inst['Y'][N],Inst['Z'][N])
return getgamFW(g,s)+np.log(2.0)*(alp+bet)/(alp*bet)
elif 'C' in Inst['Type'][0]:
s = sig(pos/2.,Inst['U'][N],Inst['V'][N],Inst['W'][N])
g = gam(pos/2.,Inst['X'][N],Inst['Y'][N],Inst['Z'][N])
return getgamFW(g,s)/100. #returns FWHM in deg
elif 'E' in Inst['Type'][0]:
s = sigED(pos,Inst['A'][N],Inst['B'][N],Inst['C'][N])
g = gamED(pos,Inst['X'][N],Inst['Y'][N],Inst['Z'][N])
return getgamFW(g,s)
else: #'B'
if 'X' in Inst['Type'][0]:
alp = alpPinkX(pos,Inst['alpha-0'][N],Inst['alpha-1'][N])
bet = betPinkX(pos,Inst['beta-0'][N],Inst['beta-1'][N])
else:
alp = alpPinkN(pos,Inst['alpha-0'][N],Inst['alpha-1'][N])
bet = betPinkN(pos,Inst['beta-0'][N],Inst['beta-1'][N])
s = sig(pos/2.,Inst['U'][N],Inst['V'][N],Inst['W'][N])
g = gam(pos/2.,Inst['X'][N],Inst['Y'][N],Inst['Z'][N])
return getgamFW(g,s)/100.+np.log(2.0)*(alp+bet)/(alp*bet) #returns FWHM in deg
def getgamFW(g,s):
'''Compute total FWHM from Thompson, Cox & Hastings (1987), J. Appl. Cryst. 20, 79-83
lambda fxn needs FWHM for both Gaussian & Lorentzian components
:param g: float Lorentzian gamma = FWHM(L)
:param s: float Gaussian sig
:returns float: total FWHM of pseudoVoigt
'''
gamFW = lambda s,g: np.exp(np.log(s**5+2.69269*s**4*g+2.42843*s**3*g**2+4.47163*s**2*g**3+0.07842*s*g**4+g**5)/5.)
return gamFW(2.35482*s,g) #sqrt(8ln2)*sig = FWHM(G)
def getBackground(pfx,parmDict,bakType,dataType,xdata,fixback=None):
'''Computes the background based on parameters that may be taken from
a gpx file or the data tree.
:param str pfx: histogram prefix (:h:)
:param dict parmDict: Refinement parameter values
:param str bakType: defines background function to be used. Should be
one of these: 'chebyschev', 'cosine', 'chebyschev-1',
'Q^2 power series', 'Q^-2 power series', 'lin interpolate',
'inv interpolate', 'log interpolate'
:param str dataType: Code to indicate histogram type (PXC, PNC, PNT,...)
:param MaskedArray xdata: independent variable, 2theta (deg*100) or
TOF (microsec?)
:param numpy.array fixback: Array of fixed background points (length
matching xdata) or None
:returns: yb,sumBK where yp is an array of background values (length
matching xdata) and sumBK is a list with three values. The sumBK[0] is
the sum of all yb values, sumBK[1] is the sum of Debye background terms
and sumBK[2] is the sum of background peaks.
'''
if 'T' in dataType:
q = 2.*np.pi*parmDict[pfx+'difC']/xdata
elif 'E' in dataType:
const = 4.*np.pi*npsind(parmDict[pfx+'2-theta']/2.0)
q = const*xdata
else:
wave = parmDict.get(pfx+'Lam',parmDict.get(pfx+'Lam1',1.0))
q = npT2q(xdata,wave)
yb = np.zeros_like(xdata)
nBak = 0
sumBk = [0.,0.,0]
while True:
key = pfx+'Back;'+str(nBak)
if key in parmDict:
nBak += 1
else:
break
#empirical functions
if bakType in ['chebyschev','cosine','chebyschev-1']:
dt = xdata[-1]-xdata[0]
for iBak in range(nBak):
key = pfx+'Back;'+str(iBak)
if bakType == 'chebyschev':
ybi = parmDict[key]*(-1.+2.*(xdata-xdata[0])/dt)**iBak
elif bakType == 'chebyschev-1':
xpos = -1.+2.*(xdata-xdata[0])/dt
ybi = parmDict[key]*np.cos(iBak*np.arccos(xpos))
elif bakType == 'cosine':
ybi = parmDict[key]*npcosd(180.*xdata*iBak/xdata[-1])
yb += ybi
sumBk[0] = np.sum(yb)
elif bakType in ['Q^2 power series','Q^-2 power series']:
QT = 1.
yb += np.ones_like(yb)*parmDict[pfx+'Back;0']
for iBak in range(nBak-1):
key = pfx+'Back;'+str(iBak+1)
if '-2' in bakType:
QT *= (iBak+1)*q**-2
else:
QT *= q**2/(iBak+1)
yb += QT*parmDict[key]
sumBk[0] = np.sum(yb)
elif bakType in ['lin interpolate','inv interpolate','log interpolate',]:
if nBak == 1:
yb = np.ones_like(xdata)*parmDict[pfx+'Back;0']
elif nBak == 2:
dX = xdata[-1]-xdata[0]
T2 = (xdata-xdata[0])/dX
T1 = 1.0-T2
yb = parmDict[pfx+'Back;0']*T1+parmDict[pfx+'Back;1']*T2
else: