-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplot1D.py
More file actions
380 lines (297 loc) · 14.5 KB
/
Copy pathplot1D.py
File metadata and controls
380 lines (297 loc) · 14.5 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
import os
import re
import numpy as np
from silx.gui import qt
from silx.gui import icons
from silx.gui.plot.PlotWindow import PlotWindow
import logging
_logger = logging.getLogger(__name__)
class Plot1D(PlotWindow):
"""PlotWindow with tools specific for curves.
This widgets provides the plot API of :class:`.PlotWidget`.
:param parent: The parent of this widget
:param backend: The backend to use for the plot (default: matplotlib).
See :class:`.PlotWidget` for the list of supported backend.
:type backend: str or :class:`BackendBase.BackendBase`
"""
def __init__(self, parent=None, backend=None):
super(Plot1D, self).__init__(parent=parent, backend=backend,
resetzoom=True, autoScale=False,
logScale=True, grid=True,
curveStyle=True, colormap=False,
aspectRatio=False, yInverted=False,
copy=True, save=True, print_=True,
control=True, position=True,
roi=False, mask=False, fit=False)
# Retrieve PlotWidget's plot area widget
plotArea = self.getWidgetHandle()
# Data margins
self.setDataMargins(0.01, 0.01, 0.01, 0.01)
self._path = ''
self._filename = ''
self.setDefaultPlotPoints(False)
self.getGridAction().setChecked(False)
self.setGraphGrid(False)
@property
def path(self):
return self._path
@property
def filename(self):
return self._filename
def setPath(self, path):
self._path = path
def setFilename(self, filename):
self._filename = filename
def resetZoom(self, dataMargins=None):
"""Reset the plot limits to the bounds of the data and redraw the plot.
It automatically scale limits of axes that are in autoscale mode
(see :meth:`getXAxis`, :meth:`getYAxis` and :meth:`Axis.setAutoScale`).
It keeps current limits on axes that are not in autoscale mode.
Extra margins can be added around the data inside the plot area
(see :meth:`setDataMargins`).
Margins are given as one ratio of the data range per limit of the
data (xMin, xMax, yMin and yMax limits).
For log scale, extra margins are applied in log10 of the data.
:param dataMargins: Ratios of margins to add around the data inside
the plot area for each side (default: no margins).
:type dataMargins: A 4-tuple of float as (xMin, xMax, yMin, yMax).
Changed zoom history to be deleted when resetZoom is called.
"""
xLimits = self._xAxis.getLimits()
yLimits = self._yAxis.getLimits()
y2Limits = self._yRightAxis.getLimits()
xAuto = self._xAxis.isAutoScale()
yAuto = self._yAxis.isAutoScale()
# With log axes, autoscale if limits are <= 0
# This avoids issues with toggling log scale with matplotlib 2.1.0
if self._xAxis.getScale() == self._xAxis.LOGARITHMIC and xLimits[0] <= 0:
xAuto = True
if self._yAxis.getScale() == self._yAxis.LOGARITHMIC and (yLimits[0] <= 0 or y2Limits[0] <= 0):
yAuto = True
if not xAuto and not yAuto:
_logger.debug("Nothing to autoscale")
else: # Some axes to autoscale
self._forceResetZoom(dataMargins=dataMargins)
# Restore limits for axis not in autoscale
if not xAuto and yAuto:
self.setGraphXLimits(*xLimits)
elif xAuto and not yAuto:
if y2Limits is not None:
self.setGraphYLimits(
y2Limits[0], y2Limits[1], axis='right')
if yLimits is not None:
self.setGraphYLimits(yLimits[0], yLimits[1], axis='left')
if (xLimits != self._xAxis.getLimits() or
yLimits != self._yAxis.getLimits() or
y2Limits != self._yRightAxis.getLimits()):
self._notifyLimitsChanged()
# Changed Zoom history to be deleted when resetZoom is called.
self._limitsHistory.clear()
class Plot1DHistogram(PlotWindow):
def __init__(self, parent=None, backend=None):
super(Plot1DHistogram, self).__init__(parent=parent, backend=backend,
resetzoom=True, autoScale=False,
logScale=True, grid=True,
curveStyle=True, colormap=False,
aspectRatio=False, yInverted=False,
copy=True, save=False, print_=True,
control=True, position=True,
roi=False, mask=False, fit=False)
# Retrieve PlotWidget's plot area widget
plotArea = self.getWidgetHandle()
# Data margins
self.setDataMargins(0.01, 0.01, 0.01, 0.01)
self._path = ''
self._filename = ''
self.setDefaultPlotPoints(False)
self.getGridAction().setChecked(False)
self.setGraphGrid(False)
self._saveAction = qt.QAction(icons.getQIcon('document-save'), 'Save', self)
self._saveAction.setCheckable(False)
self._saveAction.triggered.connect(self.savePlot)
self._outputToolBar.addAction(self._saveAction)
@property
def path(self):
return self._path
@property
def filename(self):
return self._filename
def setPath(self, path):
self._path = path
def setFilename(self, filename):
self._filename = filename
def savePlot(self):
"""Save histogram to a file."""
data = self.getHistogram().getData()
stack = np.stack([data[1], np.append(data[0], 0)]).T
selected_file = qt.QFileDialog.getSaveFileName(self,
'Save File',
self.path,
'dat (*.dat)')
# split extension
path = os.path.splitext(selected_file[0])[0]
# save curves
np.savetxt(path+'.dat', stack, fmt='%.8e', delimiter='\t')
def resetZoom(self, dataMargins=None):
"""Reset the plot limits to the bounds of the data and redraw the plot.
It automatically scale limits of axes that are in autoscale mode
(see :meth:`getXAxis`, :meth:`getYAxis` and :meth:`Axis.setAutoScale`).
It keeps current limits on axes that are not in autoscale mode.
Extra margins can be added around the data inside the plot area
(see :meth:`setDataMargins`).
Margins are given as one ratio of the data range per limit of the
data (xMin, xMax, yMin and yMax limits).
For log scale, extra margins are applied in log10 of the data.
:param dataMargins: Ratios of margins to add around the data inside
the plot area for each side (default: no margins).
:type dataMargins: A 4-tuple of float as (xMin, xMax, yMin, yMax).
Changed zoom history to be deleted when resetZoom is called.
"""
xLimits = self._xAxis.getLimits()
yLimits = self._yAxis.getLimits()
y2Limits = self._yRightAxis.getLimits()
xAuto = self._xAxis.isAutoScale()
yAuto = self._yAxis.isAutoScale()
# With log axes, autoscale if limits are <= 0
# This avoids issues with toggling log scale with matplotlib 2.1.0
if self._xAxis.getScale() == self._xAxis.LOGARITHMIC and xLimits[0] <= 0:
xAuto = True
if self._yAxis.getScale() == self._yAxis.LOGARITHMIC and (yLimits[0] <= 0 or y2Limits[0] <= 0):
yAuto = True
if not xAuto and not yAuto:
_logger.debug("Nothing to autoscale")
else: # Some axes to autoscale
self._forceResetZoom(dataMargins=dataMargins)
# Restore limits for axis not in autoscale
if not xAuto and yAuto:
self.setGraphXLimits(*xLimits)
elif xAuto and not yAuto:
if y2Limits is not None:
self.setGraphYLimits(
y2Limits[0], y2Limits[1], axis='right')
if yLimits is not None:
self.setGraphYLimits(yLimits[0], yLimits[1], axis='left')
if (xLimits != self._xAxis.getLimits() or
yLimits != self._yAxis.getLimits() or
y2Limits != self._yRightAxis.getLimits()):
self._notifyLimitsChanged()
# Changed Zoom history to be deleted when resetZoom is called.
self._limitsHistory.clear()
class Plot1DCustom(PlotWindow):
"""PlotWindow with tools specific for curves.
This widgets provides the plot API of :class:`.PlotWidget`.
:param parent: The parent of this widget
:param backend: The backend to use for the plot (default: matplotlib).
See :class:`.PlotWidget` for the list of supported backend.
:type backend: str or :class:`BackendBase.BackendBase`
"""
def __init__(self, parent=None, backend=None):
super(Plot1DCustom, self).__init__(parent=parent, backend=backend,
resetzoom=True, autoScale=False,
logScale=True, grid=True,
curveStyle=True, colormap=False,
aspectRatio=False, yInverted=False,
copy=True, save=False, print_=True,
control=True, position=True,
roi=False, mask=False, fit=False)
# Retrieve PlotWidget's plot area widget
plotArea = self.getWidgetHandle()
# Data margins
self.setDataMargins(0.01, 0.01, 0.01, 0.01)
self._path = ''
self._filename = ''
self.setDefaultPlotPoints(False)
self.getGridAction().setChecked(False)
self.setGraphGrid(False)
self._saveAction = qt.QAction(icons.getQIcon('document-save'), 'Save', self)
self._saveAction.setCheckable(False)
self._saveAction.triggered.connect(self.savePlots)
self._outputToolBar.addAction(self._saveAction)
@property
def path(self):
return self._path
@property
def filename(self):
return self._filename
def setPath(self, path):
self._path = path
def setFilename(self, filename):
self._filename = filename
def savePlots(self):
"""Save plots to file."""
curve_names = []
data = []
header = ''
curves = self.getAllCurves()
if len(curves) > 0:
for idx, curve in enumerate(curves):
curve_names.append(curve.getName())
curve_names = sorted(curve_names)
header = 'Energy\t' + '\t'.join(curve_names)
re_pat = re.compile(r"[0-9]+")
print(f"path : {self.path}, filename : {self.filename}")
last_num = -1
with os.scandir(self.path) as it:
for item in it:
if item.is_file() and item.name.find(self.filename) >= -1:
idx = item.name[:-4].split('_spectrum_')[-1]
if re_pat.match(idx):
try:
if int(idx) > last_num:
last_num = int(idx)
except:
...
num = last_num + 1
save_file = os.path.join(self.path, f"{self.filename}_spectrum_{num:d}.dat")
for idx, curve_name in enumerate(curve_names):
if idx == 0:
data.append(self.getCurve(curve_name).getXData())
data.append(self.getCurve(curve_name).getYData())
data = np.array(data).transpose()
# save curves
np.savetxt(save_file, data, header=header, fmt='%.4e', delimiter='\t')
def resetZoom(self, dataMargins=None):
"""Reset the plot limits to the bounds of the data and redraw the plot.
It automatically scale limits of axes that are in autoscale mode
(see :meth:`getXAxis`, :meth:`getYAxis` and :meth:`Axis.setAutoScale`).
It keeps current limits on axes that are not in autoscale mode.
Extra margins can be added around the data inside the plot area
(see :meth:`setDataMargins`).
Margins are given as one ratio of the data range per limit of the
data (xMin, xMax, yMin and yMax limits).
For log scale, extra margins are applied in log10 of the data.
:param dataMargins: Ratios of margins to add around the data inside
the plot area for each side (default: no margins).
:type dataMargins: A 4-tuple of float as (xMin, xMax, yMin, yMax).
Changed zoom history to be deleted when resetZoom is called.
"""
xLimits = self._xAxis.getLimits()
yLimits = self._yAxis.getLimits()
y2Limits = self._yRightAxis.getLimits()
xAuto = self._xAxis.isAutoScale()
yAuto = self._yAxis.isAutoScale()
# With log axes, autoscale if limits are <= 0
# This avoids issues with toggling log scale with matplotlib 2.1.0
if self._xAxis.getScale() == self._xAxis.LOGARITHMIC and xLimits[0] <= 0:
xAuto = True
if self._yAxis.getScale() == self._yAxis.LOGARITHMIC and (yLimits[0] <= 0 or y2Limits[0] <= 0):
yAuto = True
if not xAuto and not yAuto:
_logger.debug("Nothing to autoscale")
else: # Some axes to autoscale
self._forceResetZoom(dataMargins=dataMargins)
# Restore limits for axis not in autoscale
if not xAuto and yAuto:
self.setGraphXLimits(*xLimits)
elif xAuto and not yAuto:
if y2Limits is not None:
self.setGraphYLimits(
y2Limits[0], y2Limits[1], axis='right')
if yLimits is not None:
self.setGraphYLimits(yLimits[0], yLimits[1], axis='left')
if (xLimits != self._xAxis.getLimits() or
yLimits != self._yAxis.getLimits() or
y2Limits != self._yRightAxis.getLimits()):
self._notifyLimitsChanged()
# Changed Zoom history to be deleted when resetZoom is called.
self._limitsHistory.clear()