This repository was archived by the owner on Sep 16, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathGSASIIimgGUI.py
More file actions
4322 lines (4104 loc) · 207 KB
/
GSASIIimgGUI.py
File metadata and controls
4322 lines (4104 loc) · 207 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
#GSASII - image data display routines
########### SVN repository information ###################
# $Date: 2024-02-07 17:00:54 -0600 (Wed, 07 Feb 2024) $
# $Author: toby $
# $Revision: 5724 $
# $URL: https://subversion.xray.aps.anl.gov/pyGSAS/trunk/GSASIIimgGUI.py $
# $Id: GSASIIimgGUI.py 5724 2024-02-07 23:00:54Z toby $
########### SVN repository information ###################
'''Image GUI routines follow.
'''
from __future__ import division, print_function
import os
import copy
import glob
import time
import re
import math
import sys
import wx
import wx.lib.mixins.listctrl as listmix
import wx.grid as wg
import matplotlib as mpl
import numpy as np
import numpy.ma as ma
import GSASIIpath
GSASIIpath.SetVersionNumber("$Revision: 5724 $")
import GSASIIimage as G2img
import GSASIImath as G2mth
import GSASIIElem as G2elem
import GSASIIpwdGUI as G2pdG
import GSASIIplot as G2plt
import GSASIIIO as G2IO
import GSASIIfiles as G2fil
import GSASIIdataGUI as G2gd
import GSASIIctrlGUI as G2G
import GSASIIobj as G2obj
import ImageCalibrants as calFile
# documentation build kludge. This prevents an error with sphinx 1.8.5 (fixed by 2.3) where all mock objects are of type _MockObject
if (type(wx.ListCtrl).__name__ ==
type(listmix.ListCtrlAutoWidthMixin).__name__ ==
type(listmix.TextEditMixin).__name__):
print('Using Sphinx 1.8.5 _MockObject kludge fix in GSASIIimgGUI')
class Junk1(object): pass
listmix.ListCtrlAutoWidthMixin = Junk1
class Junk2(object): pass
listmix.TextEditMixin = Junk2
try:
#VERY_LIGHT_GREY = wx.Colour(235,235,235)
VERY_LIGHT_GREY = wx.SystemSettings.GetColour(wx.SYS_COLOUR_BTNFACE)
WACV = wx.ALIGN_CENTER_VERTICAL
except:
pass
# trig functions in degrees
sind = lambda x: math.sin(x*math.pi/180.)
tand = lambda x: math.tan(x*math.pi/180.)
cosd = lambda x: math.cos(x*math.pi/180.)
asind = lambda x: 180.*math.asin(x)/math.pi
tth2q = lambda t,w:4.0*math.pi*sind(t/2.0)/w
tof2q = lambda t,C:2.0*math.pi*C/t
atand = lambda x: 180.*math.atan(x)/math.pi
atan2d = lambda y,x: 180.*math.atan2(y,x)/math.pi
################################################################################
##### Image Data
################################################################################
def GetImageZ(G2frame,data,newRange=False):
'''Gets image & applies dark, background & flat background corrections.
:param wx.Frame G2frame: main GSAS-II frame
:param dict data: Image Controls dictionary
:returns: array sumImg: corrected image for background/dark/flat back
'''
# Note that routine GSASIIscriptable._getCorrImage is based on this
# so changes made here should be repeated there.
Npix,imagefile,imagetag = G2IO.GetCheckImageFile(G2frame,G2frame.Image)
if imagefile is None: return []
formatName = data.get('formatName','')
sumImg = np.array(G2IO.GetImageData(G2frame,imagefile,True,ImageTag=imagetag,FormatName=formatName),dtype='float32')
if sumImg is None:
return []
darkImg = False
if 'dark image' in data:
darkImg,darkScale = data['dark image']
if darkImg:
Did = G2gd.GetGPXtreeItemId(G2frame, G2frame.root, darkImg)
if Did:
Ddata = G2frame.GPXtree.GetItemPyData(G2gd.GetGPXtreeItemId(G2frame,Did,'Image Controls'))
dformatName = Ddata.get('formatName','')
Npix,darkfile,imagetag = G2IO.GetCheckImageFile(G2frame,Did)
# darkImage = G2IO.GetImageData(G2frame,darkfile,True,ImageTag=imagetag,FormatName=dformatName)
darkImage = np.array(G2IO.GetImageData(G2frame,darkfile,True,ImageTag=imagetag,FormatName=dformatName),dtype='float32')
if darkImg is not None:
sumImg += np.array(darkImage*darkScale,dtype='float32')
else:
print('Warning: resetting dark image (not found: {})'.format(
darkImg))
data['dark image'][0] = darkImg = ''
if 'background image' in data:
backImg,backScale = data['background image']
if backImg: #ignores any transmission effect in the background image
Bid = G2gd.GetGPXtreeItemId(G2frame, G2frame.root, backImg)
if Bid:
Npix,backfile,imagetag = G2IO.GetCheckImageFile(G2frame,Bid)
Bdata = G2frame.GPXtree.GetItemPyData(G2gd.GetGPXtreeItemId(G2frame,Bid,'Image Controls'))
bformatName = Bdata.get('formatName','')
backImage = np.array(G2IO.GetImageData(G2frame,backfile,True,ImageTag=imagetag,FormatName=bformatName),dtype='float32')
if darkImg and backImage is not None:
backImage += np.array(darkImage*darkScale/backScale,dtype='float32')
if backImage is not None:
sumImg += np.array(backImage*backScale,dtype='float32')
if 'Gain map' in data:
gainMap = data['Gain map']
if gainMap:
GMid = G2gd.GetGPXtreeItemId(G2frame, G2frame.root, gainMap)
if GMid:
Npix,gainfile,imagetag = G2IO.GetCheckImageFile(G2frame,GMid)
Gdata = G2frame.GPXtree.GetItemPyData(G2gd.GetGPXtreeItemId(G2frame,GMid,'Image Controls'))
gformat = Gdata['formatName']
GMimage = G2IO.GetImageData(G2frame,gainfile,True,ImageTag=imagetag,FormatName=gformat)
sumImg = sumImg*GMimage/1000
sumImg -= int(data.get('Flat Bkg',0))
Imax = np.max(sumImg)
Imin = np.min(sumImg)
if 'range' not in data or newRange:
data['range'] = [(Imin,Imax),[Imin,Imax]]
return np.asarray(np.rint(sumImg),dtype='int32')
def UpdateImageData(G2frame,data):
def OnPixVal(invalid,value,tc):
G2plt.PlotExposedImage(G2frame,newPlot=True,event=tc.event)
def OnPolaCalib(event):
if data['IOtth'][1] < 34.:
G2G.G2MessageBox(G2frame,'Maximum 2-theta not greater than 34 deg',
'Polarization Calibration Error')
return
IOtth = [32.,data['IOtth'][1]-2.]
dlg = G2G.SingleFloatDialog(G2frame,'Polarization test arc mask',
''' Do not use if pattern has uneven absorption
Set 2-theta max in image controls to be fully inside image
Enter 2-theta position for arc mask (32-%.1f) '''%IOtth[1],IOtth[1],IOtth,fmt='%.2f')
if dlg.ShowModal() == wx.ID_OK:
arcTth = dlg.GetValue()
G2fil.G2SetPrintLevel('none')
G2img.DoPolaCalib(G2frame.ImageZ,data,arcTth)
G2fil.G2SetPrintLevel('all')
UpdateImageData(G2frame,data)
dlg.Destroy()
def OnMakeGainMap(event):
import scipy.ndimage.filters as sdif
sumImg = GetImageZ(G2frame,data)
masks = copy.deepcopy(G2frame.GPXtree.GetItemPyData(
G2gd.GetGPXtreeItemId(G2frame,G2frame.Image,'Masks')))
Data = copy.deepcopy(data)
#force defaults for GainMap calc
Data['IOtth'] = [0.1,60.0]
Data['outAzimuths'] = 1
Data['LRazimuth'] = [0.,360.]
Data['outChannels'] = 5000
Data['binType'] = '2-theta'
Data['color'] = 'gray'
G2frame.Integrate = G2img.ImageIntegrate(sumImg,Data,masks,blkSize)
Iy,azms,Ix = G2frame.Integrate[:3]
GainMap = G2img.MakeGainMap(sumImg,Ix,Iy,Data,blkSize)*1000.
Npix,imagefile,imagetag = G2IO.GetCheckImageFile(G2frame,G2frame.Image)
pth = os.path.split(os.path.abspath(imagefile))[0]
outname = 'GainMap'
dlg = wx.FileDialog(G2frame, 'Choose gain map filename', pth,outname,
'G2img files (*.G2img)|*.G2img',wx.FD_SAVE|wx.FD_OVERWRITE_PROMPT)
if dlg.ShowModal() == wx.ID_OK:
newimagefile = dlg.GetPath()
newimagefile = G2IO.FileDlgFixExt(dlg,newimagefile)
Data['formatName'] = 'GSAS-II image'
Data['range'] = [(500,2000),[800,1200]]
GainMap = np.where(GainMap > 2000,2000,GainMap)
GainMap = np.where(GainMap < 500,500,GainMap)
masks['Thresholds'] = [(500.,2000.),[800.,1200.]]
G2IO.PutG2Image(newimagefile,[],data,Npix,GainMap)
GMname = 'IMG '+os.path.split(newimagefile)[1]
Id = G2gd.GetGPXtreeItemId(G2frame,G2frame.root,GMname)
if not Id:
Id = G2frame.GPXtree.AppendItem(parent=G2frame.root,text=GMname)
G2frame.GPXtree.SetItemPyData(Id,[Npix,newimagefile])
G2frame.GPXtree.SetItemPyData(G2frame.GPXtree.AppendItem(Id,text='Comments'),[])
G2frame.GPXtree.SetItemPyData(G2frame.GPXtree.AppendItem(Id,text='Image Controls'),Data)
G2frame.GPXtree.SetItemPyData(G2frame.GPXtree.AppendItem(Id,text='Masks'),masks)
else:
G2frame.GPXtree.SetItemPyData(Id,[Npix,newimagefile])
G2frame.GPXtree.SetItemPyData(G2gd.GetGPXtreeItemId(G2frame,Id,'Comments'),[])
G2frame.GPXtree.SetItemPyData(G2gd.GetGPXtreeItemId(G2frame,Id,'Image Controls'),Data)
G2frame.GPXtree.SetItemPyData(G2gd.GetGPXtreeItemId(G2frame,Id,'Masks'),masks)
G2frame.GPXtree.Expand(Id)
G2frame.GPXtree.SelectItem(Id) #to show the gain map & put it in the list
G2frame.dataWindow.ClearData()
G2frame.ImageZ = GetImageZ(G2frame,data)
mainSizer = G2frame.dataWindow.GetSizer()
topSizer = wx.BoxSizer(wx.HORIZONTAL)
topSizer.Add(wx.StaticText(G2frame.dataWindow,label=' Do not change anything here unless you are absolutely sure!'),0)
topSizer.Add((-1,-1),1,wx.EXPAND)
topSizer.Add(G2G.HelpButton(G2frame.dataWindow,helpIndex=G2frame.dataWindow.helpKey))
mainSizer.Add(topSizer,0,wx.EXPAND)
mainSizer.Add(wx.StaticText(G2frame.dataWindow,label=' Image size: %d by %d'%(data['size'][0],data['size'][1])),0)
pixSize = wx.FlexGridSizer(0,4,5,5)
pixLabels = [u' Pixel X-dimension (\xb5m)',u' Pixel Y-dimension (\xb5m)']
for i,[pixLabel,pix] in enumerate(zip(pixLabels,data['pixelSize'])):
pixSize.Add(wx.StaticText(G2frame.dataWindow,label=pixLabel),0,WACV)
pixVal = G2G.ValidatedTxtCtrl(G2frame.dataWindow,data['pixelSize'],i,nDig=(10,3),
typeHint=float,OnLeave=OnPixVal)
pixSize.Add(pixVal,0,WACV)
mainSizer.Add(pixSize,0)
distSizer = wx.BoxSizer(wx.HORIZONTAL)
distSizer.Add(wx.StaticText(G2frame.dataWindow,label=' Set detector distance: '),0,WACV)
if 'setdist' not in data:
data['setdist'] = data['distance']
distSizer.Add(G2G.ValidatedTxtCtrl(G2frame.dataWindow,data,'setdist',nDig=(10,4),
typeHint=float),0,WACV)
distSizer.Add(wx.StaticText(G2frame.dataWindow,label=' Polarization: '),0,WACV)
if 'PolaVal' not in data: #patch
data['PolaVal'] = [0.99,False]
distSizer.Add(G2G.ValidatedTxtCtrl(G2frame.dataWindow,data['PolaVal'],0,nDig=(10,4),
xmin=0.,xmax=1.,typeHint=float),0,WACV)
polaCalib = wx.Button(G2frame.dataWindow,label='Calibrate?')
polaCalib.Bind(wx.EVT_BUTTON,OnPolaCalib)
distSizer.Add(polaCalib,0,WACV)
mainSizer.Add(distSizer,0)
#patch
if 'samplechangerpos' not in data or data['samplechangerpos'] is None:
data['samplechangerpos'] = 0.0
if 'det2theta' not in data:
data['det2theta'] = 0.0
if 'Gain map' not in data:
data['Gain map'] = ''
#end patch
tthSizer = wx.BoxSizer(wx.HORIZONTAL)
tthSizer.Add(wx.StaticText(G2frame.dataWindow,label=' Detector 2-theta: '),0,WACV)
tthSizer.Add(G2G.ValidatedTxtCtrl(G2frame.dataWindow,data,'det2theta',xmin=-180.,xmax=180.,nDig=(10,2)),0,WACV)
tthSizer.Add(wx.StaticText(G2frame.dataWindow,label=' Sample changer position %.2f mm '%data['samplechangerpos']),0,WACV)
mainSizer.Add(tthSizer,0)
if not data['Gain map']:
makeGain = wx.Button(G2frame.dataWindow,label='Make gain map from this image? NB: use only an amorphous pattern for this')
makeGain.Bind(wx.EVT_BUTTON,OnMakeGainMap)
mainSizer.Add(makeGain)
G2frame.dataWindow.SetDataSize()
################################################################################
##### Image Controls
################################################################################
blkSize = 128 #128 seems to be optimal; will break in polymask if >1024
def UpdateImageControls(G2frame,data,masks,useTA=None,useMask=None,IntegrateOnly=False):
'''Shows and handles the controls on the "Image Controls"
data tree entry
'''
#patch
if 'Flat Bkg' not in data:
data['Flat Bkg'] = 0.0
if 'Gain map' not in data:
data['Gain map'] = ''
if 'GonioAngles' not in data:
data['GonioAngles'] = [0.,0.,0.]
if 'DetDepth' not in data:
data['DetDepth'] = 0.
if 'SampleAbs' not in data:
data['SampleShape'] = 'Cylinder'
data['SampleAbs'] = [0.0,False]
if 'binType' not in data:
if 'PWDR' in data['type']:
data['binType'] = '2-theta'
elif 'SASD' in data['type']:
data['binType'] = 'log(q)'
if 'varyList' not in data:
data['varyList'] = {'dist':True,'det-X':True,'det-Y':True,'tilt':True,'phi':True,'dep':False,'wave':False}
if data['DetDepth'] > 0.5:
data['DetDepth'] /= data['distance']
if 'setdist' not in data:
data['setdist'] = data['distance']
if 'linescan' not in data:
data['linescan'] = [False,0.0] #includes azimuth to draw line scan
if 'det2theta' not in data:
data['det2theta'] = 0.0
if 'orientation' not in data:
data['orientation'] = 'horizontal'
#end patch
# Menu items
def OnCalibrate(event):
if not data['calibrant']:
G2G.G2MessageBox(G2frame,'No calibrant material specified.\n'+
'Please correct this and try again.')
return
G2frame.GetStatusBar().SetStatusText('Select > 4 points on 1st used ring; LB to pick (shift key to force pick), RB on point to delete else RB to finish',1)
G2frame.ifGetRing = True
def OnRecalibrate(event):
'''Use existing calibration values as starting point for a calibration
fit
'''
G2img.ImageRecalibrate(G2frame,G2frame.ImageZ,data,masks)
wx.CallAfter(UpdateImageControls,G2frame,data,masks)
def OnRecalibAll(event):
'''Use existing calibration values as starting point for a calibration
fit for a selected series of images
'''
Id = None
Names = G2gd.GetGPXtreeDataNames(G2frame,['IMG ',])
dlg = G2G.G2MultiChoiceDialog(G2frame,'Image calibration controls','Select images to recalibrate:',Names)
try:
if dlg.ShowModal() == wx.ID_OK:
Id = G2gd.GetGPXtreeItemId(G2frame,G2frame.root,'Sequential image calibration results')
if Id:
SeqResult = G2frame.GPXtree.GetItemPyData(Id)
else:
Id = G2frame.GPXtree.AppendItem(parent=G2frame.root,text='Sequential image calibration results')
SeqResult = {'SeqPseudoVars':{},'SeqParFitEqList':[]}
items = dlg.GetSelections()
G2frame.EnablePlot = False
for item in items:
name = Names[item]
print ('calibrating'+name)
G2frame.Image = G2gd.GetGPXtreeItemId(G2frame,G2frame.root,name)
Data = G2frame.GPXtree.GetItemPyData(G2gd.GetGPXtreeItemId(G2frame,G2frame.Image,'Image Controls'))
G2frame.ImageZ = GetImageZ(G2frame,Data)
Data['setRings'] = True
Mid = G2gd.GetGPXtreeItemId(G2frame,G2frame.Image,'Masks')
Masks = G2frame.GPXtree.GetItemPyData(Mid)
result = G2img.ImageRecalibrate(G2frame,G2frame.ImageZ,Data,Masks)
if not len(result):
print('calibrant missing from local image calibrants files')
return
vals,varyList,sigList,parmDict,covar = result
sigList = list(sigList)
if 'dist' not in varyList:
vals.append(parmDict['dist'])
varyList.append('dist')
sigList.append(None)
vals.append(Data.get('setdist',Data['distance']))
# add setdist to varylist etc. so that it is displayed in Seq Res table
varyList.append('setdist')
sigList.append(None)
covar = np.lib.pad(covar, (0,1), 'constant')
# vals.append(Data.get('samplechangerpos',Data['samplechangerpos']))
# varyList.append('chgrpos')
# sigList.append(None)
SeqResult[name] = {'variables':vals,'varyList':varyList,'sig':sigList,'Rvals':[],
'covMatrix':covar,'title':name,'parmDict':parmDict}
SeqResult['histNames'] = Names
G2frame.GPXtree.SetItemPyData(Id,SeqResult)
finally:
dlg.Destroy()
print ('All selected images recalibrated - results in Sequential image calibration results')
G2frame.G2plotNB.Delete('Sequential refinement') #clear away probably invalid plot
G2plt.PlotExposedImage(G2frame,event=None)
if Id: G2frame.GPXtree.SelectItem(Id)
def OnCalcRings(event):
'''Use existing calibration values to compute rings & display them
'''
G2img.CalcRings(G2frame,G2frame.ImageZ,data,masks)
G2plt.PlotExposedImage(G2frame,event=None)
wx.CallAfter(UpdateImageControls,G2frame,data,masks)
def OnDistRecalib(event):
'''Assemble rings & calibration input for a series of images with
differing distances
'''
obsArr = np.array([]).reshape(0,4)
parmDict = {}
varList = []
HKL = {}
Names = G2gd.GetGPXtreeDataNames(G2frame,['IMG ',])
startID = G2frame.GPXtree.GetSelection()
dlg = G2G.G2MultiChoiceDialog(G2frame,'Image calibration controls','Select images to recalibrate:',Names)
try:
if dlg.ShowModal() == wx.ID_OK:
wx.BeginBusyCursor()
items = dlg.GetSelections()
print('Scanning for ring picks...')
# G2frame.EnablePlot = False
for item in items:
name = Names[item]
print ('getting rings for',name)
G2frame.Image = G2gd.GetGPXtreeItemId(G2frame,G2frame.root,name)
Data = G2frame.GPXtree.GetItemPyData(G2gd.GetGPXtreeItemId(G2frame,G2frame.Image,'Image Controls'))
key = str(int(Data['setdist']))
# create a parameter dict for combined fit
if 'wavelength' not in parmDict:
parmDict['wavelength'] = Data['wavelength']
if Data['varyList']['wave']:
varList += ['wavelength']
if Data['varyList']['dist']:
G2G.G2MessageBox(G2frame,
'You cannot vary individual detector positions and the global wavelength.\n\nChange flags for 1st image.',
'Conflicting vars')
return
parmDict['dep'] = Data['DetDepth']
if Data['varyList']['dep']:
varList += ['dep']
# distance flag determines if individual values are refined
if not Data['varyList']['dist']:
# starts as zero, single variable, always refined
parmDict['deltaDist'] = 0.
varList += ['deltaDist']
parmDict['phi'] = Data['rotation']
if Data['varyList']['phi']:
varList += ['phi']
parmDict['tilt'] = Data['tilt']
if Data['varyList']['tilt']:
varList += ['tilt']
G2frame.ImageZ = GetImageZ(G2frame,Data)
Data['setRings'] = True
Mid = G2gd.GetGPXtreeItemId(G2frame,G2frame.Image,'Masks')
Masks = G2frame.GPXtree.GetItemPyData(Mid)
result = G2img.ImageRecalibrate(G2frame,G2frame.ImageZ,Data,Masks,getRingsOnly=True)
if not len(result):
print('calibrant missing from local image calibrants files')
return
rings,HKL[key] = result
# add detector set dist into data array, create a single really large array
distarr = np.zeros_like(rings[:,2:3])
if 'setdist' not in Data:
print('Distance (setdist) not in image metadata')
return
distarr += Data['setdist']
obsArr = np.concatenate((
obsArr,
np.concatenate((rings[:,0:2],distarr,rings[:,2:3]),axis=1)),axis=0)
if 'deltaDist' not in parmDict:
# starts as zero, variable refined for each image
parmDict['delta'+key] = 0
varList += ['delta'+key]
for i,z in enumerate(['X','Y']):
v = 'det-'+z
if v+key in parmDict:
print('Error: two images with setdist ~=',key)
return
parmDict[v+key] = Data['center'][i]
if Data['varyList'][v]:
varList += [v+key]
#GSASIIpath.IPyBreak()
print('\nFitting',obsArr.shape[0],'ring picks and',len(varList),'variables...')
result = G2img.FitMultiDist(obsArr,varList,parmDict,covar=True)
covar = result[3]
covData = {'title':'Multi-distance recalibrate','covMatrix':covar,'varyList':varList,'variables':result[1]}
Id = G2gd.GetGPXtreeItemId(G2frame,G2frame.root,'Covariance')
G2frame.GPXtree.SetItemPyData(Id,covData)
for item in items:
name = Names[item]
print ('updating',name)
G2frame.Image = G2gd.GetGPXtreeItemId(G2frame,G2frame.root,name)
Data = G2frame.GPXtree.GetItemPyData(G2gd.GetGPXtreeItemId(G2frame,G2frame.Image,'Image Controls'))
Data['wavelength'] = parmDict['wavelength']
key = str(int(Data['setdist']))
Data['center'] = [parmDict['det-X'+key],parmDict['det-Y'+key]]
if 'deltaDist' in parmDict:
Data['distance'] = Data['setdist'] - parmDict['deltaDist']
else:
Data['distance'] = Data['setdist'] - parmDict['delta'+key]
Data['rotation'] = np.mod(parmDict['phi'],360.0)
Data['tilt'] = parmDict['tilt']
Data['DetDepth'] = parmDict['dep']
#Data['chisq'] = chisq
N = len(Data['ellipses'])
Data['ellipses'] = [] #clear away individual ellipse fits
for H in HKL[key][:N]:
ellipse = G2img.GetEllipse(H[3],Data)
Data['ellipses'].append(copy.deepcopy(ellipse+('b',)))
G2frame.EnablePlot = True
G2frame.GPXtree.SelectItem(G2frame.root) # there is probably a better way to force the reload of the current page
wx.CallAfter(G2frame.GPXtree.SelectItem,startID)
#GSASIIpath.IPyBreak()
# create a sequential table?
# Id = G2gd.GetGPXtreeItemId(G2frame,G2frame.root,'Sequential image calibration results')
# if Id:
# SeqResult = G2frame.GPXtree.GetItemPyData(Id)
# else:
# Id = G2frame.GPXtree.AppendItem(parent=G2frame.root,text='Sequential image calibration results')
#SeqResult = {'SeqPseudoVars':{},'SeqParFitEqList':[]}
# vals,varyList,sigList,parmDict,covar = result
# sigList = list(sigList)
# if 'dist' not in varyList:
# vals.append(parmDict['dist'])
# varyList.append('dist')
# sigList.append(None)
# vals.append(Data.get('setdist',Data['distance']))
# # add setdist to varylist etc. so that it is displayed in Seq Res table
# varyList.append('setdist')
# sigList.append(None)
# covar = np.lib.pad(covar, (0,1), 'constant')
# vals.append(Data.get('samplechangerpos',Data['samplechangerpos']))
# varyList.append('chgrpos')
# sigList.append(None)
# SeqResult[name] = {'variables':vals,'varyList':varyList,'sig':sigList,'Rvals':[],
# 'covMatrix':covar,'title':name,'parmDict':parmDict}
# SeqResult['histNames'] = Names
# G2frame.GPXtree.SetItemPyData(Id,SeqResult)
else:
wx.BeginBusyCursor()
finally:
dlg.Destroy()
wx.EndBusyCursor()
# print ('All selected images recalibrated - results in Sequential image calibration results')
# G2frame.G2plotNB.Delete('Sequential refinement') #clear away probably invalid plot
# G2plt.PlotExposedImage(G2frame,event=None)
# G2frame.GPXtree.SelectItem(Id)
def OnClearCalib(event):
data['ring'] = []
data['rings'] = []
data['ellipses'] = []
G2plt.PlotExposedImage(G2frame,event=event)
def ResetThresholds():
Imin = max(0.,np.min(G2frame.ImageZ))
Imax = np.max(G2frame.ImageZ)
data['range'] = [(0,Imax),[Imin,Imax]]
masks['Thresholds'] = [(0,Imax),[Imin,Imax]]
G2frame.slideSizer.GetChildren()[1].Window.SetValue(Imax) #tricky
G2frame.slideSizer.GetChildren()[4].Window.SetValue(Imin) #tricky
def OnIntegrate(event,useTA=None,useMask=None):
'''Integrate image in response to a menu event or from the AutoIntegrate
dialog. In the latter case, event=None.
'''
CleanupMasks(masks)
sumImg = GetImageZ(G2frame,data)
if masks.get('SpotMask',{'spotMask':None})['spotMask'] is not None:
sumImg = ma.array(sumImg,mask=masks['SpotMask']['spotMask'])
G2frame.Integrate = G2img.ImageIntegrate(sumImg,data,masks,blkSize,useTA=useTA,useMask=useMask)
G2frame.PauseIntegration = G2frame.Integrate[-1]
del sumImg #force cleanup
Id = G2IO.SaveIntegration(G2frame,G2frame.PickId,data,(event is None))
G2frame.PatternId = Id
G2frame.GPXtree.SelectItem(Id)
G2frame.GPXtree.Expand(Id)
for item in G2frame.MakePDF: item.Enable(True)
def OnIntegrateAll(event):
Names = G2gd.GetGPXtreeDataNames(G2frame,['IMG ',])
dlg = G2G.G2MultiChoiceDialog(G2frame,'Image integration controls','Select images to integrate:',Names)
try:
if dlg.ShowModal() == wx.ID_OK:
items = dlg.GetSelections()
G2frame.EnablePlot = False
dlgp = wx.ProgressDialog("Elapsed time","2D image integrations",len(items)+1,
style = wx.PD_ELAPSED_TIME|wx.PD_CAN_ABORT,parent=G2frame)
try:
pId = 0
oldData = {'tilt':0.,'distance':0.,'rotation':0.,'center':[0.,0.],'DetDepth':0.,'azmthOff':0.,'det2theta':0.}
oldMhash = 0
for icnt,item in enumerate(items):
dlgp.Raise()
GoOn = dlgp.Update(icnt)
if not GoOn[0]:
break
name = Names[item]
G2frame.Image = G2gd.GetGPXtreeItemId(G2frame,G2frame.root,name)
CId = G2gd.GetGPXtreeItemId(G2frame,G2frame.Image,'Image Controls')
Data = G2frame.GPXtree.GetItemPyData(CId)
same = True
for item in ['tilt','distance','rotation','DetDepth','azmthOff','det2theta']:
if Data[item] != oldData[item]:
same = False
if (Data['center'][0] != oldData['center'][0] or
Data['center'][1] != oldData['center'][1]):
same = False
if not same:
t0 = time.time()
useTA = G2img.MakeUseTA(Data,blkSize)
print(' Use new image controls; new xy -> th,azm time %.3f'%(time.time()-t0))
Masks = G2frame.GPXtree.GetItemPyData(
G2gd.GetGPXtreeItemId(G2frame,G2frame.Image,'Masks'))
Mhash = copy.deepcopy(Masks)
Mhash.pop('Thresholds')
Mhash = hash(str(Mhash))
if Mhash != oldMhash:
t0 = time.time()
useMask = G2img.MakeUseMask(Data,Masks,blkSize)
print(' Use new mask; make mask time: %.3f'%(time.time()-t0))
oldMhash = Mhash
image = GetImageZ(G2frame,Data)
if not Masks['SpotMask']['spotMask'] is None:
image = ma.array(image,mask=Masks['SpotMask']['spotMask'])
G2frame.Integrate = G2img.ImageIntegrate(image,Data,Masks,blkSize,useTA=useTA,useMask=useMask)
del image #force cleanup
pId = G2IO.SaveIntegration(G2frame,CId,Data)
oldData = Data
finally:
dlgp.Destroy()
G2frame.EnablePlot = True
if pId:
G2frame.GPXtree.SelectItem(pId)
G2frame.GPXtree.Expand(pId)
G2frame.PatternId = pId
finally:
dlg.Destroy()
def OnCopyControls(event):
Names = G2gd.GetGPXtreeDataNames(G2frame,['IMG ',])
if len(Names) == 1:
G2frame.ErrorDialog('Nothing to copy controls to','There must be more than one "IMG" pattern')
return
Source = G2frame.GPXtree.GetItemText(G2frame.Image)
Names.pop(Names.index(Source))
# select targets & do copy
dlg = G2G.G2MultiChoiceDialog(G2frame,'Copy image controls','Copy controls from '+Source+' to:',Names)
try:
if dlg.ShowModal() == wx.ID_OK:
items = dlg.GetSelections()
G2frame.EnablePlot = False
for item in items: #preserve some values
name = Names[item]
Id = G2gd.GetGPXtreeItemId(G2frame,G2frame.root,name)
CId = G2gd.GetGPXtreeItemId(G2frame,Id,'Image Controls')
oldData = copy.deepcopy(G2frame.GPXtree.GetItemPyData(CId))
Data = copy.deepcopy(data)
Data['range'][0] = oldData['range'][0]
Data['size'] = oldData['size']
Data['GonioAngles'] = oldData.get('GonioAngles', [0.,0.,0.])
Data['samplechangerpos'] = oldData.get('samplechangerpos',0.0)
Data['det2theta'] = oldData.get('det2theta',0.0)
Data['ring'] = []
Data['rings'] = []
Data['ellipses'] = []
if name == Data['dark image'][0]:
Data['dark image'] = ['',-1.]
if name == Data['background image'][0]:
Data['background image'] = ['',-1.]
G2frame.GPXtree.SetItemPyData(G2gd.GetGPXtreeItemId(G2frame,Id, 'Image Controls'),Data)
finally:
dlg.Destroy()
if G2frame.PickId: G2frame.GPXtree.SelectItem(G2frame.PickId)
def OnCopySelected(event):
Names = G2gd.GetGPXtreeDataNames(G2frame,['IMG ',])
if len(Names) == 1:
G2frame.ErrorDialog('Nothing to copy controls to','There must be more than one "IMG" pattern')
return
Source = G2frame.GPXtree.GetItemText(G2frame.Image)
# Assemble a list of item labels
keyList = ['type','color','wavelength','calibrant','distance','center','Oblique',
'tilt','rotation','azmthOff','fullIntegrate','LRazimuth','setdist',
'IOtth','outChannels','outAzimuths','invert_x','invert_y','DetDepth',
'calibskip','pixLimit','cutoff','calibdmin','Flat Bkg','varyList','orientation',
'binType','SampleShape','PolaVal','SampleAbs','dark image','background image']
keyList.sort(key=lambda s: s.lower())
keyText = [i+' = '+str(data[i]) for i in keyList]
# sort both lists together, ordered by keyText
selectedKeys = []
dlg = G2G.G2MultiChoiceDialog(G2frame,'Select which image controls\nto copy',
'Select image controls', keyText)
try:
if dlg.ShowModal() == wx.ID_OK:
selectedKeys = [keyList[i] for i in dlg.GetSelections()]
finally:
dlg.Destroy()
if not selectedKeys: return # nothing to copy
copyDict = {}
for parm in selectedKeys:
copyDict[parm] = data[parm]
dlg = G2G.G2MultiChoiceDialog(G2frame,'Copy image controls from\n'+Source+' to...',
'Copy image controls', Names)
try:
if dlg.ShowModal() == wx.ID_OK:
result = dlg.GetSelections()
for i in result:
item = Names[i]
Id = G2gd.GetGPXtreeItemId(G2frame,G2frame.root,item)
Controls = G2frame.GPXtree.GetItemPyData(G2gd.GetGPXtreeItemId(G2frame,Id,'Image Controls'))
Controls.update(copy.deepcopy(copyDict))
finally:
dlg.Destroy()
def OnSaveControls(event):
pth = G2G.GetExportPath(G2frame)
dlg = wx.FileDialog(G2frame, 'Choose image controls file', pth, '',
'image control files (*.imctrl)|*.imctrl',wx.FD_SAVE|wx.FD_OVERWRITE_PROMPT)
try:
if dlg.ShowModal() == wx.ID_OK:
filename = dlg.GetPath()
# make sure extension is .imctrl
filename = os.path.splitext(filename)[0]+'.imctrl'
G2fil.WriteControls(filename,data)
finally:
dlg.Destroy()
def OnSaveMultiControls(event):
'''Save controls from multiple images
'''
imglist = []
item, cookie = G2frame.GPXtree.GetFirstChild(G2frame.root)
while item:
name = G2frame.GPXtree.GetItemText(item)
if name.startswith('IMG '):
imglist.append(name)
item, cookie = G2frame.GPXtree.GetNextChild(G2frame.root, cookie)
if not imglist:
print('No images!')
return
dlg = G2G.G2MultiChoiceDialog(G2frame, 'Which images to select?',
'Select images', imglist, wx.CHOICEDLG_STYLE)
try:
if dlg.ShowModal() == wx.ID_OK:
treeEntries = [imglist[i] for i in dlg.GetSelections()]
finally:
dlg.Destroy()
if not treeEntries:
print('No images selected!')
return
pth = G2G.GetExportPath(G2frame)
dlg = wx.DirDialog(
G2frame, 'Select directory for output files',pth,wx.DD_DEFAULT_STYLE)
dlg.CenterOnParent()
outdir = None
try:
if dlg.ShowModal() == wx.ID_OK:
outdir = dlg.GetPath()
finally:
dlg.Destroy()
if not outdir:
print('No directory')
return
for img in treeEntries:
item = G2gd.GetGPXtreeItemId(G2frame,G2frame.root,img)
data = G2frame.GPXtree.GetItemPyData(G2gd.GetGPXtreeItemId(
G2frame,item,'Image Controls'))
Npix,imagefile,imagetag = G2frame.GPXtree.GetImageLoc(item)
filename = os.path.join(outdir,
os.path.splitext(os.path.split(imagefile)[1])[0]
+ '.imctrl')
print('writing '+filename)
G2fil.WriteControls(filename,data)
def OnLoadControls(event):
pth = G2G.GetImportPath(G2frame)
if not pth: pth = '.'
dlg = wx.FileDialog(G2frame, 'Choose image controls file', pth, '',
'image control files (*.imctrl)|*.imctrl',wx.FD_OPEN)
try:
if dlg.ShowModal() == wx.ID_OK:
filename = dlg.GetPath()
File = open(filename,'r')
Slines = File.readlines()
File.close()
G2fil.LoadControls(Slines,data)
finally:
dlg.Destroy()
G2frame.ImageZ = GetImageZ(G2frame,data)
ResetThresholds()
G2plt.PlotExposedImage(G2frame,event=event)
wx.CallLater(100,UpdateImageControls,G2frame,data,masks)
def OnLoadMultiControls(event): #TODO: how read in multiple image controls & match them by 'twoth' tag?
print('This is not implemented yet, sorry')
G2G.G2MessageBox(G2frame,'This is not implemented yet, sorry')
return
pth = G2G.GetImportPath(G2frame)
if not pth: pth = '.'
controlsDict = {}
dlg = wx.FileDialog(G2frame, 'Choose image control files', pth, '',
'image control files (*.imctrl)|*.imctrl',wx.FD_OPEN|wx.FD_MULTIPLE)
try:
if dlg.ShowModal() == wx.ID_OK:
filelist = dlg.GetPaths()
if len(filelist) == 0: return
for filename in filelist:
File = open(filename,'r')
Slines = File.readlines()
for S in Slines:
if S.find('twoth') == 0:
indx = S.split(':')[1][:-1] #remove '\n'!
controlsDict[indx] = Slines
File.close()
finally:
dlg.Destroy()
if not len(controlsDict):
return
Names = G2gd.GetGPXtreeDataNames(G2frame,['IMG ',])
dlg = G2G.G2MultiChoiceDialog(G2frame,'Select images','Select images for updating controls:',
Names)
try:
if dlg.ShowModal() == wx.ID_OK:
images = dlg.GetSelections()
if not len(images):
return
for image in images:
Id = G2gd.GetGPXtreeItemId(G2frame,G2frame.root,Names[image])
imctrls = G2frame.GPXtree.GetItemPyData(G2gd.GetGPXtreeItemId(G2frame,Id,'Image Controls'))
Slines = controlsDict[imctrls['twoth']]
G2fil.LoadControls(Slines,imctrls)
finally:
dlg.Destroy()
def OnTransferAngles(event):
'''Sets the integration range for the selected Images based on the difference in detector distance
'''
Names = G2gd.GetGPXtreeDataNames(G2frame,['IMG ',])
if len(Names) == 1:
G2frame.ErrorDialog('No images to transfer integration angles to','Need more "IMG"s')
return
Source = G2frame.GPXtree.GetItemText(G2frame.Image)
Names.pop(Names.index(Source))
# select targets & do copy
extraopts = {"label_1":"Xfer scaled calib d-min", "value_1":False,
"label_2":"Xfer scaled 2-theta min", "value_2":False,
"label_3":"Xfer scaled 2-theta max", "value_3":True,
"label_4":"Xfer fixed background ", "value_4":False,
}
dlg = G2G.G2MultiChoiceDialog(G2frame,'Xfer angles','Transfer integration range from '+Source+' to:',
Names,extraOpts=extraopts)
try:
if dlg.ShowModal() == wx.ID_OK:
for i in '_1','_2','_3','_4':
if extraopts['value'+i]: break
else:
G2G.G2MessageBox(G2frame,'Nothing to do!')
return
xferAng = lambda tth,dist1,dist2: atand(dist1 * tand(tth) / dist2)
items = dlg.GetSelections()
G2frame.EnablePlot = False
Id = G2gd.GetGPXtreeItemId(G2frame,G2frame.root,Source)
data = G2frame.GPXtree.GetItemPyData(G2gd.GetGPXtreeItemId(G2frame,Id,'Image Controls'))
ttmin0,ttmax0 = data['IOtth']
dist0 = data['distance']
wave0 = data['wavelength']
dsp0 = data['calibdmin']
flatBkg = data['Flat Bkg']
print('distance = {:.2f} integration range: [{:.4f}, {:.4f}], calib dmin {:.3f}'
.format(dist0,ttmin0,ttmax0,dsp0))
for item in items:
name = Names[item]
Id = G2gd.GetGPXtreeItemId(G2frame,G2frame.root,name)
data = G2frame.GPXtree.GetItemPyData(G2gd.GetGPXtreeItemId(G2frame,Id,'Image Controls'))
dist1 = data['distance']
if extraopts["value_2"]:
data['IOtth'][0] = xferAng(ttmin0,dist0,dist1)
if extraopts["value_3"]:
data['IOtth'][1] = xferAng(ttmax0,dist0,dist1)
if extraopts["value_1"]:
ang1 = xferAng(2.0*asind(wave0/(2.*dsp0)),dist0,dist1)
data['calibdmin'] = data['wavelength']/(2.*sind(ang1/2.))
print('distance = {:.2f} integration range: [{:.4f}, {:.4f}], calib dmin {:.3f}'
.format(dist1,data['IOtth'][0],data['IOtth'][1],data['calibdmin']))
if extraopts['value_4']:
data['Flat Bkg'] = flatBkg*(dist0/dist1)**2
else:
print('distance = {:.2f} integration range: [{:.4f}, {:.4f}]'
.format(dist1,data['IOtth'][0],data['IOtth'][1]))
finally:
dlg.Destroy()
G2frame.GPXtree.SelectItem(G2frame.PickId)
def OnResetDist(event):
dlg = wx.MessageDialog(G2frame,'Are you sure you want to do this?',caption='Reset dist to set dist',style=wx.YES_NO|wx.ICON_EXCLAMATION)
if dlg.ShowModal() != wx.ID_YES:
dlg.Destroy()
return
dlg.Destroy()
Names = G2gd.GetGPXtreeDataNames(G2frame,['IMG ',])
dlg = G2G.G2MultiChoiceDialog(G2frame,'Reset dist','Reset dist to set dist for:',Names)
try:
if dlg.ShowModal() == wx.ID_OK:
items = dlg.GetSelections()
for item in items:
name = Names[item]
Id = G2gd.GetGPXtreeItemId(G2frame,G2frame.root,name)
Data = G2frame.GPXtree.GetItemPyData(G2gd.GetGPXtreeItemId(G2frame,Id,'Image Controls'))
Data['distance'] = Data['setdist']
finally:
dlg.Destroy()
wx.CallAfter(UpdateImageControls,G2frame,data,masks)
# Sizers
Indx = {}
def ComboSizer():
def OnDataType(event):
data['type'] = typeSel.GetValue()[:4]
if 'SASD' in data['type']:
data['SampleAbs'][0] = np.exp(-data['SampleAbs'][0]) #switch from muT to trans!
if data['binType'] == '2-theta': data['binType'] = 'log(q)' #switch default bin type
elif 'PWDR' in data['type']:
data['SampleAbs'][0] = -np.log(data['SampleAbs'][0]) #switch from trans to muT!
if data['binType'] == 'log(q)': data['binType'] = '2-theta' #switch default bin type
wx.CallLater(100,UpdateImageControls,G2frame,data,masks)
def OnNewColorBar(event):
data['color'] = colSel.GetValue()
wx.CallAfter(G2plt.PlotExposedImage,G2frame,event=event)
def OnAzmthOff(invalid,value,tc):
wx.CallAfter(G2plt.PlotExposedImage,G2frame,event=tc.event)
comboSizer = wx.BoxSizer(wx.HORIZONTAL)
comboSizer.Add(wx.StaticText(parent=G2frame.dataWindow,label=' Type of image data: '),0,WACV)
typeSel = wx.ComboBox(parent=G2frame.dataWindow,value=typeDict[data['type']],choices=typeList,
style=wx.CB_READONLY|wx.CB_DROPDOWN)
typeSel.SetValue(data['type'])
typeSel.Bind(wx.EVT_COMBOBOX, OnDataType)
comboSizer.Add(typeSel,0,WACV)
comboSizer.Add(wx.StaticText(parent=G2frame.dataWindow,label=' Color bar '),0,WACV)
colSel = wx.ComboBox(parent=G2frame.dataWindow,value=data['color'],choices=colorList,
style=wx.CB_READONLY|wx.CB_DROPDOWN)
colSel.Bind(wx.EVT_COMBOBOX, OnNewColorBar)
comboSizer.Add(colSel,0,WACV)
comboSizer.Add(wx.StaticText(parent=G2frame.dataWindow,label=' Azimuth offset '),0,WACV)
azmthOff = G2G.ValidatedTxtCtrl(G2frame.dataWindow,data,'azmthOff',nDig=(10,2),
typeHint=float,OnLeave=OnAzmthOff)
comboSizer.Add(azmthOff,0,WACV)
return comboSizer
def MaxSizer():
'''Defines a sizer with sliders and TextCtrl widgets for controlling the colormap
for the image, as well as callback routines.
'''
def OnNewVal(invalid,value,tc):
'''Called when a Imax or Imin value is typed into a Validated TextCrtl (which puts
the value into the data['range'] nested list).
This adjusts the slider positions to match the current values
'''
scaleSel.SetSelection(len(scaleChoices)-1)
r11 = min(max(Range[1][1],Range[1][0]+1),Range[0][1]) # keep values in range
if r11 != Range[1][1]:
Range[1][1] = r11
maxVal.SetValue(int(Range[1][1]))
r10 = max(min(Range[1][0],Range[1][1]-1),Range[0][0])
if r10 != Range[1][0]:
Range[1][0] = r10
minVal.SetValue(int(Range[1][0]))
sqrtDeltZero = math.sqrt(max(1.0,Range[0][1]-max(0.0,Range[1][0])-1)) # sqrt(Imax0-Imin-1)
sqrtDeltOne = math.sqrt(max(1.0,Range[1][1]-max(0.0,Range[1][0])-1)) # sqrt(Imax-Imin-1)
sv1 = min(100,max(0,int(0.5+100.*sqrtDeltOne/sqrtDeltZero)))
maxSel.SetValue(sv1)
DeltOne = max(1.0,Range[1][1]-max(0.0,Range[0][0])-1)
sv0 = min(100,max(0,int(0.5+100.*(Range[1][0]-Range[0][0])/DeltOne)))
minSel.SetValue(sv0)
new,plotNum,Page,Plot,lim = G2frame.G2plotNB.FindPlotTab('2D Powder Image','mpl',newImage=False)
Page.ImgObj.set_clim([Range[1][0],Range[1][1]])
if mplOld:
Page.canvas.draw()
else:
Page.canvas.draw_idle()
G2frame.prevMaxValue = None
def OnMaxSlider(event):
val = maxSel.GetValue()
if G2frame.prevMaxValue == val: return # if this val has been processed, no need to repeat
scaleSel.SetSelection(len(scaleChoices)-1)
G2frame.prevMaxValue = val
sqrtDeltZero = math.sqrt(max(1.0,Range[0][1]-max(0.0,Range[1][0])-1)) # sqrt(Imax0-Imin-1)
Range[1][1] = int(0.5 + (val * sqrtDeltZero / 100.)**2 + Range[1][0] + 1)
maxVal.SetValue(int(0.5+Range[1][1]))
DeltOne = max(1.0,Range[1][1]-max(0.0,Range[0][0])-1)
minSel.SetValue(int(0.5 + 100*(Range[1][0]/DeltOne)))
sv0 = min(100,max(0,int(0.5+100.*(Range[1][0]-Range[0][0])/DeltOne)))
minSel.SetValue(sv0)
new,plotNum,Page,Plot,lim = G2frame.G2plotNB.FindPlotTab('2D Powder Image','mpl',newImage=False)
Page.ImgObj.set_clim([Range[1][0],Range[1][1]])
if mplOld:
Page.canvas.draw()
else:
Page.canvas.draw_idle()
G2frame.prevMinValue = None
def OnMinSlider(event):
val = minSel.GetValue()
scaleSel.SetSelection(len(scaleChoices)-1)
if G2frame.prevMinValue == val: return # if this val has been processed, no need to repeat
G2frame.prevMinValue = val
DeltOne = max(1.0,Range[1][1]-max(0.0,Range[0][0])-1) # Imax-Imin0-1
Range[1][0] = max(0,int(0.5 + val * DeltOne / 100 + Range[0][0]))
minVal.SetValue(int(Range[1][0]))
sqrtDeltZero = math.sqrt(max(1.0,Range[0][1]-max(0.0,Range[1][0])-1)) # sqrt(Imax0-Imin-1)
sqrtDeltOne = math.sqrt(max(1.0,Range[1][1]-max(0.0,Range[1][0])-1)) # sqrt(Imax-Imin-1)
sv1 = min(100,max(0,int(0.5+100.*sqrtDeltOne/sqrtDeltZero)))
maxSel.SetValue(sv1)
new,plotNum,Page,Plot,lim = G2frame.G2plotNB.FindPlotTab('2D Powder Image','mpl',newImage=False)
Page.ImgObj.set_clim([Range[1][0],Range[1][1]])
if mplOld:
Page.canvas.draw()
else:
Page.canvas.draw_idle()