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 pathGSASIIplot.py
12162 lines (11585 loc) · 529 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 -*-
########### SVN repository information ###################
# $Date: 2024-03-17 12:50:24 -0500 (Sun, 17 Mar 2024) $
# $Author: toby $
# $Revision: 5767 $
# $URL: https://subversion.xray.aps.anl.gov/pyGSAS/trunk/GSASIIplot.py $
# $Id: GSASIIplot.py 5767 2024-03-17 17:50:24Z toby $
########### SVN repository information ###################
'''
Classes and routines defined in :mod:`GSASIIplot` follow.
'''
# Note that documentation for GSASIIplot.py has been moved
# to file docs/source/GSASIIplot.rst
from __future__ import division, print_function
import platform
import time
import copy
import math
import sys
import os.path
import numpy as np
import numpy.ma as ma
import numpy.linalg as nl
import GSASIIpath
# Don't depend on wx/matplotlib/scipy for scriptable; or for Sphinx docs
try:
import wx
import wx.aui
import wx.glcanvas
except (ImportError, ValueError):
print('GSASIIplot: wx not imported')
try:
import matplotlib as mpl
if not mpl.get_backend(): #could be assigned by spyder debugger
mpl.use('wxAgg')
import matplotlib.figure as mplfig
import matplotlib.collections as mplC
# import mpl_toolkits.mplot3d.axes3d as mp3d
from scipy.ndimage import map_coordinates
except (ImportError, ValueError) as err:
print('GSASIIplot: matplotlib not imported')
if GSASIIpath.GetConfigValue('debug'): print('error msg:',err)
Clip_on = GSASIIpath.GetConfigValue('Clip_on',True)
GSASIIpath.SetVersionNumber("$Revision: 5767 $")
import GSASIIdataGUI 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 GSASIIctrlGUI as G2G
import GSASIIobj as G2obj
import GSASIIElem as G2elem
try:
import pytexture as ptx
ptx.pyqlmninit()
except ImportError:
print('binary load error: pytexture not found')
#import scipy.special as spsp
import OpenGL.GL as GL
import OpenGL.GLU as GLU
import gltext
import matplotlib.colors as mpcls
try:
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as Canvas
except ImportError:
from matplotlib.backends.backend_wx import FigureCanvas as Canvas
try:
from matplotlib.backends.backend_wxagg import NavigationToolbar2WxAgg as Toolbar
except ImportError:
from matplotlib.backends.backend_wxagg import Toolbar as Toolbar # name changes in wx4.0.1
try:
from matplotlib.backends.backend_agg import FigureCanvasAgg as hcCanvas
except ImportError:
from matplotlib.backends.backend_agg import FigureCanvas as hcCanvas # standard name
except RuntimeError: # happens during doc builds
pass
# 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
try: # fails on doc build
sq8ln2 = np.sqrt(8.0*np.log(2.0))
except TypeError:
pass
if '2' not in platform.python_version_tuple()[0]:
unichr = chr
GkDelta = unichr(0x0394)
Gkrho = unichr(0x03C1)
super2 = unichr(0xb2)
Angstr = unichr(0x00c5)
Pwrm1 = unichr(0x207b)+unichr(0x0b9)
# misc global vars
nxs = np.newaxis
plotDebug = False
timeDebug = GSASIIpath.GetConfigValue('Show_timing',False)
obsInCaption = True # include the observed, calc,... items in the plot caption (PlotPatterns)
#matplotlib 2.0.x dumbed down Paired to 16 colors -
# this restores the pre 2.0 Paired color map found in matplotlib._cm.py
try:
_Old_Paired_data = {'blue': [(0.0, 0.89019608497619629,
0.89019608497619629), (0.090909090909090912, 0.70588237047195435,
0.70588237047195435), (0.18181818181818182, 0.54117649793624878,
0.54117649793624878), (0.27272727272727271, 0.17254902422428131,
0.17254902422428131), (0.36363636363636365, 0.60000002384185791,
0.60000002384185791), (0.45454545454545453, 0.10980392247438431,
0.10980392247438431), (0.54545454545454541, 0.43529412150382996,
0.43529412150382996), (0.63636363636363635, 0.0, 0.0),
(0.72727272727272729, 0.83921569585800171, 0.83921569585800171),
(0.81818181818181823, 0.60392159223556519, 0.60392159223556519),
(0.90909090909090906, 0.60000002384185791, 0.60000002384185791), (1.0,
0.15686275064945221, 0.15686275064945221)],
'green': [(0.0, 0.80784314870834351, 0.80784314870834351),
(0.090909090909090912, 0.47058823704719543, 0.47058823704719543),
(0.18181818181818182, 0.87450981140136719, 0.87450981140136719),
(0.27272727272727271, 0.62745100259780884, 0.62745100259780884),
(0.36363636363636365, 0.60392159223556519, 0.60392159223556519),
(0.45454545454545453, 0.10196078568696976, 0.10196078568696976),
(0.54545454545454541, 0.74901962280273438, 0.74901962280273438),
(0.63636363636363635, 0.49803921580314636, 0.49803921580314636),
(0.72727272727272729, 0.69803923368453979, 0.69803923368453979),
(0.81818181818181823, 0.23921568691730499, 0.23921568691730499),
(0.90909090909090906, 1.0, 1.0), (1.0, 0.3490196168422699,
0.3490196168422699)],
'red': [(0.0, 0.65098041296005249, 0.65098041296005249),
(0.090909090909090912, 0.12156862765550613, 0.12156862765550613),
(0.18181818181818182, 0.69803923368453979, 0.69803923368453979),
(0.27272727272727271, 0.20000000298023224, 0.20000000298023224),
(0.36363636363636365, 0.9843137264251709, 0.9843137264251709),
(0.45454545454545453, 0.89019608497619629, 0.89019608497619629),
(0.54545454545454541, 0.99215686321258545, 0.99215686321258545),
(0.63636363636363635, 1.0, 1.0), (0.72727272727272729,
0.7921568751335144, 0.7921568751335144), (0.81818181818181823,
0.41568627953529358, 0.41568627953529358), (0.90909090909090906,
1.0, 1.0), (1.0, 0.69411766529083252, 0.69411766529083252)]}
'''This can be done on request for other colors - any new names must be explicitly added to color list
obtained from mpl.cm.datad.keys() (currently 10 places in GSAS-II code)
'''
oldpaired = mpl.colors.LinearSegmentedColormap('GSPaired',_Old_Paired_data,N=256)
try:
mpl.colormaps.register(oldpaired,name='GSPaired')
except:
mpl.cm.register_cmap(cmap=oldpaired,name='GSPaired') #deprecated
blue = [tuple(1.-np.array(item)) for item in _Old_Paired_data['blue']]
blue.reverse()
green = [tuple(1.-np.array(item)) for item in _Old_Paired_data['green']]
green.reverse()
red = [tuple(1.-np.array(item)) for item in _Old_Paired_data['red']]
red.reverse()
Old_Paired_data_r = {'blue':blue,'green':green,'red':red}
oldpaired_r = mpl.colors.LinearSegmentedColormap('GSPaired_r',Old_Paired_data_r,N=256)
try:
mpl.colormaps.register(oldpaired_r,name='GSPaired_r')
except:
mpl.cm.register_cmap(cmap=oldpaired_r,name='GSPaired_r') #deprecated
except Exception as err:
if GSASIIpath.GetConfigValue('debug'): print('\nMPL CM setup error: {}\n'.format(err))
def GetColorMap(color):
try:
return mpl.colormaps[color]
except:
return mpl.cm.get_cmap(color)
# options for publication-quality Rietveld plots
plotOpt = {}
plotOpt['labelSize'] = '11'
plotOpt['dpi'] = 600
plotOpt['width'] = 8.
plotOpt['height'] = 6.
plotOpt['Show'] = {}
plotOpt['legend'] = {}
plotOpt['colors'] = {}
plotOpt['format'] = None
plotOpt['initNeeded'] = True
plotOpt['lineList'] = ('obs','calc','bkg','zero','diff')
plotOpt['phaseList'] = []
plotOpt['phaseLabels'] = {}
plotOpt['fmtChoices'] = {}
plotOpt['lineWid'] = '1'
plotOpt['saveCSV'] = False
plotOpt['CSVfile'] = None
def Write2csv(fil,dataItems,header=False):
'''Write a line to a CSV file
:param object fil: file object
:param list dataItems: items to write as row in file
:param bool header: True if all items should be written with quotes (default is False)
'''
line = ''
for item in dataItems:
if line: line += ','
item = str(item)
if header or ' ' in item:
line += '"'+item+'"'
else:
line += item
fil.write(line+'\n')
class _tabPlotWin(wx.Panel):
'Creates a basic tabbed plot window for GSAS-II graphics'
def __init__(self,parent,id=-1,dpi=None,**kwargs):
self.replotFunction = None
self.replotArgs = []
self.replotKwArgs = {}
self.plotInvalid = False # valid
self.plotRequiresRedraw = True # delete plot if not updated
wx.Panel.__init__(self,parent,id=id,**kwargs)
class G2PlotMpl(_tabPlotWin):
'Creates a Matplotlib 2-D plot in the GSAS-II graphics window'
def __init__(self,parent,id=-1,dpi=None,publish=None,**kwargs):
_tabPlotWin.__init__(self,parent,id=id,**kwargs)
mpl.rcParams['legend.fontsize'] = 10
mpl.rcParams['axes.grid'] = False
self.figure = mplfig.Figure(dpi=dpi,figsize=(5,6))
self.canvas = Canvas(self,-1,self.figure)
self.toolbar = GSASIItoolbar(self.canvas,publish=publish)
self.toolbar.Realize()
self.plotStyle = {'qPlot':False,'dPlot':False,'sqrtPlot':False,'sqPlot':False,
'logPlot':False,'exclude':False,'partials':True,'chanPlot':False}
sizer=wx.BoxSizer(wx.VERTICAL)
sizer.Add(self.canvas,1,wx.EXPAND)
sizer.Add(self.toolbar,0,)
self.SetSizer(sizer)
def SetToolTipString(self,text):
if 'phoenix' in wx.version():
return self.canvas.SetToolTip(text)
else:
return self.canvas.SetToolTipString(text)
def ToolBarDraw(self):
mplv = eval(mpl.__version__.replace('.',','))
if mplv[0] >= 3 and mplv[1] >= 3:
self.toolbar.canvas.draw_idle()
else:
self.toolbar.draw()
class G2PlotOgl(_tabPlotWin):
'Creates an OpenGL plot in the GSAS-II graphics window'
def __init__(self,parent,id=-1,dpi=None,**kwargs):
self.figure = _tabPlotWin.__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,wx.glcanvas.WX_GL_DEPTH_SIZE,24)
self.canvas = wx.glcanvas.GLCanvas(self,-1,attribList=attribs,**kwargs)
GL.glEnable(GL.GL_NORMALIZE)
# create GL context
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)
def SetToolTipString(self,text):
if 'phoenix' in wx.version():
self.canvas.SetToolTip(wx.ToolTip(text))
else:
self.canvas.SetToolTipString(text)
class G2Plot3D(_tabPlotWin):
'Creates a 3D Matplotlib plot in the GSAS-II graphics window'
def __init__(self,parent,id=-1,dpi=None,**kwargs):
_tabPlotWin.__init__(self,parent,id=id,**kwargs)
self.figure = mplfig.Figure(dpi=dpi,figsize=(6,6))
self.canvas = Canvas(self,-1,self.figure)
self.toolbar = GSASIItoolbar(self.canvas,Arrows=False)
self.toolbar.Realize()
sizer=wx.BoxSizer(wx.VERTICAL)
sizer.Add(self.canvas,1,wx.EXPAND)
sizer.Add(self.toolbar,)
self.SetSizer(sizer)
def SetToolTipString(self,text):
if 'phoenix' in wx.version():
self.canvas.SetToolTip(wx.ToolTip(text))
else:
self.canvas.SetToolTipString(text)
def ToolBarDraw(self):
mplv = eval(mpl.__version__.replace('.',','))
if mplv[0] >= 3 and mplv[1] >= 3:
self.toolbar.canvas.draw_idle()
else:
self.toolbar.draw()
# mplv = eval(mpl.__version__.replace('.',','))
# if mplv[0] >= 3 and mplv[1] >= 3:
# self.toolbar.draw_idle()
# else:
# self.toolbar.draw()
class G2PlotNoteBook(wx.Panel):
'create a tabbed panel to hold a GSAS-II graphics window'
def __init__(self,parent,id=-1,G2frame=None):
wx.Panel.__init__(self,parent,id=id)
#so one can't delete a plot page from tab!!
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.SetBackgroundColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOW)) # unneeded
# self.status.SetForegroundColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_BTNTEXT)) # ignored, alas
self.status.SetFieldsCount(2)
self.status.firstLen = 150
self.status.SetStatusWidths([self.status.firstLen,-1])
self.Bind(wx.aui.EVT_AUINOTEBOOK_PAGE_CHANGED, self.OnPageChanged)
self.nb.Bind(wx.EVT_KEY_UP,self.OnNotebookKey)
self.G2frame = G2frame
self.MPLwarn = False
self.plotList = [] # contains the tab label for each plot
self.panelList = [] # contains the panel object for each plot
#self.skipPageChange = False # set to True when no plot update is needed
self.allowZoomReset = True # this indicates plot should be updated not initialized
# (BHT: should this be in tabbed panel rather than here?)
self.lastRaisedPlotTab = None
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: # occurs with no plot tabs
event.Skip()
return
try:
Page.canvas.SetFocus()
wx.PostEvent(Page.canvas,event)
except AttributeError:
pass
def SetNoDelete(self,name):
'''Indicate that a plot does not need to be redrawn
'''
if name not in self.plotList:
print('Error, in SetNoDelete plot not found: '+name)
return
page = self.panelList[self.plotList.index(name)]
page.plotRequiresRedraw = False # plot should not be deleted even if not redrawn
def RegisterRedrawRoutine(self,name,routine=None,args=(),kwargs={}):
'''Save information to determine how to redraw a plot
:param str name: label on tab of plot
:param Object routine: a function to be called
:param args: a list of positional parameters for the function
:param kwargs: a dict with keyword parameters for the function
'''
if name not in self.plotList:
print('Error, plot not found: '+name)
return
page = self.panelList[self.plotList.index(name)]
page.replotFunction = routine
page.replotArgs = args
page.replotKWargs = kwargs
def GetTabIndex(self,label):
'''Look up a tab label and return the index in the notebook (this appears to be
independent to the order it is dragged to -- at least in Windows) as well as
the associated wx.Panel
An exception is raised if the label is not found
'''
for i in range(self.nb.GetPageCount()):
if label == self.nb.GetPageText(i):
return i,self.nb.GetPage(i)
else:
raise ValueError('Plot not found')
# def RaiseLastPage(self,lastRaisedPlotTab,treeItemPlot):
# '''Raises either the Last tab clicked on or what is drawn by the selected tree item
# This is called after a refinement is completed by :meth:`GSASIIdataGUI.GSASII.ResetPlots`
# '''
# plotNum = None
# if lastRaisedPlotTab in self.plotList:
# plotNum = self.plotList.index(lastRaisedPlotTab)
# elif treeItemPlot in self.plotList:
# plotNum = self.plotList.index(treeItemPlot)
# if plotNum is not None:
# wx.CallAfter(self.SetSelectionNoRefresh,plotNum)
def FindPlotTab(self,label,Type,newImage=True,publish=None):
'''Open a plot tab for initial plotting, or raise the tab if it already exists
Set a flag (Page.plotInvalid) that it has been redrawn
Record the name of the this plot in self.lastRaisedPlotTab
:param str label: title of plot
:param str Type: determines the type of plot that will be opened.
'mpl' for 2D graphs in matplotlib
'ogl' for openGL
'3d' for 3D plotting in matplotlib
:param bool newImage: forces creation of a new graph for matplotlib
plots only (defaults as True)
:param function publish: reference to routine used to create a
publication version of the current mpl plot (default is None,
which prevents use of this).
:returns: new,plotNum,Page,Plot,limits where
* new: will be True if the tab was just created
* plotNum: is the tab number
* Page: is the subclassed wx.Panel (:class:`G2PlotMpl`, etc.) where
the plot appears
* Plot: the mpl.Axes object for the graphic (mpl) or the figure for
openGL.
* limits: for mpl plots, when a plot already exists, this will be a tuple
with plot scaling. None otherwise.
'''
limits = None
Plot = None
try:
new = False
plotNum,Page = self.GetTabIndex(label)
if Type == 'mpl' or Type == '3d':
Axes = Page.figure.get_axes()
Plot = Page.figure.gca() #get previous plot
limits = [Plot.get_xlim(),Plot.get_ylim()] # save previous limits
if len(Axes)>1 and Plot.get_aspect() == 'auto': # aspect will be equal for image plotting
if Axes[1].get_aspect() != 'auto': #not colorbars!
limits[1] = Axes[0].get_ylim()
else:
limits[1] = Axes[1].get_ylim()
if newImage:
Page.figure.clf()
Plot = Page.figure.gca() #get a fresh plot after clf()
self.SetSelectionNoRefresh(plotNum) # raises plot tab
except (ValueError,AttributeError):
new = True
if Type == 'mpl':
Plot = self.addMpl(label,publish=publish).gca()
elif Type == 'ogl':
Plot = self.addOgl(label)
elif Type == '3d':
Plot = self.add3D(label).add_subplot(111, projection='3d')
# Plot = mp3d.Axes3D(self.add3D(label)) #doesn't work in mpl 3.6.2 (+)
plotNum = self.plotList.index(label)
Page = self.nb.GetPage(plotNum)
self.SetSelectionNoRefresh(plotNum) # raises plot tab
try:
Plot.format_coord = lambda x,y: "" # remove coord display from toolbar
except:
pass
Page.plotInvalid = False # plot has just been drawn
Page.excludeMode = False
self.lastRaisedPlotTab = label
self.RaisePageNoRefresh(Page)
# Save the help name from the DataItem that has created the plot in Tabbed page object
# so we can use it in self.OnHelp().
# Are there any cases where plot tabs are created that are not tied to Data Tree entries?
# One example is GSASII.SumDialog, where a test plot is created. Are there others?
try:
Page.helpKey = self.G2frame.dataWindow.helpKey
except AttributeError:
Page.helpKey = 'Data tree'
return new,plotNum,Page,Plot,limits
def _addPage(self,name,page):
'''Add the newly created page to the notebook and associated lists.
:param name: the label placed on the tab, which should be unique
:param page: the wx.Frame for the matplotlib, openGL, etc. window
'''
#self.skipPageChange = True
if name in self.plotList:
print('Warning: duplicate plot name! Name='+name)
self.nb.AddPage(page,name)
self.plotList.append(name) # used to lookup plot in self.panelList
# Note that order in lists make not agree with actual tab order; use self.nb.GetPageText(i)
# where (self=G2plotNB) for latter
self.panelList.append(page) # panel object for plot
self.lastRaisedPlotTab = name
#page.plotInvalid = False # plot has just been drawn
#page.plotRequiresRedraw = True # set to False if plot should be retained even if not refreshed
#page.replotFunction = None # used to specify a routine to redraw the routine
#page.replotArgs = []
#page.replotKWargs = {}
#self.skipPageChange = False
def addMpl(self,name="",publish=None):
'Add a tabbed page with a matplotlib plot'
page = G2PlotMpl(self.nb,publish=publish)
self._addPage(name,page)
return page.figure
def add3D(self,name=""):
'Add a tabbed page with a 3D plot'
page = G2Plot3D(self.nb)
self._addPage(name,page)
mplv = eval(mpl.__version__.replace('.',','))
if mplv[0] == 3:
if mplv == [3,0,3] or mplv[1] >= 3:
pass
elif not self.MPLwarn: # patch for bad MPL 3D
self.MPLwarn = True
G2G.G2MessageBox(self,'3D plots with Matplotlib 3.1.x and 3.2.x are distorted, use MPL 3.0.3 or 3.3. You have '+mpl.__version__,
'Avoid Matplotlib 3.1 & 3.2')
return page.figure
def addOgl(self,name=""):
'Add a tabbed page with an openGL plot'
page = G2PlotOgl(self.nb)
self._addPage(name,page)
self.RaisePageNoRefresh(page) # need to give window focus before GL use
return page.figure
def Delete(self,name):
'delete a tabbed page'
try:
item = self.plotList.index(name)
del self.plotList[item]
del self.panelList[item]
self.nb.DeletePage(item)
except ValueError: #no plot of this name - do nothing
return
def clear(self):
'clear all pages from plot window'
for i in range(self.nb.GetPageCount()-1,-1,-1):
self.nb.DeletePage(i)
self.plotList = []
self.panelList = []
self.status.DestroyChildren() #get rid of special stuff on status bar
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 RaisePageNoRefresh(self,Page):
'Raises a plot tab without triggering a refresh via OnPageChanged'
if plotDebug: print ('Raise'+str(self).split('0x')[1])
#self.skipPageChange = True
Page.SetFocus()
#self.skipPageChange = False
def SetSelectionNoRefresh(self,plotNum):
'Raises a plot tab without triggering a refresh via OnPageChanged'
if plotDebug: print ('Select'+str(self).split('0x')[1])
#self.skipPageChange = True
self.nb.SetSelection(plotNum) # raises plot tab
Page = self.G2frame.G2plotNB.nb.GetPage(plotNum)
Page.SetFocus()
#self.skipPageChange = False
def OnPageChanged(self,event):
'''respond to someone pressing a tab on the plot window.
Called when a plot tab is clicked. on some platforms (Mac for sure) this
is also called when a plot is created or selected with .SetSelection() or
.SetFocus().
(removed) The self.skipPageChange is used variable is set to suppress repeated replotting.
'''
tabLabel = event.GetEventObject().GetPageText(event.GetSelection())
self.lastRaisedPlotTab = tabLabel
if plotDebug:
print ('PageChanged, self='+str(self).split('0x')[1]+tabLabel)
print ('event type=',event.GetEventType())
self.status.DestroyChildren() #get rid of special stuff on status bar
self.status.SetStatusText('') # clear old status message
self.status.SetStatusWidths([self.status.firstLen,-1])
def SetHelpButton(self,help):
'''Adds a Help button to the status bar on plots.
TODO: This has a problem with PlotPatterns where creation of the
HelpButton causes the notebook tabs to be duplicated. A manual
resize fixes that, but the SendSizeEvent has not worked.
'''
hlp = G2G.HelpButton(self.status,helpIndex=help)
rect = self.status.GetFieldRect(1)
rect.x += rect.width - 20
rect.width = 20
rect.y += 1
hlp.SetRect(rect)
#wx.CallLater(100,self.TopLevelParent.SendSizeEvent)
def InvokeTreeItem(self,pid):
'''This is called to select an item from the tree using the self.allowZoomReset
flag to prevent a reset to the zoom of the plot (where implemented)
'''
self.allowZoomReset = False
if pid: self.G2frame.GPXtree.SelectItem(pid)
self.allowZoomReset = True
if plotDebug: print ('invoke'+str(self).split('0x')[1]+str(pid))
class GSASIItoolbar(Toolbar):
'Override the matplotlib toolbar so we can add more icons'
def __init__(self,plotCanvas,publish=None,Arrows=True):
'''Adds additional icons to toolbar'''
self.arrows = {}
# try to remove a button from the bar
POS_CONFIG_SPLTS_BTN = 6 # position of button to remove
self.plotCanvas = plotCanvas
Toolbar.__init__(self,plotCanvas)
self.updateActions = None # defines a call to be made as part of plot updates
self.DeleteToolByPos(POS_CONFIG_SPLTS_BTN)
self.parent = self.GetParent()
if wx.__version__.startswith('4.2'):
self.SetToolBitmapSize(wx.Size(28, 20)) # seems needed in wx4.2, packs icons closer
self.AddToolBarTool('Key press','Select key press','key.ico',self.OnKey)
self.AddToolBarTool('Help on','Show help on this plot','help.ico',self.OnHelp)
# add arrow keys to control zooming
if Arrows:
for direc in ('left','right','up','down', 'Expand X','Shrink X','Expand Y','Shrink Y'):
if ' ' in direc:
sprfx = ''
prfx = 'Zoom: '
else:
sprfx = 'Shift '
prfx = 'Shift plot '
fil = ''.join([i[0].lower() for i in direc.split()]+['arrow.ico'])
self.arrows[direc] = self.AddToolBarTool(sprfx+direc,prfx+direc,fil,self.OnArrow)
if publish:
self.AddToolBarTool('Publish plot','Create publishable version of plot','publish.ico',publish)
self.Realize()
def set_message(self,s):
''' this removes spurious text messages from the tool bar
'''
pass
def AddToolBarTool(self,label,title,filename,callback):
bmpFilename = GSASIIpath.getIconFile(filename)
if bmpFilename is None:
print(f'Could not find bitmap file {filename!r}; skipping')
bmp = wx.EmptyBitmap(32,32)
else:
bmp = wx.Bitmap(bmpFilename)
# bmp = wx.Bitmap(bmpFilename,type=wx.BITMAP_TYPE_ANY) # probably better
if 'phoenix' in wx.version():
button = self.AddTool(wx.ID_ANY, label, bmp, title)
else:
button = self.AddSimpleTool(wx.ID_ANY, bmp, label, title)
wx.EVT_TOOL.Bind(self, button.GetId(), button.GetId(), callback)
return button.GetId()
def _update_view(self):
'''Overrides the post-buttonbar update action to invoke a redraw; needed for plot magnification
'''
if self.updateActions:
wx.CallAfter(*self.updateActions)
Toolbar._update_view(self)
def AnyActive(self):
for Itool in range(self.GetToolsCount()):
if self.GetToolState(self.GetToolByPos(Itool).GetId()):
return True
return False
def GetActive(self):
for Itool in range(self.GetToolsCount()):
tool = self.GetToolByPos(Itool)
if self.GetToolState(tool.GetId()):
return tool.GetLabel()
return None
def OnArrow(self,event):
'reposition limits to scan or zoom by button press'
axlist = self.plotCanvas.figure.get_axes()
if len(axlist) == 1:
ax = axlist[0]
ax1 = None
elif len(axlist) == 3: # used in "w" mode in PlotPatterns
_,ax,ax1 = axlist
xmin,xmax,ymin1,ymax1 = ax1.axis()
else:
return
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!
if GSASIIpath.GetConfigValue('debug'):
GSASIIpath.IPyBreak()
self.parent.toolbar.push_current() #NB: self.parent.toolbar = self
ax.axis((xmin,xmax,ymin,ymax))
if ax1:
ax1.axis((xmin,xmax,ymin1,ymax1))
#print xmin,xmax,ymin,ymax
self.plotCanvas.figure.canvas.draw()
self.parent.ToolBarDraw()
# self.parent.toolbar.push_current()
if self.updateActions:
wx.CallAfter(*self.updateActions)
def OnHelp(self,event):
'Respond to press of help button on plot toolbar'
bookmark = self.Parent.helpKey # get help category used to create plot
#if GSASIIpath.GetConfigValue('debug'): print 'plot help: key=',bookmark
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:
# remove the 1st entry in list if key press
if 'key press' in parent.Choice[0].lower():
choices = list(parent.Choice[1:])
else:
choices = list(parent.Choice)
dlg = wx.SingleChoiceDialog(parent,'Select a keyboard command',
'Key press list',choices)
if dlg.ShowModal() == wx.ID_OK:
sel = dlg.GetSelection()
dlg.Destroy()
event.key = choices[sel][0]
if event.key != ' ':
parent.keyPress(event)
else:
G2G.G2MessageBox(self.TopLevelParent,
'Use this command only from the keyboard',
'Key not in menu')
return
else:
dlg.Destroy()
def get_zoompan(self):
"""Return "Zoom" if Zoom is active, "Pan" if Pan is active,
or None if neither
"""
return self.GetActive()
# this routine is not currently in use, and needs to be updated
# to match internals of lib/python3.x/site-packages/matplotlib/backend_bases.py
# but there are probably good places in the graphics to disable the
# zoom/pan and release the mouse bind
#
# def reset_zoompan(self):
# '''Turns off Zoom or Pan mode, if on. Ignored if neither is set.
# call as Page.toolbar.reset_zoompan()
# '''
# if self._active == 'ZOOM':
# self._active = None
# if self._idPress is not None:
# self._idPress = self.canvas.mpl_disconnect(self._idPress)
# self.mode = ''
# if self._idRelease is not None:
# self._idRelease = self.canvas.mpl_disconnect(self._idRelease)
# self.mode = ''
# self.canvas.widgetlock.release(self)
# if hasattr(self,'_NTB2_ZOOM'):
# self.ToggleTool(self._NTB2_ZOOM, False)
# elif hasattr(self,'wx_ids'):
# self.ToggleTool(self.wx_ids['Zoom'], False)
# else:
# print('Unable to reset Zoom button, please report this with matplotlib version')
# elif self._active == 'PAN':
# self._active = None
# if self._idPress is not None:
# self._idPress = self.canvas.mpl_disconnect(self._idPress)
# self.mode = ''
# if self._idRelease is not None:
# self._idRelease = self.canvas.mpl_disconnect(self._idRelease)
# self.mode = ''
# self.canvas.widgetlock.release(self)
# if hasattr(self,'_NTB2_PAN'):
# self.ToggleTool(self._NTB2_PAN, False)
# elif hasattr(self,'wx_ids'):
# self.ToggleTool(self.wx_ids['Pan'], False)
# else:
# print('Unable to reset Pan button, please report this with matplotlib version')
def SetCursor(page):
mode = page.toolbar.GetActive()
if mode == 'Pan':
if 'phoenix' in wx.version():
page.canvas.Cursor = wx.Cursor(wx.CURSOR_SIZING)
else:
page.canvas.SetCursor(wx.StockCursor(wx.CURSOR_SIZING))
elif mode == 'Zoom':
if 'phoenix' in wx.version():
page.canvas.Cursor = wx.Cursor(wx.CURSOR_MAGNIFIER)
else:
page.canvas.SetCursor(wx.StockCursor(wx.CURSOR_MAGNIFIER))
else:
if 'phoenix' in wx.version():
page.canvas.Cursor = wx.Cursor(wx.CURSOR_CROSS)
else:
page.canvas.SetCursor(wx.StockCursor(wx.CURSOR_CROSS))
def PlotFPAconvolutors(G2frame,NISTpk,conv2T=None,convI=None,convList=None):
'''Plot the convolutions used for the current peak computed with
:func:`GSASIIfpaGUI.doFPAcalc`
'''
import NIST_profile as FP
new,plotNum,Page,Plot,lim = G2frame.G2plotNB.FindPlotTab('FPA convolutors','mpl')
Page.SetToolTipString('')
cntr = NISTpk.twotheta_window_center_deg
Plot.set_title('Peak convolution functions @ 2theta={:.3f}'.format(cntr))
Plot.set_xlabel(r'$\Delta 2\theta, deg$',fontsize=14)
Plot.set_ylabel(r'Intensity (arbitrary)',fontsize=14)
# refColors=['b','r','c','g','m','k']
refColors = ['xkcd:blue','xkcd:red','xkcd:green','xkcd:cyan','xkcd:magenta','xkcd:black',
'xkcd:pink','xkcd:brown','xkcd:teal','xkcd:orange','xkcd:grey','xkcd:violet',]
ttmin = ttmax = 0
#GSASIIpath.IPyBreak()
i = -1
if convList is None:
convList = NISTpk.convolvers
for conv in convList:
if 'smoother' in conv: continue
if 'crystallite_size' in conv: continue
f = NISTpk.convolver_funcs[conv]()
if f is None: continue
i += 1
FFT = FP.best_irfft(f)
if f[1].real > 0: FFT = np.roll(FFT,int(len(FFT)/2.))
FFT /= FFT.max()
ttArr = np.linspace(-NISTpk.twotheta_window_fullwidth_deg/2,
NISTpk.twotheta_window_fullwidth_deg/2,len(FFT))
ttmin = min(ttmin,ttArr[np.argmax(FFT>.005)])
ttmax = max(ttmax,ttArr[::-1][np.argmax(FFT[::-1]>.005)])
color = refColors[i%len(refColors)]
Plot.plot(ttArr,FFT,color,label=conv[5:])
if conv2T is not None and convI is not None:
color = refColors[(i+1)%len(refColors)]
Plot.plot(conv2T,convI,color,label='Convolution')
legend = Plot.legend(loc='best')
SetupLegendPick(legend,new)
Page.toolbar.push_current()
Plot.set_xlim((ttmin,ttmax))
Page.toolbar.push_current()
Page.ToolBarDraw()
Page.canvas.draw()
def SetupLegendPick(legend,new,delay=5):
mplv = eval(mpl.__version__.replace('.',','))
legend.delay = delay*1000 # Hold time in ms for clear; 0 == forever
for line in legend.get_lines():
if mplv[0] >= 3 and mplv[1] >= 3:
line.set_pickradius(4)
else:
line.set_picker(4)
# bug: legend items with single markers don't seem to respond to a "pick"
#GSASIIpath.IPyBreak()
for txt in legend.get_texts():
try: # as of MPL 3.3.2 this has not changed
txt.set_picker(4)
except AttributeError:
txt.set_pickradius(4)
if new:
legend.figure.canvas.mpl_connect('pick_event',onLegendPick)
def onLegendPick(event):
'''When a line in the legend is selected, find the matching line
in the plot and then highlight it by adding/enlarging markers.
Set up a timer to make a reset after delay selected in SetupLegendPick
'''
def clearHighlight(event):
if not canvas.timer: return
l,lm,lms,lmw = canvas.timer.lineinfo
l.set_marker(lm)
l.set_markersize(lms)
l.set_markeredgewidth(lmw)
canvas.draw()
canvas.timer = None
canvas = event.artist.get_figure().canvas
if not hasattr(canvas,'timer'): canvas.timer = None
plot = event.artist.get_figure().get_axes()[0]
if hasattr(plot.get_legend(),'delay'):
delay = plot.get_legend().delay
if canvas.timer: # clear previous highlight
if delay > 0: canvas.timer.Stop()
clearHighlight(None)
#if delay <= 0: return # use this in place of return
# so that the next selected item is automatically highlighted (except when delay is 0)
return
if event.artist in plot.get_legend().get_lines(): # is this an artist item in the legend?
lbl = event.artist.get_label()
elif event.artist in plot.get_legend().get_texts(): # is this a text item in the legend?
lbl = event.artist.get_text()
else:
#GSASIIpath.IPyBreak()
return
for l in plot.get_lines():
if lbl == l.get_label():
canvas.timer = wx.Timer()
canvas.timer.Bind(wx.EVT_TIMER, clearHighlight)
#GSASIIpath.IPyBreak()
canvas.timer.lineinfo = (l,l.get_marker(),l.get_markersize(),l.get_markeredgewidth())
# highlight the selected item
if l.get_marker() == 'None':
l.set_marker('o')
else:
l.set_markersize(2*l.get_markersize())
l.set_markeredgewidth(2*l.get_markeredgewidth())
canvas.draw()
if delay > 0:
canvas.timer.Start(delay,oneShot=True)
break
else:
print('Warning: artist matching ',lbl,' not found')
def changePlotSettings(G2frame,Plot):
'''Code in development to allow changes to plot settings
prior to export of plot with "floppy disk" button
'''
def RefreshPlot(*args,**kwargs):
'''Apply settings to the plot
'''
Plot.figure.subplots_adjust(left=int(plotOpt['labelSize'])/100.,
bottom=int(plotOpt['labelSize'])/150.,
right=.98,
top=1.-int(plotOpt['labelSize'])/200.,
hspace=0.0)
for P in Plot.figure.axes:
P.get_xaxis().get_label().set_fontsize(plotOpt['labelSize'])
P.get_yaxis().get_label().set_fontsize(plotOpt['labelSize'])
for l in P.get_xaxis().get_ticklabels():
l.set_fontsize(plotOpt['labelSize'])
for l in P.get_yaxis().get_ticklabels():
l.set_fontsize(plotOpt['labelSize'])
for l in P.lines:
l.set_linewidth(plotOpt['lineWid'])
P.get_xaxis().set_tick_params(width=plotOpt['lineWid'])
P.get_yaxis().set_tick_params(width=plotOpt['lineWid'])
for l in P.spines.values():
l.set_linewidth(plotOpt['lineWid'])