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
/
Copy pathGSASIIscriptable.py
6683 lines (5910 loc) · 286 KB
/
GSASIIscriptable.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-15 15:24:19 -0600 (Mon, 15 Jan 2024) $
# $Author: toby $
# $Revision: 5716 $
# $URL: https://subversion.xray.aps.anl.gov/pyGSAS/trunk/GSASIIscriptable.py $
# $Id: GSASIIscriptable.py 5716 2024-01-15 21:24:19Z toby $
########### SVN repository information ###################
#
"""
Classes and routines defined in :mod:`GSASIIscriptable` follow.
A script will create one or more :class:`G2Project` objects by reading
a GSAS-II project (.gpx) file or creating a new one and will then
perform actions such as adding a histogram (method :meth:`G2Project.add_powder_histogram`),
adding a phase (method :meth:`G2Project.add_phase`),
or setting parameters and performing a refinement
(method :meth:`G2Project.do_refinements`).
To change settings within histograms, images and phases, one usually needs to use
methods inside :class:`G2PwdrData`, :class:`G2Image` or :class:`G2Phase`.
"""
# Note that documentation for GSASIIscriptable.py has been moved
# to file docs/source/GSASIIscriptable.rst
#============================================================================
# Notes for adding a new object type
# 1) add a new object class (e.g. G2PDF)
# 2) add the wrapper into G2Project (e.g. _pdfs, pdf, pdfs)
# 3) add a new method to add the object into a project (G2Project.add_PDF)
# 4) add to documentation in section :class:`G2Project`
# 5) add a new documentation section for the new class
#============================================================================
from __future__ import division, print_function
import argparse
import os.path as ospath
#import datetime as dt
import sys
import platform
if '2' in platform.python_version_tuple()[0]:
import cPickle
strtypes = (str,unicode)
else:
import pickle as cPickle
strtypes = (str,bytes)
#import imp
import copy
import os
import random as ran
import numpy.ma as ma
import scipy.interpolate as si
import numpy as np
import scipy as sp
import GSASIIpath
GSASIIpath.SetBinaryPath(True) # for now, this is needed before some of these modules can be imported
import GSASIIobj as G2obj
import GSASIIpwd as G2pwd
import GSASIIstrMain as G2strMain
import GSASIIstrIO as G2stIO
import GSASIIspc as G2spc
import GSASIIElem as G2elem
import GSASIIfiles as G2fil
import GSASIIimage as G2img
import GSASIIlattice as G2lat
import GSASIImapvars as G2mv
# Delay imports to not slow down small scripts that don't need them
Readers = {'Pwdr':[], 'Phase':[], 'Image':[]}
'''Readers by reader type'''
exportersByExtension = {}
'''Specifies the list of extensions that are supported for Powder data export'''
npsind = lambda x: np.sin(x*np.pi/180.)
def SetPrintLevel(level):
'''Set the level of output from calls to :func:`GSASIIfiles.G2Print`,
which should be used in place of print() where possible. This is a
wrapper for :func:`GSASIIfiles.G2SetPrintLevel` so that this routine is
documented here.
:param str level: a string used to set the print level, which may be
'all', 'warn', 'error' or 'none'.
Note that capitalization and extra letters in level are ignored, so
'Warn', 'warnings', etc. will all set the mode to 'warn'
'''
G2fil.G2SetPrintLevel(level)
global printLevel
for mode in 'all', 'warn', 'error', 'none':
if mode in level.lower():
printLevel = mode
return
def installScriptingShortcut():
'''Creates a file named G2script in the current Python site-packages directory.
This is equivalent to the "Install GSASIIscriptable shortcut" command in the GUI's
File menu. Once this is done, a shortcut for calling GSASIIscriptable is created,
where the command:
>>> import G2script as G2sc
will provide access to GSASIIscriptable without changing the sys.path; also see
:ref:`ScriptingShortcut`.
Note that this only affects the current Python installation. If more than one
Python installation will be used with GSAS-II (for example because different
conda environments are used), this command should be called from within each
Python environment.
If more than one GSAS-II installation will be used with a Python installation,
this shortcut can only be used with one of them.
'''
f = GSASIIpath.makeScriptShortcut()
if f:
G2fil.G2Print(f'success creating {f}')
else:
raise G2ScriptException('error creating G2script')
def LoadG2fil():
'''Setup GSAS-II importers.
Delay importing this module when possible, it is slow.
Multiple calls are not. Only the first does anything.
'''
if len(Readers['Pwdr']) > 0: return
# initialize imports
Readers['Pwdr'] = G2fil.LoadImportRoutines("pwd", "Powder_Data")
Readers['Phase'] = G2fil.LoadImportRoutines("phase", "Phase")
Readers['Image'] = G2fil.LoadImportRoutines("img", "Image")
# initialize exports
for obj in G2fil.LoadExportRoutines(None):
try:
obj.Writer
except AttributeError:
continue
for typ in obj.exporttype:
if typ not in exportersByExtension:
exportersByExtension[typ] = {obj.extension:obj}
elif obj.extension in exportersByExtension[typ]:
if type(exportersByExtension[typ][obj.extension]) is list:
exportersByExtension[typ][obj.extension].append(obj)
else:
exportersByExtension[typ][obj.extension] = [
exportersByExtension[typ][obj.extension],
obj]
else:
exportersByExtension[typ][obj.extension] = obj
def LoadDictFromProjFile(ProjFile):
'''Read a GSAS-II project file and load items to dictionary
:param str ProjFile: GSAS-II project (name.gpx) full file name
:returns: Project,nameList, where
* Project (dict) is a representation of gpx file following the GSAS-II tree structure
for each item: key = tree name (e.g. 'Controls','Restraints',etc.), data is dict
data dict = {'data':item data whch may be list, dict or None,'subitems':subdata (if any)}
* nameList (list) has names of main tree entries & subentries used to reconstruct project file
Example for fap.gpx::
Project = { #NB:dict order is not tree order
'Phases':{'data':None,'fap':{phase dict}},
'PWDR FAP.XRA Bank 1':{'data':[histogram data list],'Comments':comments,'Limits':limits, etc},
'Rigid bodies':{'data': {rigid body dict}},
'Covariance':{'data':{covariance data dict}},
'Controls':{'data':{controls data dict}},
'Notebook':{'data':[notebook list]},
'Restraints':{'data':{restraint data dict}},
'Constraints':{'data':{constraint data dict}}]
}
nameList = [ #NB: reproduces tree order
['Notebook',],
['Controls',],
['Covariance',],
['Constraints',],
['Restraints',],
['Rigid bodies',],
['PWDR FAP.XRA Bank 1',
'Comments',
'Limits',
'Background',
'Instrument Parameters',
'Sample Parameters',
'Peak List',
'Index Peak List',
'Unit Cells List',
'Reflection Lists'],
['Phases', 'fap']
]
'''
# Let IOError be thrown if file does not exist
if not ospath.exists(ProjFile):
G2fil.G2Print ('\n*** Error attempt to open project file that does not exist: \n {}'.
format(ProjFile))
raise IOError('GPX file {} does not exist'.format(ProjFile))
try:
Project, nameList = G2stIO.GetFullGPX(ProjFile)
except Exception as msg:
raise IOError(msg)
return Project,nameList
def SaveDictToProjFile(Project,nameList,ProjFile):
'''Save a GSAS-II project file from dictionary/nameList created by LoadDictFromProjFile
:param dict Project: representation of gpx file following the GSAS-II
tree structure as described for LoadDictFromProjFile
:param list nameList: names of main tree entries & subentries used to reconstruct project file
:param str ProjFile: full file name for output project.gpx file (including extension)
'''
file = open(ProjFile,'wb')
try:
for name in nameList:
data = []
item = Project[name[0]]
data.append([name[0],item['data']])
for item2 in name[1:]:
data.append([item2,item[item2]])
cPickle.dump(data,file,1)
finally:
file.close()
G2fil.G2Print('gpx file saved as %s'%ProjFile)
def SetDefaultDData(dType,histoName,NShkl=0,NDij=0):
'''Create an initial Histogram dictionary
Author: Jackson O'Donnell (jacksonhodonnell .at. gmail.com)
'''
if dType in ['SXC','SNC','SEC',]:
return {'Histogram':histoName,'Show':False,'Scale':[1.0,True],
'Babinet':{'BabA':[0.0,False],'BabU':[0.0,False]},
'Extinction':['Lorentzian','None', {'Tbar':0.1,'Cos2TM':0.955,
'Eg':[1.e-10,False],'Es':[1.e-10,False],'Ep':[1.e-10,False]}],
'Flack':[0.0,False]}
elif dType == 'SNT':
return {'Histogram':histoName,'Show':False,'Scale':[1.0,True],
'Babinet':{'BabA':[0.0,False],'BabU':[0.0,False]},
'Extinction':['Lorentzian','None', {
'Eg':[1.e-10,False],'Es':[1.e-10,False],'Ep':[1.e-10,False]}]}
elif 'P' in dType:
return {'Histogram':histoName,'Show':False,'Scale':[1.0,False],
'Pref.Ori.':['MD',1.0,False,[0,0,1],0,{},[],0.1],
'Size':['isotropic',[1.,1.,1.],[False,False,False],[0,0,1],
[1.,1.,1.,0.,0.,0.],6*[False,]],
'Mustrain':['isotropic',[1000.0,1000.0,1.0],[False,False,False],[0,0,1],
NShkl*[0.01,],NShkl*[False,]],
'HStrain':[NDij*[0.0,],NDij*[False,]],
'Extinction':[0.0,False],'Babinet':{'BabA':[0.0,False],'BabU':[0.0,False]}}
def PreSetup(data):
'''Create part of an initial (empty) phase dictionary
from GSASIIphsGUI.py, near end of UpdatePhaseData
Author: Jackson O'Donnell (jacksonhodonnell .at. gmail.com)
'''
if 'RBModels' not in data:
data['RBModels'] = {}
if 'MCSA' not in data:
data['MCSA'] = {'Models':[{'Type':'MD','Coef':[1.0,False,[.8,1.2],],'axis':[0,0,1]}],'Results':[],'AtInfo':{}}
if 'dict' in str(type(data['MCSA']['Results'])):
data['MCSA']['Results'] = []
if 'Modulated' not in data['General']:
data['General']['Modulated'] = False
# if 'modulated' in data['General']['Type']:
# data['General']['Modulated'] = True
# data['General']['Type'] = 'nuclear'
def SetupGeneral(data, dirname):
'''Initialize phase data.
'''
try:
G2elem.SetupGeneral(data,dirname)
except ValueError as msg:
raise G2ScriptException(msg)
def make_empty_project(author=None, filename=None):
"""Creates an dictionary in the style of GSASIIscriptable, for an empty
project.
If no author name or filename is supplied, 'no name' and
<current dir>/test_output.gpx are used , respectively.
Returns: project dictionary, name list
Author: Jackson O'Donnell (jacksonhodonnell .at. gmail.com)
"""
if not filename:
filename = 'test_output.gpx'
filename = os.path.abspath(filename)
gsasii_version = str(GSASIIpath.GetVersionNumber())
LoadG2fil()
try:
import matplotlib as mpl
python_library_versions = G2fil.get_python_versions([mpl, np, sp])
except ImportError:
python_library_versions = G2fil.get_python_versions([np, sp])
controls_data = dict(G2obj.DefaultControls)
controls_data['LastSavedAs'] = filename
controls_data['LastSavedUsing'] = gsasii_version
controls_data['PythonVersions'] = python_library_versions
if author:
controls_data['Author'] = author
output = {'Constraints': {'data': {'HAP': [], 'Hist': [], 'Phase': [],
'Global': []}},
'Controls': {'data': controls_data},
u'Covariance': {'data': {}},
u'Notebook': {'data': ['']},
u'Restraints': {'data': {}},
u'Rigid bodies': {'data': {'RBIds': {'Residue': [], 'Vector': []},
'Residue': {'AtInfo': {}},
'Vector': {'AtInfo': {}}}}}
names = [[u'Notebook'], [u'Controls'], [u'Covariance'],
[u'Constraints'], [u'Restraints'], [u'Rigid bodies']]
return output, names
def GenerateReflections(spcGrp,cell,Qmax=None,dmin=None,TTmax=None,wave=None):
"""Generates the crystallographically unique powder diffraction reflections
for a lattice and space group (see :func:`GSASIIlattice.GenHLaue`).
:param str spcGrp: A GSAS-II formatted space group (with spaces between
axial fields, e.g. 'P 21 21 21' or 'P 42/m m c'). Note that non-standard
space groups, such as 'P 21/n' or 'F -1' are allowed (see
:func:`GSASIIspc.SpcGroup`).
:param list cell: A list/tuple with six unit cell constants,
(a, b, c, alpha, beta, gamma) with values in Angstroms/degrees.
Note that the cell constants are not checked for consistency
with the space group.
:param float Qmax: Reflections up to this Q value are computed
(do not use with dmin or TTmax)
:param float dmin: Reflections with d-space above this value are computed
(do not use with Qmax or TTmax)
:param float TTmax: Reflections up to this 2-theta value are computed
(do not use with dmin or Qmax, use of wave is required.)
:param float wave: wavelength in Angstroms for use with TTmax (ignored
otherwise.)
:returns: a list of reflections, where each reflection contains four items:
h, k, l, d, where d is the d-space (Angstroms)
Example:
>>> import os,sys
>>> sys.path.insert(0,'/Users/toby/software/G2/GSASII')
>>> import GSASIIscriptable as G2sc
GSAS-II binary directory: /Users/toby/software/G2/GSASII/bin
17 values read from config file /Users/toby/software/G2/GSASII/config.py
>>> refs = G2sc.GenerateReflections('P 1',
... (5.,6.,7.,90.,90.,90),
... TTmax=20,wave=1)
>>> for r in refs: print(r)
...
[0, 0, 1, 7.0]
[0, 1, 0, 6.0]
[1, 0, 0, 5.0]
[0, 1, 1, 4.55553961419178]
[0, 1, -1, 4.55553961419178]
[1, 0, 1, 4.068667356033675]
[1, 0, -1, 4.068667356033674]
[1, 1, 0, 3.8411063979868794]
[1, -1, 0, 3.8411063979868794]
"""
if len(cell) != 6:
raise G2ScriptException("GenerateReflections: Invalid unit cell:" + str(cell))
opts = (Qmax is not None) + (dmin is not None) + (TTmax is not None)
if Qmax:
dmin = 2 * np.pi / Qmax
#print('Q,d',Qmax,dmin)
elif TTmax and wave is None:
raise G2ScriptException("GenerateReflections: specify a wavelength with TTmax")
elif TTmax:
dmin = wave / (2.0 * np.sin(np.pi*TTmax/360.))
#print('2theta,d',TTmax,dmin)
if opts != 1:
raise G2ScriptException("GenerateReflections: specify one Qmax, dmin or TTmax")
err,SGData = G2spc.SpcGroup(spcGrp)
if err != 0:
print('GenerateReflections space group error:',G2spc.SGErrors(err))
raise G2ScriptException("GenerateReflections: Invalid space group: " + str(spcGrp))
A = G2lat.cell2A(cell)
return G2lat.GenHLaue(dmin,SGData,A)
class G2ImportException(Exception):
pass
class G2ScriptException(Exception):
pass
def import_generic(filename, readerlist, fmthint=None, bank=None):
"""Attempt to import a filename, using a list of reader objects.
Returns the first reader object which worked."""
# Translated from OnImportGeneric method in GSASII.py
primaryReaders, secondaryReaders = [], []
for reader in readerlist:
if fmthint is not None and fmthint not in reader.formatName: continue
flag = reader.ExtensionValidator(filename)
if flag is None:
secondaryReaders.append(reader)
elif flag:
primaryReaders.append(reader)
if not secondaryReaders and not primaryReaders:
raise G2ImportException("Could not read file: ", filename)
with open(filename, 'r'):
rd_list = []
for rd in primaryReaders + secondaryReaders:
# Initialize reader
rd.selections = []
if bank is None:
rd.selections = []
else:
try:
rd.selections = [i-1 for i in bank]
except TypeError:
rd.selections = [bank-1]
rd.dnames = []
rd.ReInitialize()
# Rewind file
rd.errors = ""
if not rd.ContentsValidator(filename):
# Report error
G2fil.G2Print("Warning: File {} has a validation error, continuing".format(filename))
#if len(rd.selections) > 1:
# raise G2ImportException("File {} has {} banks. Specify which bank to read with databank param."
# .format(filename,len(rd.selections)))
block = 0
rdbuffer = {}
repeat = True
while repeat:
repeat = False
block += 1
rd.objname = os.path.basename(filename)
try:
flag = rd.Reader(filename,buffer=rdbuffer, blocknum=block)
except:
flag = False
if flag:
# Omitting image loading special cases
rd.readfilename = filename
rd_list.append(copy.deepcopy(rd))
repeat = rd.repeat
else:
G2fil.G2Print("Warning: {} Reader failed to read {}".format(rd.formatName,filename))
if rd_list:
if rd.warnings:
G2fil.G2Print("Read warning by", rd.formatName, "reader:",
rd.warnings)
elif bank is None:
G2fil.G2Print("{} read by Reader {}"
.format(filename,rd.formatName))
else:
G2fil.G2Print("{} block # {} read by Reader {}"
.format(filename,bank,rd.formatName))
return rd_list
raise G2ImportException("No reader could read file: " + filename)
def load_iprms(instfile, reader, bank=None):
"""Loads instrument parameters from a file, and edits the
given reader.
Returns a 2-tuple of (Iparm1, Iparm2) parameters
"""
LoadG2fil()
ext = os.path.splitext(instfile)[1]
if ext.lower() == '.instprm':
# New GSAS File, load appropriate bank
with open(instfile) as f:
lines = f.readlines()
if bank is None:
bank = reader.powderentry[2]
numbanks = reader.numbanks
iparms = G2fil.ReadPowderInstprm(lines, bank, numbanks, reader)
reader.instfile = instfile
reader.instmsg = '{} (G2 fmt) bank {}'.format(instfile,bank)
return iparms
elif ext.lower() not in ('.prm', '.inst', '.ins'):
raise ValueError('Expected .prm file, found: ', instfile)
# It's an old GSAS file, load appropriately
Iparm = {}
with open(instfile, 'r') as fp:
for line in fp:
if '#' in line:
continue
Iparm[line[:12]] = line[12:-1]
ibanks = int(Iparm.get('INS BANK ', '1').strip())
if bank is not None:
# pull out requested bank # bank from the data, and change the bank to 1
Iparm,IparmC = {},Iparm
for key in IparmC:
if 'INS' not in key[:3]: continue #skip around rubbish lines in some old iparm
if key[4:6] == " ":
Iparm[key] = IparmC[key]
elif int(key[4:6].strip()) == bank:
Iparm[key[:4]+' 1'+key[6:]] = IparmC[key]
reader.instbank = bank
elif ibanks == 1:
reader.instbank = 1
else:
raise G2ImportException("Instrument parameter file has {} banks, select one with instbank param."
.format(ibanks))
reader.powderentry[2] = 1
reader.instfile = instfile
reader.instmsg = '{} bank {}'.format(instfile,reader.instbank)
return G2fil.SetPowderInstParms(Iparm, reader)
def load_pwd_from_reader(reader, instprm, existingnames=[],bank=None):
"""Loads powder data from a reader object, and assembles it into a GSASII data tree.
:returns: (name, tree) - 2-tuple of the histogram name (str), and data
Author: Jackson O'Donnell (jacksonhodonnell .at. gmail.com)
"""
HistName = 'PWDR ' + G2obj.StripUnicode(reader.idstring, '_')
HistName = G2obj.MakeUniqueLabel(HistName, existingnames)
try:
Iparm1, Iparm2 = instprm
except ValueError:
Iparm1, Iparm2 = load_iprms(instprm, reader, bank=bank)
G2fil.G2Print('Instrument parameters read:',reader.instmsg)
except TypeError: # instprm is None, get iparms from reader
Iparm1, Iparm2 = reader.pwdparms['Instrument Parameters']
if 'T' in Iparm1['Type'][0]:
if not reader.clockWd and reader.GSAS:
reader.powderdata[0] *= 100. #put back the CW centideg correction
cw = np.diff(reader.powderdata[0])
reader.powderdata[0] = reader.powderdata[0][:-1]+cw/2.
if reader.GSAS: #NB: old GSAS wanted intensities*CW even if normalized!
npts = min(len(reader.powderdata[0]),len(reader.powderdata[1]),len(cw))
reader.powderdata[1] = reader.powderdata[1][:npts]/cw[:npts]
reader.powderdata[2] = reader.powderdata[2][:npts]*cw[:npts]**2 #1/var=w at this point
else: #NB: from topas/fullprof type files
reader.powderdata[1] = reader.powderdata[1][:-1]
reader.powderdata[2] = reader.powderdata[2][:-1]
if 'Itype' in Iparm2:
Ibeg = np.searchsorted(reader.powderdata[0],Iparm2['Tminmax'][0])
Ifin = np.searchsorted(reader.powderdata[0],Iparm2['Tminmax'][1])
reader.powderdata[0] = reader.powderdata[0][Ibeg:Ifin]
YI,WYI = G2pwd.calcIncident(Iparm2,reader.powderdata[0])
reader.powderdata[1] = reader.powderdata[1][Ibeg:Ifin]/YI
var = 1./reader.powderdata[2][Ibeg:Ifin]
var += WYI*reader.powderdata[1]**2
var /= YI**2
reader.powderdata[2] = 1./var
reader.powderdata[1] = np.where(np.isinf(reader.powderdata[1]),0.,reader.powderdata[1])
reader.powderdata[3] = np.zeros_like(reader.powderdata[0])
reader.powderdata[4] = np.zeros_like(reader.powderdata[0])
reader.powderdata[5] = np.zeros_like(reader.powderdata[0])
Ymin = np.min(reader.powderdata[1])
Ymax = np.max(reader.powderdata[1])
valuesdict = {'wtFactor': 1.0,
'Dummy': False,
'ranId': ran.randint(0, sys.maxsize),
'Offset': [0.0, 0.0], 'delOffset': 0.02*Ymax,
'refOffset': -0.1*Ymax, 'refDelt': 0.1*Ymax,
'Yminmax': [Ymin, Ymax]}
# apply user-supplied corrections to powder data
if 'CorrectionCode' in Iparm1:
G2fil.G2Print('Applying corrections from instprm file')
corr = Iparm1['CorrectionCode'][0]
try:
exec(corr)
G2fil.G2Print('done')
except Exception as err:
print(u'error: {}'.format(err))
print('with commands -------------------')
print(corr)
print('---------------------------------')
finally:
del Iparm1['CorrectionCode']
reader.Sample['ranId'] = valuesdict['ranId']
# Ending keys:
# [u'Reflection Lists',
# u'Limits',
# 'data',
# u'Index Peak List',
# u'Comments',
# u'Unit Cells List',
# u'Sample Parameters',
# u'Peak List',
# u'Background',
# u'Instrument Parameters']
Tmin = np.min(reader.powderdata[0])
Tmax = np.max(reader.powderdata[0])
Tmin1 = Tmin
if 'NT' in Iparm1['Type'][0] and G2lat.Pos2dsp(Iparm1,Tmin) < 0.4:
Tmin1 = G2lat.Dsp2pos(Iparm1,0.4)
default_background = [['chebyschev-1', False, 3, 1.0, 0.0, 0.0],
{'nDebye': 0, 'debyeTerms': [], 'nPeaks': 0,
'peaksList': [],'background PWDR':['',1.0,False]}]
output_dict = {u'Reflection Lists': {},
u'Limits': reader.pwdparms.get('Limits', [(Tmin, Tmax), [Tmin1, Tmax]]),
u'data': [valuesdict, reader.powderdata, HistName],
u'Index Peak List': [[], []],
u'Comments': reader.comments,
u'Unit Cells List': [],
u'Sample Parameters': reader.Sample,
u'Peak List': {'peaks': [], 'sigDict': {}},
u'Background': reader.pwdparms.get('Background', default_background),
u'Instrument Parameters': [Iparm1, Iparm2],
}
names = [u'Comments',
u'Limits',
u'Background',
u'Instrument Parameters',
u'Sample Parameters',
u'Peak List',
u'Index Peak List',
u'Unit Cells List',
u'Reflection Lists']
# TODO controls?? GSASII.py:1664-7
return HistName, [HistName] + names, output_dict
def _deep_copy_into(from_, into):
"""Helper function for reloading .gpx file. See G2Project.reload()
:author: Jackson O'Donnell (jacksonhodonnell .at. gmail.com)
"""
if isinstance(from_, dict) and isinstance(into, dict):
combined_keys = set(from_.keys()).union(into.keys())
for key in combined_keys:
if key in from_ and key in into:
both_dicts = (isinstance(from_[key], dict)
and isinstance(into[key], dict))
both_lists = (isinstance(from_[key], list)
and isinstance(into[key], list))
if both_dicts or both_lists:
_deep_copy_into(from_[key], into[key])
else:
into[key] = from_[key]
elif key in from_:
into[key] = from_[key]
else: # key in into
del into[key]
elif isinstance(from_, list) and isinstance(into, list):
if len(from_) == len(into):
for i in range(len(from_)):
both_dicts = (isinstance(from_[i], dict)
and isinstance(into[i], dict))
both_lists = (isinstance(from_[i], list)
and isinstance(into[i], list))
if both_dicts or both_lists:
_deep_copy_into(from_[i], into[i])
else:
into[i] = from_[i]
else:
into[:] = from_
def _getCorrImage(ImageReaderlist,proj,imageRef):
'''Gets image & applies dark, background & flat background corrections.
based on :func:`GSASIIimgGUI.GetImageZ`. Expected to be for internal
use only.
:param list ImageReaderlist: list of Reader objects for images
:param object proj: references a :class:`G2Project` project
:param imageRef: A reference to the desired image in the project.
Either the Image tree name (str), the image's index (int) or
a image object (:class:`G2Image`)
:return: array sumImg: corrected image for background/dark/flat back
'''
ImgObj = proj.image(imageRef)
Controls = ImgObj.data['Image Controls']
formatName = Controls.get('formatName','')
imagefile = ImgObj.data['data'][1]
if isinstance(imagefile, tuple) or isinstance(imagefile, list):
imagefile, ImageTag = imagefile # fix for multiimage files
else:
ImageTag = None # single-image file
sumImg = G2fil.RereadImageData(ImageReaderlist,imagefile,ImageTag=ImageTag,FormatName=formatName)
if sumImg is None:
return []
sumImg = np.array(sumImg,dtype='int32')
darkImg = False
if 'dark image' in Controls:
darkImg,darkScale = Controls['dark image']
if darkImg:
dImgObj = proj.image(darkImg)
formatName = dImgObj.data['Image Controls'].get('formatName','')
imagefile = dImgObj.data['data'][1]
if type(imagefile) is tuple:
imagefile,ImageTag = imagefile
darkImage = G2fil.RereadImageData(ImageReaderlist,imagefile,ImageTag=ImageTag,FormatName=formatName)
if darkImg is None:
raise Exception('Error reading dark image {}'.format(imagefile))
sumImg += np.array(darkImage*darkScale,dtype='int32')
if 'background image' in Controls:
backImg,backScale = Controls['background image']
if backImg: #ignores any transmission effect in the background image
bImgObj = proj.image(backImg)
formatName = bImgObj.data['Image Controls'].get('formatName','')
imagefile = bImgObj.data['data'][1]
ImageTag = None # fix this for multiimage files
backImage = G2fil.RereadImageData(ImageReaderlist,imagefile,ImageTag=ImageTag,FormatName=formatName)
if backImage is None:
raise Exception('Error reading background image {}'.format(imagefile))
if darkImg:
backImage += np.array(darkImage*darkScale/backScale,dtype='int32')
else:
sumImg += np.array(backImage*backScale,dtype='int32')
if 'Gain map' in Controls:
gainMap = Controls['Gain map']
if gainMap:
gImgObj = proj.image(gainMap)
formatName = gImgObj.data['Image Controls'].get('formatName','')
imagefile = gImgObj.data['data'][1]
ImageTag = None # fix this for multiimage files
GMimage = G2fil.RereadImageData(ImageReaderlist,imagefile,ImageTag=ImageTag,FormatName=formatName)
if GMimage is None:
raise Exception('Error reading Gain map image {}'.format(imagefile))
sumImg = sumImg*GMimage/1000
sumImg -= int(Controls.get('Flat Bkg',0))
Imax = np.max(sumImg)
Controls['range'] = [(0,Imax),[0,Imax]]
return np.asarray(sumImg,dtype='int32')
def patchControls(Controls):
'''patch routine to convert variable names used in parameter limits
to G2VarObj objects
(See :ref:`Parameter Limits<ParameterLimits>` description.)
'''
#patch (added Oct 2020) convert variable names for parm limits to G2VarObj
for d in 'parmMaxDict','parmMinDict':
if d not in Controls: Controls[d] = {}
for k in Controls[d]:
if type(k) is str:
G2fil.G2Print("Applying patch to Controls['{}']".format(d))
Controls[d] = {G2obj.G2VarObj(k):v for k,v in Controls[d].items()}
break
conv = False
if 'parmFrozen' not in Controls: Controls['parmFrozen'] = {}
for k in Controls['parmFrozen']:
for item in Controls['parmFrozen'][k]:
if type(item) is str:
conv = True
Controls['parmFrozen'][k] = [G2obj.G2VarObj(i) for i in Controls['parmFrozen'][k]]
break
if conv: G2fil.G2Print("Applying patch to Controls['parmFrozen']")
if 'newLeBail' not in Controls:
Controls['newLeBail'] = False
# end patch
def _constr_type(var):
'''returns the constraint type based on phase/histogram use
in a variable
'''
if var.histogram and var.phase:
return 'HAP'
elif var.phase:
return 'Phase'
elif var.histogram:
return 'Hist'
else:
return 'Global'
class G2ObjectWrapper(object):
"""Base class for all GSAS-II object wrappers.
The underlying GSAS-II format can be accessed as `wrapper.data`. A number
of overrides are implemented so that the wrapper behaves like a dictionary.
Author: Jackson O'Donnell (jacksonhodonnell .at. gmail.com)
"""
def __init__(self, datadict):
self.data = datadict
def __getitem__(self, key):
return self.data[key]
def __setitem__(self, key, value):
self.data[key] = value
def __contains__(self, key):
return key in self.data
def get(self, k, d=None):
return self.data.get(k, d)
def keys(self):
return self.data.keys()
def values(self):
return self.data.values()
def items(self):
return self.data.items()
class G2Project(G2ObjectWrapper):
"""Represents an entire GSAS-II project. The object contains these
class variables:
* G2Project.filename: contains the .gpx filename
* G2Project.names: contains the contents of the project "tree" as a list
of lists. Each top-level entry in the tree is an item in the list. The
name of the top-level item is the first item in the inner list. Children
of that item, if any, are subsequent entries in that list.
* G2Project.data: contains the entire project as a dict. The keys
for the dict are the top-level names in the project tree (initial items
in the G2Project.names inner lists) and each top-level item is stored
as a dict.
* The contents of Top-level entries will be found in the item
named 'data', as an example, ``G2Project.data['Notebook']['data']``
* The contents of child entries will be found in the item
using the names of the parent and child, for example
``G2Project.data['Phases']['NaCl']``
:param str gpxfile: Existing .gpx file to be loaded. If nonexistent,
creates an empty project.
:param str author: Author's name (not yet implemented)
:param str newgpx: The filename the project should be saved to in
the future. If both newgpx and gpxfile are present, the project is
loaded from the file named by gpxfile and then when saved will
be written to the file named by newgpx.
:param str filename: To be deprecated. Serves the same function as newgpx,
which has a somewhat more clear name.
(Do not specify both newgpx and filename).
There are two ways to initialize this object:
>>> # Load an existing project file
>>> proj = G2Project('filename.gpx')
>>> # Create a new project
>>> proj = G2Project(newgpx='new_file.gpx')
Histograms can be accessed easily.
>>> # By name
>>> hist = proj.histogram('PWDR my-histogram-name')
>>> # Or by index
>>> hist = proj.histogram(0)
>>> assert hist.id == 0
>>> # Or by random id
>>> assert hist == proj.histogram(hist.ranId)
Phases can be accessed the same way.
>>> phase = proj.phase('name of phase')
New data can also be loaded via :meth:`~G2Project.add_phase` and
:meth:`~G2Project.add_powder_histogram`.
>>> hist = proj.add_powder_histogram('some_data_file.chi',
'instrument_parameters.prm')
>>> phase = proj.add_phase('my_phase.cif', histograms=[hist])
Parameters for Rietveld refinement can be turned on and off at the project level
as well as described in
:meth:`~G2Project.set_refinement`, :meth:`~G2Project.iter_refinements` and
:meth:`~G2Project.do_refinements`.
"""
def __init__(self, gpxfile=None, author=None, filename=None, newgpx=None):
if filename is not None and newgpx is not None:
raise G2ScriptException('Do not use filename and newgpx together')
elif filename is not None:
G2fil.G2Print("Warning - recommending use of parameter newgpx rather than filename\n\twhen creating a G2Project")
elif newgpx:
filename = newgpx
if not gpxfile:
filename = os.path.abspath(os.path.expanduser(filename))
self.filename = filename
self.data, self.names = make_empty_project(author=author, filename=filename)
elif os.path.exists(os.path.expanduser(gpxfile)):
# TODO set author
self.data, self.names = LoadDictFromProjFile(gpxfile)
self.update_ids()
if filename:
filename = os.path.abspath(os.path.expanduser(filename))
dr = os.path.split(filename)[0]
if not os.path.exists(dr):
raise Exception("Directory {} for filename/newgpx does not exist".format(dr))
self.filename = filename
else:
self.filename = os.path.abspath(os.path.expanduser(gpxfile))
else:
raise ValueError("Not sure what to do with gpxfile {}. Does not exist?".format(gpxfile))
@classmethod
def from_dict_and_names(cls, gpxdict, names, filename=None):
"""Creates a :class:`G2Project` directly from
a dictionary and a list of names. If in doubt, do not use this.
:returns: a :class:`G2Project`
"""
out = cls()
if filename:
filename = os.path.abspath(os.path.expanduser(filename))
out.filename = filename
gpxdict['Controls']['data']['LastSavedAs'] = filename
else:
try:
out.filename = gpxdict['Controls']['data']['LastSavedAs']
except KeyError:
out.filename = None
out.data = gpxdict
out.names = names
def save(self, filename=None):
"""Saves the project, either to the current filename, or to a new file.
Updates self.filename if a new filename provided"""
# TODO update LastSavedUsing ?
if filename:
filename = os.path.abspath(os.path.expanduser(filename))
self.data['Controls']['data']['LastSavedAs'] = filename
self.filename = filename
elif not self.filename:
raise AttributeError("No file name to save to")
SaveDictToProjFile(self.data, self.names, self.filename)
def add_powder_histogram(self, datafile, iparams=None, phases=[],
fmthint=None,
databank=None, instbank=None, multiple=False):
"""Loads a powder data histogram or multiple powder histograms
into the project.
Note that the data type (x-ray/CW neutron/TOF) for the histogram
will be set from the instrument parameter file. The instrument
geometry is assumed to be Debye-Scherrer except for
dual-wavelength x-ray, where Bragg-Brentano is assumed.
:param str datafile: A filename with the powder data file to read.
Note that in unix fashion, "~" can be used to indicate the
home directory (e.g. ~/G2data/data.fxye).
:param str iparams: A filenme for an instrument parameters file,
or a pair of instrument parameter dicts from :func:`load_iprms`.
This may be omitted for readers that provide the instrument
parameters in the file. (Only a few importers do this.)
:param list phases: A list of phases to link to the new histogram,
phases can be references by object, name, rId or number.
Alternately, use 'all' to link to all phases in the project.
:param str fmthint: If specified, only importers where the format name
(reader.formatName, as shown in Import menu) contains the
supplied string will be tried as importers. If not specified, all
importers consistent with the file extension will be tried
(equivalent to "guess format" in menu).
:param int databank: Specifies a dataset number to read, if file contains
more than set of data. This should be 1 to read the first bank in
the file (etc.) regardless of the number on the Bank line, etc.
Default is None which means the first dataset in the file is read.
When multiple is True, optionally a list of dataset numbers can
be supplied here.
:param int instbank: Specifies an instrument parameter set to read, if
the instrument parameter file contains more than set of parameters.
This will match the INS # in an GSAS type file so it will typically
be 1 to read the first parameter set in the file (etc.)
Default is None which means there should only be one parameter set
in the file.
:param bool multiple: If False (default) only one dataset is read, but if
specified as True, all selected banks of data (see databank)
are read in.
:returns: A :class:`G2PwdrData` object representing
the histogram, or if multiple is True, a list of :class:`G2PwdrData`
objects is returned.
"""
LoadG2fil()
datafile = os.path.abspath(os.path.expanduser(datafile))
try:
iparams = os.path.abspath(os.path.expanduser(iparams))
except:
pass
pwdrreaders = import_generic(datafile, Readers['Pwdr'],fmthint=fmthint,bank=databank)
if not multiple: pwdrreaders = pwdrreaders[0:1]
histlist = []
for r in pwdrreaders:
histname, new_names, pwdrdata = load_pwd_from_reader(r, iparams,
[h.name for h in self.histograms()],bank=instbank)
if histname in self.data:
G2fil.G2Print("Warning - redefining histogram", histname)
elif self.names[-1][0] == 'Phases':
self.names.insert(-1, new_names)
else:
self.names.append(new_names)
self.data[histname] = pwdrdata