forked from mikewalker92/thea
-
Notifications
You must be signed in to change notification settings - Fork 0
/
theaMainWindow.py
573 lines (419 loc) · 19.7 KB
/
theaMainWindow.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
# -*- coding: iso-8859-1 -*-
import iris, cartopy, matplotlib, theaMainInterface, colorbarOptions, matplotlibwidgetFile
import CubeControl as cc
import guiLogic as logic
import matplotlib.pyplot as plt
import iris.plot as iplt
import numpy as np
from PySide import QtGui, QtCore
from PySide.QtGui import QApplication, QCursor
from matplotlib.figure import Figure
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg as NavigationToolbar
class GUI(QtGui.QMainWindow, theaMainInterface.Ui_MainWindow):
def __init__(self):
super(GUI, self).__init__()
self.initUI()
self.setStateIndicators()
self.cbDialog = colorbarOptions.ColorbarOptions()
self.setActions()
def initUI(self):
"""
This method sets up the initial layout of the GUI.
We first call setupUi, a method from theaUI, which has been generated by Qt to recreate the
interface created in Qt Designer.
We are then able to attatch the matplotlib toolbar our embedded image.
The window is then displayed
"""
self.setupUi(self)
self.mpl_toolbar = NavigationToolbar(self.matplotlibDisplay.canvas, self.matplotlibDisplay)
self.matplotlibDisplay.vbl.addWidget(self.mpl_toolbar)
self.show()
def setActions(self):
"""
This function sets up all of the interactivity for the GUI (except for that which was implemented
directly in Qt Designer)
activated / triggered => when the user interacts with the object (ie. will not be sent if a method in this code
changes the object)
currentValueChanged and similar => when the object is changed by anything
"""
self.updateButton.clicked.connect(self.update)
self.actionOpen.triggered.connect(self.showOpenDialog)
self.actionSave.triggered.connect(self.showSaveDialog)
self.actionColorbar.triggered.connect(self.showColorbarDialog)
self.actionGridlines.triggered.connect(self.stateChanged)
self.actionCoastlines.triggered.connect(self.stateChanged)
self.actionCountry_Boundaries.triggered.connect(self.stateChanged)
self.actionRivers_and_Lakes.triggered.connect(self.stateChanged)
self.actionFix_Colorbar.triggered.connect(self.stateChangedFix)
self.actionContour_Labels.triggered.connect(self.stateChanged)
self.actionNextSlice.triggered.connect(self.nextSlice)
self.actionPreviousSlice.triggered.connect(self.previousSlice)
self.selectPlotType.activated.connect(self.stateChangedPlotType)
self.selectProjection.currentIndexChanged.connect(self.stateChanged)
self.selectColormap.currentIndexChanged.connect(self.stateChanged)
self.contourSlider.valueChanged.connect(self.stateChanged)
self.selectCube.activated.connect(self.setDimensionCombos)
self.selectCube.activated.connect(self.stateChangedSlicedDim)
self.selectDimension1.activated.connect(self.stateChangedAxis)
self.selectDimension2.activated.connect(self.stateChangedAxis)
self.selectSlicedDim.currentIndexChanged.connect(self.stateChangedSlicedDim)
self.selectSliceCombo.currentIndexChanged.connect(self.stateChanged)
for i in range(6):
exec("self.selectSliceIndex{}.currentIndexChanged.connect(self.stateChanged)".format(i+1))
self.selectDimension1.activated.connect(self.arrangeCoords1)
self.selectDimension2.activated.connect(self.arrangeCoords2)
self.selectSlicedDim.activated.connect(self.arrangeCoords3)
self.cbDialog.autoselectRange.stateChanged.connect(self.stateChanged)
self.cbDialog.minContour.valueChanged.connect(self.stateChanged)
self.cbDialog.maxContour.valueChanged.connect(self.stateChanged)
self.cubeInfoTab.currentChanged.connect(self.showData)
def setDimensionCombos(self):
QApplication.setOverrideCursor(QtCore.Qt.WaitCursor)
self.statusBar().showMessage('Updating Interface')
self.clearDims()
dim_names = [dim_coord.name() for dim_coord in self.cube.dim_coords]
missing_dims = cc.getMissingCoords(self.cube)
enabled, data = logic.getDataSelectDim1(dim_names, missing_dims)
self.fillCombo("selectDimension1", enabled, data)
enabled, data = logic.getDataSelectDim2(dim_names, missing_dims)
self.fillCombo("selectDimension2", enabled, data)
if self.cube.ndim > 2:
enabled, data = logic.getDataSelectSlicedDim(self.cube, dim_names)
self.fillCombo("selectSlicedDim", enabled, data)
enabled, data = logic.getDataSelectSliceIndex(self.cube, self.selectSlicedDim.currentText())
self.fillCombo("selectSliceCombo", enabled, data)
self.setSliceScroll()
self.selectSliceScroll.setEnabled(True)
self.selectSliceScroll.setRange
self.actionNextSlice.setEnabled(True)
self.actionPreviousSlice.setEnabled(True)
self.actionLoadSlices.setEnabled(True)
self.setInitialIndex(missing_dims)
self.setCollapsedDims()
self.stateChangedAxis()
self.dim1 = self.selectDimension1.currentIndex()
self.dim2 = self.selectDimension2.currentIndex()
self.dim3 = self.selectSlicedDim.currentIndex()
QApplication.restoreOverrideCursor()
def update(self):
QApplication.setOverrideCursor(QtCore.Qt.WaitCursor)
self.updateButton.setEnabled(False)
cube = self.getCurrentCube()
plotType = self.selectPlotType.currentText()
projection = self.selectProjection.currentText()
cmap = self.selectColormap.currentText()
Ncontours = self.contourSlider.value()
coastlines = self.actionCoastlines.isChecked()
gridlines = self.actionGridlines.isChecked()
contourLabels = self.actionContour_Labels.isChecked()
countries = self.actionCountry_Boundaries.isChecked()
rivers = self.actionRivers_and_Lakes.isChecked()
dim1_name = self.selectDimension1.currentText()
dim1_index = self.selectDimension1.currentIndex()
dim2_name = self.selectDimension2.currentText()
dim2_index = self.selectDimension2.currentIndex()
slicedDimName = self.selectSlicedDim.currentText()
slicedDimIndex = self.selectSlicedDim.currentIndex()
sliceIndex = self.selectSliceScroll.value()
collapsedNames = []
collapsedIndices = []
for i in range(cube.ndim - 3):
exec("collapsedNames.append(self.collapsedDim{}.text())".format(i+1))
exec("collapsedIndices.append(self.selectSliceIndex{}.currentIndex())".format(i+1))
if self.cbDialog.autoselectRange.isChecked():
cbMax = None
cbMin = None
elif self.cbDialog.fixedColorbar.isChecked():
if self.fixedCb == False:
self.Max, self.Min = cc.setFixedColorbar(cube, dim1_name, dim2_name, slicedDimName, dim1_index, dim2_index, slicedDimIndex, collapsedIndices)
self.fixedCb == True
cbMax = self.Max
cbMin = self.Min
else:
cbMax = self.cbDialog.maxContour.value()
cbMin = self.cbDialog.minContour.value()
self.clearFig()
self.statusBar().showMessage('Plotting Cube')
try:
self.plotted_cube = cc.update(cube, plotType, projection, cmap, Ncontours, coastlines, gridlines, contourLabels, countries, rivers,
cbMax, cbMin, dim1_name, dim1_index, dim2_name, dim2_index, slicedDimName,
slicedDimIndex, sliceIndex, collapsedNames, collapsedIndices)
except Exception as e:
flags = QtGui.QMessageBox.StandardButton.Ok
response = QtGui.QMessageBox.critical(self, 'Unable to plot cube!', str(e), flags)
self.statusBar().showMessage('Failed to Plot Cube')
QApplication.restoreOverrideCursor()
self.statusBar().showMessage('Drawing Plot')
self.display()
self.printCubeSliceBrowser.setText(str(self.plotted_cube))
self.statusBar().showMessage('Ready')
QApplication.restoreOverrideCursor()
def showOpenDialog(self):
"""
Handles the loading of a file, and calls functions to set up the GUI accordingly and then display the cube
"""
self.filename, _ = QtGui.QFileDialog.getOpenFileName(self, 'Open File', '/project/avd/iris/resources/public_sample_data_1.0')
self.clearAll()
QApplication.setOverrideCursor(QtCore.Qt.WaitCursor)
self.statusBar().showMessage('Loading Cube')
try:
self.cubes = iris.load(self.filename)
except ValueError as e:
flags = QtGui.QMessageBox.StandardButton.Ok
response = QtGui.QMessageBox.critical(self, 'Unable to Load Cube: File type could not be read', str(e), flags)
self.statusBar().showMessage('Load Failed')
QApplication.restoreOverrideCursor()
QApplication.restoreOverrideCursor()
for self.cube in self.cubes:
self.selectCube.addItem(self.cube.name()) #fills the selectCube combo box with the cubes from the file
if len(self.cubes) == 1:
self.selectCube.setEnabled(False)
else:
self.selectCube.setEnabled(True)
self.cubeLoaded = True
self.printCubeBrowser.setText(str(self.cube))
self.setDimensionCombos()
self.update()
def showSaveDialog(self):
"""
Saves the image which is currently being displayed
"""
filename,_ = QtGui.QFileDialog.getSaveFileName()
QApplication.setOverrideCursor(QtCore.Qt.WaitCursor)
self.statusBar().showMessage('Saving')
try:
plt.savefig(filename)
except Exception as e:
flags = QtGui.QMessageBox.StandardButton.Ok
response = QtGui.QMessageBox.critical(self, 'Unable to Save Cube', str(e), flags)
self.statusBar().showMessage('Save Failed')
QApplication.restoreOverrideCursor()
self.statusBar().showMessage('Ready')
def setStateIndicators(self):
self.tableDrawn = False #A variable to help reduce the number of times that the table is drawn
self.cubeLoaded = False #A variable used to ensure that the program does not crash attempting to draw cubes before one is loaded.
self.updateButton.setEnabled(False)
self.fixedCb = "No"
def getCurrentCube(self):
cube_index = self.selectCube.currentIndex()
return self.cubes[cube_index]
def fillCombo (self, comboBox, enabled, items):
if enabled:
exec("self.{}.setEnabled(True)".format(comboBox))
exec("self.{}.clear()".format(comboBox))
for item in items:
exec("self.{}.addItem(str(item))".format(comboBox))
else:
exec("self.{}.setEnabled(False)".format(comboBox))
def showColorbarDialog(self):
self.cbDialog.show()
def stateChanged(self):
"""
when an option has been changed, we re-enable
the update button.
"""
self.updateButton.setEnabled(True)
def stateChangedFix(self):
"""
Marks that the fix contour button has been pressed
"""
self.updateButton.setEnabled(True)
if self.fixedCb == "No":
self.fixedCb = "clicked"
else:
self.fixedCb = "No"
def stateChangedSlicedDim(self):
"""
any change in which the sliced dimension might have
changed.
"""
self.stateChanged()
self.stateChangedAxis()
self.fixedCb = False
if self.cube.ndim >= 3:
self.actionLoadSlices.setEnabled(True)
self.actionLoadSlices.setChecked(False)
def stateChangedAxis(self):
"""
every time the 2 plotted dimensions change, we check
to see if it makes sense to pick projections or geographic
feature. If it does, then these buttons are enabled, if not,
then they are disabled.
"""
valid_dims = False
self.stateChanged()
if cc.getMissingCoords(self.cube) == 0 :
if self.cube.ndim > 1:
coord1 = self.selectDimension1.currentText()
coord2 = self.selectDimension2.currentText()
exec ("valid_dims = iplt._can_draw_map([self.cube.coord('{}'),self.cube.coord('{}')])".format(coord1, coord2))
if valid_dims == True:
self.selectProjection.setEnabled(True)
self.actionCoastlines.setEnabled(True)
self.actionRivers_and_Lakes.setEnabled(True)
self.actionCountry_Boundaries.setEnabled(True)
else:
self.selectProjection.setCurrentIndex(0)
self.selectProjection.setEnabled(False)
self.actionCoastlines.setEnabled(False)
self.actionRivers_and_Lakes.setEnabled(False)
self.actionCountry_Boundaries.setEnabled(False)
def stateChangedPlotType(self):
"""
controls buttons that only make sense for some types of plot.
"""
self.stateChanged()
if self.selectPlotType.currentText() == "pcolormesh":
self.contourSlider.setEnabled(False)
self.actionContour_Labels.setEnabled(False)
elif self.selectPlotType.currentText() == "Contour":
self.actionContour_Labels.setEnabled(True)
else:
self.contourSlider.setEnabled(True)
self.actionContour_Labels.setEnabled(False)
def setInitialIndex(self, missing_dims):
if missing_dims == 0:
self.selectDimension1.setCurrentIndex(self.cube.ndim - 2)
self.selectDimension2.setCurrentIndex(self.cube.ndim - 1)
if self.cube.ndim > 2:
self.selectSlicedDim.setCurrentIndex(0)
def clearAll(self):
self.clearDims()
self.clearFig()
self.selectCube.clear()
self.actionNextSlice.setEnabled(False)
self.actionPreviousSlice.setEnabled(False)
def clearDims(self):
self.selectDimension1.clear()
self.selectDimension2.clear()
self.selectSlicedDim.clear()
self.selectDimension1.setEnabled(False)
self.selectDimension2.setEnabled(False)
self.selectSlicedDim.setEnabled(False)
self.selectSliceCombo.setEnabled(False)
self.selectSliceScroll.setEnabled(False)
self.actionLoadSlices.setEnabled(False)
for i in range(6):
exec("self.collapsedDim{}.clear()".format(i+1))
exec("self.selectSliceIndex{}.clear()".format(i+1))
exec("self.selectSliceIndex{}.setEnabled(False)".format(i+1))
def clearFig(self):
im = plt.clf()
self.display()
def nextSlice(self):
i = self.selectSliceCombo.currentIndex()
self.selectSliceCombo.setCurrentIndex(i+1)
self.update()
def previousSlice(self):
i = self.selectSliceCombo.currentIndex()
if i == 0:
i = self.selectSliceCombo.count()
self.selectSliceCombo.setCurrentIndex(i-1)
self.update()
def arrangeCoords1(self):
"""
The arrange Methods are present to prevent any one coordinate being used more than once in the
selectDimension1, selectDimension2 and selectSlicedDim combo boxes.
When a coordinate is selected in any one of the combo boxes, it checks the other 2 for matches
and if matches are found then it will put the old value for the selected combo box into the
combo box with the match.
"""
if self.selectDimension1.currentText() == self.selectDimension2.currentText():
self.selectDimension2.setCurrentIndex(self.dim1)
elif self.selectDimension1.currentText() == self.selectSlicedDim.currentText():
self.selectSlicedDim.setCurrentIndex(self.dim1)
self.dim1 = self.selectDimension1.currentIndex()
self.dim2 = self.selectDimension2.currentIndex()
self.dim3 = self.selectSlicedDim.currentIndex()
enabled, data = logic.getDataSelectSliceIndex(self.cube, self.selectSlicedDim.currentText())
self.fillCombo("selectSliceCombo", enabled, data)
self.setSliceScroll()
self.setCollapsedDims()
def arrangeCoords2(self):
if self.selectDimension2.currentText() == self.selectDimension1.currentText():
self.selectDimension1.setCurrentIndex(self.dim2)
elif self.selectDimension2.currentText() == self.selectSlicedDim.currentText():
self.selectSlicedDim.setCurrentIndex(self.dim2)
self.dim1 = self.selectDimension1.currentIndex()
self.dim2 = self.selectDimension2.currentIndex()
self.dim3 = self.selectSlicedDim.currentIndex()
enabled, data = logic.getDataSelectSliceIndex(self.cube, self.selectSlicedDim.currentText())
self.fillCombo("selectSliceCombo", enabled, data)
self.setSliceScroll()
self.setCollapsedDims()
def arrangeCoords3(self):
if self.selectSlicedDim.currentText() == self.selectDimension1.currentText():
self.selectDimension1.setCurrentIndex(self.dim3)
elif self.selectSlicedDim.currentText() == self.selectDimension2.currentText():
self.selectDimension2.setCurrentIndex(self.dim3)
self.dim1 = self.selectDimension1.currentIndex()
self.dim2 = self.selectDimension2.currentIndex()
self.dim3 = self.selectSlicedDim.currentIndex()
enabled, data = logic.getDataSelectSliceIndex(self.cube, self.selectSlicedDim.currentText())
self.fillCombo("selectSliceCombo", enabled, data)
self.setSliceScroll()
self.setCollapsedDims()
def setCollapsedDims(self):
"""
Beyond 3 dimensions, the program allows you to pick a single value to collapse the cube
around. This method fills and enables the relevant labels and combo boxes to allow this.
"""
if self.cube.ndim > 3:
usedDims = []
usedDims.append(self.selectDimension1.currentText())
usedDims.append(self.selectDimension2.currentText())
usedDims.append(self.selectSlicedDim.currentText())
dim_names = [dim_coord.name() for dim_coord in self.cube.dim_coords]
unusedDims = logic.getRemainingDims(dim_names, usedDims)
i = 1
for dimension in unusedDims:
exec("self.collapsedDim{}.setText(dimension)".format(i))
enabled, data = logic.getDataSelectSliceIndex(self.cube, dimension)
exec("self.fillCombo('selectSliceIndex{}', enabled, data)".format(i))
i += 1
def setSliceScroll(self): #Sets the maximum value of the scroll bar
sliced_coord = self.selectSlicedDim.currentText()
max_slice = len(self.cube.coord(sliced_coord).points)
self.selectSliceScroll.setMaximum(max_slice - 1)
def showData(self):
"""
Here we take the currently plotted cube (in general NOT the full cube)
and write the data in it into a table.
The table used is a table widget from Qt. This has the advantage of an
elegant presentation and could in future support interactivity with the
plot, as clicking on a cell can be used as a signal.
However, the disadvantage of this method is that it is quite slow. This
is probably because of the number of objects created to draw the table,
and because each of the objects is more complicated than required as they
are capable of holding more complex objects such as buttons.
This lack of speed may require a rewrite of this section.
"""
if self.tableDrawn == False and self.cubeInfoTab.currentIndex() == 2:
QApplication.setOverrideCursor(QtCore.Qt.WaitCursor)
self.statusBar().showMessage('Constructing Data Table')
self.dataViewer.clear()
coord1 = self.selectDimension1.currentText()
coord2 = self.selectDimension2.currentText()
shape = self.plotted_cube.shape
self.dataViewer.setColumnCount(shape[1])
self.dataViewer.setRowCount(shape[0])
headersx = []
headersy = []
for i in range(shape[0]):
headersx.append(str(self.cube.coord(coord1).points[i]))
self.dataViewer.setVerticalHeaderLabels(headersx)
for j in range(shape[1]):
headersy.append(str(self.cube.coord(coord2).points[j]))
self.dataViewer.setHorizontalHeaderLabels(headersy)
for i in range(shape[0]):
for j in range(shape[1]):
exec("lbl{}{} = QtGui.QLabel()".format(i,j))
exec("lbl{}{}.setText(str(self.plotted_cube.data[i,j]))".format(i,j))
exec("self.dataViewer.setCellWidget(i,j,lbl{}{})".format(i,j))
QApplication.restoreOverrideCursor()
self.statusBar().showMessage('Ready')
self.tableDrawn = True
def display(self):
matplotlibwidgetFile.fig = plt.gcf()
self.matplotlibDisplay.canvas.draw()