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
/
GSASIIobj.py
2260 lines (2041 loc) · 90.9 KB
/
GSASIIobj.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 -*-
#GSASIIobj - data objects for GSAS-II
########### SVN repository information ###################
# $Date: 2023-09-29 15:47:55 -0500 (Fri, 29 Sep 2023) $
# $Author: vondreele $
# $Revision: 5663 $
# $URL: https://subversion.xray.aps.anl.gov/pyGSAS/trunk/GSASIIobj.py $
# $Id: GSASIIobj.py 5663 2023-09-29 20:47:55Z vondreele $
########### SVN repository information ###################
'''
Classes and routines defined in :mod:`GSASIIobj` follow.
'''
# Note that documentation for GSASIIobj.py has been moved
# to file docs/source/GSASIIobj.rst
from __future__ import division, print_function
import platform
import re
import random as ran
import sys
import os.path
if '2' in platform.python_version_tuple()[0]:
import cPickle
else:
import pickle as cPickle
import GSASIIpath
import GSASIImath as G2mth
import GSASIIspc as G2spc
import numpy as np
GSASIIpath.SetVersionNumber("$Revision: 5663 $")
DefaultControls = {
'deriv type':'analytic Hessian',
'min dM/M':0.001,'shift factor':1.,'max cyc':3,'F**2':False,'SVDtol':1.e-6,
'UsrReject':{'minF/sig':0.,'MinExt':0.01,'MaxDF/F':100.,'MaxD':500.,'MinD':0.05},
'Copy2Next':False,'Reverse Seq':False,'HatomFix':False,
'Author':'no name','newLeBail':False,
'FreePrm1':'Sample humidity (%)',
'FreePrm2':'Sample voltage (V)',
'FreePrm3':'Applied load (MN)',
'ShowCell':False,
}
'''Values to be used as defaults for the initial contents of the ``Controls``
data tree item.
'''
def StripUnicode(string,subs='.'):
'''Strip non-ASCII characters from strings
:param str string: string to strip Unicode characters from
:param str subs: character(s) to place into string in place of each
Unicode character. Defaults to '.'
:returns: a new string with only ASCII characters
'''
s = ''
for c in string:
if ord(c) < 128:
s += c
else:
s += subs
return s
# return s.encode('ascii','replace')
def MakeUniqueLabel(lbl,labellist):
'''Make sure that every a label is unique against a list by adding
digits at the end until it is not found in list.
:param str lbl: the input label
:param list labellist: the labels that have already been encountered
:returns: lbl if not found in labellist or lbl with ``_1-9`` (or
``_10-99``, etc.) appended at the end
'''
lbl = StripUnicode(lbl.strip(),'_')
if not lbl: # deal with a blank label
lbl = '_1'
if lbl not in labellist:
labellist.append(lbl)
return lbl
i = 1
prefix = lbl
if '_' in lbl:
prefix = lbl[:lbl.rfind('_')]
suffix = lbl[lbl.rfind('_')+1:]
try:
i = int(suffix)+1
except: # suffix could not be parsed
i = 1
prefix = lbl
while prefix+'_'+str(i) in labellist:
i += 1
else:
lbl = prefix+'_'+str(i)
labellist.append(lbl)
return lbl
PhaseIdLookup = {}
'''dict listing phase name and random Id keyed by sequential phase index as a str;
best to access this using :func:`LookupPhaseName`
'''
PhaseRanIdLookup = {}
'''dict listing phase sequential index keyed by phase random Id;
best to access this using :func:`LookupPhaseId`
'''
HistIdLookup = {}
'''dict listing histogram name and random Id, keyed by sequential histogram index as a str;
best to access this using :func:`LookupHistName`
'''
HistRanIdLookup = {}
'''dict listing histogram sequential index keyed by histogram random Id;
best to access this using :func:`LookupHistId`
'''
AtomIdLookup = {}
'''dict listing for each phase index as a str, the atom label and atom random Id,
keyed by atom sequential index as a str;
best to access this using :func:`LookupAtomLabel`
'''
AtomRanIdLookup = {}
'''dict listing for each phase the atom sequential index keyed by atom random Id;
best to access this using :func:`LookupAtomId`
'''
ShortPhaseNames = {}
'''a dict containing a possibly shortened and when non-unique numbered
version of the phase name. Keyed by the phase sequential index.
'''
ShortHistNames = {}
'''a dict containing a possibly shortened and when non-unique numbered
version of the histogram name. Keyed by the histogram sequential index.
'''
#VarDesc = {} # removed 1/30/19 BHT as no longer needed (I think)
#''' This dictionary lists descriptions for GSAS-II variables,
#as set in :func:`CompileVarDesc`. See that function for a description
#for how keys and values are written.
#'''
reVarDesc = {}
''' This dictionary lists descriptions for GSAS-II variables where
keys are compiled regular expressions that will match the name portion
of a parameter name. Initialized in :func:`CompileVarDesc`.
'''
reVarStep = {}
''' This dictionary lists the preferred step size for numerical
derivative computation w/r to a GSAS-II variable. Keys are compiled
regular expressions and values are the step size for that parameter.
Initialized in :func:`CompileVarDesc`.
'''
# create a default space group object for P1; N.B. fails when building documentation
try:
P1SGData = G2spc.SpcGroup('P 1')[1] # data structure for default space group
except:
pass
def GetPhaseNames(fl):
''' Returns a list of phase names found under 'Phases' in GSASII gpx file
NB: there is another one of these in GSASIIstrIO.py that uses the gpx filename
:param file fl: opened .gpx file
:return: list of phase names
'''
PhaseNames = []
while True:
try:
data = cPickle.load(fl)
except EOFError:
break
datum = data[0]
if 'Phases' == datum[0]:
for datus in data[1:]:
PhaseNames.append(datus[0])
fl.seek(0) #reposition file
return PhaseNames
def SetNewPhase(Name='New Phase',SGData=None,cell=None,Super=None):
'''Create a new phase dict with default values for various parameters
:param str Name: Name for new Phase
:param dict SGData: space group data from :func:`GSASIIspc:SpcGroup`;
defaults to data for P 1
:param list cell: unit cell parameter list; defaults to
[1.0,1.0,1.0,90.,90,90.,1.]
'''
if SGData is None: SGData = P1SGData
if cell is None: cell=[1.0,1.0,1.0,90.,90.,90.,1.]
phaseData = {
'ranId':ran.randint(0,sys.maxsize),
'General':{
'Name':Name,
'Type':'nuclear',
'Modulated':False,
'AtomPtrs':[3,1,7,9],
'SGData':SGData,
'Cell':[False,]+cell,
'Pawley dmin':1.0,
'Data plot type':'None',
'SH Texture':{
'Order':0,
'Model':'cylindrical',
'Sample omega':[False,0.0],
'Sample chi':[False,0.0],
'Sample phi':[False,0.0],
'SH Coeff':[False,{}],
'SHShow':False,
'PFhkl':[0,0,1],
'PFxyz':[0,0,1],
'PlotType':'Pole figure',
'Penalty':[['',],0.1,False,1.0]}},
'Atoms':[],
'Drawing':{},
'Histograms':{},
'Pawley ref':[],
'RBModels':{},
}
if Super and Super.get('Use',False):
phaseData['General'].update({'Modulated':True,'Super':True,'SuperSg':Super['ssSymb']})
phaseData['General']['SSGData'] = G2spc.SSpcGroup(SGData,Super['ssSymb'])[1]
phaseData['General']['SuperVec'] = [Super['ModVec'],False,Super['maxH']]
return phaseData
def ReadCIF(URLorFile):
'''Open a CIF, which may be specified as a file name or as a URL using PyCifRW
(from James Hester).
The open routine gets confused with DOS names that begin with a letter and colon
"C:\\dir\" so this routine will try to open the passed name as a file and if that
fails, try it as a URL
:param str URLorFile: string containing a URL or a file name. Code will try first
to open it as a file and then as a URL.
:returns: a PyCifRW CIF object.
'''
import CifFile as cif # PyCifRW from James Hester
# alternate approach:
#import urllib
#ciffile = 'file:'+urllib.pathname2url(filename)
try:
fp = open(URLorFile,'r')
cf = cif.ReadCif(fp)
fp.close()
return cf
except IOError:
return cif.ReadCif(URLorFile)
def TestIndexAll():
'''Test if :func:`IndexAllIds` has been called to index all phases and
histograms (this is needed before :func:`G2VarObj` can be used.
:returns: Returns True if indexing is needed.
'''
if PhaseIdLookup or AtomIdLookup or HistIdLookup:
return False
return True
def IndexAllIds(Histograms,Phases):
'''Scan through the used phases & histograms and create an index
to the random numbers of phases, histograms and atoms. While doing this,
confirm that assigned random numbers are unique -- just in case lightning
strikes twice in the same place.
Note: this code assumes that the atom random Id (ranId) is the last
element each atom record.
This is called when phases & histograms are looked up
in these places (only):
* :func:`GSASIIstrIO.GetUsedHistogramsAndPhases` (which loads the histograms and phases from a GPX file),
* :meth:`~GSASIIdataGUI.GSASII.GetUsedHistogramsAndPhasesfromTree` (which does the same thing but from the data tree.)
* :meth:`~GSASIIdataGUI.GSASII.OnFileClose` (clears out an old project)
Note that globals :data:`PhaseIdLookup` and :data:`PhaseRanIdLookup` are
also set in :func:`AddPhase2Index` to temporarily assign a phase number
as a phase is being imported.
TODO: do we need a lookup for rigid body variables?
'''
# process phases and atoms
PhaseIdLookup.clear()
PhaseRanIdLookup.clear()
AtomIdLookup.clear()
AtomRanIdLookup.clear()
ShortPhaseNames.clear()
for ph in Phases:
cx,ct,cs,cia = Phases[ph]['General']['AtomPtrs']
ranId = Phases[ph]['ranId']
while ranId in PhaseRanIdLookup:
# Found duplicate random Id! note and reassign
print ("\n\n*** Phase "+str(ph)+" has repeated ranId. Fixing.\n")
Phases[ph]['ranId'] = ranId = ran.randint(0,sys.maxsize)
pId = str(Phases[ph]['pId'])
PhaseIdLookup[pId] = (ph,ranId)
PhaseRanIdLookup[ranId] = pId
shortname = ph #[:10]
while shortname in ShortPhaseNames.values():
shortname = ph[:8] + ' ('+ pId + ')'
ShortPhaseNames[pId] = shortname
AtomIdLookup[pId] = {}
AtomRanIdLookup[pId] = {}
for iatm,at in enumerate(Phases[ph]['Atoms']):
ranId = at[cia+8]
while ranId in AtomRanIdLookup[pId]: # check for dups
print ("\n\n*** Phase "+str(ph)+" atom "+str(iatm)+" has repeated ranId. Fixing.\n")
at[cia+8] = ranId = ran.randint(0,sys.maxsize)
AtomRanIdLookup[pId][ranId] = str(iatm)
if Phases[ph]['General']['Type'] == 'macromolecular':
label = '%s_%s_%s_%s'%(at[ct-1],at[ct-3],at[ct-4],at[ct-2])
else:
label = at[ct-1]
AtomIdLookup[pId][str(iatm)] = (label,ranId)
# process histograms
HistIdLookup.clear()
HistRanIdLookup.clear()
ShortHistNames.clear()
for hist in Histograms:
ranId = Histograms[hist]['ranId']
while ranId in HistRanIdLookup:
# Found duplicate random Id! note and reassign
print ("\n\n*** Histogram "+str(hist)+" has repeated ranId. Fixing.\n")
Histograms[hist]['ranId'] = ranId = ran.randint(0,sys.maxsize)
hId = str(Histograms[hist]['hId'])
HistIdLookup[hId] = (hist,ranId)
HistRanIdLookup[ranId] = hId
shortname = hist[:15]
while shortname in ShortHistNames.values():
shortname = hist[:11] + ' ('+ hId + ')'
ShortHistNames[hId] = shortname
def AddPhase2Index(rdObj,filename):
'''Add a phase to the index during reading
Used where constraints are generated during import (ISODISTORT CIFs)
'''
ranId = rdObj.Phase['ranId']
ph = 'from '+filename # phase is not named yet
if ranId in PhaseRanIdLookup: return
maxph = -1
for r in PhaseRanIdLookup:
maxph = max(maxph,int(PhaseRanIdLookup[r]))
PhaseRanIdLookup[ranId] = pId = str(maxph + 1)
PhaseIdLookup[pId] = (ph,ranId)
shortname = 'from '+ os.path.splitext((os.path.split(filename))[1])[0]
while shortname in ShortPhaseNames.values():
shortname = ph[:8] + ' ('+ pId + ')'
ShortPhaseNames[pId] = shortname
AtomIdLookup[pId] = {}
AtomRanIdLookup[pId] = {}
for iatm,at in enumerate(rdObj.Phase['Atoms']):
ranId = at[-1]
while ranId in AtomRanIdLookup[pId]: # check for dups
print ("\n\n*** Phase "+str(ph)+" atom "+str(iatm)+" has repeated ranId. Fixing.\n")
at[-1] = ranId = ran.randint(0,sys.maxsize)
AtomRanIdLookup[pId][ranId] = str(iatm)
#if Phases[ph]['General']['Type'] == 'macromolecular':
# label = '%s_%s_%s_%s'%(at[ct-1],at[ct-3],at[ct-4],at[ct-2])
#else:
# label = at[ct-1]
label = at[0]
AtomIdLookup[pId][str(iatm)] = (label,ranId)
def LookupAtomId(pId,ranId):
'''Get the atom number from a phase and atom random Id
:param int/str pId: the sequential number of the phase
:param int ranId: the random Id assigned to an atom
:returns: the index number of the atom (str)
'''
if not AtomRanIdLookup:
raise Exception('Error: LookupAtomId called before IndexAllIds was run')
if pId is None or pId == '':
raise KeyError('Error: phase is invalid (None or blank)')
pId = str(pId)
if pId not in AtomRanIdLookup:
raise KeyError('Error: LookupAtomId does not have phase '+pId)
if ranId not in AtomRanIdLookup[pId]:
raise KeyError('Error: LookupAtomId, ranId '+str(ranId)+' not in AtomRanIdLookup['+pId+']')
return AtomRanIdLookup[pId][ranId]
def LookupAtomLabel(pId,index):
'''Get the atom label from a phase and atom index number
:param int/str pId: the sequential number of the phase
:param int index: the index of the atom in the list of atoms
:returns: the label for the atom (str) and the random Id of the atom (int)
'''
if not AtomIdLookup:
raise Exception('Error: LookupAtomLabel called before IndexAllIds was run')
if pId is None or pId == '':
raise KeyError('Error: phase is invalid (None or blank)')
pId = str(pId)
if pId not in AtomIdLookup:
raise KeyError('Error: LookupAtomLabel does not have phase '+pId)
if index not in AtomIdLookup[pId]:
raise KeyError('Error: LookupAtomLabel, ranId '+str(index)+' not in AtomRanIdLookup['+pId+']')
return AtomIdLookup[pId][index]
def LookupPhaseId(ranId):
'''Get the phase number and name from a phase random Id
:param int ranId: the random Id assigned to a phase
:returns: the sequential Id (pId) number for the phase (str)
'''
if not PhaseRanIdLookup:
raise Exception('Error: LookupPhaseId called before IndexAllIds was run')
if ranId not in PhaseRanIdLookup:
raise KeyError('Error: LookupPhaseId does not have ranId '+str(ranId))
return PhaseRanIdLookup[ranId]
def LookupPhaseName(pId):
'''Get the phase number and name from a phase Id
:param int/str pId: the sequential assigned to a phase
:returns: (phase,ranId) where phase is the name of the phase (str)
and ranId is the random # id for the phase (int)
'''
if not PhaseIdLookup:
raise Exception('Error: LookupPhaseName called before IndexAllIds was run')
if pId is None or pId == '':
raise KeyError('Error: phase is invalid (None or blank)')
pId = str(pId)
if pId not in PhaseIdLookup:
raise KeyError('Error: LookupPhaseName does not have index '+pId)
return PhaseIdLookup[pId]
def LookupHistId(ranId):
'''Get the histogram number and name from a histogram random Id
:param int ranId: the random Id assigned to a histogram
:returns: the sequential Id (hId) number for the histogram (str)
'''
if not HistRanIdLookup:
raise Exception('Error: LookupHistId called before IndexAllIds was run')
if ranId not in HistRanIdLookup:
raise KeyError('Error: LookupHistId does not have ranId '+str(ranId))
return HistRanIdLookup[ranId]
def LookupHistName(hId):
'''Get the histogram number and name from a histogram Id
:param int/str hId: the sequential assigned to a histogram
:returns: (hist,ranId) where hist is the name of the histogram (str)
and ranId is the random # id for the histogram (int)
'''
if not HistIdLookup:
raise Exception('Error: LookupHistName called before IndexAllIds was run')
if hId is None or hId == '':
raise KeyError('Error: histogram is invalid (None or blank)')
hId = str(hId)
if hId not in HistIdLookup:
raise KeyError('Error: LookupHistName does not have index '+hId)
return HistIdLookup[hId]
def fmtVarDescr(varname):
'''Return a string with a more complete description for a GSAS-II variable
:param str varname: A full G2 variable name with 2 or 3 or 4
colons (<p>:<h>:name[:<a>] or <p>::RBname:<r>:<t>])
:returns: a string with the description
'''
s,l = VarDescr(varname)
return s+": "+l
def VarDescr(varname):
'''Return two strings with a more complete description for a GSAS-II variable
:param str name: A full G2 variable name with 2 or 3 or 4
colons (<p>:<h>:name[:<a>] or <p>::RBname:<r>:<t>])
:returns: (loc,meaning) where loc describes what item the variable is mapped
(phase, histogram, etc.) and meaning describes what the variable does.
'''
# special handling for parameter names without a colon
# for now, assume self-defining
if varname.find(':') == -1:
return "Global",varname
l = getVarDescr(varname)
if not l:
return ("invalid variable name ("+str(varname)+")!"),""
# return "invalid variable name!",""
if not l[-1]:
l[-1] = "(variable needs a definition! Set it in CompileVarDesc)"
if len(l) == 3: #SASD variable name!
s = 'component:'+l[1]
return s,l[-1]
s = ""
if l[0] is not None and l[1] is not None: # HAP: keep short
if l[2] == "Scale": # fix up ambigous name
l[5] = "Phase fraction"
if l[0] == '*':
lbl = 'Seq. ref.'
else:
lbl = ShortPhaseNames.get(l[0],'? #'+str(l[0]))
if l[1] == '*':
hlbl = 'Seq. ref.'
else:
hlbl = ShortHistNames.get(l[1],'? #'+str(l[1]))
if hlbl[:4] == 'HKLF':
hlbl = 'Xtl='+hlbl[5:]
elif hlbl[:4] == 'PWDR':
hlbl = 'Pwd='+hlbl[5:]
else:
hlbl = 'Hist='+hlbl
s = "Ph="+str(lbl)+" * "+str(hlbl)
else:
if l[2] == "Scale": # fix up ambigous name: must be scale factor, since not HAP
l[5] = "Scale factor"
if l[2] == 'Back': # background parameters are "special", alas
s = 'Hist='+ShortHistNames.get(l[1],'? #'+str(l[1]))
l[-1] += ' #'+str(l[3])
elif l[4] is not None: # rigid body parameter or modulation parm
lbl = ShortPhaseNames.get(l[0],'phase?')
if 'RB' in l[2]: #rigid body parm
s = "RB body #"+str(l[3])+" (type "+str(l[4])+") in "+str(lbl) + ','
else: #modulation parm
s = 'Atom %s wave %s in %s'%(LookupAtomLabel(l[0],l[3])[0],l[4],lbl)
elif l[3] is not None: # atom parameter,
lbl = ShortPhaseNames.get(l[0],'phase?')
try:
albl = LookupAtomLabel(l[0],l[3])[0]
except KeyError:
albl = 'Atom?'
s = "Atom "+str(albl)+" in "+str(lbl)
elif l[0] == '*':
s = "All phases "
elif l[0] is not None:
lbl = ShortPhaseNames.get(l[0],'phase?')
s = "Phase "+str(lbl)
elif l[1] == '*':
s = 'All hists'
elif l[1] is not None:
hlbl = ShortHistNames.get(l[1],'? #'+str(l[1]))
if hlbl[:4] == 'HKLF':
hlbl = 'Xtl='+hlbl[5:]
elif hlbl[:4] == 'PWDR':
hlbl = 'Pwd='+hlbl[5:]
else:
hlbl = 'Hist='+hlbl
s = str(hlbl)
if not s:
s = 'Global'
return s,l[-1]
def getVarDescr(varname):
'''Return a short description for a GSAS-II variable
:param str name: A full G2 variable name with 2 or 3 or 4
colons (<p>:<h>:name[:<a1>][:<a2>])
:returns: a six element list as [`p`,`h`,`name`,`a1`,`a2`,`description`],
where `p`, `h`, `a1`, `a2` are str values or `None`, for the phase number,
the histogram number and the atom number; `name` will always be
a str; and `description` is str or `None`.
If the variable name is incorrectly formed (for example, wrong
number of colons), `None` is returned instead of a list.
'''
l = varname.split(':')
if len(l) == 2: #SASD parameter name
return varname,l[0],getDescr(l[1])
if len(l) == 3:
l += [None,None]
elif len(l) == 4:
l += [None]
elif len(l) != 5:
return None
for i in (0,1,3,4):
if l[i] == "":
l[i] = None
l += [getDescr(l[2])]
return l
def CompileVarDesc():
'''Set the values in the variable lookup tables
(:attr:`reVarDesc` and :attr:`reVarStep`).
This is called in :func:`getDescr` and :func:`getVarStep` so this
initialization is always done before use. These variables are
also used in script `makeVarTbl.py` which creates the table in section 3.2
of the Sphinx docs (:ref:`VarNames_table`).
Note that keys may contain regular expressions, where '[xyz]'
matches 'x' 'y' or 'z' (equivalently '[x-z]' describes this as range
of values). '.*' matches any string. For example::
'AUiso':'Atomic isotropic displacement parameter',
will match variable ``'p::AUiso:a'``.
If parentheses are used in the key, the contents of those parentheses can be
used in the value, such as::
'AU([123][123])':'Atomic anisotropic displacement parameter U\\1',
will match ``AU11``, ``AU23``,... and `U11`, `U23` etc will be displayed
in the value when used.
'''
if reVarDesc: return # already done
for key,value in {
# derived or other sequential vars
'([abc])$' : 'Lattice parameter, \\1, from Ai and Djk', # N.B. '$' prevents match if any characters follow
u'\u03B1' : u'Lattice parameter, \u03B1, computed from both Ai and Djk',
u'\u03B2' : u'Lattice parameter, \u03B2, computed from both Ai and Djk',
u'\u03B3' : u'Lattice parameter, \u03B3, computed from both Ai and Djk',
# ambiguous, alas:
'Scale' : 'Phase fraction (as p:h:Scale) or Histogram scale factor (as :h:Scale)',
# Phase vars (p::<var>)
'A([0-5])' : ('Reciprocal metric tensor component \\1',1e-5),
'([vV]ol)' : 'Unit cell volume', # probably an error that both upper and lower case are used
# Atom vars (p::<var>:a)
'dA([xyz])$' : ('Refined change to atomic coordinate, \\1',1e-6),
'A([xyz])$' : 'Fractional atomic coordinate, \\1',
'AUiso':('Atomic isotropic displacement parameter',1e-4),
'AU([123][123])':('Atomic anisotropic displacement parameter U\\1',1e-4),
'Afrac': ('Atomic site fraction parameter',1e-5),
'Amul': 'Atomic site multiplicity value',
'AM([xyz])$' : 'Atomic magnetic moment parameter, \\1',
# Atom deformation parameters
'Akappa([0-6])' : ' Atomic orbital softness for orbital, \\1',
'ANe([01])' : ' Atomic <j0> orbital population for orbital, \\1',
'AD\\([0-6],[0-6]\\)([0-6])' : ' Atomic sp. harm. coeff for orbital, \\1',
'AD\\([0-6],-[0-6]\\)([0-6])' : ' Atomic sp. harm. coeff for orbital, \\1', #need both!
# Hist (:h:<var>) & Phase (HAP) vars (p:h:<var>)
'Back(.*)': 'Background term #\\1',
'BkPkint;(.*)':'Background peak #\\1 intensity',
'BkPkpos;(.*)':'Background peak #\\1 position',
'BkPksig;(.*)':'Background peak #\\1 Gaussian width',
'BkPkgam;(.*)':'Background peak #\\1 Cauchy width',
# 'Back File' : 'Background file name',
'BF mult' : 'Background file multiplier',
'Bab([AU])': 'Babinet solvent scattering coef. \\1',
'D([123][123])' : 'Anisotropic strain coef. \\1',
'Extinction' : 'Extinction coef.',
'MD' : 'March-Dollase coef.',
'Mustrain;.*' : 'Microstrain coefficient (delta Q/Q x 10**6)',
'Size;.*' : 'Crystallite size value (in microns)',
'eA$' : 'Cubic mustrain value',
'Ep$' : 'Primary extinction',
'Es$' : 'Secondary type II extinction',
'Eg$' : 'Secondary type I extinction',
'Flack' : 'Flack parameter',
'TwinFr' : 'Twin fraction',
'Layer Disp' : 'Layer displacement along beam',
#Histogram vars (:h:<var>)
'Absorption' : 'Absorption coef.',
'LayerDisp' : 'Bragg-Brentano Layer displacement',
'Displace([XY])' : ('Debye-Scherrer sample displacement \\1',0.1),
'Lam' : ('Wavelength',1e-6),
'I\\(L2\\)\\/I\\(L1\\)' : ('Ka2/Ka1 intensity ratio',0.001),
'Polariz.' : ('Polarization correction',1e-3),
'SH/L' : ('FCJ peak asymmetry correction',1e-4),
'([UVW])$' : ('Gaussian instrument broadening \\1',1e-5),
'([XYZ])$' : ('Cauchy instrument broadening \\1',1e-5),
'Zero' : 'Debye-Scherrer zero correction',
'Shift' : 'Bragg-Brentano sample displ.',
'SurfRoughA' : 'Bragg-Brenano surface roughness A',
'SurfRoughB' : 'Bragg-Brenano surface roughness B',
'Transparency' : 'Bragg-Brentano sample tranparency',
'DebyeA' : 'Debye model amplitude',
'DebyeR' : 'Debye model radius',
'DebyeU' : 'Debye model Uiso',
'RBV.*' : 'Vector rigid body parameter',
'RBVO([aijk])' : 'Vector rigid body orientation parameter \\1',
'RBVP([xyz])' : 'Vector rigid body \\1 position parameter',
'RBVf' : 'Vector rigid body site fraction',
'RBV([TLS])([123AB][123AB])' : 'Residue rigid body group disp. param.',
'RBVU' : 'Residue rigid body group Uiso param.',
'RBRO([aijk])' : 'Residue rigid body orientation parameter \\1',
'RBRP([xyz])' : 'Residue rigid body \\1 position parameter',
'RBRTr;.*' : 'Residue rigid body torsion parameter',
'RBRf' : 'Residue rigid body site fraction',
'RBR([TLS])([123AB][123AB])' : 'Residue rigid body group disp. param.',
'RBRU' : 'Residue rigid body group Uiso param.',
'RBSAtNo' : 'Atom number for spinning rigid body',
'RBSO([aijk])' : 'Spinning rigid body orientation parameter \\1',
'RBSP([xyz])' : 'Spinning rigid body \\1 position parameter',
'RBSShRadius' : 'Spinning rigid body shell radius',
'RBSShC([1-20,1-20])' : 'Spinning rigid body sph. harmonics term',
'constr([0-9]*)' : 'Generated degree of freedom from constraint',
'nv-(.+)' : 'New variable assignment with name \\1',
# supersymmetry parameters p::<var>:a:o 'Flen','Fcent'?
'mV([0-2])$' : 'Modulation vector component \\1',
'Fsin' : 'Sin site fraction modulation',
'Fcos' : 'Cos site fraction modulation',
'Fzero' : 'Crenel function offset', #may go away
'Fwid' : 'Crenel function width',
'Tmin' : 'ZigZag/Block min location',
'Tmax' : 'ZigZag/Block max location',
'([XYZ])max': 'ZigZag/Block max value for \\1',
'([XYZ])sin' : 'Sin position wave for \\1',
'([XYZ])cos' : 'Cos position wave for \\1',
'U([123][123])sin$' : 'Sin thermal wave for U\\1',
'U([123][123])cos$' : 'Cos thermal wave for U\\1',
'M([XYZ])sin$' : 'Sin mag. moment wave for \\1',
'M([XYZ])cos$' : 'Cos mag. moment wave for \\1',
# PDF peak parms (l:<var>;l = peak no.)
'PDFpos' : 'PDF peak position',
'PDFmag' : 'PDF peak magnitude',
'PDFsig' : 'PDF peak std. dev.',
# SASD vars (l:<var>;l = component)
'Aspect ratio' : 'Particle aspect ratio',
'Length' : 'Cylinder length',
'Diameter' : 'Cylinder/disk diameter',
'Thickness' : 'Disk thickness',
'Shell thickness' : 'Multiplier to get inner(<1) or outer(>1) sphere radius',
'Dist' : 'Interparticle distance',
'VolFr' : 'Dense scatterer volume fraction',
'epis' : 'Sticky sphere epsilon',
'Sticky' : 'Stickyness',
'Depth' : 'Well depth',
'Width' : 'Well width',
'Volume' : 'Particle volume',
'Radius' : 'Sphere/cylinder/disk radius',
'Mean' : 'Particle mean radius',
'StdDev' : 'Standard deviation in Mean',
'G$': 'Guinier prefactor',
'Rg$': 'Guinier radius of gyration',
'B$': 'Porod prefactor',
'P$': 'Porod power',
'Cutoff': 'Porod cutoff',
'PkInt': 'Bragg peak intensity',
'PkPos': 'Bragg peak position',
'PkSig': 'Bragg peak sigma',
'PkGam': 'Bragg peak gamma',
'e([12][12])' : 'strain tensor e\\1', # strain vars e11, e22, e12
'Dcalc': 'Calc. d-spacing',
'Back$': 'background parameter',
'pos$': 'peak position',
'int$': 'peak intensity',
'WgtFrac':'phase weight fraction',
'alpha':'TOF profile term',
'alpha-([01])':'Pink profile term',
'beta-([01q])':'TOF/Pink profile term',
'sig-([012q])':'TOF profile term',
'dif([ABC])':'TOF to d-space calibration',
'C\\([0-9]*,[0-9]*\\)' : 'spherical harmonics preferred orientation coef.',
'Pressure': 'Pressure level for measurement in MPa',
'Temperature': 'T value for measurement, K',
'FreePrm([123])': 'User defined measurement parameter \\1',
'Gonio. radius': 'Distance from sample to detector, mm',
}.items():
# Needs documentation: HAP: LeBail, newLeBail
# hist: Azimuth, Chi, Omega, Phi, Bank, nDebye, nPeaks
if len(value) == 2:
#VarDesc[key] = value[0]
reVarDesc[re.compile(key)] = value[0]
reVarStep[re.compile(key)] = value[1]
else:
#VarDesc[key] = value
reVarDesc[re.compile(key)] = value
def removeNonRefined(parmList):
'''Remove items from variable list that are not refined and should not
appear as options for constraints
:param list parmList: a list of strings of form "p:h:VAR:a" where
VAR is the variable name
:returns: a list after removing variables where VAR matches a
entry in local variable NonRefinedList
'''
NonRefinedList = ['Omega','Type','Chi','Phi', 'Azimuth','Gonio. radius',
'Lam1','Lam2','Back','Temperature','Pressure',
'FreePrm1','FreePrm2','FreePrm3',
'Source','nPeaks','LeBail','newLeBail','Bank',
'nDebye', #'',
]
return [prm for prm in parmList if prm.split(':')[2] not in NonRefinedList]
def getDescr(name):
'''Return a short description for a GSAS-II variable
:param str name: The descriptive part of the variable name without colons (:)
:returns: a short description or None if not found
'''
CompileVarDesc() # compile the regular expressions, if needed
for key in reVarDesc:
m = key.match(name)
if m:
reVarDesc[key]
try:
return m.expand(reVarDesc[key])
except:
print('Error in key: %s'%key)
return None
def getVarStep(name,parmDict=None):
'''Return a step size for computing the derivative of a GSAS-II variable
:param str name: A complete variable name (with colons, :)
:param dict parmDict: A dict with parameter values or None (default)
:returns: a float that should be an appropriate step size, either from
the value supplied in :func:`CompileVarDesc` or based on the value for
name in parmDict, if supplied. If not found or the value is zero,
a default value of 1e-5 is used. If parmDict is None (default) and
no value is provided in :func:`CompileVarDesc`, then None is returned.
'''
CompileVarDesc() # compile the regular expressions, if needed
for key in reVarStep:
m = key.match(name)
if m:
return reVarStep[key]
if parmDict is None: return None
val = parmDict.get(key,0.0)
if abs(val) > 0.05:
return abs(val)/1000.
else:
return 1e-5
def GenWildCard(varlist):
'''Generate wildcard versions of G2 variables. These introduce '*'
for a phase, histogram or atom number (but only for one of these
fields) but only when there is more than one matching variable in the
input variable list. So if the input is this::
varlist = ['0::AUiso:0', '0::AUiso:1', '1::AUiso:0']
then the output will be this::
wildList = ['*::AUiso:0', '0::AUiso:*']
:param list varlist: an input list of GSAS-II variable names
(such as 0::AUiso:0)
:returns: wildList, the generated list of wild card variable names.
'''
wild = []
for i in (0,1,3):
currentL = varlist[:]
while currentL:
item1 = currentL.pop(0)
i1splt = item1.split(':')
if i >= len(i1splt): continue
if i1splt[i]:
nextL = []
i1splt[i] = '[0-9]+'
rexp = re.compile(':'.join(i1splt))
matchlist = [item1]
for nxtitem in currentL:
if rexp.match(nxtitem):
matchlist += [nxtitem]
else:
nextL.append(nxtitem)
if len(matchlist) > 1:
i1splt[i] = '*'
wild.append(':'.join(i1splt))
currentL = nextL
return wild
def LookupWildCard(varname,varlist):
'''returns a list of variable names from list varname
that match wildcard name in varname
:param str varname: a G2 variable name containing a wildcard
(such as \\*::var)
:param list varlist: the list of all variable names used in
the current project
:returns: a list of matching GSAS-II variables (may be empty)
'''
rexp = re.compile(varname.replace('*','[0-9]+'))
return sorted([var for var in varlist if rexp.match(var)])
def prmLookup(name,prmDict):
'''Looks for a parameter in a min/max dictionary, optionally
considering a wild card for histogram or atom number (use of
both will never occur at the same time).
:param name: a GSAS-II parameter name (str, see :func:`getVarDescr`
and :func:`CompileVarDesc`) or a :class:`G2VarObj` object.
:param dict prmDict: a min/max dictionary, (parmMinDict
or parmMaxDict in Controls) where keys are :class:`G2VarObj`
objects.
:returns: Two values, (**matchname**, **value**), are returned where:
* **matchname** *(str)* is the :class:`G2VarObj` object
corresponding to the actual matched name,
which could contain a wildcard even if **name** does not; and
* **value** *(float)* which contains the parameter limit.
'''
for key,value in prmDict.items():
if str(key) == str(name): return key,value
if key == name: return key,value
return None,None
def _lookup(dic,key):
'''Lookup a key in a dictionary, where None returns an empty string
but an unmatched key returns a question mark. Used in :class:`G2VarObj`
'''
if key is None:
return ""
elif key == "*":
return "*"
else:
return dic.get(key,'?')
def SortVariables(varlist):
'''Sorts variable names in a sensible manner
'''
def cvnnums(var):
v = []
for i in var.split(':'):
# if i == '' or i == '*':
# v.append(-1)
# continue
try:
v.append(int(i))
except:
v.append(-1)
return v
return sorted(varlist,key=cvnnums)
class G2VarObj(object):
'''Defines a GSAS-II variable either using the phase/atom/histogram
unique Id numbers or using a character string that specifies
variables by phase/atom/histogram number (which can change).
Note that :func:`GSASIIstrIO.GetUsedHistogramsAndPhases`,
which calls :func:`IndexAllIds` (or
:func:`GSASIIscriptable.G2Project.index_ids`) should be used to
(re)load the current Ids
before creating or later using the G2VarObj object.
This can store rigid body variables, but does not translate the residue # and
body # to/from random Ids
A :class:`G2VarObj` object can be created with a single parameter:
:param str/tuple varname: a single value can be used to create a :class:`G2VarObj`
object. If a string, it must be of form "p:h:var" or "p:h:var:a", where
* p is the phase number (which may be left blank or may be '*' to indicate all phases);
* h is the histogram number (which may be left blank or may be '*' to indicate all histograms);
* a is the atom number (which may be left blank in which case the third colon is omitted).
The atom number can be specified as '*' if a phase number is specified (not as '*').
For rigid body variables, specify a will be a string of form "residue:body#"
Alternately a single tuple of form (Phase,Histogram,VarName,AtomID) can be used, where
Phase, Histogram, and AtomID are None or are ranId values (or one can be '*')
and VarName is a string. Note that if Phase is '*' then the AtomID is an atom number.
For a rigid body variables, AtomID is a string of form "residue:body#".
If four positional arguments are supplied, they are:
:param str/int phasenum: The number for the phase (or None or '*')
:param str/int histnum: The number for the histogram (or None or '*')
:param str varname: a single value can be used to create a :class:`G2VarObj`
:param str/int atomnum: The number for the atom (or None or '*')
'''
IDdict = {}
IDdict['phases'] = {}
IDdict['hists'] = {}
IDdict['atoms'] = {}
def __init__(self,*args):
self.phase = None
self.histogram = None
self.name = ''
self.atom = None
if len(args) == 1 and (type(args[0]) is list or type(args[0]) is tuple) and len(args[0]) == 4:
# single arg with 4 values
self.phase,self.histogram,self.name,self.atom = args[0]
elif len(args) == 1 and ':' in args[0]:
#parse a string
lst = args[0].split(':')
if lst[0] == '*':
self.phase = '*'
if len(lst) > 3:
self.atom = lst[3]
self.histogram = HistIdLookup.get(lst[1],[None,None])[1]
elif lst[1] == '*':
self.histogram = '*'
self.phase = PhaseIdLookup.get(lst[0],[None,None])[1]
else:
self.histogram = HistIdLookup.get(lst[1],[None,None])[1]
self.phase = PhaseIdLookup.get(lst[0],[None,None])[1]
if len(lst) == 4:
if lst[3] == '*':
self.atom = '*'
else:
self.atom = AtomIdLookup[lst[0]].get(lst[3],[None,None])[1]
elif len(lst) == 5:
self.atom = lst[3]+":"+lst[4]
elif len(lst) == 3:
pass
else:
raise Exception("Incorrect number of colons in var name "+str(args[0]))
self.name = lst[2]