-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmainWindow.py
1334 lines (1206 loc) · 56 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
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
from PyQt5 import QtWidgets as qWidget
from PyQt5 import QtGui as qGui
from PyQt5 import QtCore as qCore
from PyQt5.QtCore import pyqtSlot
from PyQt5.QtGui import QImage, QPixmap
from pathlib import Path
from PyQt5.QtWidgets import (
QFileDialog,
QCheckBox,
QMessageBox,
QButtonGroup,
QAbstractButton,
QVBoxLayout,
QListWidgetItem,
QAbstractItemView,
QSizePolicy,
)
#from PyQt5.QtWebEngineWidgets import QWebEngineView
from PyQt5.QtCore import QThread
from PyQt5.QtWidgets import QInputDialog, QErrorMessage
qWidget.QApplication.setAttribute(
qCore.Qt.AA_EnableHighDpiScaling, True
) # enable highdpi scaling
qWidget.QApplication.setAttribute(
qCore.Qt.AA_UseHighDpiPixmaps, True
) # use highdpi icons
from PyQt5 import uic, Qt
from PyQt5.QtGui import QColor
from vtk.qt.QVTKRenderWindowInteractor import QVTKRenderWindowInteractor
import sys
import vtk
vtk.vtkObject.GlobalWarningDisplayOff()
import os
import time
import ctypes
import modules.utils as Utils
import modules.gradient as Gd
import matplotlib
import xml.etree.ElementTree as ET
import numpy as np
import vtkplotlib as vpl
# import matplotlib.colorsp
from netCDF4 import Dataset
import netCDF4 as nc
from netCDF4 import num2date, date2num, date2index
# import folium
import io
import xarray as xr
# Pyinstaller exe requirements
# import pkg_resources.py2_warn
import vtkmodules
import vtkmodules.all
import vtkmodules.qt.QVTKRenderWindowInteractor
import vtkmodules.util
import vtkmodules.util.numpy_support
os.environ['__NV_PRIME_RENDER_OFFLOAD'] = '1'
os.environ['__GLX_VENDOR_LIBRARY_NAME'] = 'nvidia'
if os.name == "nt":
import cftime
import cftime._strptime
myappid = "uio.geovis.netcdfvisualizer.100" # arbitrary string
ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(myappid)
class mainWindow(qWidget.QMainWindow):
"""Main window class."""
def __init__(self, *args):
"""Init."""
super(mainWindow, self).__init__(*args)
self.path = None
self.rawTimes = []
self.pa = None
self.cmaps = None
self.cmapFile = os.path.join(os.path.dirname(__file__), "assets/colormaps/colormaps.xml")
self.cmapDefaultFile = os.path.join(os.path.dirname(__file__), "assets/colormaps/colormapsDefault.xml")
self.currentTimeStep = None
self.animationDirection = 1
self.actualTimeStrings = None
self.IsTemporalDataset = False
self.maxTimeSteps = None
self.newMin = None
self.newMax = None
self.newMinContours = None
self.newMaxContours = None
self.dataRange = None
self.varName = None
self.contourVarName = None
self.videoExportFolderName = None
self.contActor = None
#self.update()
# set app icon
app_icon = qGui.QIcon()
app_icon.addFile(os.path.join(os.path.dirname(__file__), "assets/icons/geo.png"), qCore.QSize(80, 80))
self.setWindowIcon(app_icon)
ui = os.path.join(os.path.dirname(__file__), "assets/ui/gui.ui")
uic.loadUi(ui, self)
def setupUI(self):
print("Starting application...")
print("Please note that the application may take some time to start. So please be patient and wait...")
self.pushButton_LoadDataset.clicked.connect(
self.on_buttonClick
) # Attaching button click handler.
self.pushButton_SetDimensions.clicked.connect(
self.on_buttonClick
) # Attaching button click handler.
self.pushButton_PlayReverse.clicked.connect(
self.on_buttonClick
) # Attaching button click handler.
self.pushButton_PreviousFrame.clicked.connect(
self.on_buttonClick
) # Attaching button click handler.
self.pushButton_Pause.clicked.connect(
self.on_buttonClick
) # Attaching button click handler.
self.pushButton_NextFrame.clicked.connect(
self.on_buttonClick
) # Attaching button click handler.
self.pushButton_PlayForward.clicked.connect(
self.on_buttonClick
) # Attaching button click handler.
self.pushButton_UpdateRange.clicked.connect(
self.on_buttonClick
) # Attaching button click handler.
self.pushButton_ResetRange.clicked.connect(
self.on_buttonClick
) # Attaching button click handler.
self.pushButton_ExportImage.clicked.connect(
self.on_buttonClick
) # Attaching button click handler.
self.pushButton_ExportVideo.clicked.connect(
self.on_buttonClick
) # Attaching button click handler.
self.pushButton_SaveColorMap.clicked.connect(
self.on_buttonClick
) # Attaching button click handler.
self.pushButton_RemoveColormap.clicked.connect(
self.on_buttonClick
) # Attaching button click handler.
self.pushButton_RestoreDefaultColormaps.clicked.connect(
self.on_buttonClick
) # Attaching button click handler.
self.pushButton_Export3DModel.clicked.connect(
self.on_buttonClick
) # Attaching button click handler.
self.dial_videoQuality.valueChanged.connect(self.on_videoQualityUpdate)
self.dial_videoFrameRate.valueChanged.connect(self.on_frameRateUpdate)
self.comboBox_dims.currentTextChanged.connect(
self.on_comboboxDims_changed
) # Changed dimensions handler.
# View radio buttons
self.radioButton_RawView.toggled.connect(self.changeView)
# self.radioButton_2DView.toggled.connect(self.changeView)
self.radioButton_3DView.toggled.connect(self.changeView)
# Variable list double click
self.listWidget_Variables.doubleClicked.connect(self.applyVariable)
#self.listWidget_Variables.setSelectionMode(QAbstractItemView.NoSelection)
#self.listWidget_Variables.setSelectionMode(QAbstractItemView.NoSelection)
# time slider
self.horizontalSlider_Main.valueChanged.connect(self.on_timeSlider_Changed)
# Contour thickness updated
self.spinBox_ContourThickness.valueChanged.connect(self.on_contourThicknessUpdated)
# Log scale
self.checkBox_LogScale.stateChanged.connect(self.on_scaleChanged)
self.progbar()
# View mode radio buttons
self.radioButton_ColorMode.toggled.connect(self.on_colorModeSelected)
self.radioButton_ContourMode.toggled.connect(self.on_contourModeSelected)
self.myLongTask = TaskThread(
self, isRefresh=True
) # initializing and passing data to QThread
self.myLongTask.taskFinished.connect(
self.onFinished
) # this won't be read until QThread send a signal i think
self.myDimensionUpdateTask = TaskThread(
self, isRefresh=False
) # initializing and passing data to QThread
self.myDimensionUpdateTask.taskFinished.connect(
self.onFinished
) # this won't be read until QThread send a signal i think
# self.videoExportTask = Utils.VideoTaskThread(self)
# self.videoExportTask.taskFinished.connect(self.onFinishedVideoExport)
logoImagePath = os.path.join(os.path.dirname(__file__), "assets/ui/logo.png")
self.label_8.setStyleSheet("border-image: url(" + logoImagePath + ") 0 0 0 0 stretch stretch;border-radius: 0px;")
self.horizontalSlider_Main.setVisible(False)
self.initializeApp()
self.initializeRenderer()
@pyqtSlot()
def on_contourThicknessUpdated(self):
if(self.varName != None and self.radioButton_ContourMode.isChecked()):
Utils.loadContours(self, self.varName)
@pyqtSlot()
def on_colorModeSelected(self):
if self.radioButton_ColorMode.isChecked():
self.gradientContours.setVisible(False)
self.gradient.setVisible(True)
if(self.varName != None):
items = self.listWidget_Variables.findItems(self.varName, qCore.Qt.MatchExactly)
item = items[0]
item.setSelected(True)
if self.contActor != None:
self.ren.RemoveActor(self.contActor)
self.iren.Render()
@pyqtSlot()
def on_contourModeSelected(self):
if self.radioButton_ContourMode.isChecked():
if(self.newMinContours != None):
self.gradientContours.setVisible(True)
self.gradient.setVisible(True)
if(self.contourVarName != None):
items = self.listWidget_Variables.findItems(self.contourVarName, qCore.Qt.MatchExactly)
item = items[0]
item.setSelected(True)
if self.contActor != None:
self.ren.AddActor(self.contActor)
self.iren.Render()
#self.applyVariable(False) # commented as part of bug fix
else:
self.listWidget_Variables.clearSelection()
@pyqtSlot()
def on_videoQualityUpdate(self):
dialValue = self.dial_videoQuality.value()
self.label_videoQuality.setText(str(dialValue))
@pyqtSlot()
def on_frameRateUpdate(self):
dialValue = self.dial_videoFrameRate.value()
self.label_frameRate.setText(str(dialValue))
@pyqtSlot()
def on_scaleChanged(self):
if self.checkBox_LogScale.isChecked() == True:
self.ctf.SetScaleToLog10()
else:
self.ctf.SetScaleToLinear()
self.ctf.Build()
self.mapper.SetLookupTable(self.ctf)
self.mapper.Update()
self.iren.Render()
@pyqtSlot()
def applyVariable(self, refreshVariable = True):
if(refreshVariable == True and self.radioButton_ColorMode.isChecked()): # if color mode
self.varName = self.listWidget_Variables.currentItem().text()
self.label_color_varname.setText(self.varName)
if self.radioButton_ContourMode.isChecked(): # if contour mode
self.contourVarName = self.listWidget_Variables.currentItem().text()
self.label_contour_varname.setText(self.contourVarName)
# currentItemIndex = self.listWidget_Variables.indexFromItem(self.listWidget_Variables.currentItem()).row()
# for index in range(self.listWidget_Variables.count()):
# item = self.listWidget_Variables.item(index)
# print(currentItemIndex, index)
# if(currentItemIndex==index):
# self.listWidget_Variables.item(index).setBackground((QColor(138, 157, 191)))
# else:
# self.listWidget_Variables.item(index).setBackground((QColor(52, 59, 72)))
self.fmt = qGui.QTextCharFormat()
self.cursor = qGui.QTextCursor(self.plainTextEdit_netCDFDataText.document())
self.cursor.select(qGui.QTextCursor.Document)
self.cursor.setCharFormat(qGui.QTextCharFormat()) # Clear existing selections
self.cursor.clearSelection()
pattern = "Name:" + str(self.varName)
regex = qCore.QRegExp(pattern)
pos = 0
index = regex.indexIn(
self.plainTextEdit_netCDFDataText.document().toPlainText(), pos
)
if index != -1:
self.cursor.setPosition(index, qGui.QTextCursor.MoveAnchor)
self.cursor.setPosition(index + len(pattern), qGui.QTextCursor.KeepAnchor)
self.plainTextEdit_netCDFDataText.ensureCursorVisible()
self.cursor.setCharFormat(self.fmt)
self.plainTextEdit_netCDFDataText.setTextCursor(self.cursor)
self.plainTextEdit_netCDFDataText.textCursor().clearSelection()
if self.radioButton_3DView.isChecked() == True:
Utils.variableControlsSetVisible(self, True)
if self.radioButton_ColorMode.isChecked(): # If color mode is selected
Utils.updateGlobeGeometry(self, self.varName)
if(refreshVariable):
self.dataRange = self.mapper.GetInput().GetCellData().GetScalars(self.varName).GetRange()
self.newMin = self.dataRange[0]
self.newMax = self.dataRange[1]
self.gradient.update()
if self.radioButton_ContourMode.isChecked(): # If contour mode is selected
# self.colorGradientsBackup = self.gradient.gradient()
# self.contourGradients = [(0.0, QColor(52, 59, 72)), (0.5, QColor(52, 59, 72)), (1.0, QColor(52, 59, 72))]
# self.gradient.setGradient(self.contourGradients)
# print(self.colorGradientsBackup)
self.dataRangeContours = self.mapper.GetInput().GetCellData().GetScalars(self.contourVarName).GetRange()
self.newMinContours = self.dataRangeContours[0]
self.newMaxContours = self.dataRangeContours[1]
Utils.loadContours(self, self.contourVarName)
self.gradientContours.update()
if(self.gradientContours.isVisible() == False):
self.gradientContours.setVisible(True)
@pyqtSlot()
def changeView(self):
rbtn = self.sender()
if rbtn.isChecked() == True:
if rbtn.text() == "Metadata":
Utils.variableControlsSetVisible(self, False)
self.stackedWidget.setCurrentWidget(self.page_InspectData)
self.stackedWidget.update()
self.stackedWidget.repaint()
############################
# 2D Render View (# Not going to be implemented.)
############################
# if (rbtn.text() == "2D"): # Not going to be implemented.
# self.stackedWidget.setCurrentWidget(self.page_2DMap)
# layout = QVBoxLayout()
# self.frame_2D.setLayout(layout)
# coordinate = (37.8199286, -122.4782551)
# m = folium.Map(
# tiles='cartodbpositron',
# zoom_start=13,
# location=coordinate, zoom_control=False
# )
## save map data to data object
# data = io.BytesIO()
# m.save(data, close_file=False)
## Enable the following two lines when 2D maps are required.
##self.webView.setHtml(data.getvalue().decode())
##layout.addWidget(self.webView)
############################
# 3D Render View
############################
if rbtn.text() == "3D":
if self.varName != None:
Utils.variableControlsSetVisible(self, True)
self.stackedWidget.setCurrentWidget(self.page_3DMap)
self.stackedWidget.update()
self.stackedWidget.repaint()
@pyqtSlot()
def on_timeSlider_Changed(self):
self.currentTimeStep = self.horizontalSlider_Main.value()
if self.IsTemporalDataset == True:
self.textActor.SetInput(str(self.actualTimeStrings[self.currentTimeStep]))
self.reader.GetOutputInformation(0).Set(
vtk.vtkStreamingDemandDrivenPipeline.UPDATE_TIME_STEP(),
self.rawTimes[self.currentTimeStep - 1],
)
self.pa.AddArray(
1, self.varName
) # 0 for PointData, 1 for CellData, 2 for FieldData
self.pa.Update()
self.mapper.GetInput().GetCellData().AddArray(
self.pa.GetOutput().GetCellData().GetAbstractArray(self.varName)
)
# self.mapper.GetInput().GetCellData().AddArray(self.pa.GetOutput().GetCellData().GetArray(0))
self.label_FrameStatus.setText(
str(self.currentTimeStep) + "/" + str(self.maxTimeSteps)
)
if self.radioButton_ContourMode.isChecked():
Utils.loadContours(self, self.contourVarName)
else:
if self.contActor != None:
self.ren.RemoveActor(self.contActor)
self.iren.Render()
@pyqtSlot()
def on_comboboxDims_changed(self):
selectedDimension = str(self.comboBox_dims.currentText())
# self.reader.ComputeArraySelection()
# self.reader.SetDimensions(selectedDimension)
dimNames = self.reader.GetVariableDimensions()
varNames = self.reader.GetAllVariableArrayNames()
dimNamesList = []
varNamesList = []
for i in range(dimNames.GetNumberOfValues()):
dimNamesList.append(str(dimNames.GetValue(i)))
for i in range(varNames.GetNumberOfValues()):
varNamesList.append(str(varNames.GetValue(i)))
index_pos_list = [
i for i in range(len(dimNamesList)) if dimNamesList[i] == selectedDimension
]
visVarList = [] # Variables of interest
for indexLocation in index_pos_list:
visVarList.append(self.reader.GetVariableArrayName(indexLocation))
# Update variable list
self.listWidget_Variables.clear()
for i in range(len(visVarList)):
item = QListWidgetItem(str(visVarList[i]))
# item.setFlags(item.flags() | qCore.Qt.ItemIsUserCheckable)
# item.setCheckState(qCore.Qt.Unchecked)
self.listWidget_Variables.addItem(item)
@pyqtSlot()
def comboBox_ColorMaps_changed(self):
if(self.tabWidget.currentWidget().objectName() == "Settings"): # Do not update when user in settings page.
return
for cmapItem in self.cmaps:
if cmapItem["name"] == str(self.comboBox_ColorMaps.currentText()):
color1List = [int(x) for x in cmapItem["color1"].split(",")]
color2List = [int(x) for x in cmapItem["color2"].split(",")]
gradientList = []
cstart = (
0,
QColor(color1List[0], color1List[1], color1List[2], color1List[3]),
)
cend = (
1,
QColor(color2List[0], color2List[1], color2List[2], color2List[3]),
)
stops = cmapItem["stops"].split(":")
gradientList.append(cstart)
for item in stops:
stopData = item.split(";")
stop = float(stopData[0])
cvalues = [int(x) for x in stopData[1].split(",")]
gradientList.append(
(stop, QColor(cvalues[0], cvalues[1], cvalues[2], cvalues[3]))
)
gradientList.append(cend)
self.gradient.setGradient(gradientList)
self.gradient.update()
break
@pyqtSlot()
def updateLUT(self):
# print("updating lut")
gradients = self.gradient.gradient()
stops = [data[0] for data in gradients]
oldMin = 0
oldMax = 1
newRange = self.newMax - self.newMin
self.ctf.RemoveAllPoints()
for gradient in gradients:
# print(type(gradient[1]))
oldValue = float(gradient[0])
newValue = ((oldValue - oldMin) * newRange) + self.newMin
if isinstance(gradient[1], str) == True:
rgb = matplotlib.colors.to_rgb(gradient[1])
self.ctf.AddRGBPoint(newValue, rgb[0], rgb[1], rgb[2])
else:
self.ctf.AddRGBPoint(
newValue,
gradient[1].redF(),
gradient[1].greenF(),
gradient[1].blueF(),
)
self.ctf.Build()
self.mapper.Update()
self.iren.Render()
# Handler for browse folder button click.
@pyqtSlot()
def initializeRenderer(self):
self.vl = Qt.QVBoxLayout()
self.vl.setContentsMargins(0,0,0,0)
self.vtkWidget = QVTKRenderWindowInteractor(self.frame)
self.vl.addWidget(self.vtkWidget)
self.frame.setLayout(self.vl)
self.ren = vtk.vtkRenderer()
self.ren.SetBackground(33 / 255.0, 37.0 / 255, 43.0 / 255)
self.vtkWidget.GetRenderWindow().AddRenderer(self.ren)
# self.vtkWidget.GetRenderWindow().SetMultiSamples(4)
self.iren = self.vtkWidget.GetRenderWindow().GetInteractor()
self.actor_style = vtk.vtkInteractorStyleTrackballCamera()
self.iren.SetInteractorStyle(self.actor_style)
#self.iren.SetRenderWindow(self.vtkWidget.GetRenderWindow())
# self.ren.UseFXAAOn()
self.iren.Initialize()
self.ren.ResetCamera()
# Get the generic render window ID
#gl_info = self.vtkWidget.GetRenderWindow().GetOpenGLInformation()
openglRendererInUse = self.ren.GetRenderWindow().ReportCapabilities().splitlines()[1].split(":")[1].strip()
# Print the active graphics card info
self.label_6.setText("Current Graphics Vendor:" + "\n" + str(openglRendererInUse))
# Sign up to receive TimerEvent
# cb = vtkTimerCallback(1, self.iren)
# self.iren.AddObserver('TimerEvent', cb.execute)
# cb.timerId = self.iren.CreateRepeatingTimer(500)
#self.iren.Render()
#self.ren.Render()
self.timer = qCore.QTimer()
self.timer.timeout.connect(self.onTimerEvent)
# self.timer.start(100)
self.contourFilter = vtk.vtkContourFilter()
# web view
# self.webView = QWebEngineView()
#print("Renderer Initialized.")
def onTimerEvent(self):
if (
self.stackedWidget.currentWidget().objectName() == "page_3DMap"
or self.stackedWidget.currentWidget().objectName() == "page_2DMap"
):
if self.animationDirection == -1:
if self.currentTimeStep > 1:
self.currentTimeStep = self.currentTimeStep - 1
else:
self.currentTimeStep = self.maxTimeSteps
else:
if self.currentTimeStep < self.maxTimeSteps:
self.currentTimeStep = self.currentTimeStep + 1
else:
self.currentTimeStep = 1
self.reader.GetOutputInformation(0).Set(
vtk.vtkStreamingDemandDrivenPipeline.UPDATE_TIME_STEP(),
self.rawTimes[self.currentTimeStep - 1],
)
self.pa.AddArray(
1, self.varName
) # 0 for PointData, 1 for CellData, 2 for FieldData
self.pa.Update()
if self.IsTemporalDataset == True:
self.textActor.SetInput(
str(self.actualTimeStrings[self.currentTimeStep - 1])
)
self.mapper.GetInput().GetCellData().AddArray(
self.pa.GetOutput().GetCellData().GetAbstractArray(self.varName)
)
# self.mapper.GetInput().GetCellData().AddArray(self.pa.GetOutput().GetCellData().GetArray(0))
self.label_FrameStatus.setText(
str(self.currentTimeStep) + "/" + str(self.maxTimeSteps)
)
if self.radioButton_ContourMode.isChecked():
Utils.loadContours(self, self.contourVarName)
else:
if self.contActor != None:
self.ren.RemoveActor(self.contActor)
self.iren.Render()
def closeEvent(self, QCloseEvent):
super().closeEvent(QCloseEvent)
self.vtkWidget.Finalize()
def initializeApp(self):
self.pa = vtk.vtkPassArrays()
self.gradient = Gd.Gradient("color", self)
self.gradient.setGradient([(0, "black"), (1, "green"), (0.5, "red")])
self.gradientContours = Gd.Gradient("contour", self)
self.gradientContours.setGradient(
[
(0, QColor(52, 59, 72)),
(1, QColor(52, 59, 72)),
(0.5, QColor(52, 59, 72)),
]
)
self.gradient.setFixedHeight(35)
self.gradientContours.setFixedHeight(35)
self.layout = QVBoxLayout()
self.layout.addWidget(self.gradient, qCore.Qt.AlignCenter)
self.layout.addWidget(self.gradientContours, qCore.Qt.AlignCenter)
self.gradientContours.setVisible(False)
self.frame_colormap.setLayout(self.layout)
# Read color map information.
self.cmaps = Utils.readColorMapInfo(self, self.cmapFile)
for item in self.cmaps:
self.comboBox_ColorMaps.addItem(item["name"])
self.comboBox_ColorMapsSettings.addItem(item["name"])
color1List = [int(x) for x in self.cmaps[0]["color1"].split(",")]
color2List = [int(x) for x in self.cmaps[0]["color2"].split(",")]
gradientList = []
cstart = (0, QColor(color1List[0], color1List[1], color1List[2], color1List[3]))
cend = (1, QColor(color2List[0], color2List[1], color2List[2], color2List[3]))
stops = self.cmaps[0]["stops"].split(":")
gradientList.append(cstart)
for item in stops:
stopData = item.split(";")
stop = float(stopData[0])
cvalues = [int(x) for x in stopData[1].split(",")]
gradientList.append(
(stop, QColor(cvalues[0], cvalues[1], cvalues[2], cvalues[3]))
)
gradientList.append(cend)
self.gradient.setGradient(gradientList)
self.comboBox_ColorMaps.currentTextChanged.connect(
self.comboBox_ColorMaps_changed
) # Changed dimensions handler.
self.gradient.gradientChanged.connect(self.colorMapChanged)
self.gradientContours.gradientChanged.connect(self.contourValuesChanged)
self.progressBar_ExportVideo.setVisible(False)
# Disable all data controls when mainwindow loads.
self.tabWidget.setVisible(False)
Utils.controlsSetVisible(self, False)
# Contour values changed.
def contourValuesChanged(self):
Utils.loadContours(self, self.contourVarName)
# Visualization color map changed.
def colorMapChanged(self):
self.updateLUT()
# Reset UI state when loading dataset.
def resetUI(self):
pass
def progbar(self):
self.layout = QVBoxLayout()
self.prog_win = qWidget.QDialog()
self.prog_win.resize(500, 300)
self.prog_win.setModal(True)
self.prog_win.setWindowFlags(qCore.Qt.FramelessWindowHint)
self.prog_win.setFixedSize(self.prog_win.size())
self.prog_win.setWindowTitle("Processing request")
stylesheet = "border: 2px solid rgb(52, 59, 72);border-radius: 5px; background-color: rgb(52, 59, 72);color:rgb(175, 199, 242);"
self.prog_win.setStyleSheet(stylesheet)
self.lbl = qWidget.QLabel(self.prog_win)
self.lbl.setAlignment(qCore.Qt.AlignCenter)
self.lbl.setStyleSheet("font: 12pt Arial;")
self.lbl.setText("Processing data... Please wait...")
# self.lbl.move(15,18)
self.progressBar = qWidget.QProgressBar(self.prog_win)
# self.progressBar.resize(410, 25)
self.progressBar.setMaximum(0)
self.progressBar.setMinimum(0)
self.progressBar.setMaximumHeight(15)
self.progressBar.setStyleSheet(
"background-color: rgb(90, 102, 125); border-radius: 2px;"
)
# self.progressBar.move(15, 40)
self.layout.addWidget(self.lbl, qCore.Qt.AlignCenter)
self.layout.addWidget(self.progressBar, qCore.Qt.AlignCenter)
# widget = QWidget()
self.prog_win.setLayout(self.layout)
# self.setCentralWidget(self.prog_win)
# self.progressBar.setRange(0,1)
def onStart(self, reload=True):
# self.progressBar.setRange(0,0)
if reload == True:
self.myLongTask.start()
else:
self.myDimensionUpdateTask.start()
# added this function to close the progress bar
# def onFinishedVideoExport(self):
# self.prog_win.close()
# added this function to close the progress bar
def onFinished(self):
# self.progressBar.setRange(0,1)
self.prog_win.close()
for item in self.dataDimensions:
self.comboBox_dims.addItem(item)
self.plainTextEdit_netCDFDataText.setPlainText(self.str_data)
if self.rawTimes != None: # valid time points available.
self.maxTimeSteps = len(self.rawTimes)
self.label_FrameStatus.setText("1/" + str(self.maxTimeSteps))
self.horizontalSlider_Main.setMaximum(self.maxTimeSteps - 1)
self.horizontalSlider_Main.setEnabled(True)
self.IsTemporalDataset = True
else: # no time points available
self.maxTimeSteps = 1
self.horizontalSlider_Main.setEnabled(False)
self.label_FrameStatus.setText("1/1")
self.IsTemporalDataset = False
self.currentTimeStep = 1
# self.stackedWidget.setCurrentWidget(self.page_InspectData)
# Enable all data controls
self.tabWidget.setVisible(True)
Utils.controlsSetVisible(self, True)
# Handler for browse folder button click.
@pyqtSlot()
def on_buttonClick(self):
btn = self.sender()
btnName = btn.objectName()
###########################
# Browse NetCDF data button
############################
if btnName == "pushButton_LoadDataset":
path = QFileDialog.getOpenFileName(
self, "Open a file", "", "NetCDF files (*.nc)"
)
if path != ("", ""):
# Stop play threads if running
if self.timer.isActive() == True:
self.timer.stop()
self.radioButton_RawView.setChecked(True)
self.path = path[0]
self.comboBox_dims.clear() # clear dim var combobox
self.listWidget_Variables.clear() # clear variable list.
self.gradientContours.setVisible(False) # hide contour widget.
self.currentTimeStep = None
self.animationDirection = 1
self.actualTimeStrings = None
self.varName = None
self.contourVarName = None
self.IsTemporalDataset = False
self.maxTimeSteps = None
self.newMin = None
self.newMax = None
self.newMinContours = None
self.newMaxContours = None
self.dataRange = None
self.contActor = None
self.radioButton_ColorMode.blockSignals(True)
self.radioButton_ColorMode.setChecked(True)
self.radioButton_ColorMode.blockSignals(False)
#if(self.ren!=None):
# self.ren.RemoveAllViewProps()
self.label_color_varname.setText("")
self.label_contour_varname.setText("")
self.prog_win.show()
self.onStart() # Start your very very long computation/process
############################
# Apply selected variables.
############################
if btnName == "pushButton_SetDimensions":
# print("need to something here to regrid the data based on selected dimensions.")
# print("Setting dimensions to ", self.comboBox_dims.currentText())
# Stop play threads if running
if self.timer.isActive() == True:
self.timer.stop()
self.comboBox_dims.clear()
self.listWidget_Variables.clearSelection()
self.reader.SetDimensions(self.comboBox_dims.currentText())
self.reader.ComputeArraySelection()
self.radioButton_RawView.setChecked(True)
self.prog_win.show()
self.onStart(False) # Start your very very long computation/process
# Utils.loadGlobeGeometry(self)
# self.reader.Update()disc
# self.mapper.Update()
# self.reader.Update()
# print("NUmber of var array is ", self.reader.GetNumberOfVariableArrays())
# print(selectedDimension)
# selectedVariables = []
# #print("count is", self.listWidget_Variables.count())
# for index in range(self.listWidget_Variables.count()):
# if(self.listWidget_Variables.item(index).isSelected() == True):
# selectedVariables.append(self.listWidget_Variables.item(index).text())
# #print(selectedVariables)
# # Update vis params list
# self.listWidget_VisParams.clear()
# for i in range(len(selectedVariables)):
# item = QListWidgetItem(str(selectedVariables[i]))
# #item.setFlags(item.flags() | qCore.Qt.ItemIsUserCheckable)
# #item.setCheckState(qCore.Qt.Unchecked)
# self.listWidget_VisParams.addItem(item)
#
# self.tabWidget.setCurrentIndex(1)
# self.stackedWidget.setCurrentWidget(self.page_3DMap)
############################
# Play Reverse
############################
if btnName == "pushButton_PlayReverse":
if self.maxTimeSteps != 1:
self.animationDirection = -1
if self.timer.isActive() == False:
self.timer.start()
############################
# Previous Frame
############################
if btnName == "pushButton_PreviousFrame":
if self.maxTimeSteps == 1:
return
if (
self.stackedWidget.currentWidget().objectName() == "page_3DMap"
or self.stackedWidget.currentWidget().objectName() == "page_2DMap"
):
if self.currentTimeStep > 1:
self.currentTimeStep = self.currentTimeStep - 1
else:
self.currentTimeStep = self.maxTimeSteps
self.reader.GetOutputInformation(0).Set(
vtk.vtkStreamingDemandDrivenPipeline.UPDATE_TIME_STEP(),
self.rawTimes[self.currentTimeStep - 1],
)
if self.IsTemporalDataset == True:
self.textActor.SetInput(
str(self.actualTimeStrings[self.currentTimeStep - 1])
)
self.pa.AddArray(
1, self.varName
) # 0 for PointData, 1 for CellData, 2 for FieldData
self.pa.Update()
self.mapper.GetInput().GetCellData().AddArray(
self.pa.GetOutput().GetCellData().GetAbstractArray(self.varName)
)
# self.mapper.GetInput().GetCellData().AddArray(self.pa.GetOutput().GetCellData().GetArray(0))
self.label_FrameStatus.setText(
str(self.currentTimeStep) + "/" + str(self.maxTimeSteps)
)
if self.radioButton_ContourMode.isChecked():
Utils.loadContours(self, self.contourVarName)
else:
if self.contActor != None:
self.ren.RemoveActor(self.contActor)
self.iren.Render()
############################
# Pause
############################
if btnName == "pushButton_Pause":
# print("pause playback")
self.timer.stop()
############################
# Next frame
############################
if btnName == "pushButton_NextFrame":
if self.maxTimeSteps == 1:
return
if (
self.stackedWidget.currentWidget().objectName() == "page_3DMap"
or self.stackedWidget.currentWidget().objectName() == "page_2DMap"
):
if self.currentTimeStep < self.maxTimeSteps:
self.currentTimeStep = self.currentTimeStep + 1
else:
self.currentTimeStep = 1
self.reader.GetOutputInformation(0).Set(
vtk.vtkStreamingDemandDrivenPipeline.UPDATE_TIME_STEP(),
self.rawTimes[self.currentTimeStep - 1],
)
self.pa.AddArray(
1, self.varName
) # 0 for PointData, 1 for CellData, 2 for FieldData
self.pa.Update()
if self.IsTemporalDataset == True:
self.textActor.SetInput(
str(self.actualTimeStrings[self.currentTimeStep - 1])
)
self.mapper.GetInput().GetCellData().AddArray(
self.pa.GetOutput().GetCellData().GetAbstractArray(self.varName)
)
# self.mapper.GetInput().GetCellData().AddArray(self.pa.GetOutput().GetCellData().GetArray(0))
self.mapper.GetInput().GetCellData().SetActiveScalars(self.varName)
self.label_FrameStatus.setText(
str(self.currentTimeStep) + "/" + str(self.maxTimeSteps)
)
if self.radioButton_ContourMode.isChecked():
Utils.loadContours(self, self.contourVarName)
else:
if self.contActor != None:
self.ren.RemoveActor(self.contActor)
# self.mapper.Update()
self.iren.Render()
############################
# Play forward
############################
if btnName == "pushButton_PlayForward":
if self.maxTimeSteps != 1:
self.animationDirection = 1
if self.timer.isActive() == False:
self.timer.start()
############################
# Set New Scalar Range
############################
if btnName == "pushButton_UpdateRange":
if self.radioButton_ColorMode.isChecked():
if self.varName == None:
return
else:
if(self.contourVarName == None):
return
inputDialog = QInputDialog(None)
inputDialog.setInputMode(QInputDialog.TextInput)
inputDialog.setLabelText('Please enter the start value:')
Utils.applyTheme(inputDialog)
inputDialog.setWindowFlags(qCore.Qt.FramelessWindowHint)
ok = inputDialog.exec_()
if not ok:
return
text_start = inputDialog.textValue()
if (
isinstance(text_start, int) == True
or isinstance(text_start, float) == True
):
em = QErrorMessage(self)
em.showMessage("Unable to set the range. Please check your data.")
return
inputDialog = QInputDialog(None)
inputDialog.setInputMode(QInputDialog.TextInput)
inputDialog.setLabelText('Please enter the end value:')
Utils.applyTheme(inputDialog)
inputDialog.setWindowFlags(qCore.Qt.FramelessWindowHint)
ok = inputDialog.exec_()
if not ok:
return
text_end = inputDialog.textValue()
if (
isinstance(text_end, int) == True or isinstance(text_end, float) == True
): # if not a numberupdate_scene_for_new_range
em = QErrorMessage(self)
em.showMessage("Unable to set the range. Please check your data.")
return
self.update_scene_for_new_range(text_start, text_end)
self.gradient.update()
############################
# Reset variable scalar range to default.
############################
if btnName == "pushButton_ResetRange":
if self.radioButton_ColorMode.isChecked():
if self.varName == None:
return
else:
if(self.contourVarName == None):
return
self.update_scene_for_new_range()
if self.radioButton_ColorMode.isChecked():
self.gradient.update()
if self.radioButton_ContourMode.isChecked():
self.gradientContours.update()
Utils.loadContours(self, self.contourVarName)
############################
# Export image.
############################
if btnName == "pushButton_ExportImage":
if self.varName == None:
dlg = QMessageBox(self)
dlg.setWindowTitle("No variable selected!")
Utils.applyTheme(dlg)
dlg.setText(
"No variable has been selected. Please select a variable first for using export feature."
)
dlg.exec()
return
Utils.exportImage(self)
############################
# Export video.
############################
if btnName == "pushButton_ExportVideo":
if self.varName == None:
dlg = QMessageBox(self)
dlg.setWindowTitle("No variable selected!")
Utils.applyTheme(dlg)
dlg.setText(
"No variable has been selected. Please select a variable first for using export feature."
)
dlg.exec()
return
if self.IsTemporalDataset == False:
dlg = QMessageBox(self)
dlg.setWindowTitle("Cannot export as video.")