-
Notifications
You must be signed in to change notification settings - Fork 1
/
MainWindow.py
363 lines (255 loc) · 9.6 KB
/
MainWindow.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
# segyExplorer - display segy file data and header information
# Copyright (C) 2019 Micha Feigin-Almon
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from PyQt5 import QtWidgets, QtCore
from PyQt5 import uic
import os
import numpy as np
import pandas as pd
import segyio
try:
from hdf5storage import savemat, loadmat
except ModuleNotFoundError:
print('hdf5storage missing falling back to scipy.io and matlab file version 5')
from scipy.io import savemat, loadmat
class SegyMainWindow(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
ui_path = os.path.dirname(os.path.abspath(__file__))
ui_file = os.path.join(ui_path, "MainWindow.ui")
uic.loadUi(ui_file, self)
self.img = None
self._data = None
self._processDataRange = True
def onOpen(self):
fileName, _ = QtWidgets.QFileDialog.getOpenFileName(self, 'Open file', '', 'All Files (*);;segy Files (*.segy)')
if fileName:
_, ext = os.path.splitext(fileName)
if ext == '.segy':
self.openSegy(fileName)
elif ext == '.mat':
self.openMat(fileName)
else:
ShowErrorDialog('Unknown extension for file: {}\n'.format(fileName))
def onSave(self):
fileName, _ = QtWidgets.QFileDialog.getSaveFileName(self, 'Save file', '', 'mat Files (*.mat)')
if fileName:
self.saveMat(fileName)
def onColorRangeChange(self):
if self._img is None:
return
linked = self.colorRangeLinked.isChecked()
self.colorRangeMin.setEnabled(False if linked else True)
c = self.colorRangeMin.value()
C = self.colorRangeMax.value()
if linked:
c = self.colorRangeMin.minimum() + (self.colorRangeMax.maximum() - C)
self.colorRangeMin.setValue(c)
if self.c == c and self.C == C:
return
self.c = c
self.C = C
self._img.set_clim(self.c, self.C)
self.mplWindow.canvas.draw()
def drawData(self):
self.mplWindow.ax.clear()
self.mplWindow.cax.clear()
m = self.dataRangeMin.value()
M = self.dataRangeMax.value()
self._img = self.mplWindow.ax.imshow(self._data[m:M+1, :].T,
extent=[m, M, self._data.shape[1], 0],
aspect='auto', cmap='gray', vmin=self.c, vmax=self.C)
self.mplWindow.fig.colorbar(self._img, cax=self.mplWindow.cax)
self.mplWindow.canvas.draw()
def updateDataRange(self, min, max):
self._processDataRange = False
self.dataRangeMin.setValue(min)
self._processDataRange = True
self.dataRangeMax.setValue(max)
def onDataRangeChange(self):
if self._data is None or not self._processDataRange:
return
m = self.dataRangeMin.value()
M = self.dataRangeMax.value()
if m >= M:
return # Do not draw, assuming user is still updating range
self.drawData()
def onDataJumpRight(self):
m = self.dataRangeMin.value()
M = self.dataRangeMax.value()
if M == self.dataRangeMax.maximum():
return
step = M - m + 1
M = min(M + step * self.dataJumpStep.value(), self.dataRangeMax.maximum())
m = M - step + 1
self.updateDataRange(m, M)
def onDataJumpLeft(self):
m = self.dataRangeMin.value()
M = self.dataRangeMax.value()
if m == self.dataRangeMax.minimum():
return
step = M - m + 1
m = max(m - step * self.dataJumpStep.value(), self.dataRangeMin.minimum())
M = m + step - 1
self.updateDataRange(m, M)
def openSegy(self, file: str):
try:
with segyio.open(file, strict=False) as s:
self._img = None
self._data = None
s.mmap()
self.fileHeader = pd.DataFrame(columns=['tag','values'], index=range(len(s.bin)), dtype=str)
for i, val in enumerate(s.bin.items()):
self.fileHeader.iloc[i,:] = [str(v) for v in val]
self.fileHeaderTable.setModel(PandasModel(self.fileHeader))
traceHeaderData = np.empty((len(s.header), len(s.header[0].keys())), dtype=np.int32)
for i, val in enumerate(s.header):
traceHeaderData[i, :] = [x for x in val.values()]
self.traceHeader = pd.DataFrame(data=traceHeaderData, columns=[str(k) for k in s.header[0].keys()])
self.traceHeaderTable.setModel(PandasModel(self.traceHeader))
data = np.zeros((s.tracecount, s.bin[segyio.BinField.Samples]), s.dtype)
for i in range(s.tracecount):
data[i, :] = s.trace[i]
# Set color range before displaying image as a workaround for now as this changes the color scale
# and the slider bar does not support fractional values so nothing is shown if the range is bellow 1
self.c = np.min(data)
self.C = np.max(data)
self.colorRangeLinked.setChecked(True if self.c < 0 else False)
self.colorRangeMin.setEnabled(False if self.colorRangeLinked.isChecked() else True)
self.colorRangeMin.setMinimum(self.c)
self.colorRangeMin.setMaximum(0.5 * (self.c + self.C) if self.colorRangeLinked.isChecked() else self.C)
self.colorRangeMin.setSingleStep((self.C - self.c) / 40)
self.colorRangeMax.setMinimum(0.5 * (self.c + self.C) if self.colorRangeLinked.isChecked() else self.c)
self.colorRangeMax.setMaximum(self.C)
self.colorRangeMax.setSingleStep((self.C - self.c) / 40)
self.colorRangeMin.setValue(self.c)
self.colorRangeMax.setValue(self.C)
m = 0
M = data.shape[0]-1
self.dataRangeMin.setMinimum(0)
self.dataRangeMin.setMaximum(M)
self.dataRangeMax.setMinimum(0)
self.dataRangeMax.setMaximum(M)
self._data = data
self.updateDataRange(m, M)
except Exception as e:
ShowErrorDialog('Failed to open SEGY file {} - {}'.format(file, e.args[0]))
def openMat(self, file: str):
try:
data = loadmat(file)
if len(data.keys()) == 1:
key = list(data.keys())[0]
else:
dialog = Dialog()
dialog.setModal(True)
selected = None
for k in data.keys():
item = QtWidgets.QListWidgetItem()
item.setText(k)
dialog.list.addItem(item)
if selected is None or k == 'data':
selected = item
dialog.list.addItem(item)
dialog.list.sortItems()
dialog.list.setAlternatingRowColors(True)
dialog.list.setCurrentItem(selected)
ret = dialog.exec_()
if not ret:
return
key = dialog.list.currentItem().text()
self._img = None
self._data = None
self.fileHeader = pd.DataFrame()
self.fileHeaderTable.setModel(PandasModel(self.fileHeader))
self.traceHeader = pd.DataFrame()
self.traceHeaderTable.setModel(PandasModel(self.traceHeader))
data = data[key]
self.c = np.min(data)
self.C = np.max(data)
self.colorRangeLinked.setChecked(True if self.c < 0 else False)
self.colorRangeMin.setEnabled(False if self.colorRangeLinked.isChecked() else True)
self.colorRangeMin.setMinimum(self.c)
self.colorRangeMin.setMaximum(0.5 * (self.c + self.C) if self.colorRangeLinked.isChecked() else self.C)
self.colorRangeMin.setSingleStep((self.C - self.c) / 40)
self.colorRangeMax.setMinimum(0.5 * (self.c + self.C) if self.colorRangeLinked.isChecked() else self.c)
self.colorRangeMax.setMaximum(self.C)
self.colorRangeMax.setSingleStep((self.C - self.c) / 40)
self.colorRangeMin.setValue(self.c)
self.colorRangeMax.setValue(self.C)
m = 0
M = data.shape[0]-1
self.dataRangeMin.setMinimum(0)
self.dataRangeMin.setMaximum(M)
self.dataRangeMax.setMinimum(0)
self.dataRangeMax.setMaximum(M)
self._data = data
self.updateDataRange(m, M)
except Exception as e:
ShowErrorDialog('Failed to open MAT file {} - {}'.format(file, e.args[0]))
def saveMat(self, file: str):
saveMat(file, {'data': self._data[m:M+1, :]}, truncate_invalid_matlab=True, truncate_existing=True)
class Dialog(QtWidgets.QDialog):
def __init__(self):
super().__init__()
self.layout = QtWidgets.QHBoxLayout()
self.list = QtWidgets.QListWidget(self)
self.layout.addWidget(self.list)
self.btnBox = QtWidgets.QDialogButtonBox(
QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel,
QtCore.Qt.Vertical,
self)
self.btnBox.accepted.connect(self.accept)
self.btnBox.rejected.connect(self.reject)
self.layout.addWidget(self.btnBox)
self.setLayout(self.layout)
class PandasModel(QtCore.QAbstractTableModel):
def __init__(self, data, parent=None):
super(PandasModel, self).__init__()
self._data = data
def rowCount(self, parent=None):
return self._data.shape[0]
def columnCount(self, parent=None):
return self._data.shape[1]
def headerData(self, idx, orientation, role):
if role != QtCore.Qt.DisplayRole:
return None
if orientation == QtCore.Qt.Horizontal:
return self._data.columns[idx]
if orientation == QtCore.Qt.Vertical:
return self._data.index[idx]
return None
def data(self, index, role=QtCore.Qt.DisplayRole):
if not index.isValid():
return None
if role == QtCore.Qt.DisplayRole:
return str(self._data.values[index.row(),index.column()])
return None
def flags(self, index):
flags = super(self.__class__, self).flags(index)
flags |= QtCore.Qt.ItemIsSelectable
flags |= QtCore.Qt.ItemIsEnabled
return flags
def sort(self, Ncol, order):
try:
self.layoutAboutToBeChanged.emit()
self._data = self._data.sort_values(self._data.columns[Ncol], ascending=not order)
self.layoutChanged.emit()
except Exception as e:
print(e)
def ShowErrorDialog(msg: str):
error_dialog = QtWidgets.QErrorMessage()
error_dialog.showMessage(msg)
error_dialog.setModal(True)
error_dialog.exec_()