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 pathGSASIIIO.py
2319 lines (2203 loc) · 99.4 KB
/
GSASIIIO.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 -*-
########### SVN repository information ###################
# $Date: 2024-01-22 12:08:46 -0600 (Mon, 22 Jan 2024) $
# $Author: toby $
# $Revision: 5720 $
# $URL: https://subversion.xray.aps.anl.gov/pyGSAS/trunk/GSASIIIO.py $
# $Id: GSASIIIO.py 5720 2024-01-22 18:08:46Z toby $
########### SVN repository information ###################
'''
Misc routines for input and output, including image reading follow.
TODO: This module needs some work to separate wx from non-wx routines. GUI
routines should probably move to GSASIIctrlGUI.
'''
from __future__ import division, print_function
# Allow this to be imported without wx present. Was needed for G2scriptable, but is
# likely not needed anymore
try:
import wx
except ImportError:
# was needed by sphinx, but probably not anymore
class Placeholder(object):
def __init__(self):
self.Dialog = object
wx = Placeholder()
import math
import numpy as np
import numpy.ma as ma
import copy
import platform
if '2' in platform.python_version_tuple()[0]:
import cPickle
else:
import pickle as cPickle
import sys
import re
import random as ran
import GSASIIpath
GSASIIpath.SetVersionNumber("$Revision: 5720 $")
try:
import GSASIIdataGUI as G2gd
except ImportError:
pass
import GSASIIobj as G2obj
import GSASIIlattice as G2lat
try:
import GSASIIpwdGUI as G2pdG
import GSASIIimgGUI as G2imG
except ImportError:
pass
import GSASIIElem as G2el
import GSASIIstrIO as G2stIO
import GSASIImapvars as G2mv
import GSASIIfiles as G2fil
try:
import GSASIIctrlGUI as G2G
except ImportError:
pass
import os
import os.path as ospath
DEBUG = False #=True for various prints
TRANSP = False #=true to transpose images for testing
if GSASIIpath.GetConfigValue('Transpose'): TRANSP = True
npsind = lambda x: np.sin(x*np.pi/180.)
def sfloat(S):
'Convert a string to float. An empty field or a unconvertable value is treated as zero'
if S.strip():
try:
return float(S)
except ValueError:
pass
return 0.0
def sint(S):
'Convert a string to int. An empty field is treated as zero'
if S.strip():
return int(S)
else:
return 0
def trim(val):
'''Simplify a string containing leading and trailing spaces
as well as newlines, tabs, repeated spaces etc. into a shorter and
more simple string, by replacing all ranges of whitespace
characters with a single space.
:param str val: the string to be simplified
:returns: the (usually) shortened version of the string
'''
return re.sub('\\s+', ' ', val).strip()
def FileDlgFixExt(dlg,file):
'this is needed to fix a problem in linux wx.FileDialog'
ext = dlg.GetWildcard().split('|')[2*dlg.GetFilterIndex()+1].strip('*')
if ext not in file:
file += ext
return file
def GetPowderPeaks(fileName):
'Read powder peaks from a file'
sind = lambda x: math.sin(x*math.pi/180.)
asind = lambda x: 180.*math.asin(x)/math.pi
wave = 1.54052
File = open(fileName,'r')
Comments = []
peaks = []
S = File.readline()
while S:
if S[:1] == '#':
Comments.append(S[:-1])
else:
item = S.split()
if len(item) == 1:
peaks.append([float(item[0]),1.0])
elif len(item) > 1:
peaks.append([float(item[0]),float(item[1])])
S = File.readline()
File.close()
if Comments:
print ('Comments on file:')
for Comment in Comments:
print (Comment)
if 'wavelength' in Comment:
wave = float(Comment.split('=')[1])
Peaks = []
if peaks[0][0] > peaks[-1][0]: # d-spacings - assume CuKa
for peak in peaks:
dsp = peak[0]
sth = wave/(2.0*dsp)
if sth < 1.0:
tth = 2.0*asind(sth)
else:
break
Peaks.append([tth,peak[1],True,False,0,0,0,dsp,0.0])
else: #2-thetas - assume Cuka (for now)
for peak in peaks:
tth = peak[0]
dsp = wave/(2.0*sind(tth/2.0))
Peaks.append([tth,peak[1],True,False,0,0,0,dsp,0.0])
limits = [1000.,0.]
for peak in Peaks:
limits[0] = min(limits[0],peak[0])
limits[1] = max(limits[1],peak[0])
limits[0] = max(1.,(int(limits[0]-1.)/5)*5.)
limits[1] = min(170.,(int(limits[1]+1.)/5)*5.)
return Comments,Peaks,limits,wave
def GetCheckImageFile(G2frame,treeId):
'''Try to locate an image file if the project and image have been moved
together. If the image file cannot be found, request the location from
the user.
:param wx.Frame G2frame: main GSAS-II Frame and data object
:param wx.Id treeId: Id for the main tree item for the image
:returns: Npix,imagefile,imagetag with (Npix) number of pixels,
imagefile, if it exists, or the name of a file that does exist or False if the user presses Cancel
and (imagetag) an optional image number
'''
Npix,Imagefile,imagetag = G2frame.GPXtree.GetImageLoc(treeId)
if isinstance(Imagefile,list):
imagefile,imagetag = Imagefile
else:
imagefile = Imagefile
if not os.path.exists(imagefile):
print ('Image file '+imagefile+' not found')
fil = imagefile.replace('\\','/') # windows?!
# see if we can find a file with same name or in a similarly named sub-dir
pth,fil = os.path.split(fil)
prevpth = None
while pth and pth != prevpth:
prevpth = pth
if os.path.exists(os.path.join(G2frame.dirname,fil)):
print ('found image file '+os.path.join(G2frame.dirname,fil))
imagefile = os.path.join(G2frame.dirname,fil)
G2frame.GPXtree.UpdateImageLoc(treeId,imagefile)
return Npix,imagefile,imagetag
pth,enddir = os.path.split(pth)
fil = os.path.join(enddir,fil)
# not found as a subdirectory, drop common parts of path for last saved & image file names
# if image was .../A/B/C/imgs/ima.ge
# & GPX was .../A/B/C/refs/fil.gpx but is now .../NEW/TEST/TEST1
# will look for .../NEW/TEST/TEST1/imgs/ima.ge, .../NEW/TEST/imgs/ima.ge, .../NEW/imgs/ima.ge and so on
Controls = G2frame.GPXtree.GetItemPyData(G2gd.GetGPXtreeItemId(G2frame,G2frame.root, 'Controls'))
gpxPath = Controls.get('LastSavedAs','').replace('\\','/').split('/') # blank in older .GPX files
imgPath = imagefile.replace('\\','/').split('/')
for p1,p2 in zip(gpxPath,imgPath):
if p1 == p2:
gpxPath.pop(0),imgPath.pop(0)
else:
break
fil = os.path.join(*imgPath) # file with non-common prefix elements
prevpth = None
pth = os.path.abspath(G2frame.dirname)
while pth and pth != prevpth:
prevpth = pth
if os.path.exists(os.path.join(pth,fil)):
print ('found image file '+os.path.join(pth,fil))
imagefile = os.path.join(pth,fil)
G2frame.GPXtree.UpdateImageLoc(treeId,imagefile)
return Npix,imagefile,imagetag
pth,enddir = os.path.split(pth)
#GSASIIpath.IPyBreak()
if not os.path.exists(imagefile):
# note that this fails (at least on Mac) to get an image during the GUI initialization
prevnam = os.path.split(imagefile)[1]
prevext = os.path.splitext(imagefile)[1]
wildcard = 'Image format (*'+prevext+')|*'+prevext
dlg = wx.FileDialog(G2frame, 'Previous image file ('+prevnam+') not found; open here', '.', prevnam,
wildcard,wx.FD_OPEN)
try:
dlg.SetFilename(''+ospath.split(imagefile)[1])
if dlg.ShowModal() == wx.ID_OK:
imagefile = dlg.GetPath()
G2frame.GPXtree.UpdateImageLoc(treeId,imagefile)
else:
imagefile = None # was False
finally:
dlg.Destroy()
return Npix,imagefile,imagetag
def EditImageParms(parent,Data,Comments,Image,filename):
dlg = wx.Dialog(parent, wx.ID_ANY, 'Edit image parameters',
style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER)
def onClose(event):
dlg.EndModal(wx.ID_OK)
mainsizer = wx.BoxSizer(wx.VERTICAL)
h,w = Image.size[:2]
mainsizer.Add(wx.StaticText(dlg,wx.ID_ANY,'File '+str(filename)+'\nImage size: '+str(h)+' x '+str(w)),
0,wx.ALIGN_LEFT|wx.ALL, 2)
vsizer = wx.BoxSizer(wx.HORIZONTAL)
vsizer.Add(wx.StaticText(dlg,wx.ID_ANY,u'Wavelength (\xC5) '),
0,wx.ALIGN_LEFT|wx.ALL, 2)
wdgt = G2G.ValidatedTxtCtrl(dlg,Data,'wavelength')
vsizer.Add(wdgt)
mainsizer.Add(vsizer,0,wx.ALIGN_LEFT|wx.ALL, 2)
vsizer = wx.BoxSizer(wx.HORIZONTAL)
vsizer.Add(wx.StaticText(dlg,wx.ID_ANY,u'Pixel size (\xb5m). Width '),
0,wx.ALIGN_LEFT|wx.ALL, 2)
wdgt = G2G.ValidatedTxtCtrl(dlg,Data['pixelSize'],0,size=(50,-1))
vsizer.Add(wdgt)
vsizer.Add(wx.StaticText(dlg,wx.ID_ANY,u' Height '),wx.ALIGN_LEFT|wx.ALL, 2)
wdgt = G2G.ValidatedTxtCtrl(dlg,Data['pixelSize'],1,size=(50,-1))
vsizer.Add(wdgt)
mainsizer.Add(vsizer,0,wx.ALIGN_LEFT|wx.ALL, 2)
vsizer = wx.BoxSizer(wx.HORIZONTAL)
vsizer.Add(wx.StaticText(dlg,wx.ID_ANY,u'Sample to detector (mm) '),
0,wx.ALIGN_LEFT|wx.ALL, 2)
wdgt = G2G.ValidatedTxtCtrl(dlg,Data,'distance')
vsizer.Add(wdgt)
mainsizer.Add(vsizer,0,wx.ALIGN_LEFT|wx.ALL, 2)
vsizer = wx.BoxSizer(wx.HORIZONTAL)
vsizer.Add(wx.StaticText(dlg,wx.ID_ANY,u'Beam center (pixels). X = '),
0,wx.ALIGN_LEFT|wx.ALL, 2)
wdgt = G2G.ValidatedTxtCtrl(dlg,Data['center'],0,size=(75,-1))
vsizer.Add(wdgt)
vsizer.Add(wx.StaticText(dlg,wx.ID_ANY,u' Y = '),wx.ALIGN_LEFT|wx.ALL, 2)
wdgt = G2G.ValidatedTxtCtrl(dlg,Data['center'],1,size=(75,-1))
vsizer.Add(wdgt)
mainsizer.Add(vsizer,0,wx.ALIGN_LEFT|wx.ALL, 2)
vsizer = wx.BoxSizer(wx.HORIZONTAL)
vsizer.Add(wx.StaticText(dlg,wx.ID_ANY,u'Comments '),
0,wx.ALIGN_LEFT|wx.ALL, 2)
wdgt = G2G.ValidatedTxtCtrl(dlg,Comments,0,size=(250,-1))
vsizer.Add(wdgt)
mainsizer.Add(vsizer,0,wx.ALIGN_LEFT|wx.ALL, 2)
btnsizer = wx.StdDialogButtonSizer()
OKbtn = wx.Button(dlg, wx.ID_OK, 'Continue')
OKbtn.SetDefault()
OKbtn.Bind(wx.EVT_BUTTON,onClose)
btnsizer.AddButton(OKbtn) # not sure why this is needed
btnsizer.Realize()
mainsizer.Add(btnsizer, 1, wx.ALL|wx.EXPAND, 5)
dlg.SetSizer(mainsizer)
dlg.CenterOnParent()
dlg.ShowModal()
def LoadImage2Tree(imagefile,G2frame,Comments,Data,Npix,Image):
'''Load an image into the tree. Saves the location of the image, as well as the
ImageTag (where there is more than one image in the file), if defined.
'''
ImgNames = G2gd.GetGPXtreeDataNames(G2frame,['IMG ',])
TreeLbl = 'IMG '+os.path.basename(imagefile)
ImageTag = Data.get('ImageTag')
if ImageTag:
TreeLbl += ' #'+'%04d'%(ImageTag)
imageInfo = (imagefile,ImageTag)
else:
imageInfo = imagefile
TreeName = G2obj.MakeUniqueLabel(TreeLbl,ImgNames)
Id = G2frame.GPXtree.AppendItem(parent=G2frame.root,text=TreeName)
G2frame.GPXtree.SetItemPyData(G2frame.GPXtree.AppendItem(Id,text='Comments'),Comments)
Imax = np.amax(Image)
if G2frame.imageDefault:
Data.update(copy.deepcopy(G2frame.imageDefault))
Data['showLines'] = True
Data['ring'] = []
Data['rings'] = []
Data['cutoff'] = 10.
Data['pixLimit'] = 20
Data['edgemin'] = 100000000
Data['calibdmin'] = 0.5
Data['calibskip'] = 0
Data['ellipses'] = []
Data['calibrant'] = ''
Data['GonioAngles'] = [0.,0.,0.]
Data['DetDepthRef'] = False
else:
Data['type'] = 'PWDR'
Data['color'] = GSASIIpath.GetConfigValue('Contour_color','Paired')
if 'tilt' not in Data: #defaults if not preset in e.g. Bruker importer
Data['tilt'] = 0.0
Data['rotation'] = 0.0
Data['pixLimit'] = 20
Data['calibdmin'] = 0.5
Data['cutoff'] = 10.
Data['showLines'] = False
Data['calibskip'] = 0
Data['ring'] = []
Data['rings'] = []
Data['edgemin'] = 100000000
Data['ellipses'] = []
Data['GonioAngles'] = [0.,0.,0.]
Data['DetDepth'] = 0.
Data['DetDepthRef'] = False
Data['calibrant'] = ''
Data['IOtth'] = [5.0,50.0]
if GSASIIpath.GetConfigValue('Image_2theta_min'):
try:
Data['IOtth'][0] = float(GSASIIpath.GetConfigValue('Image_2theta_min'))
except:
pass
if GSASIIpath.GetConfigValue('Image_2theta_max'):
try:
Data['IOtth'][1] = float(GSASIIpath.GetConfigValue('Image_2theta_max'))
except:
pass
Data['LRazimuth'] = [0.,180.]
Data['azmthOff'] = 0.0
Data['outChannels'] = 2500
Data['outAzimuths'] = 1
Data['centerAzm'] = False
Data['fullIntegrate'] = GSASIIpath.GetConfigValue('fullIntegrate',True)
Data['setRings'] = False
Data['background image'] = ['',-1.0]
Data['dark image'] = ['',-1.0]
Data['Flat Bkg'] = 0.0
Data['Oblique'] = [0.5,False]
Data['setDefault'] = False
Data['range'] = [(0,Imax),[0,Imax]]
G2frame.GPXtree.SetItemPyData(G2frame.GPXtree.AppendItem(Id,text='Image Controls'),Data)
Masks = {'Points':[],'Rings':[],'Arcs':[],'Polygons':[],'Frames':[],
'Thresholds':[(0,Imax),[0,Imax]],
'SpotMask':{'esdMul':3.,'spotMask':None}}
G2frame.GPXtree.SetItemPyData(G2frame.GPXtree.AppendItem(Id,text='Masks'),Masks)
G2frame.GPXtree.SetItemPyData(G2frame.GPXtree.AppendItem(Id,text='Stress/Strain'),
{'Type':'True','d-zero':[],'Sample phi':0.0,'Sample z':0.0,'Sample load':0.0})
G2frame.GPXtree.SetItemPyData(Id,[Npix,imageInfo])
G2frame.PickId = Id
G2frame.PickIdText = G2frame.GetTreeItemsList(G2frame.PickId)
G2frame.Image = Id
def GetImageData(G2frame,imagefile,imageOnly=False,ImageTag=None,FormatName=''):
'''Read a single image with an image importer. This is called to reread an image
after it has already been imported with :meth:`GSASIIdataGUI.GSASII.OnImportGeneric`
(or :func:`ReadImages` in Auto Integration) so it is not necessary to reload metadata.
:param wx.Frame G2frame: main GSAS-II Frame and data object.
:param str imagefile: name of image file
:param bool imageOnly: If True return only the image,
otherwise (default) return more (see below)
:param int/str ImageTag: specifies a particular image to be read from a file.
First image is read if None (default).
:param str formatName: the image reader formatName
:returns: an image as a numpy array or a list of four items:
Comments, Data, Npix and the Image, as selected by imageOnly
'''
# determine which formats are compatible with this file
primaryReaders = []
secondaryReaders = []
for rd in G2frame.ImportImageReaderlist:
flag = rd.ExtensionValidator(imagefile)
if flag is None:
secondaryReaders.append(rd)
elif flag:
if not FormatName:
primaryReaders.append(rd)
elif FormatName in rd.formatName: #This is a kluge because the rd.formatName was changed!
primaryReaders.append(rd)
if len(secondaryReaders) + len(primaryReaders) == 0:
print('Error: No matching format for file '+imagefile)
raise Exception('No image read')
errorReport = ''
if not imagefile:
return
for rd in primaryReaders+secondaryReaders:
rd.ReInitialize() # purge anything from a previous read
rd.errors = "" # clear out any old errors
if not rd.ContentsValidator(imagefile): # rejected on cursory check
errorReport += "\n "+rd.formatName + ' validator error'
if rd.errors:
errorReport += ': '+rd.errors
continue
if imageOnly:
ParentFrame = None # prevent GUI access on reread
else:
ParentFrame = G2frame
if GSASIIpath.GetConfigValue('debug'):
flag = rd.Reader(imagefile,ParentFrame,blocknum=ImageTag)
else:
flag = False
try:
flag = rd.Reader(imagefile,ParentFrame,blocknum=ImageTag)
except rd.ImportException as detail:
rd.errors += "\n Read exception: "+str(detail)
except Exception as detail:
import traceback
rd.errors += "\n Unhandled read exception: "+str(detail)
rd.errors += "\n Traceback info:\n"+str(traceback.format_exc())
if flag: # this read succeeded
if rd.Image is None:
raise Exception('No image read. Strange!')
if GSASIIpath.GetConfigValue('Transpose'):
print ('Transposing Image!')
rd.Image = rd.Image.T
#rd.readfilename = imagefile
if imageOnly:
return rd.Image
else:
return rd.Comments,rd.Data,rd.Npix,rd.Image
else:
print('Error reading file '+imagefile)
print('Error messages(s)\n'+errorReport)
raise Exception('No image read')
def ReadImages(G2frame,imagefile):
'''Read one or more images from a file and put them into the Tree
using image importers. Called only in :meth:`AutoIntFrame.OnTimerLoop`.
ToDo: Images are most commonly read in :meth:`GSASIIdataGUI.GSASII.OnImportGeneric`
which is called from :meth:`GSASIIdataGUI.GSASII.OnImportImage`
it would be good if these routines used a common code core so that changes need to
be made in only one place.
:param wx.Frame G2frame: main GSAS-II Frame and data object.
:param str imagefile: name of image file
:returns: a list of the id's of the IMG tree items created
'''
# determine which formats are compatible with this file
primaryReaders = []
secondaryReaders = []
for rd in G2frame.ImportImageReaderlist:
flag = rd.ExtensionValidator(imagefile)
if flag is None:
secondaryReaders.append(rd)
elif flag:
primaryReaders.append(rd)
if len(secondaryReaders) + len(primaryReaders) == 0:
print('Error: No matching format for file '+imagefile)
raise Exception('No image read')
errorReport = ''
rdbuffer = {} # create temporary storage for file reader
for rd in primaryReaders+secondaryReaders:
rd.ReInitialize() # purge anything from a previous read
rd.errors = "" # clear out any old errors
if not rd.ContentsValidator(imagefile): # rejected on cursory check
errorReport += "\n "+rd.formatName + ' validator error'
if rd.errors:
errorReport += ': '+rd.errors
continue
ParentFrame = G2frame
block = 0
repeat = True
CreatedIMGitems = []
while repeat: # loop if the reader asks for another pass on the file
block += 1
repeat = False
if GSASIIpath.GetConfigValue('debug'):
flag = rd.Reader(imagefile,ParentFrame,blocknum=block,Buffer=rdbuffer)
else:
flag = False
try:
flag = rd.Reader(imagefile,ParentFrame,blocknum=block,Buffer=rdbuffer)
except rd.ImportException as detail:
rd.errors += "\n Read exception: "+str(detail)
except Exception as detail:
import traceback
rd.errors += "\n Unhandled read exception: "+str(detail)
rd.errors += "\n Traceback info:\n"+str(traceback.format_exc())
if flag: # this read succeeded
if rd.Image is None:
raise Exception('No image read. Strange!')
if GSASIIpath.GetConfigValue('Transpose'):
print ('Transposing Image!')
rd.Image = rd.Image.T
rd.Data['ImageTag'] = rd.repeatcount
rd.readfilename = imagefile
# Load generic metadata, as configured
G2fil.GetColumnMetadata(rd)
LoadImage2Tree(imagefile,G2frame,rd.Comments,rd.Data,rd.Npix,rd.Image)
repeat = rd.repeat
CreatedIMGitems.append(G2frame.Image)
if CreatedIMGitems: return CreatedIMGitems
else:
print('Error reading file '+imagefile)
print('Error messages(s)\n'+errorReport)
return []
#raise Exception('No image read')
def SaveMultipleImg(G2frame):
if not G2frame.GPXtree.GetCount():
print ('no images!')
return
choices = G2gd.GetGPXtreeDataNames(G2frame,['IMG ',])
if len(choices) == 1:
names = choices
else:
dlg = G2G.G2MultiChoiceDialog(G2frame,'Stress/Strain fitting','Select images to fit:',choices)
dlg.SetSelections([])
names = []
if dlg.ShowModal() == wx.ID_OK:
names = [choices[sel] for sel in dlg.GetSelections()]
dlg.Destroy()
if not names: return
for name in names:
Id = G2gd.GetGPXtreeItemId(G2frame, G2frame.root, name)
Npix,imagefile,imagetag = G2frame.GPXtree.GetImageLoc(Id)
imroot = os.path.splitext(imagefile)[0]
if imagetag:
imroot += '_' + str(imagetag)
Data = G2frame.GPXtree.GetItemPyData(G2gd.GetGPXtreeItemId(G2frame,Id, 'Image Controls'))
print('Writing '+imroot+'.imctrl')
File = open(imroot+'.imctrl','w')
keys = ['type','wavelength','calibrant','distance','center',
'tilt','rotation','azmthOff','fullIntegrate','LRazimuth',
'IOtth','outChannels','outAzimuths','invert_x','invert_y','DetDepth',
'calibskip','pixLimit','cutoff','calibdmin','chisq','Flat Bkg',
'binType','SampleShape','PolaVal','SampleAbs','dark image','background image']
for key in keys:
if key not in Data: continue #uncalibrated!
File.write(key+':'+str(Data[key])+'\n')
File.close()
mask = G2frame.GPXtree.GetItemPyData(G2gd.GetGPXtreeItemId(G2frame,Id, 'Masks'))
G2imG.CleanupMasks(mask)
print('Writing '+imroot+'.immask')
File = open(imroot+'.immask','w')
for key in ['Points','Rings','Arcs','Polygons','Frames','Thresholds']:
File.write(key+':'+str(mask[key])+'\n')
File.close()
def PutG2Image(filename,Comments,Data,Npix,image):
'Write an image as a python pickle - might be better as an .edf file?'
File = open(filename,'wb')
cPickle.dump([Comments,Data,Npix,image],File,2)
File.close()
return
objectScanIgnore = [int,bool,float,str,np.float64,np.float32,np.int32,np.int64,np.int16,np.ndarray,G2obj.G2VarObj,G2obj.ExpressionObj,np.bool_]
try:
objectScanIgnore += [ma.MaskedArray] # fails in doc builds
except AttributeError:
pass
if '2' in platform.python_version_tuple()[0]:
objectScanIgnore += [unicode,long,]
def objectScan(data,tag,indexStack=[]):
'''Recursively scan an object looking for unexpected data types.
This is used in debug mode to scan .gpx files for objects we did not
intend to be there.
'''
if type(data) is list or type(data) is tuple:
for i in range(len(data)):
val = objectScan(data[i],tag,indexStack+[i])
if val:
data[i] = val
print('...fixed')
elif type(data) is dict:
for key in data:
val = objectScan(data[key],tag,indexStack+[key])
if val:
data[key] = val
print('...fixed')
elif data is None:
return None
elif type(data) in objectScanIgnore:
return None
else:
s = 'unexpected object in '+tag
for i in indexStack:
s += "[{}]".format(i)
#print(s,data.__class__.__name__) # loses full name of class
print(s,type(data))
global unexpectedObject
unexpectedObject = True
# fix bad objects
if "gdi.Colour" in str(type(data)):
return tuple(data)
return
def cPickleLoad(fp):
if '2' in platform.python_version_tuple()[0]:
return cPickle.load(fp)
else:
return cPickle.load(fp,encoding='latin-1')
def ProjFileOpen(G2frame,showProvenance=True):
'Read a GSAS-II project file and load into the G2 data tree'
if not os.path.exists(G2frame.GSASprojectfile):
print ('\n*** Error attempt to open project file that does not exist:\n '+
str(G2frame.GSASprojectfile))
return
LastSavedUsing = None
filep = open(G2frame.GSASprojectfile,'rb')
if showProvenance: print ('loading from file: '+G2frame.GSASprojectfile)
GPXphase = os.path.splitext(G2frame.GSASprojectfile)[0]+'.seqPhase'
GPXhist = os.path.splitext(G2frame.GSASprojectfile)[0]+'.seqHist'
deleteSeq = False
hist = None
tmpHistIndex = {}
updateFromSeq = False
if os.path.exists(GPXphase) and os.path.exists(GPXhist):
dlg = wx.MessageDialog(G2frame,
'Load results from crashed sequential fit?\nNo deletes the files!', 'Recover partial sequential fit?', wx.YES | wx.NO | wx.CANCEL)
dlg.CenterOnParent()
try:
result = dlg.ShowModal()
deleteSeq = result != wx.ID_CANCEL
if result == wx.ID_YES:
updateFromSeq = True
fp = open(GPXphase,'rb')
data = cPickleLoad(fp) # first block in file should be Phases
if data[0][0] != 'Phases':
raise Exception('Unexpected block in {} file. How did this happen?'
.format(GPXphase))
Phases = {}
for name,vals in data[1:]:
Phases[name] = vals
name,CovData = cPickleLoad(fp)[0] # 2nd block in file should be Covariance
name,RigidBodies = cPickleLoad(fp)[0] # 3rd block in file should be Rigid Bodies
fp.close()
# index the histogram updates
hist = open(GPXhist,'rb')
try:
while True:
loc = hist.tell()
datum = cPickleLoad(hist)[0]
tmpHistIndex[datum[0]] = loc
except EOFError:
pass
finally:
dlg.Destroy()
wx.BeginBusyCursor()
try:
if GSASIIpath.GetConfigValue('show_gpxSize'):
posPrev = 0
sizeList = {}
while True:
try:
data = cPickleLoad(filep)
except EOFError:
break
datum = data[0]
if GSASIIpath.GetConfigValue('show_gpxSize'):
sizeList[datum[0]] = filep.tell()-posPrev
posPrev = filep.tell()
# scan the GPX file for unexpected objects
if GSASIIpath.GetConfigValue('debug'):
global unexpectedObject
unexpectedObject = False
objectScan(data,'tree item "{}" entry '.format(datum[0]))
#if unexpectedObject:
# print(datum[0])
# GSASIIpath.IPyBreak()
Id = G2frame.GPXtree.AppendItem(parent=G2frame.root,text=datum[0])
if datum[0] == 'Phases' and GSASIIpath.GetConfigValue('SeparateHistPhaseTreeItem',False):
G2frame.GPXtree.AppendItem(parent=G2frame.root,text='Hist/Phase')
if updateFromSeq and datum[0] == 'Phases':
for pdata in data[1:]:
if pdata[0] in Phases:
pdata[1].update(Phases[pdata[0]])
elif updateFromSeq and datum[0] == 'Covariance':
data[0][1] = CovData
elif updateFromSeq and datum[0] == 'Rigid bodies':
data[0][1] = RigidBodies
elif updateFromSeq and datum[0] in tmpHistIndex:
hist.seek(tmpHistIndex[datum[0]])
hdata = cPickleLoad(hist)
if data[0][0] != hdata[0][0]:
print('Error! Updating {} with {}'.format(data[0][0],hdata[0][0]))
datum = hdata[0]
xferItems = ['Background','Instrument Parameters','Sample Parameters','Reflection Lists']
hItems = {name:j+1 for j,(name,val) in enumerate(hdata[1:]) if name in xferItems}
for j,(name,val) in enumerate(data[1:]):
if name not in xferItems: continue
data[j+1][1] = hdata[hItems[name]][1]
if datum[0].startswith('PWDR'):
if 'ranId' not in datum[1][0]: # patch: add random Id if not present
datum[1][0]['ranId'] = ran.randint(0,sys.maxsize)
G2frame.GPXtree.SetItemPyData(Id,datum[1][:3]) #temp. trim off junk (patch?)
elif datum[0].startswith('HKLF'):
if 'ranId' not in datum[1][0]: # patch: add random Id if not present
datum[1][0]['ranId'] = ran.randint(0,sys.maxsize)
G2frame.GPXtree.SetItemPyData(Id,datum[1])
else:
G2frame.GPXtree.SetItemPyData(Id,datum[1])
if datum[0] == 'Controls' and 'LastSavedUsing' in datum[1]:
LastSavedUsing = datum[1]['LastSavedUsing']
if datum[0] == 'Controls' and 'PythonVersions' in datum[1] and GSASIIpath.GetConfigValue('debug') and showProvenance:
print('DBG_Packages used to create .GPX file:')
if 'dict' in str(type(datum[1]['PythonVersions'])): #patch
for p in sorted(datum[1]['PythonVersions'],key=lambda s: s.lower()):
print(" {:<14s}: {:s}".format(p[0],p[1]))
else:
for p in datum[1]['PythonVersions']:
print(" {:<12s} {:s}".format(p[0]+':',p[1]))
oldPDF = False
for datus in data[1:]:
#patch - 1/23/17 PDF cleanup
if datus[0][:4] in ['I(Q)','S(Q)','F(Q)','G(R)']:
oldPDF = True
data[1][1][datus[0][:4]] = copy.deepcopy(datus[1][:2])
continue
#end PDF cleanup
sub = G2frame.GPXtree.AppendItem(Id,datus[0])
#patch
if datus[0] == 'Instrument Parameters' and len(datus[1]) == 1:
if datum[0].startswith('PWDR'):
datus[1] = [dict(zip(datus[1][3],zip(datus[1][0],datus[1][1],datus[1][2]))),{}]
else:
datus[1] = [dict(zip(datus[1][2],zip(datus[1][0],datus[1][1]))),{}]
for item in datus[1][0]: #zip makes tuples - now make lists!
datus[1][0][item] = list(datus[1][0][item])
#end patch
G2frame.GPXtree.SetItemPyData(sub,datus[1])
if 'PDF ' in datum[0][:4] and oldPDF:
sub = G2frame.GPXtree.AppendItem(Id,'PDF Peaks')
G2frame.GPXtree.SetItemPyData(sub,{'Limits':[1.,5.],'Background':[2,[0.,-0.2*np.pi],False],'Peaks':[]})
if datum [0].startswith('IMG'): #retrieve image default flag & data if set
Data = G2frame.GPXtree.GetItemPyData(G2gd.GetGPXtreeItemId(G2frame,Id,'Image Controls'))
if Data['setDefault']:
G2frame.imageDefault = Data
G2frame.imageDefault['setDefault'] = False
if 'formatName' in G2frame.imageDefault: del G2frame.imageDefault['formatName']
if LastSavedUsing:
print('GPX load successful. Last saved with GSAS-II revision '+LastSavedUsing)
else:
print('project load successful')
if GSASIIpath.GetConfigValue('show_gpxSize'):
print(50*'=')
print('File section sizes (Kb)')
for item in sizeList:
print(' {:20s} {:10.3f}'.format(
item[:20],sizeList[item]/1024.))
print(50*'=')
G2frame.NewPlot = True
except Exception as errmsg:
if GSASIIpath.GetConfigValue('debug'):
print('\nError reading GPX file:',errmsg)
import traceback
print (traceback.format_exc())
msg = wx.MessageDialog(G2frame,message="Error reading file "+
str(G2frame.GSASprojectfile)+". This is not a current GSAS-II .gpx file",
caption="Load Error",style=wx.ICON_ERROR | wx.OK | wx.STAY_ON_TOP)
msg.ShowModal()
finally:
filep.close()
wx.EndBusyCursor()
G2frame.Status.SetStatusText('Mouse RB drag/drop to reorder',0)
if deleteSeq:
if hist: hist.close()
try:
os.remove(GPXphase)
except:
print('Warning: unable to delete {}'.format(GPXphase))
try:
os.remove(GPXhist)
except:
print('Warning: unable to delete {}'.format(GPXhist))
G2frame.SetTitleByGPX()
if LastSavedUsing:
try:
G2G.updateNotifier(G2frame,int(LastSavedUsing))
except:
pass
def ProjFileSave(G2frame):
'Save a GSAS-II project file'
if not G2frame.GPXtree.IsEmpty():
try:
file = open(G2frame.GSASprojectfile,'wb')
except PermissionError:
G2G.G2MessageBox(G2frame,'Read only file','Project cannot be saved; change permission & try again')
return
print ('save to file: '+G2frame.GSASprojectfile)
# stick the file name into the tree and version info into tree so they are saved.
# (Controls should always be created at this point)
try:
Controls = G2frame.GPXtree.GetItemPyData(
G2gd.GetGPXtreeItemId(G2frame,G2frame.root, 'Controls'))
Controls['LastSavedAs'] = os.path.abspath(G2frame.GSASprojectfile)
Controls['LastSavedUsing'] = str(GSASIIpath.GetVersionNumber())
Controls['PythonVersions'] = G2frame.PackageVersions
except:
pass
wx.BeginBusyCursor()
try:
item, cookie = G2frame.GPXtree.GetFirstChild(G2frame.root)
while item:
data = []
name = G2frame.GPXtree.GetItemText(item)
if name.startswith('Hist/Phase'): # skip over this
item, cookie = G2frame.GPXtree.GetNextChild(G2frame.root, cookie)
continue
data.append([name,G2frame.GPXtree.GetItemPyData(item)])
item2, cookie2 = G2frame.GPXtree.GetFirstChild(item)
while item2:
name = G2frame.GPXtree.GetItemText(item2)
data.append([name,G2frame.GPXtree.GetItemPyData(item2)])
item2, cookie2 = G2frame.GPXtree.GetNextChild(item, cookie2)
item, cookie = G2frame.GPXtree.GetNextChild(G2frame.root, cookie)
cPickle.dump(data,file,2)
file.close()
pth = os.path.split(os.path.abspath(G2frame.GSASprojectfile))[0]
if GSASIIpath.GetConfigValue('Save_paths'): G2G.SaveGPXdirectory(pth)
G2frame.LastGPXdir = pth
finally:
wx.EndBusyCursor()
print('project save successful')
def SaveIntegration(G2frame,PickId,data,Overwrite=False):
'Save image integration results as powder pattern(s)'
waves = {'Cu':[1.54051,1.54433],'Ti':[2.74841,2.75207],'Cr':[2.28962,2.29351],
'Fe':[1.93597,1.93991],'Co':[1.78892,1.79278],'Mo':[0.70926,0.713543],
'Ag':[0.559363,0.563775]}
azms = G2frame.Integrate[1]
X = G2frame.Integrate[2][:-1]
N = len(X)
Id = G2frame.GPXtree.GetItemParent(PickId)
name = G2frame.GPXtree.GetItemText(Id)
name = name.replace('IMG ',data['type']+' ')
Comments = G2frame.GPXtree.GetItemPyData(G2gd.GetGPXtreeItemId(G2frame,Id, 'Comments'))
Controls = G2frame.GPXtree.GetItemPyData(G2gd.GetGPXtreeItemId(G2frame,G2frame.root, 'Controls'))
Comments.append('Dark image = %s\n'%str(data['dark image']))
Comments.append('Background image = %s\n'%str(data['background image']))
Comments.append('Gain map = %s\n'%str(data['Gain map']))
if 'PWDR' in name:
if 'target' in data:
names = ['Type','Lam1','Lam2','I(L2)/I(L1)','Zero','Polariz.','U','V','W','X','Y','Z','SH/L','Azimuth']
codes = [0 for i in range(14)]
else:
if data.get('IfPink',False):
names = ['Type','Lam','Zero','Polariz.','U','V','W','X','Y','Z','alpha-0','alpha-1','beta-0','beta-1','Azimuth']
codes = [0 for i in range(15)]
else:
names = ['Type','Lam','Zero','Polariz.','U','V','W','X','Y','Z','SH/L','Azimuth']
codes = [0 for i in range(12)]
elif 'SASD' in name:
names = ['Type','Lam','Zero','Azimuth']
codes = [0 for i in range(4)]
X = 4.*np.pi*npsind(X/2.)/data['wavelength'] #convert to q
Xminmax = [X[0],X[-1]]
Azms = np.zeros(data['outAzimuths'])
dazm = 0.
if data['outAzimuths'] > 1:
dazm = np.min(np.abs(np.diff(azms)))/2.
G2frame.IntgOutList = []
for i,azm in enumerate(azms[:-1]):
Aname = name+" Azm= %.2f"%((azm+dazm)%360.)
item, cookie = G2frame.GPXtree.GetFirstChild(G2frame.root)
# if Overwrite delete any duplicate
if Overwrite and G2gd.GetGPXtreeItemId(G2frame,G2frame.root,Aname):
print('Replacing '+Aname)
item = G2gd.GetGPXtreeItemId(G2frame,G2frame.root,Aname)
G2frame.GPXtree.Delete(item)
else:
nOcc = 0
while item:
Name = G2frame.GPXtree.GetItemText(item)
if Aname in Name:
nOcc += 1
item, cookie = G2frame.GPXtree.GetNextChild(G2frame.root, cookie)
if nOcc:
Aname += '(%d)'%(nOcc)
Sample = G2obj.SetDefaultSample() #set as Debye-Scherrer
Sample['Gonio. radius'] = data['distance']
Sample['Omega'] = data['GonioAngles'][0]
Sample['Chi'] = data['GonioAngles'][1]
Sample['Phi'] = data['GonioAngles'][2]
Sample['Azimuth'] = (azm+dazm)%360. #put here as bin center
polariz = data['PolaVal'][0]
for item in Comments:
for key in ('Temperature','Pressure','Time','FreePrm1','FreePrm2','FreePrm3','Omega',
'Chi','Phi'):
if key.lower() in item.lower():
try:
Sample[key] = float(item.split('=')[1])
except:
pass
if 'label_prm' in item.lower():
for num in ('1','2','3'):
if 'label_prm'+num in item.lower():
Controls['FreePrm'+num] = item.split('=')[1].strip()
if 'PWDR' in Aname:
if 'target' in data: #from lab x-ray 2D imaging data
wave1,wave2 = waves[data['target']]
parms = ['PXC',wave1,wave2,0.5,0.0,polariz,290.,-40.,30.,6.,-14.,0.0,0.0001,Azms[i]]
else:
if data.get('IfPink',False):
parms = ['PXB',data['wavelength'],0.0,polariz,0.,8000.,-150.,-24.,0.,0.,0.,13.,-1300.,3.,-7.,Azms[i]] #from Sect 35 LSS
else:
parms = ['PXC',data['wavelength'],0.0,polariz,1.0,-0.10,0.4,0.30,1.0,0.0,0.0001,Azms[i]]
elif 'SASD' in Aname:
Sample['Trans'] = data['SampleAbs'][0]
parms = ['LXC',data['wavelength'],0.0,Azms[i]]
Y = G2frame.Integrate[0][i]
Ymin = np.min(Y)
Ymax = np.max(Y)
W = np.where(Y>0.,1./Y,1.e-6) #probably not true
Id = G2frame.GPXtree.AppendItem(parent=G2frame.root,text=Aname)
G2frame.IntgOutList.append(Id)
G2frame.GPXtree.SetItemPyData(G2frame.GPXtree.AppendItem(Id,text='Comments'),Comments)
G2frame.GPXtree.SetItemPyData(G2frame.GPXtree.AppendItem(Id,text='Limits'),copy.deepcopy([tuple(Xminmax),Xminmax]))
if 'PWDR' in Aname:
G2frame.GPXtree.SetItemPyData(G2frame.GPXtree.AppendItem(Id,text='Background'),[['chebyschev-1',1,3,1.0,0.0,0.0],
{'nDebye':0,'debyeTerms':[],'nPeaks':0,'peaksList':[],'background PWDR':['',1.0,False]}])
inst = [dict(zip(names,zip(parms,parms,codes))),{}]
for item in inst[0]:
inst[0][item] = list(inst[0][item])
G2frame.GPXtree.SetItemPyData(G2frame.GPXtree.AppendItem(Id,text='Instrument Parameters'),inst)
if 'PWDR' in Aname:
G2frame.GPXtree.SetItemPyData(G2frame.GPXtree.AppendItem(Id,text='Sample Parameters'),Sample)
G2frame.GPXtree.SetItemPyData(G2frame.GPXtree.AppendItem(Id,text='Peak List'),{'sigDict':{},'peaks':[]})
G2frame.GPXtree.SetItemPyData(G2frame.GPXtree.AppendItem(Id,text='Index Peak List'),[[],[]])
G2frame.GPXtree.SetItemPyData(G2frame.GPXtree.AppendItem(Id,text='Unit Cells List'),[])
G2frame.GPXtree.SetItemPyData(G2frame.GPXtree.AppendItem(Id,text='Reflection Lists'),{})
elif 'SASD' in Aname:
G2frame.GPXtree.SetItemPyData(G2frame.GPXtree.AppendItem(Id,text='Substances'),G2pdG.SetDefaultSubstances())
G2frame.GPXtree.SetItemPyData(G2frame.GPXtree.AppendItem(Id,text='Sample Parameters'),Sample)
G2frame.GPXtree.SetItemPyData(G2frame.GPXtree.AppendItem(Id,text='Models'),G2pdG.SetDefaultSASDModel())
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]}
G2frame.GPXtree.SetItemPyData(Id,[valuesdict,
[np.array(X),np.array(Y),np.array(W),np.zeros(N),np.zeros(N),np.zeros(N)]])
return Id #last powder pattern generated
def XYsave(G2frame,XY,labelX='X',labelY='Y',names=[]):
'Save XY table data'
pth = G2G.GetExportPath(G2frame)
dlg = wx.FileDialog(
G2frame, 'Enter csv filename for XY table', pth, '',
'XY table file (*.csv)|*.csv',wx.FD_SAVE|wx.FD_OVERWRITE_PROMPT)
try:
if dlg.ShowModal() == wx.ID_OK:
filename = dlg.GetPath()
filename = os.path.splitext(filename)[0]+'.csv'
File = open(filename,'w')
else:
filename = None
finally:
dlg.Destroy()
if not filename:
return
for i in range(len(XY)):
if len(names):
header = '%s,%s(%s)\n'%(labelX,labelY,names[i])
else:
header = '%s,%s(%d)\n'%(labelX,labelY,i)
File.write(header)
for x,y in XY[i].T:
File.write('%.3f,%.3f\n'%(x,y))
File.close()
print (' XY data saved to: '+filename)
def PeakListSave(G2frame,file,peaks):
'Save powder peaks to a data file'
print ('save peak list to file: '+G2frame.peaklistfile)
if not peaks:
dlg = wx.MessageDialog(G2frame, 'No peaks!', 'Nothing to save!', wx.OK)
try:
dlg.ShowModal()
finally: