-
Notifications
You must be signed in to change notification settings - Fork 2
/
GSASIIplot.py
5400 lines (5109 loc) · 226 KB
/
GSASIIplot.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 -*-
'''
*GSASIIplot: plotting routines*
===============================
'''
########### SVN repository information ###################
# $Date$
# $Author$
# $Revision$
# $URL$
# $Id$
########### SVN repository information ###################
import math
import time
import copy
import sys
import os.path
import numpy as np
import numpy.ma as ma
import numpy.linalg as nl
import wx
import wx.aui
import wx.glcanvas
import matplotlib as mpl
import mpl_toolkits.mplot3d.axes3d as mp3d
import GSASIIpath
GSASIIpath.SetVersionNumber("$Revision$")
import GSASIIgrid as G2gd
import GSASIIimage as G2img
import GSASIIpwd as G2pwd
import GSASIIIO as G2IO
import GSASIIpwdGUI as G2pdG
import GSASIIimgGUI as G2imG
import GSASIIphsGUI as G2phG
import GSASIIlattice as G2lat
import GSASIIspc as G2spc
import GSASIImath as G2mth
import GSASIIctrls as G2G
import pytexture as ptx
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLE import *
import gltext
from matplotlib.backends.backend_wx import _load_bitmap
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as Canvas
from matplotlib.backends.backend_wxagg import NavigationToolbar2Wx as Toolbar
# useful degree trig functions
sind = lambda x: math.sin(x*math.pi/180.)
cosd = lambda x: math.cos(x*math.pi/180.)
tand = lambda x: math.tan(x*math.pi/180.)
asind = lambda x: 180.*math.asin(x)/math.pi
acosd = lambda x: 180.*math.acos(x)/math.pi
atan2d = lambda x,y: 180.*math.atan2(y,x)/math.pi
atand = lambda x: 180.*math.atan(x)/math.pi
# numpy versions
npsind = lambda x: np.sin(x*np.pi/180.)
npcosd = lambda x: np.cos(x*np.pi/180.)
nptand = lambda x: np.tan(x*np.pi/180.)
npacosd = lambda x: 180.*np.arccos(x)/np.pi
npasind = lambda x: 180.*np.arcsin(x)/np.pi
npatand = lambda x: 180.*np.arctan(x)/np.pi
npatan2d = lambda x,y: 180.*np.arctan2(x,y)/np.pi
GkDelta = unichr(0x0394)
class G2PlotMpl(wx.Panel):
'needs a doc string'
def __init__(self,parent,id=-1,dpi=None,**kwargs):
wx.Panel.__init__(self,parent,id=id,**kwargs)
mpl.rcParams['legend.fontsize'] = 10
self.figure = mpl.figure.Figure(dpi=dpi,figsize=(5,6))
self.canvas = Canvas(self,-1,self.figure)
self.toolbar = GSASIItoolbar(self.canvas)
self.toolbar.Realize()
sizer=wx.BoxSizer(wx.VERTICAL)
sizer.Add(self.canvas,1,wx.EXPAND)
sizer.Add(self.toolbar,0,wx.LEFT|wx.EXPAND)
self.SetSizer(sizer)
class G2PlotOgl(wx.Panel):
'needs a doc string'
def __init__(self,parent,id=-1,dpi=None,**kwargs):
self.figure = wx.Panel.__init__(self,parent,id=id,**kwargs)
if 'win' in sys.platform: #Windows (& Mac) already double buffered
self.canvas = wx.glcanvas.GLCanvas(self,-1,**kwargs)
else: #fix from Jim Hester for X systems
attribs = (wx.glcanvas.WX_GL_DOUBLEBUFFER,)
self.canvas = wx.glcanvas.GLCanvas(self,-1,attribList=attribs,**kwargs)
# create GL context for wx > 2.8
i,j= wx.__version__.split('.')[0:2]
if int(i)+int(j)/10. > 2.8:
self.context = wx.glcanvas.GLContext(self.canvas)
self.canvas.SetCurrent(self.context)
else:
self.context = None
self.camera = {}
sizer=wx.BoxSizer(wx.VERTICAL)
sizer.Add(self.canvas,1,wx.EXPAND)
self.SetSizer(sizer)
class G2Plot3D(wx.Panel):
'needs a doc string'
def __init__(self,parent,id=-1,dpi=None,**kwargs):
wx.Panel.__init__(self,parent,id=id,**kwargs)
self.figure = mpl.figure.Figure(dpi=dpi,figsize=(6,6))
self.canvas = Canvas(self,-1,self.figure)
self.toolbar = GSASIItoolbar(self.canvas)
self.toolbar.Realize()
sizer=wx.BoxSizer(wx.VERTICAL)
sizer.Add(self.canvas,1,wx.EXPAND)
sizer.Add(self.toolbar,0,wx.LEFT|wx.EXPAND)
self.SetSizer(sizer)
class G2PlotNoteBook(wx.Panel):
'create a tabbed window for plotting'
def __init__(self,parent,id=-1):
wx.Panel.__init__(self,parent,id=id)
#so one can't delete a plot page!!
self.nb = wx.aui.AuiNotebook(self, \
style=wx.aui.AUI_NB_DEFAULT_STYLE ^ wx.aui.AUI_NB_CLOSE_ON_ACTIVE_TAB)
sizer = wx.BoxSizer()
sizer.Add(self.nb,1,wx.EXPAND)
self.SetSizer(sizer)
self.status = parent.CreateStatusBar()
self.status.SetFieldsCount(2)
self.status.SetStatusWidths([150,-1])
self.Bind(wx.aui.EVT_AUINOTEBOOK_PAGE_CHANGED, self.OnPageChanged)
self.nb.Bind(wx.EVT_KEY_UP,self.OnNotebookKey)
self.plotList = []
def OnNotebookKey(self,event):
'''Called when a keystroke event gets picked up by the notebook window
rather the child. This is not expected, but somehow it does sometimes
on the Mac and perhaps Linux.
Assume that the page associated with the currently displayed tab
has a child, .canvas; give that child the focus and pass it the event.
'''
try:
Page = self.nb.GetPage(self.nb.GetSelection())
except ValueError: # occurs with no plot tabs
return
try:
Page.canvas.SetFocus()
wx.PostEvent(Page.canvas,event)
except AttributeError:
pass
def addMpl(self,name=""):
'Add a tabbed page with a matplotlib plot'
page = G2PlotMpl(self.nb)
self.nb.AddPage(page,name)
self.plotList.append(name)
return page.figure
def add3D(self,name=""):
'Add a tabbed page with a 3D plot'
page = G2Plot3D(self.nb)
self.nb.AddPage(page,name)
self.plotList.append(name)
return page.figure
def addOgl(self,name=""):
'Add a tabbed page with an openGL plot'
page = G2PlotOgl(self.nb)
self.nb.AddPage(page,name)
self.plotList.append(name)
return page.figure
def Delete(self,name):
'delete a tabbed page'
try:
item = self.plotList.index(name)
del self.plotList[item]
self.nb.DeletePage(item)
except ValueError: #no plot of this name - do nothing
return
def clear(self):
'clear all pages from plot window'
while self.nb.GetPageCount():
self.nb.DeletePage(0)
self.plotList = []
self.status.DestroyChildren()
def Rename(self,oldName,newName):
'rename a tab'
try:
item = self.plotList.index(oldName)
self.plotList[item] = newName
self.nb.SetPageText(item,newName)
except ValueError: #no plot of this name - do nothing
return
def OnPageChanged(self,event):
'respond to someone pressing a tab on the plot window'
if self.plotList:
self.status.SetStatusText('Better to select this from GSAS-II data tree',1)
self.status.DestroyChildren() #get rid of special stuff on status bar
class GSASIItoolbar(Toolbar):
'Override the matplotlib toolbar so we can add more icons'
ON_MPL_HELP = wx.NewId()
ON_MPL_KEY = wx.NewId()
arrows = {}
for direc in ('left','right','up','down','Expand X',
'Shrink X','Expand Y','Shrink Y'):
arrows[direc] = wx.NewId()
def __init__(self,plotCanvas):
'''Adds additional icons to toolbar'''
Toolbar.__init__(self,plotCanvas)
self.plotCanvas = plotCanvas
POSITION_OF_CONFIGURE_SUBPLOTS_BTN = 6 # remove one button, nos. start at 1!
self.DeleteToolByPos(POSITION_OF_CONFIGURE_SUBPLOTS_BTN)
self.parent = self.GetParent()
key = os.path.join(os.path.split(__file__)[0],'key.ico')
self.AddSimpleTool(self.ON_MPL_KEY,_load_bitmap(key),'Key press','Select key press')
wx.EVT_TOOL(self,self.ON_MPL_KEY,self.OnKey)
help = os.path.join(os.path.split(__file__)[0],'help.ico')
self.AddSimpleTool(self.ON_MPL_HELP,_load_bitmap(help),'Help on','Show help on')
wx.EVT_TOOL(self,self.ON_MPL_HELP,self.OnHelp)
# add arrow keys to control zooming
for direc in ('left','right','up','down'):
wx.EVT_TOOL(self,self.arrows[direc],self.OnArrow)
icon = os.path.join(os.path.split(__file__)[0],direc[0]+'arrow.ico')
self.AddSimpleTool(self.arrows[direc],_load_bitmap(icon),
'Shift '+direc,'Shift plot '+direc)
for direc in ('Expand X','Shrink X','Expand Y','Shrink Y'):
fil = ''.join([i[0].lower() for i in direc.split()]+['arrow.ico'])
wx.EVT_TOOL(self,self.arrows[direc],self.OnArrow)
icon = os.path.join(os.path.split(__file__)[0],fil)
self.AddSimpleTool(self.arrows[direc],_load_bitmap(icon),
direc,'Zoom: '+direc)
def OnArrow(self,event):
'reposition limits to scan or zoom by button press'
ax = self.plotCanvas.figure.get_axes()[0]
xmin,xmax,ymin,ymax = ax.axis()
#print xmin,xmax,ymin,ymax
if event.Id == self.arrows['right']:
delta = (xmax-xmin)/10.
xmin -= delta
xmax -= delta
elif event.Id == self.arrows['left']:
delta = (xmax-xmin)/10.
xmin += delta
xmax += delta
elif event.Id == self.arrows['up']:
delta = (ymax-ymin)/10.
ymin -= delta
ymax -= delta
elif event.Id == self.arrows['down']:
delta = (ymax-ymin)/10.
ymin += delta
ymax += delta
elif event.Id == self.arrows['Expand X']:
delta = (xmax-xmin)/10.
xmin += delta
xmax -= delta
elif event.Id == self.arrows['Expand Y']:
delta = (ymax-ymin)/10.
ymin += delta
ymax -= delta
elif event.Id == self.arrows['Shrink X']:
delta = (xmax-xmin)/10.
xmin -= delta
xmax += delta
elif event.Id == self.arrows['Shrink Y']:
delta = (ymax-ymin)/10.
ymin -= delta
ymax += delta
else:
# should not happen!
GSASIIpath.IPyBreak()
self.parent.toolbar.push_current()
ax.axis((xmin,xmax,ymin,ymax))
#print xmin,xmax,ymin,ymax
self.plotCanvas.figure.canvas.draw()
self.parent.toolbar.draw()
# self.parent.toolbar.push_current()
def OnHelp(self,event):
'Respond to press of help button on plot toolbar'
Page = self.GetParent().GetParent()
pageNo = Page.GetSelection()
bookmark = Page.GetPageText(pageNo)
bookmark = bookmark.strip(')').replace('(','_')
G2G.ShowHelp(bookmark,self.TopLevelParent)
def OnKey(self,event):
'''Provide user with list of keystrokes defined for plot as well as an
alternate way to access the same functionality
'''
parent = self.GetParent()
if parent.Choice:
dlg = wx.SingleChoiceDialog(parent,'Select','Key press',list(parent.Choice))
if dlg.ShowModal() == wx.ID_OK:
sel = dlg.GetSelection()
event.key = parent.Choice[sel][0]
parent.keyPress(event)
dlg.Destroy()
################################################################################
##### PlotSngl
################################################################################
def PlotSngl(G2frame,newPlot=False,Data=None,hklRef=None,Title=''):
'''Structure factor plotting package - displays zone of reflections as rings proportional
to F, F**2, etc. as requested
'''
from matplotlib.patches import Circle,CirclePolygon
global HKL,HKLF
def OnSCKeyPress(event):
i = zones.index(Data['Zone'])
newPlot = False
pwdrChoice = {'f':'Fo','s':'Fosq','u':'Unit Fc'}
hklfChoice = {'1':'|DFsq|>sig','3':'|DFsq|>3sig','w':'|DFsq|/sig','f':'Fo','s':'Fosq','i':'Unit Fc'}
if event.key == 'h':
Data['Zone'] = '100'
newPlot = True
elif event.key == 'k':
Data['Zone'] = '010'
newPlot = True
elif event.key == 'l':
Data['Zone'] = '001'
newPlot = True
elif event.key == 'i':
Data['Scale'] *= 1.1
elif event.key == 'd':
Data['Scale'] /= 1.1
elif event.key in ['+','=']:
Data['Layer'] = min(Data['Layer']+1,HKLmax[i])
elif event.key == '-':
Data['Layer'] = max(Data['Layer']-1,HKLmin[i])
elif event.key == '0':
Data['Layer'] = 0
Data['Scale'] = 1.0
elif event.key in hklfChoice and 'HKLF' in Name:
Data['Type'] = hklfChoice[event.key]
newPlot = True
elif event.key in pwdrChoice and 'PWDR' in Name:
Data['Type'] = pwdrChoice[event.key]
newPlot = True
PlotSngl(G2frame,newPlot,Data,hklRef,Title)
def OnSCMotion(event):
xpos = event.xdata
if xpos:
xpos = round(xpos) #avoid out of frame mouse position
ypos = round(event.ydata)
zpos = Data['Layer']
if '100' in Data['Zone']:
HKLtxt = '(%3d,%3d,%3d)'%(zpos,xpos,ypos)
elif '010' in Data['Zone']:
HKLtxt = '(%3d,%3d,%3d)'%(xpos,zpos,ypos)
elif '001' in Data['Zone']:
HKLtxt = '(%3d,%3d,%3d)'%(xpos,ypos,zpos)
Page.canvas.SetToolTipString(HKLtxt)
G2frame.G2plotNB.status.SetStatusText('HKL = '+HKLtxt,0)
G2frame.G2plotNB.status.SetStatusText('Use K-box to set plot controls',1)
def OnSCPress(event):
zpos = Data['Layer']
xpos = event.xdata
if xpos:
pos = int(round(event.xdata)),int(round(event.ydata))
if '100' in Data['Zone']:
Page.canvas.SetToolTipString('(picked:(%3d,%3d,%3d))'%(zpos,pos[0],pos[1]))
hkl = np.array([zpos,pos[0],pos[1]])
elif '010' in Data['Zone']:
Page.canvas.SetToolTipString('(picked:(%3d,%3d,%3d))'%(pos[0],zpos,pos[1]))
hkl = np.array([pos[0],zpos,pos[1]])
elif '001' in Data['Zone']:
Page.canvas.SetToolTipString('(picked:(%3d,%3d,%3d))'%(pos[0],pos[1],zpos))
hkl = np.array([pos[0],pos[1],zpos])
h,k,l = hkl
hklf = HKLF[np.where(np.all(HKL-hkl == [0,0,0],axis=1))]
if len(hklf):
Fosq,sig,Fcsq = hklf[0]
HKLtxt = '( %.2f %.3f %.2f %.2f)'%(Fosq,sig,Fcsq,(Fosq-Fcsq)/(scale*sig))
G2frame.G2plotNB.status.SetStatusText('Fosq, sig, Fcsq, delFsq/sig = '+HKLtxt,1)
Name = G2frame.PatternTree.GetItemText(G2frame.PatternId)
if not Title:
Title = Name
try:
plotNum = G2frame.G2plotNB.plotList.index('Structure Factors')
Page = G2frame.G2plotNB.nb.GetPage(plotNum)
if not newPlot:
Plot = Page.figure.gca() #get previous powder plot & get limits
xylim = Plot.get_xlim(),Plot.get_ylim()
Page.figure.clf()
Plot = Page.figure.gca() #get a fresh plot after clf()
except ValueError:
Plot = G2frame.G2plotNB.addMpl('Structure Factors').gca()
plotNum = G2frame.G2plotNB.plotList.index('Structure Factors')
Page = G2frame.G2plotNB.nb.GetPage(plotNum)
Page.canvas.mpl_connect('button_press_event', OnSCPress)
Page.canvas.mpl_connect('motion_notify_event', OnSCMotion)
Page.canvas.mpl_connect('key_press_event', OnSCKeyPress)
Page.keyPress = OnSCKeyPress
Page.Choice = (' key press','i: increase scale','d: decrease scale',
'h: select 100 zone','k: select 010 zone','l: select 001 zone',
'f: select Fo','s: select Fosq','u: select unit Fc',
'+: increase index','-: decrease index','0: zero layer',)
if 'HKLF' in Name:
Page.Choice += ('w: select |DFsq|/sig','1: select |DFsq|>sig','3: select |DFsq|>3sig',)
Page.SetFocus()
G2frame.G2plotNB.status.SetStatusText('Use K-box to set plot controls',1)
Plot.set_aspect(aspect='equal')
Type = Data['Type']
scale = Data['Scale']
HKLmax = Data['HKLmax']
HKLmin = Data['HKLmin']
FosqMax = Data['FoMax']
Super = Data['Super']
SuperVec = []
if Super:
SuperVec = np.array(Data['SuperVec'][0])
FoMax = math.sqrt(FosqMax)
xlabel = ['k, h=','h, k=','h, l=']
ylabel = ['l','l','k']
zones = ['100','010','001']
pzone = [[1,2],[0,2],[0,1]]
izone = zones.index(Data['Zone'])
Plot.set_title(Data['Type']+' for '+Title)
HKL = []
HKLF = []
time0 = time.time()
for refl in hklRef:
H = refl[:3]
if 'HKLF' in Name:
Fosq,sig,Fcsq = refl[5+Super:8+Super]
else:
Fosq,sig,Fcsq = refl[8+Super],1.0,refl[9+Super]
if Super:
HKL.append(H+SuperVec*refl[3])
else:
HKL.append(H)
HKLF.append([Fosq,sig,Fcsq])
if H[izone] == Data['Layer']:
A = 0
B = 0
if Type == 'Fosq':
A = scale*Fosq/FosqMax
B = scale*Fcsq/FosqMax
C = abs(A-B)
elif Type == 'Fo':
A = scale*math.sqrt(max(0,Fosq))/FoMax
B = scale*math.sqrt(max(0,Fcsq))/FoMax
C = abs(A-B)
elif Type == 'Unit Fc':
A = scale/2
B = scale/2
C = 0.0
if Fcsq and Fosq > 0:
A *= min(1.0,Fosq/Fcsq)
C = abs(A-B)
elif Type == '|DFsq|/sig':
if sig > 0.:
A = (Fosq-Fcsq)/(3*sig)
B = 0
elif Type == '|DFsq|>sig':
if sig > 0.:
A = (Fosq-Fcsq)/(3*sig)
if abs(A) < 1.0: A = 0
B = 0
elif Type == '|DFsq|>3sig':
if sig > 0.:
A = (Fosq-Fcsq)/(3*sig)
if abs(A) < 3.0: A = 0
B = 0
if Super:
h = H+SuperVec*refl[3]
else:
h = H
xy = (h[pzone[izone][0]],h[pzone[izone][1]])
if Type in ['|DFsq|/sig','|DFsq|>sig','|DFsq|>3sig']:
if A > 0.0:
Plot.add_artist(Circle(xy,radius=A,ec='g',fc='w'))
else:
Plot.add_artist(Circle(xy,radius=-A,ec='r',fc='w'))
else:
if A > 0.0 and A > B:
Plot.add_artist(Circle(xy,radius=A,ec='g',fc='w'))
if B:
Plot.add_artist(Circle(xy,radius=B,ec='b',fc='w'))
if A < B:
Plot.add_artist(Circle(xy,radius=A,ec='g',fc='w'))
radius = C
if radius > 0:
if A > B:
Plot.add_artist(Circle(xy,radius=radius,ec='g',fc='g'))
else:
Plot.add_artist(Circle(xy,radius=radius,ec='r',fc='r'))
# print 'plot time: %.3f'%(time.time()-time0)
HKL = np.array(HKL)
HKLF = np.array(HKLF)
Plot.set_xlabel(xlabel[izone]+str(Data['Layer']),fontsize=12)
Plot.set_ylabel(ylabel[izone],fontsize=12)
if not newPlot:
Page.toolbar.push_current()
Plot.set_xlim(xylim[0])
Plot.set_ylim(xylim[1])
# xylim = []
Page.toolbar.push_current()
Page.toolbar.draw()
else:
Plot.set_xlim((HKLmin[pzone[izone][0]],HKLmax[pzone[izone][0]]))
Plot.set_ylim((HKLmin[pzone[izone][1]],HKLmax[pzone[izone][1]]))
Page.canvas.draw()
################################################################################
##### Plot3DSngl
################################################################################
def Plot3DSngl(G2frame,newPlot=False,Data=None,hklRef=None,Title=False):
'''3D Structure factor plotting package - displays reflections as rings proportional
to F, F**2, etc. as requested as 3D array
'''
global ifBox
ifBox = False
def OnKeyBox(event):
mode = cb.GetValue()
if mode in ['jpeg','bmp','tiff',]:
try:
import Image as Im
except ImportError:
try:
from PIL import Image as Im
except ImportError:
print "PIL/pillow Image module not present. Cannot save images without this"
raise Exception("PIL/pillow Image module not found")
try:
Fname = os.path.join(Mydir,generalData['Name']+'.'+mode)
except NameError: #for when generalData doesn't exist!
Fname = os.path.join(Mydir,'unknown'+'.'+mode)
print Fname+' saved'
size = Page.canvas.GetSize()
glPixelStorei(GL_UNPACK_ALIGNMENT, 1)
if mode in ['jpeg',]:
Pix = glReadPixels(0,0,size[0],size[1],GL_RGBA, GL_UNSIGNED_BYTE)
im = Im.new("RGBA", (size[0],size[1]))
else:
Pix = glReadPixels(0,0,size[0],size[1],GL_RGB, GL_UNSIGNED_BYTE)
im = Im.new("RGB", (size[0],size[1]))
im.fromstring(Pix)
im.save(Fname,mode)
cb.SetValue(' save as/key:')
G2frame.G2plotNB.status.SetStatusText('Drawing saved to: '+Fname,1)
else:
event.key = cb.GetValue()[0]
cb.SetValue(' save as/key:')
wx.CallAfter(OnKey,event)
Page.canvas.SetFocus() # redirect the Focus from the button back to the plot
def OnKey(event): #on key UP!!
global ifBox
Choice = {'F':'Fo','S':'Fosq','U':'Unit','D':'dFsq','W':'dFsq/sig'}
try:
keyCode = event.GetKeyCode()
if keyCode > 255:
keyCode = 0
key = chr(keyCode)
except AttributeError: #if from OnKeyBox above
key = str(event.key).upper()
if key in ['C']:
drawingData['viewPoint'][0] = drawingData['default']
drawingData['viewDir'] = [0,0,1]
drawingData['oldxy'] = []
V0 = np.array([0,0,1])
V = np.inner(Amat,V0)
V /= np.sqrt(np.sum(V**2))
A = np.arccos(np.sum(V*V0))
Q = G2mth.AV2Q(A,[0,1,0])
drawingData['Quaternion'] = Q
Q = drawingData['Quaternion']
elif key in 'B':
ifBox = not ifBox
elif key in ['+','=']:
Data['Scale'] *= 1.25
elif key == '-':
Data['Scale'] /= 1.25
elif key == '0':
drawingData['viewPoint'][0] = [0,0,0]
Data['Scale'] = 1.0
elif key == 'I':
Data['Iscale'] = not Data['Iscale']
elif key in Choice:
Data['Type'] = Choice[key]
Draw('key')
Name = G2frame.PatternTree.GetItemText(G2frame.PatternId)
if Title: #NB: save image as e.g. jpeg will fail if False; MyDir is unknown
generalData = G2frame.GetPhaseData()[Title]['General']
cell = generalData['Cell'][1:7]
Mydir = generalData['Mydir']
else:
cell = [10,10,10,90,90,90]
Mydir = G2frame.dirname
drawingData = Data['Drawing']
Super = Data['Super']
SuperVec = []
if Super:
SuperVec = np.array(Data['SuperVec'][0])
defaultViewPt = copy.copy(drawingData['viewPoint'])
Amat,Bmat = G2lat.cell2AB(cell) #Amat - crystal to cartesian, Bmat - inverse
Gmat,gmat = G2lat.cell2Gmat(cell)
invcell = G2lat.Gmat2cell(Gmat)
A4mat = np.concatenate((np.concatenate((Amat,[[0],[0],[0]]),axis=1),[[0,0,0,1],]),axis=0)
B4mat = np.concatenate((np.concatenate((Bmat,[[0],[0],[0]]),axis=1),[[0,0,0,1],]),axis=0)
drawingData['Quaternion'] = G2mth.AV2Q(2*np.pi,np.inner(Bmat,[0,0,1]))
Wt = np.array([255,255,255])
Rd = np.array([255,0,0])
Gr = np.array([0,255,0])
wxGreen = wx.Colour(0,255,0)
Bl = np.array([0,0,255])
Or = np.array([255,128,0])
wxOrange = wx.Colour(255,128,0)
uBox = np.array([[0,0,0],[1,0,0],[1,1,0],[0,1,0],[0,0,1],[1,0,1],[1,1,1],[0,1,1]])
uEdges = np.array([
[uBox[0],uBox[1]],[uBox[0],uBox[3]],[uBox[0],uBox[4]],[uBox[1],uBox[2]],
[uBox[2],uBox[3]],[uBox[1],uBox[5]],[uBox[2],uBox[6]],[uBox[3],uBox[7]],
[uBox[4],uBox[5]],[uBox[5],uBox[6]],[uBox[6],uBox[7]],[uBox[7],uBox[4]]])
uColors = [Rd,Gr,Bl, Wt,Wt,Wt, Wt,Wt,Wt, Wt,Wt,Wt]
def FillHKLRC():
R = np.zeros(len(hklRef))
C = []
HKL = []
RC = []
for i,refl in enumerate(hklRef):
H = refl[:3]
if 'HKLF' in Name:
Fosq,sig,Fcsq = refl[5+Super:8+Super]
if refl[3+Super] < 0:
Fosq,sig,Fcsq = [0,1,0]
else:
Fosq,sig,Fcsq = refl[8+Super],1.0,refl[9+Super]
if Super:
HKL.append(H+SuperVec*refl[3])
else:
HKL.append(H)
if Data['Type'] == 'Unit':
R[i] = 0.1
C.append(Gr)
elif Data['Type'] == 'Fosq':
if Fosq > 0:
R[i] = Fosq
C.append(Gr)
else:
R[i] = -Fosq
C.append(Rd)
elif Data['Type'] == 'Fo':
if Fosq > 0:
R[i] = np.sqrt(Fosq)
C.append(Gr)
else:
R[i] = np.sqrt(-Fosq)
C.append(Rd)
elif Data['Type'] == 'dFsq/sig':
dFsig = (Fosq-Fcsq)/sig
if dFsig > 0:
R[i] = dFsig
C.append(Gr)
else:
R[i] = -dFsig
C.append(Rd)
elif Data['Type'] == 'dFsq':
dF = Fosq-Fcsq
if dF > 0:
R[i] = dF
C.append(Gr)
else:
R[i] = -dF
C.append(Rd)
R /= np.max(R)
R *= Data['Scale']
R = np.where(R<1.e-5,1.e-5,R)
if Data['Iscale']:
R = np.where(R<=1.,R,1.)
C = np.array(C)
C = (C.T*R).T
R = np.ones_like(R)*0.05
return HKL,zip(list(R),C)
def GetTruePosition(xy):
View = glGetIntegerv(GL_VIEWPORT)
Proj = glGetDoublev(GL_PROJECTION_MATRIX)
Model = glGetDoublev(GL_MODELVIEW_MATRIX)
Zmax = 1.
xy = [int(xy[0]),int(View[3]-xy[1])]
for i,ref in enumerate(hklRef):
h,k,l = ref[:3]
X,Y,Z = gluProject(h,k,l,Model,Proj,View)
XY = [int(X),int(Y)]
if np.allclose(xy,XY,atol=10) and Z < Zmax:
Zmax = Z
return [int(h),int(k),int(l)]
def SetTranslation(newxy):
#first get translation vector in screen coords.
oldxy = drawingData['oldxy']
if not len(oldxy): oldxy = list(newxy)
dxy = newxy-oldxy
drawingData['oldxy'] = list(newxy)
V = np.array([-dxy[0],dxy[1],0.])
#then transform to rotated crystal coordinates & apply to view point
Q = drawingData['Quaternion']
V = np.inner(Bmat,G2mth.prodQVQ(G2mth.invQ(Q),V))
Tx,Ty,Tz = drawingData['viewPoint'][0]
Tx += V[0]*0.1
Ty += V[1]*0.1
Tz += V[2]*0.1
drawingData['viewPoint'][0] = Tx,Ty,Tz
def SetRotation(newxy):
'Perform a rotation in x-y space due to a left-mouse drag'
#first get rotation vector in screen coords. & angle increment
oldxy = drawingData['oldxy']
if not len(oldxy): oldxy = list(newxy)
dxy = newxy-oldxy
drawingData['oldxy'] = list(newxy)
V = np.array([dxy[1],dxy[0],0.])
A = 0.25*np.sqrt(dxy[0]**2+dxy[1]**2)
if not A: return # nothing changed, nothing to do
# next transform vector back to xtal coordinates via inverse quaternion
# & make new quaternion
Q = drawingData['Quaternion']
V = G2mth.prodQVQ(G2mth.invQ(Q),np.inner(Bmat,V))
DQ = G2mth.AVdeg2Q(A,V)
Q = G2mth.prodQQ(Q,DQ)
drawingData['Quaternion'] = Q
# finally get new view vector - last row of rotation matrix
VD = np.inner(Bmat,G2mth.Q2Mat(Q)[2])
VD /= np.sqrt(np.sum(VD**2))
drawingData['viewDir'] = VD
def SetRotationZ(newxy):
#first get rotation vector (= view vector) in screen coords. & angle increment
View = glGetIntegerv(GL_VIEWPORT)
cent = [View[2]/2,View[3]/2]
oldxy = drawingData['oldxy']
if not len(oldxy): oldxy = list(newxy)
dxy = newxy-oldxy
drawingData['oldxy'] = list(newxy)
V = drawingData['viewDir']
A = [0,0]
A[0] = dxy[1]*.25
A[1] = dxy[0]*.25
if newxy[0] > cent[0]:
A[0] *= -1
if newxy[1] < cent[1]:
A[1] *= -1
# next transform vector back to xtal coordinates & make new quaternion
Q = drawingData['Quaternion']
V = np.inner(Amat,V)
Qx = G2mth.AVdeg2Q(A[0],V)
Qy = G2mth.AVdeg2Q(A[1],V)
Q = G2mth.prodQQ(Q,Qx)
Q = G2mth.prodQQ(Q,Qy)
drawingData['Quaternion'] = Q
def OnMouseDown(event):
xy = event.GetPosition()
drawingData['oldxy'] = list(xy)
def OnMouseMove(event):
if event.ShiftDown(): #don't want any inadvertant moves when picking
return
newxy = event.GetPosition()
if event.Dragging():
if event.LeftIsDown():
SetRotation(newxy)
Q = drawingData['Quaternion']
elif event.RightIsDown():
SetTranslation(newxy)
Tx,Ty,Tz = drawingData['viewPoint'][0]
elif event.MiddleIsDown():
SetRotationZ(newxy)
Q = drawingData['Quaternion']
Draw('move')
else:
hkl = GetTruePosition(newxy)
if hkl:
h,k,l = hkl
Page.canvas.SetToolTipString('%d %d %d'%(h,k,l))
G2frame.G2plotNB.status.SetStatusText('hkl = %d %d %d'%(h,k,l),1)
def OnMouseWheel(event):
if event.ShiftDown():
return
drawingData['cameraPos'] += event.GetWheelRotation()/120.
drawingData['cameraPos'] = max(0.1,min(20.00,drawingData['cameraPos']))
Draw('wheel')
def SetBackground():
R,G,B,A = Page.camera['backColor']
glClearColor(R,G,B,A)
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
def SetLights():
glEnable(GL_DEPTH_TEST)
glShadeModel(GL_SMOOTH)
glEnable(GL_LIGHTING)
glEnable(GL_LIGHT0)
glLightModeli(GL_LIGHT_MODEL_TWO_SIDE,0)
glLightfv(GL_LIGHT0,GL_AMBIENT,[1,1,1,.8])
glLightfv(GL_LIGHT0,GL_DIFFUSE,[1,1,1,1])
def RenderBox(x,y,z):
xyz = np.array([x,y,z])
glEnable(GL_COLOR_MATERIAL)
glLineWidth(1)
glPushMatrix()
glTranslate(x,y,z)
glColor4ubv([0,0,0,0])
glBegin(GL_LINES)
for line,color in zip(uEdges,uColors):
glColor3ubv(color)
glVertex3fv(line[0])
glVertex3fv(line[1])
glEnd()
glPopMatrix()
glColor4ubv([0,0,0,0])
glDisable(GL_COLOR_MATERIAL)
def RenderUnitVectors(x,y,z):
xyz = np.array([x,y,z])
glEnable(GL_COLOR_MATERIAL)
glLineWidth(1)
glPushMatrix()
glTranslate(x,y,z)
glBegin(GL_LINES)
for line,color in zip(uEdges,uColors)[:3]:
glColor3ubv(color)
glVertex3fv(-line[1])
glVertex3fv(line[1])
glEnd()
glPopMatrix()
glColor4ubv([0,0,0,0])
glDisable(GL_COLOR_MATERIAL)
def RenderDots(XYZ,RC):
glEnable(GL_COLOR_MATERIAL)
XYZ = np.array(XYZ)
glPushMatrix()
for xyz,rc in zip(XYZ,RC):
x,y,z = xyz
r,c = rc
glMaterialfv(GL_FRONT_AND_BACK,GL_EMISSION,c)
glPointSize(r*50)
glBegin(GL_POINTS)
glVertex3fv(xyz)
glEnd()
glPopMatrix()
glColor4ubv([0,0,0,0])
glDisable(GL_COLOR_MATERIAL)
def Draw(caller=''):
#useful debug?
# if caller:
# print caller
# end of useful debug
G2frame.G2plotNB.status.SetStatusText('Plot type = %s for %s'%(Data['Type'],Name),1)
VS = np.array(Page.canvas.GetSize())
aspect = float(VS[0])/float(VS[1])
cPos = drawingData['cameraPos']
Zclip = drawingData['Zclip']*cPos/20.
Q = drawingData['Quaternion']
Tx,Ty,Tz = drawingData['viewPoint'][0]
G,g = G2lat.cell2Gmat(cell)
GS = G
GS[0][1] = GS[1][0] = math.sqrt(GS[0][0]*GS[1][1])
GS[0][2] = GS[2][0] = math.sqrt(GS[0][0]*GS[2][2])
GS[1][2] = GS[2][1] = math.sqrt(GS[1][1]*GS[2][2])
HKL,RC = FillHKLRC()
SetBackground()
glInitNames()
glPushName(0)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
glViewport(0,0,VS[0],VS[1])
gluPerspective(20.,aspect,cPos-Zclip,cPos+Zclip)
gluLookAt(0,0,cPos,0,0,0,0,1,0)
SetLights()
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
matRot = G2mth.Q2Mat(Q)
matRot = np.concatenate((np.concatenate((matRot,[[0],[0],[0]]),axis=1),[[0,0,0,1],]),axis=0)
glMultMatrixf(matRot.T)
glMultMatrixf(B4mat.T)
glTranslate(-Tx,-Ty,-Tz)
x,y,z = drawingData['viewPoint'][0]
if ifBox:
RenderBox(x,y,z)
else:
RenderUnitVectors(x,y,z)
RenderUnitVectors(0,0,0)
RenderDots(HKL,RC)
time0 = time.time()
if Page.context: Page.canvas.SetCurrent(Page.context) # wx 2.9 fix
Page.canvas.SwapBuffers()
# PlotStructure execution starts here (N.B. initialization above)
try:
plotNum = G2frame.G2plotNB.plotList.index('3D Structure Factors')
Page = G2frame.G2plotNB.nb.GetPage(plotNum)
except ValueError:
Plot = G2frame.G2plotNB.addOgl('3D Structure Factors')
plotNum = G2frame.G2plotNB.plotList.index('3D Structure Factors')
Page = G2frame.G2plotNB.nb.GetPage(plotNum)
Page.views = False
view = False
altDown = False
Font = Page.GetFont()
Page.SetFocus()
Page.Choice = None
choice = [' save as/key:','jpeg','tiff','bmp','c: recenter to default','b: toggle box ','+: increase scale',
'-: decrease scale','f: Fobs','s: Fobs**2','u: unit','d: Fo-Fc','w: DF/sig','i: toggle intensity scaling']
cb = wx.ComboBox(G2frame.G2plotNB.status,style=wx.CB_DROPDOWN|wx.CB_READONLY,choices=choice)
cb.Bind(wx.EVT_COMBOBOX, OnKeyBox)
cb.SetValue(' save as/key:')
Page.canvas.Bind(wx.EVT_MOUSEWHEEL, OnMouseWheel)
Page.canvas.Bind(wx.EVT_LEFT_DOWN, OnMouseDown)
Page.canvas.Bind(wx.EVT_RIGHT_DOWN, OnMouseDown)
Page.canvas.Bind(wx.EVT_MIDDLE_DOWN, OnMouseDown)
Page.canvas.Bind(wx.EVT_KEY_UP, OnKey)
Page.canvas.Bind(wx.EVT_MOTION, OnMouseMove)
# Page.canvas.Bind(wx.EVT_SIZE, OnSize)
Page.camera['position'] = drawingData['cameraPos']
Page.camera['viewPoint'] = np.inner(Amat,drawingData['viewPoint'][0])
Page.camera['backColor'] = np.array(list(drawingData['backColor'])+[0,])/255.
Page.controls = Data
try:
Page.canvas.SetCurrent()
except:
pass
Draw('main')
# if firstCall: Draw('main') # draw twice the first time that graphics are displayed
################################################################################
##### PlotPatterns
################################################################################
def PlotPatterns(G2frame,newPlot=False,plotType='PWDR'):
'''Powder pattern plotting package - displays single or multiple powder patterns as intensity vs
2-theta, q or TOF. Can display multiple patterns as "waterfall plots" or contour plots. Log I
plotting available.
'''
global HKL
global exclLines
global DifLine
global Ymax
plottype = plotType
#patch
data = G2frame.PatternTree.GetItemPyData(G2frame.PatternId)
if 'Offset' not in data[0] and plotType in ['PWDR','SASD']: #plot offset data
data[0].update({'Offset':[0.0,0.0],'delOffset':0.02,'refOffset':-1.0,
'refDelt':0.01,})
G2frame.PatternTree.SetItemPyData(G2frame.PickId,data)
#end patch
def OnPlotKeyPress(event):
try: #one way to check if key stroke will work on plot
Parms,Parms2 = G2frame.PatternTree.GetItemPyData(G2gd.GetPatternTreeItemId(G2frame,G2frame.PatternId, 'Instrument Parameters'))
except TypeError:
G2frame.G2plotNB.status.SetStatusText('Select '+plottype+' pattern first',1)
return
newPlot = False
if event.key == 'w':
G2frame.Weight = not G2frame.Weight
if not G2frame.Weight and 'PWDR' in plottype:
G2frame.SinglePlot = True
newPlot = True
elif event.key == 'e' and 'SASD' in plottype:
G2frame.ErrorBars = not G2frame.ErrorBars
elif event.key == 'b':
G2frame.SubBack = not G2frame.SubBack
if not G2frame.SubBack:
G2frame.SinglePlot = True
elif event.key == 'n':