def setupUi(self, MainWindow, renWinList):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(501, 596)
        self.centralwidget = QtGui.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.gridLayout = QtGui.QGridLayout(self.centralwidget)
        self.gridLayout.setObjectName("gridLayout")
        self.splitter = QtGui.QSplitter(self.centralwidget)
        self.splitter.setOrientation(QtCore.Qt.Vertical)
        self.splitter.setObjectName("splitter")
        self.qvtkWidget_1 = QVTKRenderWindowInteractor(self.splitter, rw=renWinList[1])
        self.qvtkWidget_1.setObjectName("qvtkWidget_1")
        self.qvtkWidget_0 = QVTKRenderWindowInteractor(self.splitter, rw=renWinList[0])
        self.qvtkWidget_0.setObjectName("qvtkWidget_0")
        self.gridLayout.addWidget(self.splitter, 0, 0, 1, 1)
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtGui.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 501, 22))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtGui.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)
        self.actionExit = QtGui.QAction(MainWindow)
        self.actionExit.setObjectName("actionExit")

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)
Exemple #2
0
class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName(_fromUtf8("MainWindow"))
        MainWindow.resize(800, 600)
        self.centralwidget = QtGui.QWidget(MainWindow)
        self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
        self.pushButton = QtGui.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(10, 230, 121, 41))
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(_fromUtf8(":/rc/Resource/Science.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.pushButton.setIcon(icon)
        self.pushButton.setObjectName(_fromUtf8("pushButton"))
        self.vtkWidget = QVTKRenderWindowInteractor(self.centralwidget)
        self.vtkWidget.setGeometry(QtCore.QRect(200, 100, 521, 391))
        self.vtkWidget.setObjectName(_fromUtf8("widget"))
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtGui.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 23))
        self.menubar.setObjectName(_fromUtf8("menubar"))
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtGui.QStatusBar(MainWindow)
        self.statusbar.setObjectName(_fromUtf8("statusbar"))
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
        self.pushButton.setText(_translate("MainWindow", "PushButton", None))
Exemple #3
0
    def __init__(self, parent):
        QVTKRenderWindowInteractor.__init__(self, parent)

        self.renderer = vtk.vtkRenderer()
        self.GetRenderWindow().AddRenderer(self.renderer)
        
        interactor = vtk.vtkInteractorStyleSwitch()
        self._Iren.SetInteractorStyle(interactor)
                
        self.surface = None

        # Remainng calls set up axes.
        tprop = vtk.vtkTextProperty()
        tprop.SetColor(1,1,1)

        # Create a faint outline to go with the axes.
        self.outline = vtk.vtkOutlineFilter()

        # Initially set up with a box as input.  This will be changed
        # to a plot once the user clicks something.
        self.box = vtk.vtkBox()
        self.box.SetBounds(0,10,0,10,0,10)
        sample = vtk.vtkSampleFunction()
        sample.SetImplicitFunction(self.box)
        sample.SetSampleDimensions(2,2,2)
        sample.SetModelBounds(0,10,0,10,0,5)
        sample.ComputeNormalsOff()

        self.outline.SetInputConnection(sample.GetOutputPort())
        mapOutline = vtk.vtkPolyDataMapper()
        mapOutline.SetInputConnection(self.outline.GetOutputPort())
        self.outlineActor = vtk.vtkActor()
        self.outlineActor.SetMapper(mapOutline)
        self.outlineActor.GetProperty().SetColor(1,1,1)
        self.outlineActor.GetProperty().SetOpacity(.25)
        self.renderer.AddActor(self.outlineActor)

        self.axes = vtk.vtkCubeAxesActor2D()
        self.axes.SetCamera(self.renderer.GetActiveCamera())
        self.axes.SetFlyModeToOuterEdges()

        self.axes.SetLabelFormat("%6.4g")
        self.axes.SetFontFactor(0.8)
        self.axes.SetAxisTitleTextProperty(tprop)
        self.axes.SetAxisLabelTextProperty(tprop)
        self.axes.SetXLabel("MPI Rank")
        self.axes.SetYLabel("Progress")
        self.axes.SetZLabel("Effort")
        self.axes.SetInput(sample.GetOutput())
        self.renderer.AddViewProp(self.axes)

        # Keep original camera around in case it gets changed
        self.originalCamera = self.renderer.GetActiveCamera()

        self.renderer.GetActiveCamera().Pitch(90)     # Want effort to be vertical
        self.renderer.GetActiveCamera().OrthogonalizeViewUp()
        self.renderer.ResetCamera()
        self.renderer.GetActiveCamera().Elevation(15)  # Be slightly above the data
class Ui_MainWindow(object):
	def setupUi(self, MainWindow, renWin):
		MainWindow.setObjectName(_fromUtf8("MainWindow"))
		MainWindow.resize(400, 450)
		self.centralwidget = QtGui.QWidget(MainWindow)
		self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
		self.verticalLayout = QtGui.QVBoxLayout(self.centralwidget)
		self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
		self.vtkWidget = QVTKRenderWindowInteractor(self.centralwidget, rw=renWin)
		self.vtkWidget.setObjectName(_fromUtf8("vtkWidget"))
		self.verticalLayout.addWidget(self.vtkWidget)
		self.horizontalSlider = QtGui.QSlider(self.centralwidget)
		self.horizontalSlider.setMinimum(0)
		self.horizontalSlider.setOrientation(QtCore.Qt.Horizontal)
		self.horizontalSlider.setObjectName(_fromUtf8("horizontalSlider"))
		self.verticalLayout.addWidget(self.horizontalSlider)
		self.horizontalLayout = QtGui.QHBoxLayout()
		self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
		self.label = QtGui.QLabel(self.centralwidget)
		self.label.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
		self.label.setObjectName(_fromUtf8("label"))
		self.horizontalLayout.addWidget(self.label)
		self.comboBox = QtGui.QComboBox(self.centralwidget)
		self.comboBox.setObjectName(_fromUtf8("comboBox"))
		self.comboBox.addItem(_fromUtf8(""))
		self.comboBox.addItem(_fromUtf8(""))
		self.comboBox.addItem(_fromUtf8(""))
		self.horizontalLayout.addWidget(self.comboBox)
		self.verticalLayout.addLayout(self.horizontalLayout)

		MainWindow.setCentralWidget(self.centralwidget)
		self.menubar = QtGui.QMenuBar(MainWindow)
		self.menubar.setGeometry(QtCore.QRect(0, 0, 1100, 22))
		self.menubar.setObjectName(_fromUtf8("menubar"))
		self.menuFile = QtGui.QMenu(self.menubar)
		self.menuFile.setObjectName(_fromUtf8("menuFile"))
		MainWindow.setMenuBar(self.menubar)
		self.statusbar = QtGui.QStatusBar(MainWindow)
		self.statusbar.setObjectName(_fromUtf8("statusbar"))
		MainWindow.setStatusBar(self.statusbar)
		self.actionOpen = QtGui.QAction(MainWindow)
		self.actionOpen.setObjectName(_fromUtf8("actionOpen"))
		self.actionExit = QtGui.QAction(MainWindow)
		self.actionExit.setObjectName(_fromUtf8("actionExit"))
		self.menuFile.addAction(self.actionOpen)
		self.menuFile.addAction(self.actionExit)
		self.menubar.addAction(self.menuFile.menuAction())

		MainWindow.setWindowTitle(QtGui.QApplication.translate("MainWindow", "Diffusion Embedding", None, QtGui.QApplication.UnicodeUTF8))
		self.label.setText(QtGui.QApplication.translate("MainWindow", "Transition style:", None, QtGui.QApplication.UnicodeUTF8))
		self.comboBox.setItemText(0, QtGui.QApplication.translate("MainWindow", "Alternating Axes", None, QtGui.QApplication.UnicodeUTF8))
		self.comboBox.setItemText(1, QtGui.QApplication.translate("MainWindow", "Diagonal", None, QtGui.QApplication.UnicodeUTF8))
		self.comboBox.setItemText(2, QtGui.QApplication.translate("MainWindow", "Simple", None, QtGui.QApplication.UnicodeUTF8))
		self.menuFile.setTitle(QtGui.QApplication.translate("MainWindow", "File", None, QtGui.QApplication.UnicodeUTF8))
		self.actionOpen.setText(QtGui.QApplication.translate("MainWindow", "Open", None, QtGui.QApplication.UnicodeUTF8))
		self.actionOpen.setShortcut(QtGui.QApplication.translate("MainWindow", "Ctrl+O", None, QtGui.QApplication.UnicodeUTF8))
		self.actionExit.setText(QtGui.QApplication.translate("MainWindow", "Exit", None, QtGui.QApplication.UnicodeUTF8))
		self.actionExit.setShortcut(QtGui.QApplication.translate("MainWindow", "Ctrl+Q", None, QtGui.QApplication.UnicodeUTF8))
Exemple #5
0
 def keyPressEvent(self, ev):
     if ev.key() == QtCore.Qt.Key_Up:
         if self.pick_radius > -1:
             self.pick_radius += 1
     if ev.key() == QtCore.Qt.Key_Down:
         if self.pick_radius > 0: 
             self.pick_radius -= 1
         
     QVTKRenderWindowInteractor.keyPressEvent(self, ev)
Exemple #6
0
 def __init__(self, widget, graph, app=None, parent = None):
     QVTKRenderWindowInteractor.__init__(self, widget)
     self._vta_graph = graph
     
     self._scoresim = None
     self._scores = None
     self._graph = None
     self.actor = None
     self.app = app
     self.pick_radius = 0
    def setupUi(self, Form):
        Form.setObjectName(_fromUtf8("Form"))
        Form.resize(800, 600)
        self.gridLayout = QtGui.QGridLayout(Form)
        self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
        self.verticalLayout_3 = QtGui.QVBoxLayout()
        self.verticalLayout_3.setSizeConstraint(QtGui.QLayout.SetDefaultConstraint)
        self.verticalLayout_3.setObjectName(_fromUtf8("verticalLayout_3"))
        self.horizontalLayout = QtGui.QHBoxLayout()
        self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
        self.verticalLayout = QtGui.QVBoxLayout()
        self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
        self.label = QtGui.QLabel(Form)
        self.label.setObjectName(_fromUtf8("label"))
        self.verticalLayout.addWidget(self.label)
        self.leftVtk = QVTKRenderWindowInteractor(Form)
        self.leftVtk.setObjectName(_fromUtf8("leftVtk"))
        self.verticalLayout.addWidget(self.leftVtk)
        self.verticalLayout.setStretch(1, 1)
        self.horizontalLayout.addLayout(self.verticalLayout)
        self.verticalLayout_2 = QtGui.QVBoxLayout()
        self.verticalLayout_2.setObjectName(_fromUtf8("verticalLayout_2"))
        self.label_2 = QtGui.QLabel(Form)
        self.label_2.setObjectName(_fromUtf8("label_2"))
        self.verticalLayout_2.addWidget(self.label_2)
        self.rightVtk = QVTKRenderWindowInteractor(Form)
        self.rightVtk.setObjectName(_fromUtf8("rightVtk"))
        self.verticalLayout_2.addWidget(self.rightVtk)
        self.verticalLayout_2.setStretch(1, 1)
        self.horizontalLayout.addLayout(self.verticalLayout_2)
        self.verticalLayout_3.addLayout(self.horizontalLayout)
        self.tabWidget = QtGui.QTabWidget(Form)
        self.tabWidget.setTabShape(QtGui.QTabWidget.Triangular)
        self.tabWidget.setTabsClosable(False)
        self.tabWidget.setMovable(False)
        self.tabWidget.setObjectName(_fromUtf8("tabWidget"))
        self.okienkowanieTab = QtGui.QWidget()
        self.okienkowanieTab.setObjectName(_fromUtf8("okienkowanieTab"))
        self.tabWidget.addTab(self.okienkowanieTab, _fromUtf8(""))
        self.cannyTab = QtGui.QWidget()
        self.cannyTab.setObjectName(_fromUtf8("cannyTab"))
        self.tabWidget.addTab(self.cannyTab, _fromUtf8(""))
        self.verticalLayout_3.addWidget(self.tabWidget)
        self.loadImage = QtGui.QPushButton(Form)
        self.loadImage.setObjectName(_fromUtf8("loadImage"))
        self.verticalLayout_3.addWidget(self.loadImage)
        self.verticalLayout_3.setStretch(0, 2)
        self.verticalLayout_3.setStretch(1, 1)
        self.gridLayout.addLayout(self.verticalLayout_3, 0, 0, 1, 1)

        self.retranslateUi(Form)
        self.tabWidget.setCurrentIndex(0)
        QtCore.QMetaObject.connectSlotsByName(Form)
Exemple #8
0
    def __init__(self, parent=None):
        super(QCDATWidget, self).__init__(parent=parent)

        self.setAcceptDrops(True)

        self.mRenWin = vtk.vtkRenderWindow()
        self.iren = QVTKRenderWindowInteractor(parent=self, rw=self.mRenWin)
        self.canvas = None

        self.canvasLayout = QtGui.QVBoxLayout()
        self.canvasLayout.addWidget(self.iren)
        self.setLayout(self.canvasLayout)

        self.becameVisible = partial(self.visiblityChanged.emit, True)
        self.becameHidden = partial(self.visiblityChanged.emit, False)

        self.setFocusPolicy(QtCore.Qt.StrongFocus)
        self.setSizePolicy(QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding,
                                             QtGui.QSizePolicy.Expanding))

        self.visiblityChanged.connect(self.manageCanvas)

        self.dragTarget = QtGui.QWidget(self)
        self.dragTarget.hide()

        self.dragLayout = QtGui.QHBoxLayout()
        self.dragTarget.setLayout(self.dragLayout)

        self.plots = []
        # Creates and hooks up the initial PlotInfo widget
        self.addedPlot()

        # Just need a callable that returns something
        self.toolBarType = lambda x: None
Exemple #9
0
    def mouseDoubleClickEvent(self, ev):
        
        picker = self.GetRenderWindow().GetInteractor().GetPicker()
        
        # Get the location of the click (in window coordinates)
        pos = self.GetRenderWindow().GetInteractor().GetEventPosition()
 
        #picker.SetTolerance(0.0005)
        picker.Pick( pos[0], pos[1], 0, self.GetRenderWindow().GetRenderers().GetFirstRenderer() )
        
        #print 'Cell id is: ' + str( picker.GetCellId() )
        #print 'Point id is: ' + str( picker.GetPointId() )
        
        actors = picker.GetActors()
        screenPos = picker.GetSelectionPoint()
        worldPosition = picker.GetPickPosition()
        
        data = picker.GetDataSet()
        
        '''
        print pickPos
        print screenPos
        print actors 
        print actors.GetLastItem()
        '''
        
        #print 'data: ' + str( data )
        self.__addVolumeSelectedActor(worldPosition)
        
        av = self.app.active_vol
        
        cellid = picker.GetPointId()
        #if self._graph is not None and cellid != -1 :
        try:
            self._graph.update_figure( cellid, self._scoresim, self._scores, \
                                       self.app._vdata[av].pt_id_ijk, \
                                       self.pat_data_img_data_list, radius=self.pick_radius )
        except:
            pass
        
        QVTKRenderWindowInteractor.mousePressEvent(self, ev)
        self.update()
Exemple #10
0
class Ui_TestbedWindow(object):
    def setupUi(self, TestbedWindow):
        TestbedWindow.setObjectName(_fromUtf8("TestbedWindow"))
        TestbedWindow.resize(789, 590)
        TestbedWindow.setWindowTitle(QtGui.QApplication.translate("TestbedWindow", "MainWindow", None, QtGui.QApplication.UnicodeUTF8))
        self.centralwidget = QtGui.QWidget(TestbedWindow)
        self.centralwidget.setObjectName(_fromUtf8("centralwidget"))

        self.renderView = QVTKRenderWindowInteractor(self.centralwidget)
        self.renderView.setGeometry(QtCore.QRect(0, 0, 781, 541))
        self.renderView.setObjectName(_fromUtf8("renderView"))

        TestbedWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtGui.QMenuBar(TestbedWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 789, 27))
        self.menubar.setObjectName(_fromUtf8("menubar"))
        self.menuData = QtGui.QMenu(self.menubar)
        self.menuData.setTitle(QtGui.QApplication.translate("TestbedWindow", "Data", None, QtGui.QApplication.UnicodeUTF8))
        self.menuData.setObjectName(_fromUtf8("menuData"))
        TestbedWindow.setMenuBar(self.menubar)
        self.statusbar = QtGui.QStatusBar(TestbedWindow)
        self.statusbar.setObjectName(_fromUtf8("statusbar"))
        TestbedWindow.setStatusBar(self.statusbar)
        self.actionLoad = QtGui.QAction(TestbedWindow)
        self.actionLoad.setCheckable(False)
        self.actionLoad.setText(QtGui.QApplication.translate("TestbedWindow", "Load...", None, QtGui.QApplication.UnicodeUTF8))
        self.actionLoad.setToolTip(QtGui.QApplication.translate("TestbedWindow", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
"p, li { white-space: pre-wrap; }\n"
"</style></head><body style=\" font-family:\'Sans Serif\'; font-size:10pt; font-weight:400; font-style:normal;\">\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-style:italic;\">Load dataset</span></p></body></html>", None, QtGui.QApplication.UnicodeUTF8))
        self.actionLoad.setShortcut(QtGui.QApplication.translate("TestbedWindow", "F2", None, QtGui.QApplication.UnicodeUTF8))
        self.actionLoad.setObjectName(_fromUtf8("actionLoad"))
        self.menuData.addAction(self.actionLoad)
        self.menubar.addAction(self.menuData.menuAction())

        self.retranslateUi(TestbedWindow)
        QtCore.QMetaObject.connectSlotsByName(TestbedWindow)

    def retranslateUi(self, TestbedWindow):
        pass
 def setupVtkRendering(self):
     self.vtkWidget = QVTKRenderWindowInteractor(self)
     self.ren = vtk.vtkRenderer()
     self.vtkWidget.GetRenderWindow().AddRenderer(self.ren)
     self.iren = self.vtkWidget.GetRenderWindow().GetInteractor()
     self.ren.ResetCamera()
     self.ren.GetActiveCamera().ParallelProjectionOn()
     self.iren.SetInteractorStyle(vtk.vtkInteractorStyleTrackballCamera())
     # layout
     vlayout = QVBoxLayout()
     vlayout.addWidget(self.vtkWidget)
     self.setLayout(vlayout)
Exemple #12
0
    def setupUi(self, MainWindow):
        MainWindow.setObjectName(_fromUtf8("MainWindow"))
        MainWindow.resize(912, 640)
        #centralWidget
        self.centralWidget = QtGui.QWidget(MainWindow)
        self.centralWidget.setObjectName(_fromUtf8("centralWidget"))

        self.m_label = QtGui.QLabel(self.centralWidget)
        self.m_label.setGeometry(QtCore.QRect(750, 70, 91, 17))
        self.m_label.setObjectName(_fromUtf8("m_label"))
        self.m_pushButton = QtGui.QPushButton(self.centralWidget)
        self.m_pushButton.setGeometry(QtCore.QRect(740, 110, 99, 27))
        self.m_pushButton.setObjectName(_fromUtf8("m_pushButton"))

        #vtkWidget
        self.m_widget = QVTKRenderWindowInteractor(self.centralWidget)
        self.m_widget.setGeometry(QtCore.QRect(60, 60, 591, 501))
        self.m_widget.setObjectName(_fromUtf8("m_widget"))
        self.setvtkWidget()

        MainWindow.setCentralWidget(self.centralWidget)

        #menuBar
        self.menuBar = QtGui.QMenuBar(MainWindow)
        self.menuBar.setGeometry(QtCore.QRect(0, 0, 912, 25))
        self.menuBar.setObjectName(_fromUtf8("menuBar"))
        MainWindow.setMenuBar(self.menuBar)

        #toolBar
        self.mainToolBar = QtGui.QToolBar(MainWindow)
        self.mainToolBar.setObjectName(_fromUtf8("mainToolBar"))
        MainWindow.addToolBar(QtCore.Qt.TopToolBarArea, self.mainToolBar)

        #statusBar
        self.statusBar = QtGui.QStatusBar(MainWindow)
        self.statusBar.setObjectName(_fromUtf8("statusBar"))
        MainWindow.setStatusBar(self.statusBar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)
Exemple #13
0
    def initGUI(self):
        QtGui.QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.setWindowTitle("Simple Dicom Viewer")

        #self.dicomReader = vtk.vtkDICOMImageReader()
        #self.dicomReader = vtkgdcm.vtkGDCMImageReader()
        self.show()

        self.figure = plt.figure()
        self.canvas = FigureCanvas(self.figure)
        self.toolbar = NavigationToolbar(self.canvas, self)
        self.ui.numpyLayout.addWidget(self.toolbar)
        self.ui.numpyLayout.addWidget(self.canvas)



        self.vtkWidget = QVTKRenderWindowInteractor(self.ui.imageFrame)
        self.vtkWidget.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
        #self.ui.imageLayout.removeWidget(self.ui.dicomSlider)
        self.ui.imageLayout.addWidget(self.vtkWidget)
        #self.ui.imageLayout.addWidget(self.ui.dicomSlider)

        self.disableSlider()

        self.viewer= vtk.vtkImageViewer()
        #self.viewer.SetupInteractor(MyInteractor())
        self.vtkWidget.GetRenderWindow().AddRenderer(self.viewer.GetRenderer())
        self.iren = self.vtkWidget.GetRenderWindow().GetInteractor()
        #self.iren.SetRenderWindow(self.vtkWidget.GetRenderWindow())


        self.drag = False
        self.measuring = False
        self.iren.AddObserver("LeftButtonPressEvent", self.leftClick)
        self.iren.AddObserver("LeftButtonReleaseEvent", self.leftRelease)
        self.iren.AddObserver("EnterEvent", self.mouseEntered)
        self.iren.AddObserver("LeaveEvent", self.mouseLeft)
        self.iren.AddObserver("MouseMoveEvent", self.mouseMoved)
Exemple #14
0
class PyqtChatApp(QtGui.QSplitter):
    """聊天界面,QSplitter用于让界面可以鼠标拖动调节"""
    def __init__(self, q=None):
        super(PyqtChatApp, self).__init__(Qt.Horizontal)

        self.setWindowTitle('pyChat')  # window标题
        # self.setMinimumSize(500, 500)   # 窗口最小大小

        self.msgList = MsgList()
        self.msgList.setDisabled(False)  # 刚打开时没有聊天显示内容才对
        self.msgInput = MsgInput()
        self.msgInput.textEntered.connect(self.sendTextMsg)

        # queue
        self.queue = q

        # 3d render
        self.frame = QtGui.QFrame()
        self.vl = QtGui.QVBoxLayout()
        self.vtkWidget = QVTKRenderWindowInteractor(self.frame)
        self.vl.addWidget(self.vtkWidget)

        self.ren = vtk.vtkRenderer()
        self.vtkWidget.GetRenderWindow().AddRenderer(self.ren)
        self.iren = self.vtkWidget.GetRenderWindow().GetInteractor()

        # Create source
        source = vtk.vtkSphereSource()
        source.SetCenter(0, 0, 0)
        source.SetRadius(5.0)

        # Create a mapper
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(source.GetOutputPort())

        # Create an actor
        actor = vtk.vtkActor()
        actor.SetMapper(mapper)

        self.ren.AddActor(actor)

        self.ren.ResetCamera()

        self.frame.setLayout(self.vl)
        self.frame.setParent(self)
        self.iren.Initialize()

        # set layout
        rSpliter = QtGui.QSplitter(Qt.Vertical, self)
        # self.frame.setParent(rSpliter)
        self.msgList.setParent(rSpliter)
        self.msgInput.setParent(rSpliter)
        #setup qa
        self.qa = QaEngine("qa/save_model/122_params.pkl",
                           "qa/data/all_vocab.txt")
        # qa.prediction(question)

    def setDemoMsg(self):
        self.msgList.clear()

    def qa_process(self, txt):
        print("qa resived" + txt)
        answer = self.qa.prediction(txt)
        print(answer)
        return answer

    def send_to_queue(self, msg):
        if self.queue is not None:
            self.queue.put(msg)

    @pyqtSlot(str)
    def sendTextMsg(self, txt):
        # display to chat
        self.msgList.addTextMsg(txt, False)
        # qa process
        qa_txt = self.qa_process(txt)
        if qa_txt['class_id'] == 0:
            qa_msg = qa_txt['answer']
            msg = [txt, qa_msg]
        else:
            qa_msg = "听不懂! ------------------"
            qa_msg = qa_txt['answer']
            msg = [txt, qa_msg]
        # send to queue
        self.send_to_queue(msg)
        self.msgList.addTextMsg(qa_msg, True)
class VtkFgBgDisplayWidget(QFrame):

    def __init__(self, parent=None):
        super(VtkFgBgDisplayWidget, self).__init__(parent)
        self.imVtkBg = None
        self.imVtkFg = None
        self.matrix4x4 = vtk.vtkMatrix4x4()
        self.matrix4x4.DeepCopy((
            1.0, 0.0, 0.0, 0.0,
            0.0, 1.0, 0.0, 0.0,
            0.0, 0.0, 1.0, 0.0,
            0.0, 0.0, 0.0, 1.0
        ))
        self.reslice = vtk.vtkImageReslice()
        self.reslice.SetOutputDimensionality(3)
        self.reslice.SetResliceAxes(self.matrix4x4)
        self.reslice.SetInterpolationModeToLinear()
        self.setupVtkRendering()

    def setupVtkRendering(self):
        self.vtkWidget = QVTKRenderWindowInteractor(self)
        self.ren = vtk.vtkRenderer()
        self.vtkWidget.GetRenderWindow().AddRenderer(self.ren)
        self.iren = self.vtkWidget.GetRenderWindow().GetInteractor()
        self.ren.ResetCamera()
        self.ren.GetActiveCamera().ParallelProjectionOn()
        self.iren.SetInteractorStyle(vtk.vtkInteractorStyleTrackballCamera())
        # layout
        vlayout = QVBoxLayout()
        vlayout.addWidget(self.vtkWidget)
        self.setLayout(vlayout)

    def initialize(self):
        self.iren.Initialize()

    @staticmethod
    def convertNpyToVtk(imgNpy):
        assert(imgNpy.dtype == np.uint8)
        nx, ny, nz = imgNpy.shape
        dataImporter = vtk.vtkImageImport()
        dataString = imgNpy.tostring(order='F')
        dataImporter.CopyImportVoidPointer(dataString, len(dataString))
        dataImporter.SetDataScalarTypeToUnsignedChar()
        dataImporter.SetNumberOfScalarComponents(1)
        dataImporter.SetDataExtent(0, nx-1, 0, ny-1, 0, nz-1)
        dataImporter.SetWholeExtent(0, nx-1, 0, ny-1, 0, nz-1)
        dataImporter.Update()
        return dataImporter.GetOutput()

    def setMatrix(self, matrix):
        if matrix is not None:
            assert(matrix.shape == (4, 4))
        self.setMatrixTuple(tuple(matrix.flatten()))

    def setMatrixTuple(self, matrix):
        if matrix is not None:
            assert(len(matrix) == 16)
        self.matrix4x4.DeepCopy(matrix)

    def render(self):
        # self.ren.Render()
        self.ren.ResetCamera()

    def setDirection(self, direction):
        if direction == 0:
            # X-Y plane
            self.ren.GetActiveCamera().SetPosition(0, 0, -1)
            self.ren.GetActiveCamera().SetFocalPoint(0, 0, 0)
            self.ren.GetActiveCamera().SetViewUp(-1, 0, 0)
        elif direction == 1:
            # X-Z plane
            self.ren.GetActiveCamera().SetPosition(0, -1, 0)
            self.ren.GetActiveCamera().SetFocalPoint(0, 0, 0)
            self.ren.GetActiveCamera().SetViewUp(0, 0, -1)
        elif direction == 2:
            # Y-Z plane
            self.ren.GetActiveCamera().SetPosition(-1, 0, 0)
            self.ren.GetActiveCamera().SetFocalPoint(0, 0, 0)
            self.ren.GetActiveCamera().SetViewUp(0, 0, -1)

    def update(self):
        self.vtkWidget.update()
        super(VtkFgBgDisplayWidget, self).update()
Exemple #16
0
 def __init__(self):
     QVTKRenderWindowInteractor.__init__(self)
     self.AddObserver("LeftButtonPressEvent", self.leftPressed)
     self.Initialize()
     self.Render()
Exemple #17
0
  def __init__(self, tree_widget):
    QtGui.QWidget.__init__(self)
    self.tree_widget = tree_widget
    self.tree_widget.mesh_item_changed.connect(self.meshItemChanged)

    self.mesh_file_name = ''

    self.mesh_renderer = None

    self.current_block_actors = {}
    self.current_sideset_actors = {}
    self.current_nodeset_actors = {}

    self.this_layout = QtGui.QVBoxLayout()
    self.setLayout(self.this_layout)

    self.vtkwidget = QVTKRenderWindowInteractor(self)

    self.renderer = vtk.vtkRenderer()
    self.renderer.SetBackground(0.2,0.2,0.2)
    self.renderer.SetBackground2(1,1,1)
    self.renderer.SetGradientBackground(1)
    self.renderer.ResetCamera()

    self.this_layout.addWidget(self.vtkwidget)
    self.this_layout.setStretchFactor(self.vtkwidget, 10)

    self.vtkwidget.setMinimumHeight(300)

    self.vtkwidget.GetRenderWindow().AddRenderer(self.renderer)
    self.interactor = self.vtkwidget.GetRenderWindow().GetInteractor()

    self.interactor.SetInteractorStyle(vtk.vtkInteractorStyleTrackballCamera())

    self.vtkwidget.Initialize()
    self.vtkwidget.Start()

    self.controls_layout = QtGui.QHBoxLayout()

    self.left_controls_layout = QtGui.QVBoxLayout()

    self.block_view_group_box = QtGui.QGroupBox('Show Blocks')
    self.block_view_group_box.setMaximumWidth(150)
#    self.block_view_group_box.setMaximumHeight(200)

    self.block_view_layout = QtGui.QVBoxLayout()
    self.block_view_list = QtGui.QListView()
    self.block_view_model = QtGui.QStandardItemModel()
    self.block_view_model.itemChanged.connect(self._blockViewItemChanged)
    self.block_view_list.setModel(self.block_view_model)
    self.block_view_layout.addWidget(self.block_view_list)

    self.block_view_group_box.setLayout(self.block_view_layout)
    self.left_controls_layout.addWidget(self.block_view_group_box)
    self.controls_layout.addLayout(self.left_controls_layout)


    self.right_controls_layout = QtGui.QVBoxLayout()
    self.controls_layout.addLayout(self.right_controls_layout)

    self.view_mesh_checkbox = QtGui.QCheckBox('View Mesh')
    self.view_mesh_checkbox.setToolTip('Toggle viewing of mesh elements')
    self.view_mesh_checkbox.setCheckState(QtCore.Qt.Checked)
    self.view_mesh_checkbox.stateChanged.connect(self.viewMeshCheckboxChanged)
    self.right_controls_layout.addWidget(self.view_mesh_checkbox)

    self.highlight_group_box = QtGui.QGroupBox('Highlight')
    self.highlight_group_box.setMaximumHeight(70)
    self.highlight_group_box.setSizePolicy(QtGui.QSizePolicy.MinimumExpanding, QtGui.QSizePolicy.Fixed)
#    self.highlight_group_box.setMaximumWidth(200)
    self.highlight_layout = QtGui.QHBoxLayout()
    self.highlight_group_box.setLayout(self.highlight_layout)
    self.right_controls_layout.addWidget(self.highlight_group_box)

    self.highlight_block_label = QtGui.QLabel('Block:')
    self.highlight_block_label.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
    self.highlight_block_combo = QtGui.QComboBox()
#    self.highlight_block_combo.setMaximumWidth(50)
    self.highlight_block_combo.setSizeAdjustPolicy(QtGui.QComboBox.AdjustToMinimumContentsLength)
    self.highlight_block_combo.setSizePolicy(QtGui.QSizePolicy.MinimumExpanding, QtGui.QSizePolicy.Fixed)
    self.highlight_block_combo.setToolTip('Highlight a block in the mesh')
    self.highlight_block_combo.currentIndexChanged[str].connect(self.showBlockSelected)
    self.highlight_layout.addWidget(self.highlight_block_label)
    self.highlight_layout.addWidget(self.highlight_block_combo)

    self.highlight_sideset_label = QtGui.QLabel('Sideset:')
    self.highlight_sideset_label.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
    self.highlight_sideset_combo = QtGui.QComboBox()
#    self.highlight_sideset_combo.setMaximumWidth(50)
    self.highlight_sideset_combo.setSizeAdjustPolicy(QtGui.QComboBox.AdjustToMinimumContentsLength)
    self.highlight_sideset_combo.setSizePolicy(QtGui.QSizePolicy.MinimumExpanding, QtGui.QSizePolicy.Fixed)
    self.highlight_sideset_combo.setToolTip('Highlight a sideset in the mesh')
    self.highlight_sideset_combo.currentIndexChanged[str].connect(self.showSidesetSelected)
    self.highlight_layout.addWidget(self.highlight_sideset_label)
    self.highlight_layout.addWidget(self.highlight_sideset_combo)

    self.highlight_nodeset_label = QtGui.QLabel('Nodeset:')
    self.highlight_nodeset_label.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
    self.highlight_nodeset_combo = QtGui.QComboBox()
#    self.highlight_nodeset_combo.setMaximumWidth(50)
    self.highlight_nodeset_combo.setSizeAdjustPolicy(QtGui.QComboBox.AdjustToMinimumContentsLength)
    self.highlight_nodeset_combo.setSizePolicy(QtGui.QSizePolicy.MinimumExpanding, QtGui.QSizePolicy.Fixed)
    self.highlight_nodeset_combo.setToolTip('Highlight a nodeset in the mesh')
    self.highlight_nodeset_combo.currentIndexChanged[str].connect(self.showNodesetSelected)
    self.highlight_layout.addWidget(self.highlight_nodeset_label)
    self.highlight_layout.addWidget(self.highlight_nodeset_combo)

    self.highlight_clear = QtGui.QPushButton('Clear')
    self.highlight_clear.setToolTip('Clear highlighting')
    self.highlight_clear.setDisabled(True)
    self.highlight_clear.clicked.connect(self.clearHighlight)
    self.highlight_layout.addWidget(self.highlight_clear)

    self.plane = vtk.vtkPlane()
    self.plane.SetOrigin(0, 0, 0)
    self.plane.SetNormal(1, 0, 0)

    self.clip_groupbox = QtGui.QGroupBox("Clip")
    self.clip_groupbox.setToolTip('Toggle clip mode to slice the mesh open along a plane')
    self.clip_groupbox.setCheckable(True)
    self.clip_groupbox.setChecked(False)
    self.clip_groupbox.setMaximumHeight(70)
    self.clip_groupbox.toggled[bool].connect(self._clippingToggled)
    clip_layout = QtGui.QHBoxLayout()

    self.clip_plane_combobox = QtGui.QComboBox()
    self.clip_plane_combobox.setToolTip('Direction of the normal for the clip plane')
    self.clip_plane_combobox.addItem('x')
    self.clip_plane_combobox.addItem('y')
    self.clip_plane_combobox.addItem('z')
    self.clip_plane_combobox.currentIndexChanged[str].connect(self._clipNormalChanged)

    clip_layout.addWidget(self.clip_plane_combobox)

    self.clip_plane_slider = QtGui.QSlider(QtCore.Qt.Horizontal)
    self.clip_plane_slider.setToolTip('Slide to change plane position')
    self.clip_plane_slider.setRange(0, 100)
    self.clip_plane_slider.setSliderPosition(50)
    self.clip_plane_slider.sliderMoved[int].connect(self._clipSliderMoved)
    clip_layout.addWidget(self.clip_plane_slider)
#     vbox->addStretch(1);
    self.clip_groupbox.setLayout(clip_layout)

    self.right_controls_layout.addWidget(self.clip_groupbox)

    self.this_layout.addLayout(self.controls_layout)
    self.this_layout.setStretchFactor(self.controls_layout, 1)

    self.bounds = {}
    self.bounds['x'] = [0.0, 0.0]
    self.bounds['y'] = [0.0, 0.0]
    self.bounds['z'] = [0.0, 0.0]
Exemple #18
0
class MeshViewer(QtGui.QWidget):

    app = QtGui.QApplication(sys.argv)
    
    """
    Qt GUI for visu. the output
    """
    def __init__(self, truss, algo): 
        QtGui.QWidget.__init__(self) 
        
        self.truss = truss
        self.algo = algo
        self.algo.dhook = self
        
        self.running = 'init'
        
        print "starting MeshViewer init..."
        
        self.__setupGUI()
        self.__setupVTK()
        
        self.app.lastWindowClosed.connect(self.app.quit)
        self.show() 
        print "MeshViewer ready." 
        
    def closeEvent(self, event):
        self.algo.stopit=True 
        self.running='running' # sort de "while self.running=='pause'"      
        print "GUI killed!"
        QtGui.QWidget.closeEvent(self,event)


    def start(self):
        self.app.exec_()

    def __setupGUI(self):

        self.setWindowTitle("MeshViewer")
        self.resize(800, 600)
        
        # vtk window
        
        self.vtkwidget = QVTKRenderWindowInteractor(self) # "self" sinon, rien ne s'affiche
        self.vtkwidget.setSizePolicy(QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, 
                                                  QtGui.QSizePolicy.Expanding))
        self.vtkwidget.setMinimumSize(QtCore.QSize(300, 300));
        self.vtkwidget.setSizePolicy(QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Expanding)
        
                      
        self.vtkwidget.Initialize() 
                       
        self.renderer = vtk.vtkRenderer()
        self.renderer.SetBackground(1.0, 1.0, 1.0)     
        self.vtkwidget.GetRenderWindow().AddRenderer(self.renderer) 
        
        style = vtk.vtkInteractorStyleTrackballCamera()
        self.vtkwidget.SetInteractorStyle(style) 


        hbox = QtGui.QHBoxLayout()
        self.setLayout(hbox)
        hbox.addWidget(self.vtkwidget)
        
        pan = QtGui.QFrame()
        pan.setMaximumSize(QtCore.QSize(200,999999))
        hbox.addWidget(pan)
        
        vbox = QtGui.QVBoxLayout()
        pan.setLayout(vbox)
        
        self.startBut = QtGui.QPushButton(self.tr("start!"))
        self.connect(self.startBut, QtCore.SIGNAL("clicked()"), self.startSlot)
        vbox.addWidget(self.startBut)
        
        groupBox = QtGui.QGroupBox("Infos")
        self.steplabel = QtGui.QLabel("step # 0")
        self.loadlabel = QtGui.QLabel("lambda = %2.8f" % 0)
        gbox = QtGui.QVBoxLayout()
        groupBox.setLayout(gbox) 
        gbox.addWidget(self.steplabel)   
        gbox.addWidget(self.loadlabel)   
        vbox.addWidget(groupBox)
        
        vbox.addStretch(1)
        
    def startSlot(self):
        if self.running=='init':  
            self.startBut.setText('Pause') # on demarre et on affiche "pause"
            self.running='running'
            self.algo.run()
            self.startBut.setText("Quit")
            self.running='quit'
        elif self.running=='running':  # on stoppe et on affiche 'continue"
            self.running='pause'
            self.startBut.setText("Continue")
            while self.running=='pause':
                self.app.processEvents(QtCore.QEventLoop.WaitForMoreEvents)
        elif self.running=='pause':
            self.running='running'
            self.startBut.setText("Pause")
        elif self.running=='quit':
            self.app.quit()
        
    def disableStart(self):
        self.startBut.setDisabled(True)
        
    def __setupVTK(self):
        # polydata
        self.__createPolyData()
        self.poly = PolyData(self.polydata)
        self.renderer.AddActor(self.poly.actor)
        self.renderer.AddActor2D(self.poly.pointLabels)
        
        self.resetCamera() 

    def resetCamera(self):
        self.renderer.ResetCamera()
        cam1 = self.renderer.GetActiveCamera()
        # 3D
        if 0:
            cam1.Elevation(35)
            cam1.SetViewUp(0, 1, 0)
            cam1.Azimuth(30)
        #2D
        else:
            cam1.Elevation(0)
            cam1.SetViewUp(0, 1, 0)
            cam1.Azimuth(0)
            self.renderer.ResetCameraClippingRange()        
        
    def display(self, step, lamda):
        
        self.steplabel.setText("step # %d" % step)
        self.loadlabel.setText("lambda = %2.8f" % lamda)
        
        self.points.Reset()
        self.vertices.Reset()
        self.lines.Reset()
        self.scalars.Reset()
        
        # points
        nmap={}
        i=0
        for nod in self.truss.nodes:
            nmap[nod.nb]=i
            self.points.InsertPoint(i, nod.x, nod.y, 0.0)
            self.scalars.InsertNextValue(nod.nb)
            # node cells
            vertex = vtk.vtkVertex()
            vertex.GetPointIds().SetId(0, i)
            self.vertices.InsertNextCell(vertex)
            i+=1
        self.points.Modified()
        self.vertices.Modified()
        
        for bar in self.truss.bars:
            line = vtk.vtkLine()
            ids = line.GetPointIds()
            ids.SetNumberOfIds(2)
            for j in range(len(bar.nodes)):
                ids.SetId(j, nmap[bar.nodes[j].nb])
            self.lines.InsertNextCell(line) 
        self.lines.Modified()
        
        self.polydata.Modified()
        
        self.render()
    
    def ragequit(self):
        print "rage quit!"
        self.algo.stopit=True
        self.app.quit()
        
    def render(self): 
        # draw the scene
        self.vtkwidget.Render()
        self.app.processEvents()
    
    def refresh(self):
        self.app.processEvents()
        
    def __createPolyData(self):
        print 'creating vtkPolyData...'
        self.points = vtk.vtkPoints()
        self.polydata  = vtk.vtkPolyData()
        self.vertices = vtk.vtkCellArray()
        self.lines = vtk.vtkCellArray()
        
        self.polydata.SetPoints(self.points)
        self.polydata.SetVerts(self.vertices)
        self.polydata.SetLines(self.lines)
        
        # points
        self.scalars = vtk.vtkFloatArray()
        self.scalars.SetNumberOfComponents(1)
        self.polydata.GetPointData().SetScalars(self.scalars)
     
        nmap={}
        i=0
        for nod in self.truss.nodes:
            nmap[nod.nb]=i
            self.points.InsertPoint(i, nod.x, nod.y, 0.0)
            self.scalars.InsertNextValue(nod.nb)
            # node cells
            vertex = vtk.vtkVertex()
            vertex.GetPointIds().SetId(0, i)
            self.vertices.InsertNextCell(vertex)
            i+=1
        self.points.Modified()
        self.vertices.Modified()
        
        for bar in self.truss.bars:
            line = vtk.vtkLine()
            ids = line.GetPointIds()
            ids.SetNumberOfIds(2)
            for j in range(len(bar.nodes)):
                ids.SetId(j, nmap[bar.nodes[j].nb])
            self.lines.InsertNextCell(line) 
        self.lines.Modified()
Exemple #19
0
class RenderWidget(QWidget):
    """
	RenderWidget for rendering volumes. It has a few render types which can be
	set and adjusted.
	"""

    dataChanged = Signal()
    updated = Signal()

    def __init__(self):
        super(RenderWidget, self).__init__()

        # Default volume renderer
        self.renderer = vtkRenderer()
        self.renderer.SetBackground2(0.4, 0.4, 0.4)
        self.renderer.SetBackground(0.1, 0.1, 0.1)
        self.renderer.SetGradientBackground(True)
        self.renderer.SetLayer(0)

        # Overlay renderer which is synced with the default renderer
        self.rendererOverlay = vtkRenderer()
        self.rendererOverlay.SetLayer(1)
        self.rendererOverlay.SetInteractive(0)
        self.renderer.GetActiveCamera().AddObserver("ModifiedEvent",
                                                    self._syncCameras)

        self.rwi = QVTKRenderWindowInteractor(parent=self)
        self.rwi.SetInteractorStyle(vtkInteractorStyleTrackballCamera())
        self.rwi.GetRenderWindow().AddRenderer(self.renderer)
        self.rwi.GetRenderWindow().AddRenderer(self.rendererOverlay)
        self.rwi.GetRenderWindow().SetNumberOfLayers(2)
        self.rwi.SetDesiredUpdateRate(0)

        self.imagePlaneWidgets = [vtkImagePlaneWidget() for i in range(3)]
        for index in range(3):
            self.imagePlaneWidgets[index].DisplayTextOn()
            self.imagePlaneWidgets[index].SetInteractor(self.rwi)
            # Disable the margin for free rotation
            self.imagePlaneWidgets[index].SetMarginSizeX(0.0)
            self.imagePlaneWidgets[index].SetMarginSizeY(0.0)

        self.mapper = vtkOpenGLGPUVolumeRayCastMapper()
        self.mapper.SetAutoAdjustSampleDistances(1)
        self.volume = None
        self.imageData = None
        self.VolumeVisualization = None
        self.shouldResetCamera = False
        self.gridItems = []
        self.orientationGridItems = []

        self.clippingBox = ClippingBox()
        self.clippingBox.setWidget(self)

        # Keep track of the base and user transforms
        self.baseTransform = vtkTransform()
        self.userTransform = vtkTransform()

        self.setMinimumWidth(340)
        self.setMinimumHeight(340)

        layout = QGridLayout(self)
        layout.setSpacing(0)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.addWidget(self.rwi, 0, 0)
        self.setLayout(layout)

    def render(self):
        self.clippingBox.update()
        if self.shouldResetCamera:
            self.renderer.ResetCamera()
            self.shouldResetCamera = False
        self.rwi.Render()
        # Prevent warning messages on OSX by not asking to render
        # when the render window has never rendered before
        if not self.rwi.GetRenderWindow().GetNeverRendered():
            self.rwi.GetRenderWindow().Render()

    @Slot(object)
    def setData(self, imageData):
        """
		Updates the image data. If the image data is none, then
		the volume gets removed from the renderer. Otherwise, the
		new image data is given to the mapper.
		"""
        self.imageData = imageData
        # Clean up the data grid
        self._cleanUpGrids()

        if self.imageData is None:
            if self.volume is not None:
                self.renderer.RemoveViewProp(self.volume)
            print "Warning: image data is None"
            self.clippingBox.setImageData(None)
            self.mapper.RemoveAllInputs()
            self.render()
            return

        # Set the image data for the mapper
        self.mapper.SetInputData(self.imageData)

        # Set the image data for the slices
        for index in range(3):
            self.imagePlaneWidgets[index].SetInputData(self.imageData)
            self.imagePlaneWidgets[index].SetPlaneOrientation(index)

        self._createGrid()
        self._createOrientationGrid()
        self.clippingBox.setImageData(self.imageData)
        self.clippingBox.resetClippingBox()
        self.shouldResetCamera = True
        # Don't call render, because camera should only be reset
        # when a volume property is loaded

    def showClippingBox(self, show):
        self.clippingBox.showClippingBox(show)
        self.render()

    def showClippingPlanes(self, show):
        self.clippingBox.showClippingPlanes(show)
        self.render()

    def resetClippingBox(self):
        self.clippingBox.resetClippingBox()
        self.render()

    @Slot(object)
    def setVolumeVisualization(self, volumeVisualization):
        """
		Updates the volume property. It actually removes the volume,
		creates a new volume and sets the updated volume property and
		then adds the new volume to the renderer.
		Just updating the vtkVolumeProperty gives artifacts and seems
		to not work correctly.
		:type volumeVisualization: volumeVisualization
		"""
        self.volumeVisualization = volumeVisualization

        if self.imageData is None or self.volumeVisualization is None:
            if self.volume is not None:
                self.renderer.RemoveViewProp(self.volume)
                self.volume = None
            return

        if self.volume is None:
            self.volume = vtkVolume()
            self.renderer.AddViewProp(self.volume)

        self.volumeVisualization.setMapper(self.mapper)
        self.mapper.SetShaderType(self.volumeVisualization.shaderType())
        if self.volume.GetProperty() != self.volumeVisualization.volProp:
            self.volume.SetProperty(self.volumeVisualization.volProp)
        if self.volume.GetMapper() != self.mapper:
            self.volume.SetMapper(self.mapper)

        self.render()

    @Slot(object)
    def setSlices(self, slices):
        for sliceIndex in range(len(slices)):
            if slices[sliceIndex]:
                self.imagePlaneWidgets[sliceIndex].On()
            else:
                self.imagePlaneWidgets[sliceIndex].Off()

    @Slot(object)
    def transformationsUpdated(self, transformations):
        """
		Get the scaling transform from the transformations and apply
		it to the volume and to the grid that shows the bounds of the
		volume.

		At the moment it is deprecated. It makes more trouble than that
		it solves any real (user) problem...
		"""
        # transform = transformations.scalingTransform()
        # if self.volume:
        # 	self.volume.SetUserTransform(transform)
        # for item in self.gridItems:
        # 	item.SetUserTransform(transform)
        # self.clippingBox.setTransform(transform)
        pass

    def _syncCameras(self, camera, ev):
        """
		Camera modified event callback. Copies the parameters of
		the renderer camera into the camera of the overlay so they
		stay synced at all times.
		"""
        self.rendererOverlay.GetActiveCamera().ShallowCopy(camera)

    def _createGrid(self):
        """
		Create a grid that shows the bounds of the dataset.
		These parts need to be updated when the user is transformed.
		"""
        bounds = self.imageData.GetBounds()
        self.gridItems = CreateBounds(bounds)
        for item in self.gridItems:
            self.renderer.AddViewProp(item)

    def _createOrientationGrid(self):
        """
		Create 3 axis that show the location / coords in 3D space.
		"""
        bounds = self.imageData.GetBounds()
        self.orientationGridItems = CreateOrientationGrid(
            bounds, self.renderer.GetActiveCamera())
        for item in self.orientationGridItems:
            self.renderer.AddViewProp(item)

    def _cleanUpGrids(self):
        for item in self.gridItems:
            self.renderer.RemoveViewProp(item)
        for item in self.orientationGridItems:
            self.renderer.RemoveViewProp(item)
        self.gridItems = []
        self.orientationGridItems = []
Exemple #20
0
    def setupUi(self, Form):
        Form.setObjectName(_fromUtf8("Form"))
        Form.resize(647, 480)
        self.horizontalLayout = QtGui.QHBoxLayout(Form)
        self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
        self.gridLayout_2 = QtGui.QGridLayout()
        self.gridLayout_2.setSizeConstraint(QtGui.QLayout.SetMinimumSize)
        self.gridLayout_2.setContentsMargins(0, -1, -1, 0)
        self.gridLayout_2.setHorizontalSpacing(6)
        self.gridLayout_2.setObjectName(_fromUtf8("gridLayout_2"))
        self.verticalLayout = QtGui.QVBoxLayout()
        self.verticalLayout.setSpacing(6)
        self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
        self.label = QtGui.QLabel(Form)
        self.label.setObjectName(_fromUtf8("label"))
        self.verticalLayout.addWidget(self.label)
        self.XYPlaneWidget = QVTKRenderWindowInteractor(Form)
        self.XYPlaneWidget.setObjectName(_fromUtf8("XYPlaneWidget"))
        self.verticalLayout.addWidget(self.XYPlaneWidget)
        self.XYSlider = QtGui.QSlider(Form)
        self.XYSlider.setOrientation(QtCore.Qt.Horizontal)
        self.XYSlider.setObjectName(_fromUtf8("XYSlider"))
        self.verticalLayout.addWidget(self.XYSlider)
        self.verticalLayout.setStretch(1, 1)
        self.gridLayout_2.addLayout(self.verticalLayout, 0, 0, 1, 1)
        self.verticalLayout_2 = QtGui.QVBoxLayout()
        self.verticalLayout_2.setObjectName(_fromUtf8("verticalLayout_2"))
        self.label_3 = QtGui.QLabel(Form)
        self.label_3.setObjectName(_fromUtf8("label_3"))
        self.verticalLayout_2.addWidget(self.label_3)
        self.YZPlaneWidget = QVTKRenderWindowInteractor(Form)
        self.YZPlaneWidget.setObjectName(_fromUtf8("YZPlaneWidget"))
        self.verticalLayout_2.addWidget(self.YZPlaneWidget)
        self.YZSlider = QtGui.QSlider(Form)
        self.YZSlider.setOrientation(QtCore.Qt.Horizontal)
        self.YZSlider.setObjectName(_fromUtf8("YZSlider"))
        self.verticalLayout_2.addWidget(self.YZSlider)
        self.verticalLayout_2.setStretch(1, 1)
        self.gridLayout_2.addLayout(self.verticalLayout_2, 0, 1, 1, 1)
        self.verticalLayout_3 = QtGui.QVBoxLayout()
        self.verticalLayout_3.setObjectName(_fromUtf8("verticalLayout_3"))
        self.label_2 = QtGui.QLabel(Form)
        self.label_2.setObjectName(_fromUtf8("label_2"))
        self.verticalLayout_3.addWidget(self.label_2)
        self.XZPlaneWidget = QVTKRenderWindowInteractor(Form)
        self.XZPlaneWidget.setObjectName(_fromUtf8("XZPlaneWidget"))
        self.verticalLayout_3.addWidget(self.XZPlaneWidget)
        self.XZSlider = QtGui.QSlider(Form)
        self.XZSlider.setOrientation(QtCore.Qt.Horizontal)
        self.XZSlider.setObjectName(_fromUtf8("XZSlider"))
        self.verticalLayout_3.addWidget(self.XZSlider)
        self.verticalLayout_3.setStretch(1, 1)
        self.gridLayout_2.addLayout(self.verticalLayout_3, 1, 0, 1, 1)
        self.verticalLayout_5 = QtGui.QVBoxLayout()
        self.verticalLayout_5.setObjectName(_fromUtf8("verticalLayout_5"))
        self.label_4 = QtGui.QLabel(Form)
        self.label_4.setObjectName(_fromUtf8("label_4"))
        self.verticalLayout_5.addWidget(self.label_4)
        self.VolumeWidget = QVTKRenderWindowInteractor(Form)
        self.VolumeWidget.setObjectName(_fromUtf8("VolumeWidget"))
        self.verticalLayout_5.addWidget(self.VolumeWidget)
        self.verticalLayout_5.setStretch(1, 1)
        self.gridLayout_2.addLayout(self.verticalLayout_5, 1, 1, 1, 1)
        self.horizontalLayout.addLayout(self.gridLayout_2)
        self.gridLayout = QtGui.QGridLayout()
        self.gridLayout.setSizeConstraint(QtGui.QLayout.SetDefaultConstraint)
        self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
        self.WindowWidthLabel = QtGui.QLabel(Form)
        self.WindowWidthLabel.setObjectName(_fromUtf8("WindowWidthLabel"))
        self.gridLayout.addWidget(self.WindowWidthLabel, 2, 0, 1, 1)
        self.WindowWidthSlider = QtGui.QSlider(Form)
        self.WindowWidthSlider.setOrientation(QtCore.Qt.Horizontal)
        self.WindowWidthSlider.setObjectName(_fromUtf8("WindowWidthSlider"))
        self.gridLayout.addWidget(self.WindowWidthSlider, 2, 1, 1, 1)
        self.WindowControlLabel = QtGui.QLabel(Form)
        self.WindowControlLabel.setFrameShape(QtGui.QFrame.NoFrame)
        self.WindowControlLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.WindowControlLabel.setObjectName(_fromUtf8("WindowControlLabel"))
        self.gridLayout.addWidget(self.WindowControlLabel, 0, 0, 1, 1)
        self.WindowCenterLabel = QtGui.QLabel(Form)
        self.WindowCenterLabel.setObjectName(_fromUtf8("WindowCenterLabel"))
        self.gridLayout.addWidget(self.WindowCenterLabel, 1, 0, 1, 1)
        self.WindowCenterSlider = QtGui.QSlider(Form)
        self.WindowCenterSlider.setOrientation(QtCore.Qt.Horizontal)
        self.WindowCenterSlider.setObjectName(_fromUtf8("WindowCenterSlider"))
        self.gridLayout.addWidget(self.WindowCenterSlider, 1, 1, 1, 1)
        spacerItem = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
        self.gridLayout.addItem(spacerItem, 3, 0, 1, 1)
        self.horizontalLayout.addLayout(self.gridLayout)
        self.horizontalLayout.setStretch(0, 3)
        self.horizontalLayout.setStretch(1, 1)

        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)
class Visualizer3Dvtk():
    def __init__(self, dataContainer):
        self.dataContainer = dataContainer
        self._GetAvailable3DFields()
        self.volumeList = list()
        self.volume = None
        self.volumeMapper = None

    def _GetAvailable3DFields(self):
        self.availableFields = list()
        speciesList = self.dataContainer.GetAvailableSpecies()
        domainFields = self.dataContainer.GetAvailableDomainFields()
        for species in speciesList:
            for field in species.GetAvailableFields():
                #if field.GetFieldDimension() == "3D":
                self.availableFields.append(field)
        for field in domainFields:
            #if field.GetFieldDimension() == "3D":
            self.availableFields.append(field)

    def GetListOfAvailable3DFields(self):
        namesList = list()
        for field in self.availableFields:
            namesList.append({
                "fieldName": field.GetName(),
                "speciesName": field.GetSpeciesName()
            })
        return namesList

    def GetTimeSteps(self):
        i = 0
        timeSteps = np.array([0])
        for volume in self.volumeList:
            if i == 0:
                timeSteps = volume.GetTimeSteps()
            else:
                timeSteps = np.intersect1d(timeSteps, volume.GetTimeSteps())
            i += 1
        return timeSteps

    def GetVTKWidget(self, parentWidget):
        self.vtkWidget = QVTKRenderWindowInteractor(parentWidget)
        self.renderer = vtk.vtkRenderer()
        self.renderer.SetBackground(0, 0, 0)
        self.vtkWidget.GetRenderWindow().AddRenderer(self.renderer)
        self.interactor = self.vtkWidget.GetRenderWindow().GetInteractor()
        self.interactor.Initialize()
        self.vtkCamera = self.renderer.GetActiveCamera()
        return self.vtkWidget

    def AddVolumeField(self, fieldName, speciesName):
        if speciesName == "":
            for volume in self.volumeList:
                if (volume.GetFieldName() == fieldName):
                    return False
            self.volumeList.append(
                VolumeVTK(self.dataContainer.GetDomainField(fieldName)))
            return True
        else:
            for volume in self.volumeList:
                if (volume.GetFieldName()
                        == fieldName) and (volume.GetSpeciesName()
                                           == speciesName):
                    return False
            self.volumeList.append(
                VolumeVTK(
                    self.dataContainer.GetSpeciesField(speciesName,
                                                       fieldName)))
            return True

    def RemoveVolumeFromName(self, fieldName, speciesName):
        for volumeField in self.volumeList:
            if (volumeField.GetFieldName()
                    == fieldName) and (volumeField.GetSpeciesName()
                                       == speciesName):
                self.volumeList.remove(volumeField)
                return

    def RemoveVolume(self, volume):
        self.volumeList.remove(volume)

    def GetVolumeField(self, fieldName, speciesName):
        for volume in self.volumeList:
            if (volume.name == fieldName) and (volume.speciesName
                                               == speciesName):
                return volume

    def CreateVolume(self, timeStep):
        firstTime = False
        # Get data
        npdatauchar = list()
        volumeprop = vtk.vtkVolumeProperty()
        volumeprop.IndependentComponentsOn()
        volumeprop.SetInterpolationTypeToLinear()
        for i, volume in enumerate(self.volumeList):
            npdatauchar.append(volume.GetData(
                timeStep, 200, 300,
                0.5))  # limit on elements only applies for 2d case
            volumeprop.SetColor(i, volume.color)
            volumeprop.SetScalarOpacity(i, volume.opacity)
            volumeprop.ShadeOff(i)
        npdatamulti = np.concatenate(
            [aux[..., np.newaxis] for aux in npdatauchar], axis=3)
        axes = self.volumeList[0].GetAxes(timeStep)
        axesSpacing = self.volumeList[0].GetAxesSpacing(
            timeStep, 200, 300,
            0.5)  # limit on elements only applies for 2d case
        # Put data in VTK format
        dataImport = vtk.vtkImageImport()
        dataImport.SetImportVoidPointer(npdatamulti)
        dataImport.SetDataScalarTypeToUnsignedChar()
        dataImport.SetNumberOfScalarComponents(len(self.volumeList))
        dataImport.SetDataExtent(0, npdatamulti.shape[2] - 1, 0,
                                 npdatamulti.shape[1] - 1, 0,
                                 npdatamulti.shape[0] - 1)
        dataImport.SetWholeExtent(0, npdatamulti.shape[2] - 1, 0,
                                  npdatamulti.shape[1] - 1, 0,
                                  npdatamulti.shape[0] - 1)
        dataImport.SetDataSpacing(axesSpacing["x"], axesSpacing["y"],
                                  axesSpacing["z"])
        dataImport.SetDataOrigin(axes["x"][0], axes["y"][0], axes["z"][0])
        dataImport.Update()
        # Set the mapper
        if self.volumeMapper == None:
            self.volumeMapper = vtk.vtkGPUVolumeRayCastMapper()
        self.volumeMapper.SetAutoAdjustSampleDistances(1)
        self.volumeMapper.SetInputConnection(dataImport.GetOutputPort())
        self.volumeMapper.Update()
        # Create volume
        if self.volume == None:
            self.volume = vtk.vtkVolume()
            firstTime = True
            self.volume.SetMapper(self.volumeMapper)
            self.volume.SetProperty(volumeprop)
        # Add to render
        if firstTime:
            self.renderer.AddVolume(self.volume)
        else:
            self.volume.Modified()
        if firstTime:
            self.renderer.ResetCamera()
            self.renderer.GetRenderWindow().Render()
        else:
            #currentCameraPosition = np.array(self.renderer.GetActiveCamera().GetPosition())
            #newDataOrigin = np.array((axes["x"][0],axes["y"][0],axes["z"][0]))
            #newCameraPosition = newDataOrigin - self.pastDataOrigin + currentCameraPosition
            self.renderer.ResetCamera()
            #self.renderer.GetActiveCamera().SetPosition(newCameraPosition[0],newCameraPosition[1],newCameraPosition[2])
            self.vtkWidget.GetRenderWindow().Render()
        #self.pastDataOrigin = np.array((axes["x"][0],axes["y"][0],axes["z"][0]))
        self.interactor.Initialize()

    def MakeRender(self, timeStep):
        self.CreateVolume(timeStep)

    def UpdateRender(self):
        self.interactor.Render()

    def SaveScreenshot(self, path):
        w2if = vtk.vtkWindowToImageFilter()
        w2if.SetInput(self.vtkWidget.GetRenderWindow())
        w2if.Update()

        writer = vtk.vtkPNGWriter()
        writer.SetFileName(path + ".png")
        writer.SetInputData(w2if.GetOutput())
        writer.Write()
Exemple #22
0
class ShowSegmentationWidget(QtGui.QWidget):
    def __init__(self,
                 segmentation=None,
                 vtk_file="mesh_{}.vtk",
                 *args,
                 **kwargs):
        super(ShowSegmentationWidget, self).__init__()
        self.ui_buttons = {}

        self.show_load_interface = False
        if "show_load_button" in kwargs:
            self.show_load_interface = kwargs.pop("show_load_button")
        if "show_load_interface" in kwargs:
            self.show_load_interface = kwargs.pop("show_load_interface")

        self.segmentation = None
        self.init_parameters()
        # self.slab_wg =
        # self.init_slab()
        self.vtk_file = vtk_file
        self._init_ui()
        if segmentation is not None:
            logger.debug("segmentation is not none")
            self.add_data(segmentation, *args, **kwargs)

    # def init_slab(self):
    #     self.

    def add_data_file(self, filename):
        import io3d
        datap = io3d.read(filename, dataplus_format=True)
        if not 'segmentation' in datap.keys():
            datap['segmentation'] = datap['data3d']

        self.add_data(**datap)

    def init_parameters(self):
        self.resize_mm = None
        self.resize_voxel_number = 10000
        self.degrad = 1
        self.smoothing = True

    def add_data(self,
                 segmentation,
                 voxelsize_mm=[1, 1, 1],
                 slab=None,
                 **kwargs):
        # self.data3d = data3d
        self.segmentation = segmentation
        self.voxelsize_mm = np.asarray(voxelsize_mm)
        self.slab = slab
        self.init_parameters()

        self.init_slab(slab)

        self.update_slab_ui()

    def init_slab(self, slab=None):
        """

        :param slab:
        :return:
        """

        self.slab_wg.init_slab(slab=slab,
                               segmentation=self.segmentation,
                               voxelsize_mm=self.voxelsize_mm)

    def update_slab_ui(self):
        self.slab_wg.update_slab_ui()

    def _init_ui(self):

        self.mainLayout = QGridLayout(self)

        self._row = 0

        if self.show_load_interface:
            keyword = "add_data_file"
            self.ui_buttons[keyword] = QPushButton("Load volumetric data",
                                                   self)
            self.ui_buttons[keyword].clicked.connect(
                self._ui_callback_add_data_file)
            self.mainLayout.addWidget(self.ui_buttons[keyword], self._row, 1,
                                      1, 3)

            self._row += 1
            lblSegConfig = QLabel('Labels')
            self.mainLayout.addWidget(lblSegConfig, self._row, 1, 1, 6)

            # self.slab_widget = QGridLayout(self)
            # self.mainLayout.addWidget(self.slab_widget, self._row, 1)

            self._row += 1
            self.slab_wg = SelectLabelWidget()
            self.slab_wg.init_slab()
            self.slab_wg.update_slab_ui()
            self.mainLayout.addWidget(self.slab_wg, self._row, 1, 1, 3)
            # self._row = self.update_slab_ui()

            self._row = 10
            self._row += 1
            keyword = "resize_voxel_number"
            resizeQLabel = QLabel('Resize [voxel number]')
            self.mainLayout.addWidget(resizeQLabel, self._row, 1)

            self.ui_buttons[keyword] = QLineEdit()
            self.ui_buttons[keyword].setText(str(self.resize_voxel_number))
            self.mainLayout.addWidget(self.ui_buttons[keyword], self._row, 2)

            self._row += 1
            keyword = "resize_mm"
            resizeQLabel = QLabel('Resize [mm]')
            self.mainLayout.addWidget(resizeQLabel, self._row, 1)
            self.mainLayout.setColumnMinimumWidth(2, 100)

            self.ui_buttons[keyword] = QLineEdit()
            self.ui_buttons[keyword].setText(str(self.resize_mm))
            self.mainLayout.addWidget(self.ui_buttons[keyword], self._row, 2)

            self._row += 1
            keyword = "degrad"
            resizeQLabel = QLabel('Degradation')
            self.mainLayout.addWidget(resizeQLabel, self._row, 1)

            self.ui_buttons[keyword] = QLineEdit()
            self.ui_buttons[keyword].setText(str(self.degrad))
            self.mainLayout.addWidget(self.ui_buttons[keyword], self._row, 2)

            self._row += 1
            keyword = "smoothing"
            # smoothingQLabel= QLabel(keyword)
            # self.mainLayout.addWidget(smoothingQLabel, self._row, 1)

            self.ui_buttons[keyword] = QCheckBox(keyword, self)
            # self.ui_buttons[keyword].setTristate(False)
            if self.smoothing:
                sm_state = QtCore.Qt.Checked
            else:
                sm_state = QtCore.Qt.Unchecked
            self.ui_buttons[keyword].setCheckState(sm_state)
            self.mainLayout.addWidget(self.ui_buttons[keyword], self._row, 1)

            self._row += 1
            sopw = io3d.outputqt.SelectOutputPathWidget(path=self.vtk_file,
                                                        parent=self)
            self.ui_buttons["output file"] = sopw
            self.mainLayout.addWidget(sopw, self._row, 1, 1, 3)
            sopw.show()

            # keyword = "vtk_file"
            # vtk_fileQLabel= QLabel("Output VTK file")
            # self.mainLayout.addWidget(vtk_fileQLabel, self._row, 1)
            #
            # self.ui_buttons[keyword] = QLineEdit()
            # self.ui_buttons[keyword].setText(str(self.vtk_file))
            # self.mainLayout.addWidget(self.ui_buttons[keyword], self._row, 2)
            # keyword = "vkt_file_button"
            # self.ui_buttons[keyword] = QPushButton("Set", self)
            # self.ui_buttons[keyword].clicked.connect(self.action_select_vtk_file)
            # self.mainLayout.addWidget(self.ui_buttons[keyword], self._row, 3)

            self._row += 1
            keyword = "Show volume"
            self.ui_buttons[keyword] = QPushButton(keyword, self)
            self.ui_buttons[keyword].clicked.connect(self.actionShow)
            self.mainLayout.addWidget(self.ui_buttons[keyword], self._row, 1,
                                      1, 3)

            self._row += 1
            keyword = "Save each"
            self.ui_buttons[keyword] = QPushButton(keyword, self)
            self.ui_buttons[keyword].clicked.connect(self._action_save_all)
            self.mainLayout.addWidget(self.ui_buttons[keyword], self._row, 1,
                                      1, 3)

            self._row += 1
            keyword = "Add extern file"
            self.ui_buttons[keyword] = QPushButton(keyword, self)
            self.ui_buttons[keyword].clicked.connect(
                self._ui_action_add_vtk_file)
            self.mainLayout.addWidget(self.ui_buttons[keyword], self._row, 1,
                                      1, 3)

            self._row += 1
            keyword = "Clear"
            self.ui_buttons[keyword] = QPushButton(keyword, self)
            self.ui_buttons[keyword].clicked.connect(self.clear_3d_viewer)
            self.mainLayout.addWidget(self.ui_buttons[keyword], self._row, 1,
                                      1, 3)

        # vtk + pyqt
        self._viewer_height = self._row
        self._init_3d_viewer()

    def _init_3d_viewer(self):
        logger.debug("init 3d view")
        self.renderer = vtk.vtkRenderer()
        self.vtkWidget = QVTKRenderWindowInteractor(self)
        self.mainLayout.addWidget(self.vtkWidget, 0, 4,
                                  self._viewer_height + 1, 1)
        self.renWin = self.vtkWidget.GetRenderWindow()
        self.renWin.AddRenderer(self.renderer)

        # vtkviewer
        import vtkviewer
        self.vtkv = vtkviewer.VTKViewer()
        self.vtkv.renderer = self.renderer
        self.vtkv.iren = self.vtkWidget
        self.vtkv.renWin = self.renWin
        self.vtkWidget.resize(300, 300)
        self.updateGeometry()
        self.vtkv_started = False

    def vtkv_start(self):
        if not self.vtkv_started:
            self.vtkv.Start()

    def action_select_vtk_file(self):
        self.ui_buttons["vtk_file"].setText(QFileDialog.getSaveFileName())

    def _ui_callback_add_data_file(self):
        self.add_data_file(str(QFileDialog.getOpenFileName()))

    def add_vtk_file(self, filename):
        self.vtkv.AddFile(filename)
        self.vtkv_start()

    def add_vtk_polydata(self, polydata, colormap=None):
        self.vtkv.AddPolyData(polydata, colormap)
        self.vtkv_start()

    def _ui_action_add_vtk_file(self):
        fn = str(QFileDialog.getOpenFileName())
        import os.path as op
        ext = op.splitext(fn)[1]
        if ext == ".yaml":
            import gen_vtk_tree
            polydata = gen_vtk_tree.vt_file2polyData(fn)
            self.add_vtk_polydata(polydata)
        else:
            self.add_vtk_file(fn)

        # self.vtkv.Start()
        # or show win
        # self.renWin.Render()
        # self.vtkv.iren.Start()

    def clear_3d_viewer(self):
        ren = self.renderer
        actors = self.renderer.GetActors()
        act = actors.GetLastActor()
        while act is not None:
            ren.RemoveActor(act)
            act = actors.GetLastActor()

        # self.renderer.removeAllViewProps()
        # self.renderer = None
        # self.mainLayout.removeWidget(self.vtkWidget)
        # self.vtkWidget.deleteLater()
        # self.vtkWidget = None
        # self.renWin = None
        # self._init_3d_viewer()
        # self.vtkWidget.show()

    def _find_None(self, lineedit):
        text = str(lineedit.text())

        print("find none ", text)
        if text == "None":
            text = None
        else:
            text = float(text)

        return text

    def action_ui_params(self):
        self.resize_mm = self._find_None(self.ui_buttons['resize_mm'])
        self.resize_voxel_number = self._find_None(
            self.ui_buttons['resize_voxel_number'])
        self.degrad = self._find_None(self.ui_buttons['degrad'])
        self.smoothing = self.ui_buttons['smoothing'].isChecked()
        self.vtk_file = str(self.ui_buttons["output file"].get_path())

        # print("degrad", self.degrad)

    def _action_save_all(self):
        # slab = self.slab
        labels = self.slab_wg.action_check_slab_ui()
        self.action_ui_params()
        # imma.get_nlabel()

        # for lab in labels:
        #     # labi = slab[lab]
        #     strlabel = imma.get_nlabels(slab=self.slab_wg.slab, labels=lab, return_mode="str")
        #     logger.debug(strlabel)
        #     filename = self.vtk_file.format(strlabel)
        #     logger.debug(filename)
        self.show_labels(labels, self.vtk_file, together_vtk_file=False)

    def get_filename_filled_with_checked_labels(self, labels=None):
        """ Fill used labels into filename """
        if labels is None:
            labels = self.slab_wg.action_check_slab_ui()
        string_labels = imma.get_nlabels(slab=self.slab_wg.slab,
                                         labels=labels,
                                         return_mode="str")
        filename = self.vtk_file.format("-".join(string_labels))
        return filename

    def actionShow(self):
        logger.debug("actionShow")
        labels = self.slab_wg.action_check_slab_ui()
        self.action_ui_params()
        filename = self.get_filename_filled_with_checked_labels(labels)
        self.show_labels(labels, filename)

    def show_labels(self, labels, vtk_file, together_vtk_file=True):
        from . import show_segmentation
        # ds = show_segmentation.select_labels(self.segmentation, labels, slab=self.slab_wg.slab)
        # if ds.max() == False:
        #     logger.info("Nothing found for labels " + str(labels))
        #     return
        # show_segmentation.SegmentationToVTK()
        s2vtk = show_segmentation.SegmentationToMesh(self.segmentation,
                                                     self.voxelsize_mm,
                                                     slab=self.slab_wg.slab)
        s2vtk.set_resize_parameters(
            degrad=self.degrad,
            labels=labels,
            resize_mm=self.resize_mm,
            resize_voxel_number=self.resize_voxel_number,
        )
        s2vtk.set_labels(labels)
        if together_vtk_file:

            s2vtk.set_output(filename=vtk_file,
                             smoothing=self.smoothing,
                             one_file_per_label=False)

            # vtk_files = s2vtk.make_mesh_file(
            #     # self.segmentation,
            #     labels=labels,
            #     vtk_file=vtk_file,
            #     smoothing=self.smoothing,
            # )
        else:
            s2vtk.set_output(filename=vtk_file,
                             smoothing=self.smoothing,
                             one_file_per_label=True)
            # vtk_files = s2vtk.make_mesh_files(
            #     # self.segmentation,
            #     labels=labels,
            #     vtk_file=vtk_file,
            #     smoothing=self.smoothing,
            # )
        s2vtk.make_mesh()

        # self._run_viewer()
        if together_vtk_file:
            self.vtkv.AddFile(vtk_file)
            self.vtkv.Start()
        else:
            for vtkf in vtk_files:
                self.vtkv.AddFile(vtkf)
                self.vtkv.Start()
Exemple #23
0
 def __init__(self, parent=None):
     QVTKRenderWindowInteractor.__init__(self, parent)
     self.GetRenderWindow().GetInteractor().SetInteractorStyle(
         vtk.vtkInteractorStyleTrackballCamera())
Exemple #24
0
    def __init__(self, parent=None):
        super(VTKFrame, self).__init__(parent)

        self.vtkWidget = QVTKRenderWindowInteractor(self)
        vl = QtGui.QVBoxLayout(self)
        vl.addWidget(self.vtkWidget)
        vl.setContentsMargins(0, 0, 0, 0)

        self.ren = vtk.vtkRenderer()
        self.ren.SetBackground(0.2, 0.3, 0.4)
        self.vtkWidget.GetRenderWindow().AddRenderer(self.ren)
        self.iren = self.vtkWidget.GetRenderWindow().GetInteractor()

        # Create Spiral tube
        nV = 256  #No. of vertices
        nCyc = 5  #No. of spiral cycles
        rT1, rT2 = 0.1, 0.5  #Start/end tube radii
        rS = 2.0  #Spiral radius
        h = 10.0
        nTv = 8  #No. of surface elements for each tube vertex

        points = vtk.vtkPoints()
        for i in range(nV):
            vX = rS * math.cos(2 * math.pi * nCyc * i / (nV - 1))
            vY = rS * math.sin(2 * math.pi * nCyc * i / (nV - 1))
            vZ = h * i / nV
            points.InsertPoint(i, vX, vY, vZ)

        lines = vtk.vtkCellArray()
        lines.InsertNextCell(nV)
        for i in range(nV):
            lines.InsertCellPoint(i)

        polyData = vtk.vtkPolyData()
        polyData.SetPoints(points)
        polyData.SetLines(lines)

        # Varying tube radius using sine-function
        tubeRadius = vtk.vtkDoubleArray()
        tubeRadius.SetName("TubeRadius")
        tubeRadius.SetNumberOfTuples(nV)
        for i in range(nV):
            tubeRadius.SetTuple1(
                i, rT1 + (rT2 - rT1) * math.sin(math.pi * i / (nV - 1)))

        polyData.GetPointData().AddArray(tubeRadius)
        polyData.GetPointData().SetActiveScalars("TubeRadius")

        # RGB array, Varying from blue to red
        colors = vtk.vtkUnsignedCharArray()
        colors.SetName("Colors")
        colors.SetNumberOfComponents(3)
        colors.SetNumberOfTuples(nV)
        for i in range(nV):
            colors.InsertTuple3(i, int(255 * i / (nV - 1)), 0,
                                int(255 * (nV - 1 - i) / (nV - 1)))

        polyData.GetPointData().AddArray(colors)

        tube = vtk.vtkTubeFilter()
        tube.SetInput(polyData)
        tube.SetNumberOfSides(nTv)
        tube.SetVaryRadiusToVaryRadiusByAbsoluteScalar()

        # Create a mapper
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(tube.GetOutputPort())
        mapper.ScalarVisibilityOn()
        mapper.SetScalarModeToUsePointFieldData()
        mapper.SelectColorArray("Colors")

        # Create an actor
        actor = vtk.vtkActor()
        actor.SetMapper(mapper)

        self.ren.AddActor(actor)
        self.ren.ResetCamera()

        self._initialized = False
Exemple #25
0
    def __init__(self, parent=None):
        QtGui.QMainWindow.__init__(self, parent)

        self.state = {"test", "stuff", "other"}
        self.data = GuiData()
        self.vtkActorList = []

        self.frame = QtGui.QFrame()
        self.resize(1000, 600)
        self.setWindowTitle('ProteusCFD')
        self.move(100, 100)

        self.vl = QtGui.QHBoxLayout()
        self.vl.setSpacing(10)

        self.frame.setLayout(self.vl)
        self.setCentralWidget(self.frame)

        #create tabs dialog and add it to the layout
        self.tabs = QtGui.QTabWidget()
        self.vl.addWidget(self.tabs, 1.0)

        #Setup our tree view
        self.treeWidget = QtGui.QTreeWidget()
        self.treeWidget.setHeaderHidden(True)
        self.addItems(self.treeWidget.invisibleRootItem())
        self.treeWidget.itemChanged.connect(self.handleChanged)
        self.tabs.addTab(self.treeWidget, "Physics Options")

        #setup solution control tab
        SolutionControlTab = QtGui.QWidget()
        self.tabs.addTab(SolutionControlTab, "Solution Control")

        #setup boundary condition tab
        self.BCTab1 = BCTab(self.data, self.visibilityChanged)
        self.tabs.addTab(self.BCTab1, "Boundary Conditions")

        #draw the tabs
        self.tabs.show()

        #Setup our menu and actions
        exitAction = QtGui.QAction('Exit', self)
        exitAction.setShortcut('Ctrl+Q')
        exitAction.setStatusTip('Exit application')
        exitAction.triggered.connect(self.close)

        saveAction = QtGui.QAction('Save', self)
        saveAction.setShortcut('Ctril+S')
        saveAction.setStatusTip('Save config')
        saveAction.triggered.connect(self.save)

        loadAction = QtGui.QAction('Load', self)
        loadAction.setStatusTip('Load config')
        loadAction.triggered.connect(self.load)

        openFileAction = QtGui.QAction('Import', self)
        openFileAction.setStatusTip('Import Grid')
        openFileAction.triggered.connect(self.selectFile)

        self.menubar = self.menuBar()
        fileMenu = self.menubar.addMenu('&File')
        fileMenu.addAction(exitAction)
        fileMenu.addAction(saveAction)
        fileMenu.addAction(loadAction)
        fileMenu.addAction(openFileAction)

        self.statusBar().showMessage('Waiting...')

        #Setup our vtk widget
        self.vtkWidget = QVTKRenderWindowInteractor(self.frame)
        self.vl.addWidget(self.vtkWidget, 2.0)

        #renderer inherits from vtkViewport so we have access to these members
        self.ren = vtk.vtkRenderer()
        self.ren.SetBackground(0.5, 0.5, 0.5)
        self.ren.SetBackground2(.5, .8, .5)
        self.ren.GradientBackgroundOn()
        self.ren.ResetCamera()

        self.vtkWidget.GetRenderWindow().AddRenderer(self.ren)
        self.iren = self.vtkWidget.GetRenderWindow().GetInteractor()
        self.iren.AddObserver("KeyPressEvent", self.keyPressVTK)

        #create axes
        axes = vtk.vtkAxesActor()
        self.ren.AddActor(axes)
        scale = vtk.vtkTransform()
        scale.Scale(0.5, 0.5, 0.5)
        axes.SetUserTransform(scale)
        translate = vtk.vtkTransform()
        translate.Translate(-0.5, -0.5, -0.5)
        axes.SetUserTransform(translate)

        self.show()
        self.iren.Initialize()
Exemple #26
0
class MainWindow(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QMainWindow.__init__(self, parent)

        self.state = {"test", "stuff", "other"}
        self.data = GuiData()
        self.vtkActorList = []

        self.frame = QtGui.QFrame()
        self.resize(1000, 600)
        self.setWindowTitle('ProteusCFD')
        self.move(100, 100)

        self.vl = QtGui.QHBoxLayout()
        self.vl.setSpacing(10)

        self.frame.setLayout(self.vl)
        self.setCentralWidget(self.frame)

        #create tabs dialog and add it to the layout
        self.tabs = QtGui.QTabWidget()
        self.vl.addWidget(self.tabs, 1.0)

        #Setup our tree view
        self.treeWidget = QtGui.QTreeWidget()
        self.treeWidget.setHeaderHidden(True)
        self.addItems(self.treeWidget.invisibleRootItem())
        self.treeWidget.itemChanged.connect(self.handleChanged)
        self.tabs.addTab(self.treeWidget, "Physics Options")

        #setup solution control tab
        SolutionControlTab = QtGui.QWidget()
        self.tabs.addTab(SolutionControlTab, "Solution Control")

        #setup boundary condition tab
        self.BCTab1 = BCTab(self.data, self.visibilityChanged)
        self.tabs.addTab(self.BCTab1, "Boundary Conditions")

        #draw the tabs
        self.tabs.show()

        #Setup our menu and actions
        exitAction = QtGui.QAction('Exit', self)
        exitAction.setShortcut('Ctrl+Q')
        exitAction.setStatusTip('Exit application')
        exitAction.triggered.connect(self.close)

        saveAction = QtGui.QAction('Save', self)
        saveAction.setShortcut('Ctril+S')
        saveAction.setStatusTip('Save config')
        saveAction.triggered.connect(self.save)

        loadAction = QtGui.QAction('Load', self)
        loadAction.setStatusTip('Load config')
        loadAction.triggered.connect(self.load)

        openFileAction = QtGui.QAction('Import', self)
        openFileAction.setStatusTip('Import Grid')
        openFileAction.triggered.connect(self.selectFile)

        self.menubar = self.menuBar()
        fileMenu = self.menubar.addMenu('&File')
        fileMenu.addAction(exitAction)
        fileMenu.addAction(saveAction)
        fileMenu.addAction(loadAction)
        fileMenu.addAction(openFileAction)

        self.statusBar().showMessage('Waiting...')

        #Setup our vtk widget
        self.vtkWidget = QVTKRenderWindowInteractor(self.frame)
        self.vl.addWidget(self.vtkWidget, 2.0)

        #renderer inherits from vtkViewport so we have access to these members
        self.ren = vtk.vtkRenderer()
        self.ren.SetBackground(0.5, 0.5, 0.5)
        self.ren.SetBackground2(.5, .8, .5)
        self.ren.GradientBackgroundOn()
        self.ren.ResetCamera()

        self.vtkWidget.GetRenderWindow().AddRenderer(self.ren)
        self.iren = self.vtkWidget.GetRenderWindow().GetInteractor()
        self.iren.AddObserver("KeyPressEvent", self.keyPressVTK)

        #create axes
        axes = vtk.vtkAxesActor()
        self.ren.AddActor(axes)
        scale = vtk.vtkTransform()
        scale.Scale(0.5, 0.5, 0.5)
        axes.SetUserTransform(scale)
        translate = vtk.vtkTransform()
        translate.Translate(-0.5, -0.5, -0.5)
        axes.SetUserTransform(translate)

        self.show()
        self.iren.Initialize()

    def addItems(self, parent):
        column = 0
        clients_item = self.addParent(parent, column, 'Clients',
                                      'data Clients')
        vendors_item = self.addParent(parent, column, 'Vendors',
                                      'data Vendors')
        time_period_item = self.addParent(parent, column, 'Time Period',
                                          'data Time Period')

        self.addChild(clients_item, column, 'Type A', 'data Type A')
        self.addChild(clients_item, column, 'Type B', 'data Type B')

        self.addChild(vendors_item, column, 'Mary', 'data Mary')
        self.addChild(vendors_item, column, 'Arnold', 'data Arnold')

        self.addChild(time_period_item, column, 'Init', 'data Init')
        self.addChild(time_period_item, column, 'End', 'data End')

    def addParent(self, parent, column, title, data):
        item = QtGui.QTreeWidgetItem(parent, [title])
        item.setData(column, QtCore.Qt.UserRole, data)
        item.setChildIndicatorPolicy(QtGui.QTreeWidgetItem.ShowIndicator)
        item.setExpanded(True)
        return item

    def addChild(self, parent, column, title, data):
        item = QtGui.QTreeWidgetItem(parent, [title])
        item.setData(column, QtCore.Qt.UserRole, data)
        item.setCheckState(column, QtCore.Qt.Unchecked)
        return item

    def handleChanged(self, item, column):
        if item.checkState(column) == QtCore.Qt.Checked:
            print "checked", item, item.text(column)
        if item.checkState(column) == QtCore.Qt.Unchecked:
            print "unchecked", item, item.text(column)

    def visibilityChanged(self, vtkGridPartId, factagId, state):
        if state == QtCore.Qt.Checked:
            self.vtkActorList[vtkGridPartId].VisibilityOn()
            self.iren.Render()
            print "visibility On for factag: ", factagId
        else:
            self.vtkActorList[vtkGridPartId].VisibilityOff()
            self.iren.Render()
            print "visibility Off for factag: ", factagId

    def save(self):
        filename = "proteusCFD.state"
        pickle.dump(self.state, open(filename, "wb"))

    def load(self):
        filename = "proteusCFD.state"
        self.state = pickle.load(open(filename, "rb"))
        print self.state

    def selectFile(self):
        meshFile = str(QtGui.QFileDialog.getOpenFileName())
        input = meshFile.split('.')
        parts = input[0].split('/')
        self.casename = parts[-1]
        parts = parts[0:-1]
        path = "/"
        for item in parts:
            path = path + item + '/'
        print 'Selected casename ' + self.casename
        print 'Case path ' + path
        self.clearMesh()
        self.readMesh(path, self.casename)

    # resets view for the camera to centered facing y
    def resetCamera(self, direction):
        self.ren.ResetCamera()
        fp = self.ren.GetActiveCamera().GetFocalPoint()
        p = self.ren.GetActiveCamera().GetPosition()
        dist = math.sqrt((p[0] - fp[0])**2 + (p[1] - fp[1])**2 +
                         (p[2] - fp[2])**2)
        if direction == "z":
            self.ren.GetActiveCamera().SetPosition(fp[0], fp[1], fp[2] + dist)
            self.ren.GetActiveCamera().SetViewUp(0.0, 1.0, 0.0)
        elif direction == "y":
            self.ren.GetActiveCamera().SetPosition(fp[0], fp[1] + dist, fp[2])
            self.ren.GetActiveCamera().SetViewUp(0.0, 0.0, 1.0)
        elif direction == "x":
            self.ren.GetActiveCamera().SetPosition(fp[0] + dist, fp[1], fp[2])
            self.ren.GetActiveCamera().SetViewUp(0.0, 1.0, 0.0)
        self.iren.Render()

    def keyPressVTK(self, obj, event):
        print "Key pressed " + str(obj.GetKeyCode()) + " " + str(
            obj.GetKeySym())
        self.keyPressEvent(str(obj.GetKeyCode()))

    def keyPressEvent(self, keyName):
        if keyName == "x":
            self.resetCamera("x")
        elif keyName == "y":
            self.resetCamera("y")
        elif keyName == "z":
            self.resetCamera("z")
        elif keyName == "c":
            self.clearMesh()

    def clearMesh(self):
        for part in self.vtkActorList:
            self.ren.RemoveActor(part)
        self.vtkActorList = []
        self.data.clear()
        self.iren.Render()

        #update mesh visibility options
        self.BCTab1.drawBCVizBoxes()

    def readMesh(self, path, casename):
        #read the mesh
        self.data.loadMesh(path, casename)

        # Create actors based on grid parts
        self.vtkActorList = []
        vtkgrids = self.data.buildVTKGrids()
        itag = 0
        c = colors()
        for vtkgrid in vtkgrids:
            mapper = vtk.vtkDataSetMapper()
            mapper.SetInput(vtkgrid)
            self.vtkActorList.append(vtk.vtkActor())
            self.vtkActorList[-1].SetMapper(mapper)
            self.vtkActorList[-1].GetProperty().SetColor(c.getNext())
            # set visibility of volumes to false on startup
            if int(self.data.elemGroups[itag]) < 0:
                self.vtkActorList[-1].VisibilityOff()
            itag = itag + 1

        #visualize the grid
        for actor in self.vtkActorList:
            self.ren.AddActor(actor)
        self.iren.Render()

        #update mesh visibility options
        self.BCTab1.drawBCVizBoxes()
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(790, 571)
        self.centralWidget = QtGui.QWidget(MainWindow)
        self.centralWidget.setObjectName("centralWidget")
        self.gridlayout = QtGui.QGridLayout(self.centralWidget)
        self.gridlayout.setObjectName("gridlayout")
        self.splitter_2 = QtGui.QSplitter(self.centralWidget)
        self.splitter_2.setOrientation(QtCore.Qt.Horizontal)
        self.splitter_2.setObjectName("splitter_2")
        self.splitter = QtGui.QSplitter(self.splitter_2)
        self.splitter.setOrientation(QtCore.Qt.Vertical)
        self.splitter.setObjectName("splitter")
        self.listWidget = QtGui.QListWidget(self.splitter)
        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.listWidget.sizePolicy().hasHeightForWidth())
        self.listWidget.setSizePolicy(sizePolicy)
        self.listWidget.setSelectionMode(QtGui.QAbstractItemView.SingleSelection)
        self.listWidget.setSelectionRectVisible(False)
        self.listWidget.setObjectName("listWidget")
        self.tabWidget = QtGui.QTabWidget(self.splitter)
        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(5)
        sizePolicy.setHeightForWidth(self.tabWidget.sizePolicy().hasHeightForWidth())
        self.tabWidget.setSizePolicy(sizePolicy)
        self.tabWidget.setTabShape(QtGui.QTabWidget.Rounded)
        self.tabWidget.setObjectName("tabWidget")
        self.tab = QtGui.QWidget()
        self.tab.setObjectName("tab")
        self.hSlider_basisIndex = QtGui.QSlider(self.tab)
        self.hSlider_basisIndex.setGeometry(QtCore.QRect(10, 160, 160, 22))
        self.hSlider_basisIndex.setMaximum(10)
        self.hSlider_basisIndex.setOrientation(QtCore.Qt.Horizontal)
        self.hSlider_basisIndex.setObjectName("hSlider_basisIndex")
        self.label_basisIndex = QtGui.QLabel(self.tab)
        self.label_basisIndex.setGeometry(QtCore.QRect(10, 140, 161, 17))
        self.label_basisIndex.setObjectName("label_basisIndex")
        self.spinBox_basisIndex = QtGui.QSpinBox(self.tab)
        self.spinBox_basisIndex.setGeometry(QtCore.QRect(180, 150, 63, 27))
        self.spinBox_basisIndex.setReadOnly(True)
        self.spinBox_basisIndex.setButtonSymbols(QtGui.QAbstractSpinBox.NoButtons)
        self.spinBox_basisIndex.setObjectName("spinBox_basisIndex")
        self.label_level = QtGui.QLabel(self.tab)
        self.label_level.setGeometry(QtCore.QRect(10, 10, 171, 17))
        self.label_level.setObjectName("label_level")
        self.spinBox_level = QtGui.QSpinBox(self.tab)
        self.spinBox_level.setGeometry(QtCore.QRect(180, 20, 63, 27))
        self.spinBox_level.setReadOnly(True)
        self.spinBox_level.setButtonSymbols(QtGui.QAbstractSpinBox.NoButtons)
        self.spinBox_level.setObjectName("spinBox_level")
        self.hSlider_level = QtGui.QSlider(self.tab)
        self.hSlider_level.setGeometry(QtCore.QRect(10, 30, 160, 22))
        self.hSlider_level.setOrientation(QtCore.Qt.Horizontal)
        self.hSlider_level.setObjectName("hSlider_level")
        self.label_cutoff = QtGui.QLabel(self.tab)
        self.label_cutoff.setGeometry(QtCore.QRect(10, 64, 221, 17))
        self.label_cutoff.setObjectName("label_cutoff")
        self.lineEdit_cutoff = QtGui.QLineEdit(self.tab)
        self.lineEdit_cutoff.setGeometry(QtCore.QRect(10, 84, 91, 22))
        self.lineEdit_cutoff.setLayoutDirection(QtCore.Qt.RightToLeft)
        self.lineEdit_cutoff.setObjectName("lineEdit_cutoff")
        self.label_cutoff_minmax = QtGui.QLabel(self.tab)
        self.label_cutoff_minmax.setGeometry(QtCore.QRect(110, 90, 121, 17))
        font = QtGui.QFont()
        font.setPointSize(11)
        self.label_cutoff_minmax.setFont(font)
        self.label_cutoff_minmax.setLayoutDirection(QtCore.Qt.LeftToRight)
        self.label_cutoff_minmax.setObjectName("label_cutoff_minmax")
        self.line = QtGui.QFrame(self.tab)
        self.line.setGeometry(QtCore.QRect(10, 110, 231, 16))
        self.line.setFrameShape(QtGui.QFrame.HLine)
        self.line.setFrameShadow(QtGui.QFrame.Sunken)
        self.line.setObjectName("line")
        self.label_basisCutoff_minmax = QtGui.QLabel(self.tab)
        self.label_basisCutoff_minmax.setGeometry(QtCore.QRect(110, 221, 121, 17))
        font = QtGui.QFont()
        font.setPointSize(11)
        self.label_basisCutoff_minmax.setFont(font)
        self.label_basisCutoff_minmax.setLayoutDirection(QtCore.Qt.LeftToRight)
        self.label_basisCutoff_minmax.setObjectName("label_basisCutoff_minmax")
        self.label_basisCutoff = QtGui.QLabel(self.tab)
        self.label_basisCutoff.setGeometry(QtCore.QRect(10, 195, 221, 17))
        self.label_basisCutoff.setObjectName("label_basisCutoff")
        self.lineEdit_basisCutoff = QtGui.QLineEdit(self.tab)
        self.lineEdit_basisCutoff.setGeometry(QtCore.QRect(10, 215, 91, 22))
        self.lineEdit_basisCutoff.setLayoutDirection(QtCore.Qt.RightToLeft)
        self.lineEdit_basisCutoff.setObjectName("lineEdit_basisCutoff")
        self.tabWidget.addTab(self.tab, "")
        self.tab_2 = QtGui.QWidget()
        self.tab_2.setObjectName("tab_2")
        self.tabWidget.addTab(self.tab_2, "")
        self.vtkWidget = QVTKRenderWindowInteractor(self.splitter_2)
        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(10)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.vtkWidget.sizePolicy().hasHeightForWidth())
        self.vtkWidget.setSizePolicy(sizePolicy)
        self.vtkWidget.setObjectName("vtkWidget")
        self.gridlayout.addWidget(self.splitter_2, 0, 1, 1, 1)
        MainWindow.setCentralWidget(self.centralWidget)
        self.menuBar = QtGui.QMenuBar(MainWindow)
        self.menuBar.setGeometry(QtCore.QRect(0, 0, 790, 22))
        self.menuBar.setObjectName("menuBar")
        self.menuFile = QtGui.QMenu(self.menuBar)
        self.menuFile.setObjectName("menuFile")
        MainWindow.setMenuBar(self.menuBar)
        self.actionNew = QtGui.QAction(MainWindow)
        self.actionNew.setObjectName("actionNew")
        self.actionExit = QtGui.QAction(MainWindow)
        self.actionExit.setObjectName("actionExit")
        self.menuFile.addAction(self.actionNew)
        self.menuFile.addSeparator()
        self.menuFile.addAction(self.actionExit)
        self.menuBar.addAction(self.menuFile.menuAction())

        self.retranslateUi(MainWindow)
        self.tabWidget.setCurrentIndex(0)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)
Exemple #28
0
class QCDATWidget(QtGui.QFrame):
    # TODO: Add a signal for addedPlots
    plotAdded = QtCore.Signal()
    visiblityChanged = QtCore.Signal(bool)
    setVariables = QtCore.Signal(list)
    setGraphicsMethod = QtCore.Signal(object)
    setTemplate = QtCore.Signal(object)
    emitAllPlots = QtCore.Signal()

    save_formats = ["PNG file (*.png)",
                    "GIF file (*.gif)",
                    "PDF file (*.pdf)",
                    "Postscript file (*.ps)",
                    "SVG file (*.svg)"]

    def __init__(self, row, col, parent=None):
        super(QCDATWidget, self).__init__(parent=parent)

        self.row = row
        self.col = col

        self.setAcceptDrops(True)

        self.mRenWin = vtk.vtkRenderWindow()
        self.iren = QVTKRenderWindowInteractor(parent=self, rw=self.mRenWin)
        self.canvas = None

        self.canvasLayout = QtGui.QVBoxLayout()
        self.canvasLayout.addWidget(self.iren)
        self.setLayout(self.canvasLayout)

        self.becameVisible = partial(self.visiblityChanged.emit, True)
        self.becameHidden = partial(self.visiblityChanged.emit, False)

        self.setFocusPolicy(QtCore.Qt.StrongFocus)
        self.setSizePolicy(QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding,
                                             QtGui.QSizePolicy.Expanding))

        self.visiblityChanged.connect(self.manageCanvas)

        self.dragTarget = QtGui.QWidget(self)
        self.dragTarget.hide()

        self.dragLayout = QtGui.QHBoxLayout()
        self.dragTarget.setLayout(self.dragLayout)
        get_variables().dataChanged.connect(self.variablesChanged)
        self.plots = []
        # Creates and hooks up the initial PlotInfo widget
        self.addedPlot()

        # Just need a callable that returns something
        self.toolBarType = lambda x: None

    def plot_at_point(self, point):
        for plot in self.plots:
            r = plot.frameGeometry()
            if r.contains(point):
                return plot
        return None

    def load(self, displays):
        for display in displays:
            info = self.plots[-1]
            info.load(display)

    def dragMoveEvent(self, event):
        plot = self.plot_at_point(event.pos())
        if plot:
            event.accept(plot.rect())
        else:
            event.ignore()

    def variablesChanged(self, start, end):
        vars = get_variables()
        any_updated = False
        for i in range(start.row(), end.row() + 1):
            var = vars.get(i)
            for plot in self.plots:
                plot_vars = plot.manager.variables
                if plot_vars is None:
                    continue
                changed = False
                new_vars = []
                for v in plot_vars:
                    if v is None:
                        continue
                    if v.id == var.id:
                        changed = True
                        new_vars.append(var.var)
                    else:
                        new_vars.append(v)
                if changed:
                    any_updated = True
                    plot.variables(new_vars)
        if any_updated:
            self.update()

    def dropEvent(self, event):
        dropped = event.source().model().get_dropped(event.mimeData())
        target = self.plot_at_point(event.pos())

        if cdms_mime in event.mimeData().formats():
            event.accept()
            target.variables(dropped)
        if vcs_template_mime in event.mimeData().formats():
            event.accept()
            target.template(dropped)
        if vcs_gm_mime in event.mimeData().formats():
            event.accept()
            target.graphics_method(dropped)

        self.iren.show()
        self.dragTarget.hide()
        self.plotAdded.emit()

    def dragEnterEvent(self, event):
        accepted = set([cdms_mime, vcs_gm_mime, vcs_template_mime])
        if set(event.mimeData().formats()) & accepted:
            event.accept()
        self.dragTarget.resize(self.size())
        self.dragTarget.show()
        self.iren.hide()

    def dragLeaveEvent(self, event=None):
        self.iren.show()
        self.dragTarget.hide()

    def loadPlot(self, dp):
        self.plots[-1].load(dp)

    def addedPlot(self):
        """Adds a new PlotInfo to the collection whenever one is made"""
        new_widget = PlotInfo(lambda: self.canvas, self.row, self.col)
        self.dragLayout.addWidget(new_widget)
        self.plots.append(new_widget)
        new_widget.initialized.connect(self.addedPlot)
        new_widget.removed.connect(self.removeWidget)

    def removeWidget(self, widget):
        self.plots.remove(widget)
        self.dragLayout.removeWidget(widget)
        widget.deleteLater()

    def manageCanvas(self, showing):
        if showing and self.canvas is None:
            self.canvas = vcs.init(backend=self.mRenWin)
            self.canvas.open()
        if not showing and self.canvas is not None:
            self.canvas.onClosing((0, 0))
            self.canvas = None

        self.emitAllPlots.emit()

    def showEvent(self, e):
        super(QCDATWidget, self).showEvent(e)
        QtCore.QTimer.singleShot(0, self.becameVisible)

    def hideEvent(self, e):
        super(QCDATWidget, self).hideEvent(e)
        QtCore.QTimer.singleShot(0, self.becameHidden)

    def prepExtraDims(self, var):
        k = {}
        for d, i in zip(self.extraDimsNames, self.extraDimsIndex):
            if d in var.getAxisIds():
                k[d] = slice(i, None)
        return k

    def get_graphics_method(self, plotType, gmName):
        method_name = "get" + str(plotType).lower()
        return getattr(self.canvas, method_name)(gmName)

    def getPlotters(self):
        return [plot.manager for plot in self.plots]

    def deleteLater(self):
        """ deleteLater() -> None
        Make sure to free render window resource when
        deallocating. Overriding PyQt deleteLater to free up
        resources
        """

        self.canvas.onClosing((0, 0))
        self.canvas = None
        self.dragTarget.deleteLater()
        super(QCDATWidget, self).deleteLater()

    def dumpToFile(self, filename):
        """ dumpToFile(filename: str, dump_as_pdf: bool) -> None
        Dumps itself as an image to a file, calling grabWindowPixmap """
        (_, ext) = os.path.splitext(filename)
        if ext.upper() == '.PDF':
            self.canvas.pdf(filename)
        elif ext.upper() == ".PNG":
            self.canvas.png(filename)
        elif ext.upper() == ".SVG":
            self.canvas.svg(filename)
        elif ext.upper() == ".GIF":
            self.canvas.gif(filename)
        elif ext.upper() == ".PS":
            self.canvas.postscript(filename)

    def saveToPNG(self, filename):
        """ saveToPNG(filename: str) -> bool
        Save the current widget contents to an image file

        """
        return self.canvas.png(filename)

    def saveToPDF(self, filename):
        """ saveToPDF(filename: str) -> bool
        Save the current widget contents to a pdf file

        """
        self.canvas.pdf(filename)
    def __init__(self, parent = None):
        super(VTKFrame, self).__init__(parent)

        self.vtkWidget = QVTKRenderWindowInteractor(self)
        self.iren = self.vtkWidget.GetRenderWindow().GetInteractor()
        vl = QtGui.QVBoxLayout(self)
        vl.addWidget(self.vtkWidget)
        vl.setContentsMargins(0, 0, 0, 0)
 
        # Create source
        # We are going to handle two different sources.
        # The first source is a superquadric source.
        torus = vtk.vtkSuperquadricSource();
        torus.SetCenter(0.0, 0.0, 0.0)
        torus.SetScale(1.0, 1.0, 1.0)
        torus.SetPhiResolution (64)
        torus.SetThetaResolution(64)
        torus.SetThetaRoundness (1)
        torus.SetThickness (0.5)
        torus.SetSize(0.5)
        torus.SetToroidal(1) 
 
        # Rotate the torus towards the observer (around the x-axis)
        torusT = vtk.vtkTransform()
        torusT.RotateX(55)
 
        torusTF = vtk.vtkTransformFilter()
        torusTF.SetInputConnection(torus.GetOutputPort())
        torusTF.SetTransform(torusT)
 
        # The quadric is made of strips, so pass it through a triangle filter as
        # the curvature filter only operates on polys
        tri = vtk.vtkTriangleFilter()
        tri.SetInputConnection(torusTF.GetOutputPort())
 
        # The quadric has nasty discontinuities from the way the edges are generated
        # so let's pass it though a CleanPolyDataFilter and merge any points which
        # are coincident, or very close
 
        cleaner = vtk.vtkCleanPolyData()
        cleaner.SetInputConnection(tri.GetOutputPort())
        cleaner.SetTolerance(0.005)
 
        # The next source will be a parametric function
        rh = vtk.vtkParametricRandomHills()
        rhFnSrc = vtk.vtkParametricFunctionSource()
        rhFnSrc.SetParametricFunction(rh)
 
        # Now we have the sources, lets put them into a list.
        sources = list()
        sources.append(cleaner)
        sources.append(cleaner)
        sources.append(rhFnSrc)
        sources.append(rhFnSrc)
 
        # Colour transfer function.
        ctf = vtk.vtkColorTransferFunction()
        ctf.SetColorSpaceToDiverging()
        ctf.AddRGBPoint(0.0, 0.230, 0.299, 0.754)
        ctf.AddRGBPoint(1.0, 0.706, 0.016, 0.150)
        cc = list()
        for i in range(256):
            cc.append(ctf.GetColor(float(i) / 255.0)) 
 
        # Lookup table.
        lut = list()
        for idx in range(len(sources)):
            lut.append(vtk.vtkLookupTable())
            lut[idx].SetNumberOfColors(256)
            for i, item in enumerate(cc):
                lut[idx].SetTableValue(i, item[0], item[1], item[2], 1.0)
            if idx == 0:
                lut[idx].SetRange(-10, 10)
            if idx == 1:
                lut[idx].SetRange(0, 4)
            if idx == 2:
                lut[idx].SetRange(-1, 1)
            if idx == 3:
                lut[idx].SetRange(-1, 1)
            lut[idx].Build()
 
        curvatures = list()        
        for idx in range(len(sources)):
            curvatures.append(vtk.vtkCurvatures())
            if idx % 2 == 0:
                curvatures[idx].SetCurvatureTypeToGaussian()
            else:
                curvatures[idx].SetCurvatureTypeToMean()
 
        renderers = list()
        mappers = list()
        actors = list()
        textmappers = list()
        textactors = list()
 
        # Create a common text property.
        textProperty = vtk.vtkTextProperty()
        textProperty.SetFontSize(10)
        textProperty.SetJustificationToCentered()
 
        names = ['Torus - Gaussian Curvature', 'Torus - Mean Curvature', 'Random Hills - Gaussian Curvature', 'Random Hills - Mean Curvature']
 
        # Link the pipeline together. 
        for idx, item in enumerate(sources):
            sources[idx].Update()
 
            curvatures[idx].SetInputConnection(sources[idx].GetOutputPort())
 
            mappers.append(vtk.vtkPolyDataMapper())
            mappers[idx].SetInputConnection(curvatures[idx].GetOutputPort())
            mappers[idx].SetLookupTable(lut[idx])
            mappers[idx].SetUseLookupTableScalarRange(1)
 
            actors.append(vtk.vtkActor())
            actors[idx].SetMapper(mappers[idx])
 
            textmappers.append(vtk.vtkTextMapper())
            textmappers[idx].SetInput(names[idx])
            textmappers[idx].SetTextProperty(textProperty)
 
            textactors.append(vtk.vtkActor2D())
            textactors[idx].SetMapper(textmappers[idx])
            textactors[idx].SetPosition(150, 16)
 
            renderers.append(vtk.vtkRenderer())
 
        gridDimensions = 2
 
        for idx in range(len(sources)):
            if idx < gridDimensions * gridDimensions:
                renderers.append(vtk.vtkRenderer)
 
        rendererSize = 300
 
        # Create the RenderWindow
        self.vtkWidget.GetRenderWindow().SetSize(rendererSize * gridDimensions, rendererSize * gridDimensions)
 
        # Add and position the renders to the render window.
        viewport = list()
        for row in range(gridDimensions):
            for col in range(gridDimensions):
                idx = row * gridDimensions + col
 
                viewport[:] = []
                viewport.append(float(col) * rendererSize / (gridDimensions * rendererSize))
                viewport.append(float(gridDimensions - (row+1)) * rendererSize / (gridDimensions * rendererSize))
                viewport.append(float(col+1)*rendererSize / (gridDimensions * rendererSize))
                viewport.append(float(gridDimensions - row) * rendererSize / (gridDimensions * rendererSize))
 
                if idx > (len(sources) - 1):
                    continue
 
                renderers[idx].SetViewport(viewport)
                self.vtkWidget.GetRenderWindow().AddRenderer(renderers[idx])
 
                renderers[idx].AddActor(actors[idx])
                renderers[idx].AddActor(textactors[idx])
                renderers[idx].SetBackground(0.4,0.3,0.2)
        
        self._initialized = False
Exemple #30
0
    def setupUi(self, MainWindow):
        # mainwindow
        MainWindow.setObjectName(_fromUtf8("MainWindow"))
        MainWindow.resize(1203, 694)

        # centralWidget
        self.centralWidget = QtGui.QWidget(MainWindow)
        self.centralWidget.setObjectName(_fromUtf8("centralWidget"))
        MainWindow.setCentralWidget(self.centralWidget)

        # left setting panel

        # frame
        self.settingFrame = QtGui.QFrame(self.centralWidget)
        self.settingFrame.setGeometry(QtCore.QRect(10, 10, 301, 581))
        self.settingFrame.setFrameShape(QtGui.QFrame.StyledPanel)
        self.settingFrame.setFrameShadow(QtGui.QFrame.Raised)
        self.settingFrame.setObjectName(_fromUtf8("settingFrame"))

        # system parameter group
        self.groupBox_system = QtGui.QGroupBox(self.settingFrame)
        self.groupBox_system.setGeometry(QtCore.QRect(20, 20, 261, 121))
        self.groupBox_system.setStyleSheet(_fromUtf8("QGroupBox{border: 1px solid rgb(192, 192, 192); border-radius:9px; font: bold}+ QGroupBox::title{subcontrol-origin: margin; left: 10px; padding: 0px 3px 0 3px}"))
        self.groupBox_system.setObjectName(_fromUtf8("groupBox_system"))
        self.label_M1 = QtGui.QLabel(self.groupBox_system)
        self.label_M1.setGeometry(QtCore.QRect(10, 40, 21, 17))
        self.label_M1.setObjectName(_fromUtf8("label_M1"))
        self.label_M2 = QtGui.QLabel(self.groupBox_system)
        self.label_M2.setGeometry(QtCore.QRect(140, 40, 21, 17))
        self.label_M2.setObjectName(_fromUtf8("label_M2"))
        self.label_L1 = QtGui.QLabel(self.groupBox_system)
        self.label_L1.setGeometry(QtCore.QRect(10, 90, 21, 17))
        self.label_L1.setObjectName(_fromUtf8("label_L1"))
        self.label_L2 = QtGui.QLabel(self.groupBox_system)
        self.label_L2.setGeometry(QtCore.QRect(140, 90, 21, 17))
        self.label_L2.setObjectName(_fromUtf8("label_L2"))
        self.lineEdit_M1 = QtGui.QLineEdit(self.groupBox_system)
        self.lineEdit_M1.setGeometry(QtCore.QRect(40, 30, 71, 27))
        self.lineEdit_M1.setObjectName(_fromUtf8("lineEdit_M1"))
        self.lineEdit_M2 = QtGui.QLineEdit(self.groupBox_system)
        self.lineEdit_M2.setGeometry(QtCore.QRect(170, 30, 71, 27))
        self.lineEdit_M2.setObjectName(_fromUtf8("lineEdit_M2"))
        self.lineEdit_L1 = QtGui.QLineEdit(self.groupBox_system)
        self.lineEdit_L1.setGeometry(QtCore.QRect(40, 80, 71, 27))
        self.lineEdit_L1.setObjectName(_fromUtf8("lineEdit_L1"))
        self.lineEdit_L2 = QtGui.QLineEdit(self.groupBox_system)
        self.lineEdit_L2.setGeometry(QtCore.QRect(170, 80, 71, 27))
        self.lineEdit_L2.setObjectName(_fromUtf8("lineEdit_L2"))

        # initial condition group
        self.groupBox_init = QtGui.QGroupBox(self.settingFrame)
        self.groupBox_init.setGeometry(QtCore.QRect(20, 170, 261, 121))
        self.groupBox_init.setStyleSheet(_fromUtf8("QGroupBox{border: 1px solid rgb(192, 192, 192); border-radius:9px; font: bold}+ QGroupBox::title{subcontrol-origin: margin; left: 10px; padding: 0px 3px 0 3px}"))
        self.groupBox_init.setObjectName(_fromUtf8("groupBox_init"))
        self.label_th1 = QtGui.QLabel(self.groupBox_init)
        self.label_th1.setGeometry(QtCore.QRect(10, 40, 31, 17))
        self.label_th1.setObjectName(_fromUtf8("label_th1"))
        self.label_th2 = QtGui.QLabel(self.groupBox_init)
        self.label_th2.setGeometry(QtCore.QRect(140, 40, 31, 17))
        self.label_th2.setObjectName(_fromUtf8("label_th2"))
        self.label_w1 = QtGui.QLabel(self.groupBox_init)
        self.label_w1.setGeometry(QtCore.QRect(10, 90, 21, 17))
        self.label_w1.setObjectName(_fromUtf8("label_w1"))
        self.label_w2 = QtGui.QLabel(self.groupBox_init)
        self.label_w2.setGeometry(QtCore.QRect(140, 90, 21, 17))
        self.label_w2.setObjectName(_fromUtf8("label_w2"))
        self.lineEdit_th1 = QtGui.QLineEdit(self.groupBox_init)
        self.lineEdit_th1.setGeometry(QtCore.QRect(40, 30, 71, 27))
        self.lineEdit_th1.setObjectName(_fromUtf8("lineEdit_th1"))
        self.lineEdit_w1 = QtGui.QLineEdit(self.groupBox_init)
        self.lineEdit_w1.setGeometry(QtCore.QRect(40, 80, 71, 27))
        self.lineEdit_w1.setObjectName(_fromUtf8("lineEdit_w1"))
        self.lineEdit_th2 = QtGui.QLineEdit(self.groupBox_init)
        self.lineEdit_th2.setGeometry(QtCore.QRect(170, 30, 71, 27))
        self.lineEdit_th2.setObjectName(_fromUtf8("lineEdit_th2"))
        self.lineEdit_w2 = QtGui.QLineEdit(self.groupBox_init)
        self.lineEdit_w2.setGeometry(QtCore.QRect(170, 80, 71, 27))
        self.lineEdit_w2.setObjectName(_fromUtf8("lineEdit_w2"))

        # time setting group
        self.groupBox_time = QtGui.QGroupBox(self.settingFrame)
        self.groupBox_time.setGeometry(QtCore.QRect(20, 310, 261, 131))
        self.groupBox_time.setStyleSheet(_fromUtf8("QGroupBox{border: 1px solid rgb(192, 192, 192); border-radius:9px; font: bold}+ QGroupBox::title{subcontrol-origin: margin; left: 10px; padding: 0px 3px 0 3px}"))
        self.groupBox_time.setObjectName(_fromUtf8("groupBox_time"))
        self.label_ts = QtGui.QLabel(self.groupBox_time)
        self.label_ts.setGeometry(QtCore.QRect(20, 40, 41, 17))
        self.label_ts.setObjectName(_fromUtf8("label_ts"))
        self.label_te = QtGui.QLabel(self.groupBox_time)
        self.label_te.setGeometry(QtCore.QRect(20, 70, 41, 17))
        self.label_te.setObjectName(_fromUtf8("label_te"))
        self.label_dt = QtGui.QLabel(self.groupBox_time)
        self.label_dt.setGeometry(QtCore.QRect(20, 100, 41, 17))
        self.label_dt.setObjectName(_fromUtf8("label_dt"))
        self.lineEdit_ts = QtGui.QLineEdit(self.groupBox_time)
        self.lineEdit_ts.setGeometry(QtCore.QRect(70, 30, 71, 27))
        self.lineEdit_ts.setObjectName(_fromUtf8("lineEdit_ts"))
        self.lineEdit_te = QtGui.QLineEdit(self.groupBox_time)
        self.lineEdit_te.setGeometry(QtCore.QRect(70, 60, 71, 27))
        self.lineEdit_te.setObjectName(_fromUtf8("lineEdit_te"))
        self.lineEdit_dt = QtGui.QLineEdit(self.groupBox_time)
        self.lineEdit_dt.setGeometry(QtCore.QRect(70, 90, 71, 27))
        self.lineEdit_dt.setObjectName(_fromUtf8("lineEdit_dt"))

        # pushButton
        self.pushButton_clear = QtGui.QPushButton(self.settingFrame)
        self.pushButton_clear.setGeometry(QtCore.QRect(60, 480, 99, 27))
        self.pushButton_clear.setObjectName(_fromUtf8("pushButton_clear"))
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(
            _fromUtf8("Icon/clear.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.pushButton_clear.setIcon(icon)
        self.pushButton_clear.setIconSize(QtCore.QSize(20, 20))

        self.pushButton_init = QtGui.QPushButton(self.settingFrame)
        self.pushButton_init.setGeometry(QtCore.QRect(180, 480, 99, 27))
        self.pushButton_init.setObjectName(_fromUtf8("pushButton_init"))
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(
            _fromUtf8("Icon/init.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.pushButton_init.setIcon(icon)
        self.pushButton_init.setIconSize(QtCore.QSize(20, 20))

        self.pushButton_simulate = QtGui.QPushButton(self.settingFrame)
        self.pushButton_simulate.setGeometry(QtCore.QRect(180, 520, 99, 27))
        self.pushButton_simulate.setObjectName(_fromUtf8("pushButton_simulate"))
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(
            _fromUtf8("Icon/tick.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.pushButton_simulate.setIcon(icon)
        self.pushButton_simulate.setIconSize(QtCore.QSize(20, 20))

        # vtk widget
        self.vtk_widget = QVTKRenderWindowInteractor(self.centralWidget)
        self.vtk_widget.setGeometry(QtCore.QRect(320, 10, 431, 581))
        self.vtk_widget.setObjectName(_fromUtf8("vtk_widget"))
        self.setvtkWidget()


        # plot_widget
        # trajectory
        self.plot_trace = MyMplCanvas(
            self.centralWidget, width=1, height=1, dpi=50, Ndim=2)
        self.plot_trace.setGeometry(QtCore.QRect(760, 10, 431, 285))
        self.plot_trace.setObjectName(_fromUtf8("plot_trace"))
        self.plot_trace.axes.set_xlim(-5, 5)
        self.plot_trace.axes.set_ylim(0, 5)
        # self.plot_trace.lines[0].set_color('red')     # it doesn't work?
        # self.plot_trace.lines[1].set_color('blue')
        self.plot_trace.fig.legend((self.plot_trace.lines[0], self.plot_trace.lines[
                                   1]), ('upper', 'lower'), (0.15, 0.76))
        self.plot_trace.axes.set_title("Trace of the pendulums", fontsize = 25)
        self.plot_trace.axes.set_xlabel("x/m", fontsize = 15)
        self.plot_trace.axes.set_ylabel("y/m", fontsize = 15)

        # phase angle
        self.plot_angle = MyMplCanvas(
            self.centralWidget, width=1, height=1, dpi=50, Ndim=2)
        self.plot_angle.setGeometry(QtCore.QRect(760, 306, 431, 285))
        self.plot_angle.setObjectName(_fromUtf8("plot_angle"))
        self.plot_angle.axes.set_xlim(0, 10)
        self.plot_angle.axes.set_ylim(-1.6, 1.6)
        self.plot_angle.axes.set_title("Angle of the pendulums", fontsize = 25)
        self.plot_angle.axes.set_xlabel("Time/sec", fontsize = 15)
        self.plot_angle.axes.set_ylabel("Angle/rad", fontsize = 15)


        # menuBar
        self.menuBar = QtGui.QMenuBar(MainWindow)
        self.menuBar.setGeometry(QtCore.QRect(0, 0, 1203, 25))
        self.menuBar.setObjectName(_fromUtf8("menuBar"))
        MainWindow.setMenuBar(self.menuBar)

        # toolbar
        self.mainToolBar = QtGui.QToolBar(MainWindow)
        self.mainToolBar.setIconSize(QtCore.QSize(50, 50))
        self.mainToolBar.setObjectName(_fromUtf8("mainToolBar"))
        self.mainToolBar.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon)
        MainWindow.addToolBar(QtCore.Qt.TopToolBarArea, self.mainToolBar)

        self.actionImport = QtGui.QAction(MainWindow)
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(_fromUtf8("Icon/import.png")), QtGui.QIcon.Normal, QtGui.QIcon.On)
        self.actionImport.setIcon(icon)
        self.actionImport.setObjectName(_fromUtf8("actionImport"))

        self.actionExport = QtGui.QAction(MainWindow)
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(_fromUtf8("Icon/export.png")), QtGui.QIcon.Normal, QtGui.QIcon.On)
        self.actionExport.setIcon(icon)
        self.actionExport.setObjectName(_fromUtf8("actionExport"))

        self.actionInit = QtGui.QAction(MainWindow)
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(_fromUtf8("Icon/init.png")), QtGui.QIcon.Normal, QtGui.QIcon.On)
        self.actionInit.setIcon(icon)
        self.actionInit.setObjectName(_fromUtf8("actionInit"))

        self.actionSimulate = QtGui.QAction(MainWindow)
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(_fromUtf8("Icon/tick.png")), QtGui.QIcon.Normal, QtGui.QIcon.On)
        self.actionSimulate.setIcon(icon)
        self.actionSimulate.setObjectName(_fromUtf8("actionSimulate"))

        self.actionStart = QtGui.QAction(MainWindow)
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(_fromUtf8("Icon/start.png")), QtGui.QIcon.Normal, QtGui.QIcon.On)
        self.actionStart.setIcon(icon)
        self.actionStart.setObjectName(_fromUtf8("actionStart"))
        
        self.actionStop = QtGui.QAction(MainWindow)
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(_fromUtf8(
            "Icon/stop.png")), QtGui.QIcon.Normal, QtGui.QIcon.On)
        self.actionStop.setIcon(icon)
        self.actionStop.setObjectName(_fromUtf8("actionStop"))

        self.actionSave = QtGui.QAction(MainWindow)
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(_fromUtf8(
            "Icon/save.png")), QtGui.QIcon.Normal, QtGui.QIcon.On)
        self.actionSave.setIcon(icon)
        self.actionSave.setObjectName(_fromUtf8("actionSave"))

        self.actionInfo = QtGui.QAction(MainWindow)
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(_fromUtf8(
            "Icon/info.svg")), QtGui.QIcon.Normal, QtGui.QIcon.On)
        self.actionInfo.setIcon(icon)
        self.actionInfo.setObjectName(_fromUtf8("actionInfo"))
        
        self.actionExit = QtGui.QAction(MainWindow)
        icon = QtGui.QIcon()
        icon.addPixmap(
            QtGui.QPixmap(_fromUtf8("Icon/exit.png")), QtGui.QIcon.Normal, QtGui.QIcon.On)
        self.actionExit.setIcon(icon)
        self.actionExit.setObjectName(_fromUtf8("actionExit"))

        self.mainToolBar.addAction(self.actionImport)
        self.mainToolBar.addAction(self.actionExport)
        self.mainToolBar.addSeparator()
        self.mainToolBar.addAction(self.actionInit)
        self.mainToolBar.addAction(self.actionSimulate)
        self.mainToolBar.addSeparator()
        self.mainToolBar.addAction(self.actionStart)
        self.mainToolBar.addAction(self.actionStop)
        self.mainToolBar.addAction(self.actionSave)
        self.mainToolBar.addSeparator()
        self.mainToolBar.addAction(self.actionInfo)
        self.mainToolBar.addAction(self.actionExit)
        self.mainToolBar.addSeparator()

        # add lineText to the toolbar to display the current time
        self.label_currenttime = QtGui.QLabel(self.mainToolBar)
        self.label_currenttime.setGeometry(QtCore.QRect(800, 25, 60, 30))
        self.label_currenttime.setObjectName(_fromUtf8("label_currenttime"))
        self.label_currenttime.setStyleSheet(
            "QLabel{font-weight: bold; font-size: 22px}")

        self.lineEdit_timer = QtGui.QLineEdit(self.mainToolBar)
        self.lineEdit_timer.setGeometry(QtCore.QRect(870, 20, 100, 40))
        self.lineEdit_timer.setObjectName(_fromUtf8("lineEdit_timer"))
        self.lineEdit_timer.setReadOnly(True)
        self.lineEdit_timer.setFont(QtGui.QFont("Arial", 20, QtGui.QFont.Bold))

        # Layout management
        #self.gridLayout = QtGui.QGridLayout(self.centralWidget)
        #self.gridLayout.setMargin(11)
        #self.gridLayout.setSpacing(6)
        #self.gridLayout.setObjectName(_fromUtf8("gridLayout"))

        #self.gridLayout.addWidget(self.settingFrame, 0, 0, 1, 1)
        #self.gridLayout.addWidget(self.vtk_widget, 0, 1, 1, 1)
        #self.gridLayout.addWidget(self.plot_widget, 0, 2, 1, 1)


        #
        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)
Exemple #31
0
class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName(_fromUtf8("Form"))
        Form.resize(800, 600)
        self.gridLayout = QtGui.QGridLayout(Form)
        self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
        self.verticalLayout_3 = QtGui.QVBoxLayout()
        self.verticalLayout_3.setSizeConstraint(
            QtGui.QLayout.SetDefaultConstraint)
        self.verticalLayout_3.setObjectName(_fromUtf8("verticalLayout_3"))
        self.horizontalLayout = QtGui.QHBoxLayout()
        self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
        self.verticalLayout = QtGui.QVBoxLayout()
        self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
        self.label = QtGui.QLabel(Form)
        self.label.setObjectName(_fromUtf8("label"))
        self.verticalLayout.addWidget(self.label)
        self.leftVtk = QVTKRenderWindowInteractor(Form)
        self.leftVtk.setObjectName(_fromUtf8("leftVtk"))
        self.verticalLayout.addWidget(self.leftVtk)
        self.verticalLayout.setStretch(1, 1)
        self.horizontalLayout.addLayout(self.verticalLayout)
        self.verticalLayout_2 = QtGui.QVBoxLayout()
        self.verticalLayout_2.setObjectName(_fromUtf8("verticalLayout_2"))
        self.label_2 = QtGui.QLabel(Form)
        self.label_2.setObjectName(_fromUtf8("label_2"))
        self.verticalLayout_2.addWidget(self.label_2)
        self.rightVtk = QVTKRenderWindowInteractor(Form)
        self.rightVtk.setObjectName(_fromUtf8("rightVtk"))
        self.verticalLayout_2.addWidget(self.rightVtk)
        self.verticalLayout_2.setStretch(1, 1)
        self.horizontalLayout.addLayout(self.verticalLayout_2)
        self.verticalLayout_3.addLayout(self.horizontalLayout)
        self.tabWidget = QtGui.QTabWidget(Form)
        self.tabWidget.setTabShape(QtGui.QTabWidget.Triangular)
        self.tabWidget.setTabsClosable(False)
        self.tabWidget.setMovable(False)
        self.tabWidget.setObjectName(_fromUtf8("tabWidget"))
        self.okienkowanieTab = QtGui.QWidget()
        self.okienkowanieTab.setObjectName(_fromUtf8("okienkowanieTab"))
        self.tabWidget.addTab(self.okienkowanieTab, _fromUtf8(""))
        self.cannyTab = QtGui.QWidget()
        self.cannyTab.setObjectName(_fromUtf8("cannyTab"))
        self.tabWidget.addTab(self.cannyTab, _fromUtf8(""))
        self.verticalLayout_3.addWidget(self.tabWidget)
        self.loadImage = QtGui.QPushButton(Form)
        self.loadImage.setObjectName(_fromUtf8("loadImage"))
        self.verticalLayout_3.addWidget(self.loadImage)
        self.verticalLayout_3.setStretch(0, 2)
        self.verticalLayout_3.setStretch(1, 1)
        self.gridLayout.addLayout(self.verticalLayout_3, 0, 0, 1, 1)

        self.retranslateUi(Form)
        self.tabWidget.setCurrentIndex(0)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        Form.setWindowTitle(_translate("Form", "Form", None))
        self.label.setText(_translate("Form", "Oryginalny obraz", None))
        self.label_2.setText(_translate("Form", "Przetworzony obraz", None))
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.okienkowanieTab),
                                  _translate("Form", "Okienkowanie", None))
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.cannyTab),
                                  _translate("Form", "Canny", None))
        self.loadImage.setText(_translate("Form", "Wczytaj obraz", None))
Exemple #32
0
class VTKPlot(QDialog):
    def __init__(self, x, y, xrange_=10.):
        super(VTKPlot, self).__init__()
        self.setGeometry(50, 50, 700, 350)

        self.setWindowOpacity(1.)

        self.view = vtk.vtkContextView()
        chartMatrix = vtk.vtkChartMatrix()
        chartMatrix.SetSize(vtk.vtkVector2i(1, 1))
        chartMatrix.SetGutter(vtk.vtkVector2f(50, 50))

        self.vtkWidget = QVTKRenderWindowInteractor(self)
        self.view.SetRenderWindow(self.vtkWidget.GetRenderWindow())
        self.view.GetRenderer().SetBackground(1.0, 1.0, 1.0)
        self.view.GetScene().AddItem(chartMatrix)

        self.chart = chartMatrix.GetChart(vtk.vtkVector2i(0, 0))
        self.arrY = vtk.vtkFloatArray()
        self.arrX = vtk.vtkFloatArray()

        self.table = vtk.vtkTable()
        self.add_plot(x, y, xrange_=xrange_)

        self.chart.GetAxis(vtk.vtkAxis.BOTTOM).SetTitle("Time")
        self.chart.GetAxis(vtk.vtkAxis.LEFT).SetTitle("Signal")

        self.view.GetRenderWindow().SetMultiSamples(0)
        self.view.GetRenderWindow().Render()

        layout = QGridLayout()
        layout.addWidget(self.vtkWidget, 0, 0)

        self.setLayout(layout)

    # Add plot (initial step)
    def add_plot(self, x, y, xrange_=10.):
        for k in range(len(x)):
            self.arrX.InsertNextValue(x[k])
            self.arrY.InsertNextValue(y[k])

        self.arrX.SetName("Time (ms)")
        self.table.AddColumn(self.arrX)

        self.arrY.SetName("Strain")
        self.table.AddColumn(self.arrY)

        self.plot = self.chart.AddPlot(0)
        self.plot.SetInput(
            self.table, 0,
            1) if vtk.VTK_VERSION < '6' else self.plot.SetInputData(
                self.table, 0, 1)

        self.plot.SetColor(0, 200, 50, 255)
        self.plot.SetWidth(2.0)

        self.plot.GetXAxis().SetRange(
            self.arrX.GetRange()[0],
            self.arrX.GetRange()[1]) if xrange_ < self.arrX.GetRange(
            )[1] else self.plot.GetXAxis().SetRange(self.arrX.GetRange()[0],
                                                    xrange_)

        self.plot.GetYAxis().SetRange(self.arrY.GetRange()[0],
                                      self.arrY.GetRange()[1])

        self.plot.GetXAxis().SetBehavior(vtk.vtkAxis.FIXED)
        self.plot.GetYAxis().SetBehavior(vtk.vtkAxis.FIXED)

        self.view.GetRenderWindow().Render()

    # Update existing plot (useful for animating plots)
    def update_plot(self, x, y, n_remove=0, xrange_=10.):
        for i in range(n_remove):
            self.arrX.RemoveFirstTuple()
            self.arrY.RemoveFirstTuple()

        for k in range(len(x)):
            self.arrX.InsertNextValue(x[k])
            self.arrY.InsertNextValue(y[k])

        self.arrX.Modified()
        self.arrY.Modified()

        self.plot.GetXAxis().SetRange(
            self.arrX.GetRange()[0],
            self.arrX.GetRange()[1]) if xrange_ < self.arrX.GetRange(
            )[1] else self.plot.GetXAxis().SetRange(self.arrX.GetRange()[0],
                                                    xrange_)
        self.plot.GetYAxis().SetRange(self.arrY.GetRange()[0],
                                      self.arrY.GetRange()[1])

        self.table.Modified()
        self.chart.Update()

        self.view.GetRenderWindow().Render()

    # Remove plot from the chart
    def remove_plot(self):
        self.chart.RemovePlot(0)
Exemple #33
0
class PickWidget(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.setStyleSheet('background-color:#333333')
        self.vtk_layout = QtGui.QGridLayout(self)
        self.vtk_widget = QVTKRenderWindowInteractor(self)
        self.vtk_layout.addWidget(self.vtk_widget)
        self.ren = vtk.vtkRenderer()
        self.vtk_widget.GetRenderWindow().AddRenderer(self.ren)
        self.meshMapper = vtk.vtkPolyDataMapper()
        self.meshActor = vtk.vtkActor()
        self.meshActor.SetMapper(self.meshMapper)
        self.ren.AddActor(self.meshActor)
        self.interactionStyle = RubberBandFacePicker()
        self.interactionStyle.SetDefaultRenderer(self.ren)
        self.vtk_widget.SetInteractorStyle(self.interactionStyle)
        self.vtk_widget.SetPicker(vtk.vtkAreaPicker())
        self.iren = self.vtk_widget.GetRenderWindow().GetInteractor()
        self.show()
        self.iren.Initialize()

        # name2actor map for calls to display_XXXX
        self.name2actor = {}

    def start(self):
        self.reader = vtk.vtkOBJReader()
        self.reader.SetFileName(self.filename)
        self.meshMapper.SetInputConnection(self.reader.GetOutputPort())
        self.interactionStyle.Data = self.reader.GetOutput()
        self.interactionStyle.Widget = self

    def set_source(self, filename):
        self.filename = filename

    def set_selected_color(self, color):
        self.interactionStyle.set_selected_pt_color(color)

    def get_selected_vertices(self):
        V = self.interactionStyle.get_selected_vertices()
        return V

    def display_cloud(self, actorName, list_points, size, vec3_color):
        # extract inlier points
        vtk_points = vtk.vtkPoints()
        for p in list_points:
            vtk_points.InsertNextPoint(p[0], p[1], p[2])

        temp_cloud = vtk.vtkPolyData()
        temp_cloud.SetPoints(vtk_points)

        # add 0D topology to every point
        glfilter = vtk.vtkVertexGlyphFilter()
        glfilter.SetInput(temp_cloud)
        glfilter.Update()
        cloud = glfilter.GetOutput()

        cloudMapper = vtk.vtkPolyDataMapper()
        cloudMapper.SetInput(cloud)

        actor = vtk.vtkActor()
        actor.SetMapper(cloudMapper)
        actor.GetProperty().SetColor(vec3_color[0], vec3_color[1],
                                     vec3_color[2])
        actor.GetProperty().SetPointSize(size)
        self.ren.AddActor(actor)
        self.name2actor[actorName] = actor
        pass

    def display_sphere(self, actorName, vec3_center, radius, vec3_color):
        sphere = vtk.vtkSphereSource()
        sphere.SetRadius(radius)
        sphere.SetCenter(vec3_center)
        sphere.SetThetaResolution(40)
        sphere.SetPhiResolution(40)
        sphere.SetCenter(vec3_center[0], vec3_center[1], vec3_center[2])
        sphere.Update()

        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(sphere.GetOutputPort())

        actor = vtk.vtkActor()
        actor.SetMapper(mapper)
        actor.GetProperty().SetColor(vec3_color[0], vec3_color[1],
                                     vec3_color[2])
        self.ren.AddActor(actor)
        self.name2actor[actorName] = actor

        pass

    def display_cylinder(self, actorName, vec3_origin, vec3_direction, height,
                         radius, vec3_color):
        cyl = vtk.vtkCylinderSource()
        cyl.SetRadius(radius)
        cyl.SetHeight(height)
        cyl.SetCapping(1)
        cyl.Update()

        # transform to center with orientation according to normal
        axis1 = [vec3_direction[0], vec3_direction[1], vec3_direction[2]]
        axis2 = np.cross(axis1, [1, 1, 1])
        axis2 = axis2 / np.linalg.norm(axis2)
        axis3 = np.cross(axis2, axis1)
        # print axis1
        # print axis2
        # print axis3
        trans = np.eye(4)
        trans[0, 0] = axis2[0]
        trans[0, 1] = axis1[0]
        trans[0, 2] = axis3[0]
        trans[0, 3] = vec3_origin[0]
        trans[1, 0] = axis2[1]
        trans[1, 1] = axis1[1]
        trans[1, 2] = axis3[1]
        trans[1, 3] = vec3_origin[1]
        trans[2, 0] = axis2[2]
        trans[2, 1] = axis1[2]
        trans[2, 2] = axis3[2]
        trans[2, 3] = vec3_origin[2]
        trans[3, 0] = 0
        trans[3, 1] = 0
        trans[3, 2] = 0
        trans[3, 3] = 1

        vtk_trans = vtk.vtkMatrix4x4()
        for i in range(0, 4):
            for j in range(0, 4):
                vtk_trans.SetElement(i, j, trans[i, j])

        ar_trans = vtk.vtkTransform()
        ar_trans.SetMatrix(vtk_trans)
        ar_trans_filter = vtk.vtkTransformPolyDataFilter()
        ar_trans_filter.SetTransform(ar_trans)
        ar_trans_filter.SetInputConnection(cyl.GetOutputPort())

        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(ar_trans_filter.GetOutputPort())

        actor = vtk.vtkActor()
        actor.SetMapper(mapper)
        actor.GetProperty().SetColor(vec3_color[0], vec3_color[1],
                                     vec3_color[2])
        self.ren.AddActor(actor)
        self.name2actor[actorName] = actor
        return

    def display_disk(self, actorName, vec3_origin, vec3_direction,
                     outer_radius, inner_radius, vec3_color):
        disk = vtk.vtkDiskSource()
        disk.SetInnerRadius(inner_radius)
        disk.SetOuterRadius(outer_radius)
        disk.SetRadialResolution(30)
        disk.SetCircumferentialResolution(30)
        disk.Update()

        # transform to center with orientation according to normal
        axis1 = [vec3_direction[0], vec3_direction[1], vec3_direction[2]]
        axis2 = np.cross(axis1, [1, 1, 1])
        axis2 = axis2 / np.linalg.norm(axis2)
        axis3 = np.cross(axis1, axis2)
        # print axis1
        # print axis2
        # print axis3
        trans = np.eye(4)
        trans[0, 0] = axis3[0]
        trans[0, 1] = axis2[0]
        trans[0, 2] = axis1[0]
        trans[0, 3] = vec3_origin[0]
        trans[1, 0] = axis3[1]
        trans[1, 1] = axis2[1]
        trans[1, 2] = axis1[1]
        trans[1, 3] = vec3_origin[1]
        trans[2, 0] = axis3[2]
        trans[2, 1] = axis2[2]
        trans[2, 2] = axis1[2]
        trans[2, 3] = vec3_origin[2]
        trans[3, 0] = 0
        trans[3, 1] = 0
        trans[3, 2] = 0
        trans[3, 3] = 1

        vtk_trans = vtk.vtkMatrix4x4()
        for i in range(0, 4):
            for j in range(0, 4):
                vtk_trans.SetElement(i, j, trans[i, j])

        ar_trans = vtk.vtkTransform()
        ar_trans.SetMatrix(vtk_trans)
        ar_trans_filter = vtk.vtkTransformPolyDataFilter()
        ar_trans_filter.SetTransform(ar_trans)
        ar_trans_filter.SetInputConnection(disk.GetOutputPort())

        diskMapper = vtk.vtkPolyDataMapper()
        diskMapper.SetInputConnection(ar_trans_filter.GetOutputPort())

        actor = vtk.vtkActor()
        actor.SetMapper(diskMapper)
        actor.GetProperty().SetColor(vec3_color[0], vec3_color[1],
                                     vec3_color[2])
        self.ren.AddActor(actor)
        self.name2actor[actorName] = actor
        return

    def display_arrow(self, actorName, vec3_origin, vec3_direction,
                      length_in_m, shaft_radius, vec3_color):
        # visualize direction arrow
        arrow = vtk.vtkArrowSource()
        arrow.SetTipLength(0.25)
        arrow.SetTipRadius((1.5 * shaft_radius) / length_in_m)
        arrow.SetTipResolution(20)
        arrow.SetShaftRadius(shaft_radius / length_in_m)  # account for scaling
        arrow.SetShaftResolution(20)
        arrow.Update()

        # scale
        scale = vtk.vtkTransform()
        scale.Scale(length_in_m, length_in_m, length_in_m)
        scale_filter = vtk.vtkTransformPolyDataFilter()
        scale_filter.SetTransform(scale)
        scale_filter.SetInputConnection(arrow.GetOutputPort())

        # transform to center with orientation according to normal
        axis1 = [vec3_direction[0], vec3_direction[1], vec3_direction[2]]
        axis2 = np.cross(axis1, [1, 1, 1])
        axis2 = axis2 / np.linalg.norm(axis2)
        axis3 = np.cross(axis1, axis2)
        # print axis1
        # print axis2
        # print axis3
        trans = np.eye(4)
        trans[0, 0] = axis1[0]
        trans[0, 1] = axis2[0]
        trans[0, 2] = axis3[0]
        trans[0, 3] = vec3_origin[0]
        trans[1, 0] = axis1[1]
        trans[1, 1] = axis2[1]
        trans[1, 2] = axis3[1]
        trans[1, 3] = vec3_origin[1]
        trans[2, 0] = axis1[2]
        trans[2, 1] = axis2[2]
        trans[2, 2] = axis3[2]
        trans[2, 3] = vec3_origin[2]
        trans[3, 0] = 0
        trans[3, 1] = 0
        trans[3, 2] = 0
        trans[3, 3] = 1

        vtk_trans = vtk.vtkMatrix4x4()
        for i in range(0, 4):
            for j in range(0, 4):
                vtk_trans.SetElement(i, j, trans[i, j])

        ar_trans = vtk.vtkTransform()
        ar_trans.SetMatrix(vtk_trans)
        ar_trans_filter = vtk.vtkTransformPolyDataFilter()
        ar_trans_filter.SetTransform(ar_trans)
        ar_trans_filter.SetInputConnection(scale_filter.GetOutputPort())

        arrowMapper = vtk.vtkPolyDataMapper()
        arrowMapper.SetInputConnection(ar_trans_filter.GetOutputPort())

        actor = vtk.vtkActor()
        actor.SetMapper(arrowMapper)
        actor.GetProperty().SetColor(vec3_color[0], vec3_color[1],
                                     vec3_color[2])
        self.ren.AddActor(actor)
        self.name2actor[actorName] = actor
        pass

    def display_affordance_primitive(self, g, type_):
        self.remove_all_displays()
        if type_ == 'axis':
            self.display_arrow('p', g.base, g.direction, g.length, g.radius,
                               [1, .2, 0])
        elif type_ == 'plane':
            self.display_disk('p', g.center, g.normal, g.radius, 0, [1, .2, 0])
            self.display_arrow('p', g.center, g.normal, .1, .002, [1, .3, 0])

    def remove_display(self, actorName):
        actor = self.name2actor.get(actorName)
        if (actor != None):
            self.ren.RemoveActor(actor)
            self.name2actor.pop(actorName)
        pass

    def remove_all_displays(self):
        for actor in self.name2actor.viewvalues():
            self.ren.RemoveActor(actor)
        self.name2actor.clear()
        pass
Exemple #34
0
class MeshRenderWidget(QtGui.QWidget):
  def __init__(self, tree_widget):
    QtGui.QWidget.__init__(self)
    self.tree_widget = tree_widget
    self.tree_widget.mesh_item_changed.connect(self.meshItemChanged)

    self.mesh_file_name = ''

    self.mesh_renderer = None

    self.current_block_actors = {}
    self.current_sideset_actors = {}
    self.current_nodeset_actors = {}

    self.this_layout = QtGui.QVBoxLayout()
    self.setLayout(self.this_layout)

    self.vtkwidget = QVTKRenderWindowInteractor(self)

    self.renderer = vtk.vtkRenderer()
    self.renderer.SetBackground(0.2,0.2,0.2)
    self.renderer.SetBackground2(1,1,1)
    self.renderer.SetGradientBackground(1)
    self.renderer.ResetCamera()

    self.this_layout.addWidget(self.vtkwidget)
    self.this_layout.setStretchFactor(self.vtkwidget, 10)

    self.vtkwidget.setMinimumHeight(300)

    self.vtkwidget.GetRenderWindow().AddRenderer(self.renderer)
    self.interactor = self.vtkwidget.GetRenderWindow().GetInteractor()

    self.interactor.SetInteractorStyle(vtk.vtkInteractorStyleTrackballCamera())

    self.vtkwidget.Initialize()
    self.vtkwidget.Start()

    self.controls_layout = QtGui.QHBoxLayout()

    self.left_controls_layout = QtGui.QVBoxLayout()

    self.block_view_group_box = QtGui.QGroupBox('Show Blocks')
    self.block_view_group_box.setMaximumWidth(150)
#    self.block_view_group_box.setMaximumHeight(200)

    self.block_view_layout = QtGui.QVBoxLayout()
    self.block_view_list = QtGui.QListView()
    self.block_view_model = QtGui.QStandardItemModel()
    self.block_view_model.itemChanged.connect(self._blockViewItemChanged)
    self.block_view_list.setModel(self.block_view_model)
    self.block_view_layout.addWidget(self.block_view_list)

    self.block_view_group_box.setLayout(self.block_view_layout)
    self.left_controls_layout.addWidget(self.block_view_group_box)
    self.controls_layout.addLayout(self.left_controls_layout)


    self.right_controls_layout = QtGui.QVBoxLayout()
    self.controls_layout.addLayout(self.right_controls_layout)

    self.view_mesh_checkbox = QtGui.QCheckBox('View Mesh')
    self.view_mesh_checkbox.setToolTip('Toggle viewing of mesh elements')
    self.view_mesh_checkbox.setCheckState(QtCore.Qt.Checked)
    self.view_mesh_checkbox.stateChanged.connect(self.viewMeshCheckboxChanged)
    self.right_controls_layout.addWidget(self.view_mesh_checkbox)

    self.highlight_group_box = QtGui.QGroupBox('Highlight')
    self.highlight_group_box.setMaximumHeight(70)
    self.highlight_group_box.setSizePolicy(QtGui.QSizePolicy.MinimumExpanding, QtGui.QSizePolicy.Fixed)
#    self.highlight_group_box.setMaximumWidth(200)
    self.highlight_layout = QtGui.QHBoxLayout()
    self.highlight_group_box.setLayout(self.highlight_layout)
    self.right_controls_layout.addWidget(self.highlight_group_box)

    self.highlight_block_label = QtGui.QLabel('Block:')
    self.highlight_block_label.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
    self.highlight_block_combo = QtGui.QComboBox()
#    self.highlight_block_combo.setMaximumWidth(50)
    self.highlight_block_combo.setSizeAdjustPolicy(QtGui.QComboBox.AdjustToMinimumContentsLength)
    self.highlight_block_combo.setSizePolicy(QtGui.QSizePolicy.MinimumExpanding, QtGui.QSizePolicy.Fixed)
    self.highlight_block_combo.setToolTip('Highlight a block in the mesh')
    self.highlight_block_combo.currentIndexChanged[str].connect(self.showBlockSelected)
    self.highlight_layout.addWidget(self.highlight_block_label)
    self.highlight_layout.addWidget(self.highlight_block_combo)

    self.highlight_sideset_label = QtGui.QLabel('Sideset:')
    self.highlight_sideset_label.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
    self.highlight_sideset_combo = QtGui.QComboBox()
#    self.highlight_sideset_combo.setMaximumWidth(50)
    self.highlight_sideset_combo.setSizeAdjustPolicy(QtGui.QComboBox.AdjustToMinimumContentsLength)
    self.highlight_sideset_combo.setSizePolicy(QtGui.QSizePolicy.MinimumExpanding, QtGui.QSizePolicy.Fixed)
    self.highlight_sideset_combo.setToolTip('Highlight a sideset in the mesh')
    self.highlight_sideset_combo.currentIndexChanged[str].connect(self.showSidesetSelected)
    self.highlight_layout.addWidget(self.highlight_sideset_label)
    self.highlight_layout.addWidget(self.highlight_sideset_combo)

    self.highlight_nodeset_label = QtGui.QLabel('Nodeset:')
    self.highlight_nodeset_label.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
    self.highlight_nodeset_combo = QtGui.QComboBox()
#    self.highlight_nodeset_combo.setMaximumWidth(50)
    self.highlight_nodeset_combo.setSizeAdjustPolicy(QtGui.QComboBox.AdjustToMinimumContentsLength)
    self.highlight_nodeset_combo.setSizePolicy(QtGui.QSizePolicy.MinimumExpanding, QtGui.QSizePolicy.Fixed)
    self.highlight_nodeset_combo.setToolTip('Highlight a nodeset in the mesh')
    self.highlight_nodeset_combo.currentIndexChanged[str].connect(self.showNodesetSelected)
    self.highlight_layout.addWidget(self.highlight_nodeset_label)
    self.highlight_layout.addWidget(self.highlight_nodeset_combo)

    self.highlight_clear = QtGui.QPushButton('Clear')
    self.highlight_clear.setToolTip('Clear highlighting')
    self.highlight_clear.setDisabled(True)
    self.highlight_clear.clicked.connect(self.clearHighlight)
    self.highlight_layout.addWidget(self.highlight_clear)

    self.plane = vtk.vtkPlane()
    self.plane.SetOrigin(0, 0, 0)
    self.plane.SetNormal(1, 0, 0)

    self.clip_groupbox = QtGui.QGroupBox("Clip")
    self.clip_groupbox.setToolTip('Toggle clip mode to slice the mesh open along a plane')
    self.clip_groupbox.setCheckable(True)
    self.clip_groupbox.setChecked(False)
    self.clip_groupbox.setMaximumHeight(70)
    self.clip_groupbox.toggled[bool].connect(self._clippingToggled)
    clip_layout = QtGui.QHBoxLayout()

    self.clip_plane_combobox = QtGui.QComboBox()
    self.clip_plane_combobox.setToolTip('Direction of the normal for the clip plane')
    self.clip_plane_combobox.addItem('x')
    self.clip_plane_combobox.addItem('y')
    self.clip_plane_combobox.addItem('z')
    self.clip_plane_combobox.currentIndexChanged[str].connect(self._clipNormalChanged)

    clip_layout.addWidget(self.clip_plane_combobox)

    self.clip_plane_slider = QtGui.QSlider(QtCore.Qt.Horizontal)
    self.clip_plane_slider.setToolTip('Slide to change plane position')
    self.clip_plane_slider.setRange(0, 100)
    self.clip_plane_slider.setSliderPosition(50)
    self.clip_plane_slider.sliderMoved[int].connect(self._clipSliderMoved)
    clip_layout.addWidget(self.clip_plane_slider)
#     vbox->addStretch(1);
    self.clip_groupbox.setLayout(clip_layout)

    self.right_controls_layout.addWidget(self.clip_groupbox)

    self.this_layout.addLayout(self.controls_layout)
    self.this_layout.setStretchFactor(self.controls_layout, 1)

    self.bounds = {}
    self.bounds['x'] = [0.0, 0.0]
    self.bounds['y'] = [0.0, 0.0]
    self.bounds['z'] = [0.0, 0.0]

#    self.draw_edges_checkbox = QtGui.QCheckBox("View Mesh")

#    self.left_controls_layout.addWidget(self.draw_edges_checkbox)

  def clear(self):
    self.highlight_block_combo.clear()
    self.highlight_sideset_combo.clear()
    self.highlight_nodeset_combo.clear()

    for block_actor_name, block_actor in self.current_block_actors.items():
      block_actor.hide()

    for sideset_actor_name, sideset_actor in self.current_sideset_actors.items():
      sideset_actor.hide()

    for nodeset_actor_name, nodeset_actor in self.current_nodeset_actors.items():
      nodeset_actor.hide()

    self.current_block_actors = {}
    self.current_sideset_actors = {}
    self.current_nodeset_actors = {}

  def meshItemChanged(self, item):
    # Disconnect some actions while we fill stuff in
    if self.mesh_renderer:
      self.highlight_block_combo.currentIndexChanged[str].disconnect(self.showBlockSelected)
      self.highlight_sideset_combo.currentIndexChanged[str].disconnect(self.showSidesetSelected)
      self.highlight_nodeset_combo.currentIndexChanged[str].disconnect(self.showNodesetSelected)

    self.clear()

    self.mesh_renderer = RendererFactory.getRenderer(self, item.table_data)

    if self.mesh_renderer:
      self.show()
    else:
      self.hide()
      return

    self.current_block_actors = self.mesh_renderer.block_actors
    self.current_sideset_actors = self.mesh_renderer.sideset_actors
    self.current_nodeset_actors = self.mesh_renderer.nodeset_actors

    self.block_view_model.clear()
    for block in self.mesh_renderer.blocks:
      block_display_name = str(block)
      if block in self.mesh_renderer.block_id_to_name:
        block_display_name += ' : ' + self.mesh_renderer.block_id_to_name[block]

      item = QtGui.QStandardItem(str(block_display_name))
      item.exodus_block = block
      item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsUserCheckable)
      item.setCheckState(QtCore.Qt.Checked)
      self.block_view_model.appendRow(item)

    for block_actor_name, block_actor in self.current_block_actors.items():
      block_actor.show()
      block_actor.showEdges()

    block_names = []
    for block_actor_id, block_actor in self.current_block_actors.items():
      name = block_actor_id.strip(' ')
      if int(name) in self.mesh_renderer.block_id_to_name:
        name += ' : ' + self.mesh_renderer.block_id_to_name[int(name)]

      block_names.append(name)

    self.highlight_block_combo.addItem('')
    for block_actor_name in sorted(block_names, key=lambda name: int(name.split(' ')[0])):
      self.highlight_block_combo.addItem(str(block_actor_name))

    sideset_names = []
    for sideset_actor_id, sideset_actor in self.current_sideset_actors.items():
      sideset_actor.setColor(red)

      name = sideset_actor_id.strip(' ')
      if int(name) in self.mesh_renderer.sideset_id_to_name:
        name += ' : ' + self.mesh_renderer.sideset_id_to_name[int(name)]

      sideset_names.append(name)

    self.highlight_sideset_combo.addItem('')
    for sideset_actor_name in sorted(sideset_names, key=lambda name: int(name.split(' ')[0])):
      self.highlight_sideset_combo.addItem(sideset_actor_name)

    nodeset_names = []
    for nodeset_actor_id, nodeset_actor in self.current_nodeset_actors.items():
      nodeset_actor.setColor(red)

      name = nodeset_actor_id.strip(' ')
      if int(name) in self.mesh_renderer.nodeset_id_to_name:
        name += ' : ' + self.mesh_renderer.nodeset_id_to_name[int(name)]

      nodeset_names.append(name)

    self.highlight_nodeset_combo.addItem('')
    for nodeset_actor_name in sorted(nodeset_names, key=lambda name: int(name.split(' ')[0])):
      self.highlight_nodeset_combo.addItem(nodeset_actor_name)


    self.highlight_block_combo.currentIndexChanged[str].connect(self.showBlockSelected)
    self.highlight_sideset_combo.currentIndexChanged[str].connect(self.showSidesetSelected)
    self.highlight_nodeset_combo.currentIndexChanged[str].connect(self.showNodesetSelected)

    self.setBounds()

     # Avoid z-buffer fighting
    vtk.vtkPolyDataMapper().SetResolveCoincidentTopologyToPolygonOffset()

    self.renderer.ResetCamera()
    self.vtkwidget.repaint()

  def setBounds(self):
    for actor_name, actor in self.current_block_actors.items():
      current_bounds = actor.getBounds()
      self.bounds['x'][0] = min(self.bounds['x'][0], current_bounds[0])
      self.bounds['x'][1] = max(self.bounds['x'][1], current_bounds[1])

      self.bounds['y'][0] = min(self.bounds['y'][0], current_bounds[2])
      self.bounds['y'][1] = max(self.bounds['y'][1], current_bounds[3])

      self.bounds['z'][0] = min(self.bounds['z'][0], current_bounds[4])
      self.bounds['z'][1] = max(self.bounds['z'][1], current_bounds[5])

  def swapActors(self, current, new):
    for old_name, old_actor in current.items():
      new[old_name].sync(old_actor)
      old_actor.hide()

  def _blockViewItemChanged(self, item):
    if item.checkState() == QtCore.Qt.Checked:
      self.current_block_actors[str(item.exodus_block)].show()
    else:
      self.current_block_actors[str(item.exodus_block)].hide()
    self.vtkwidget.repaint()

  def _clippingToggled(self, value):
    if value:
      self.swapActors(self.current_block_actors, self.mesh_renderer.clipped_block_actors)
      self.current_block_actors = self.mesh_renderer.clipped_block_actors
      self.swapActors(self.current_sideset_actors, self.mesh_renderer.clipped_sideset_actors)
      self.current_sideset_actors = self.mesh_renderer.clipped_sideset_actors
      self.swapActors(self.current_nodeset_actors, self.mesh_renderer.clipped_nodeset_actors)
      self.current_nodeset_actors = self.mesh_renderer.clipped_nodeset_actors

      self._clipNormalChanged(self.clip_plane_combobox.currentText())
    else:
      self.swapActors(self.current_block_actors, self.mesh_renderer.block_actors)
      self.current_block_actors = self.mesh_renderer.block_actors
      self.swapActors(self.current_sideset_actors, self.mesh_renderer.sideset_actors)
      self.current_sideset_actors = self.mesh_renderer.sideset_actors
      self.swapActors(self.current_nodeset_actors, self.mesh_renderer.nodeset_actors)
      self.current_nodeset_actors = self.mesh_renderer.nodeset_actors

    self.vtkwidget.repaint()

  def _clipNormalChanged(self, value):
    self.plane.SetOrigin(self.bounds['x'][0],
                         self.bounds['y'][0],
                         self.bounds['z'][0])
    if value == 'x':
      self.plane.SetNormal(1, 0, 0)
    elif value == 'y':
      self.plane.SetNormal(0, 1, 0)
    else:
      self.plane.SetNormal(0, 0, 1)

    self.clip_plane_slider.setSliderPosition(50)
    self._clipSliderMoved(50)

  def _clipSliderMoved(self, value):
    direction = str(self.clip_plane_combobox.currentText())
    step_size = (self.bounds[direction][1] - self.bounds[direction][0])/100.0
    steps = value
    distance = float(steps)*step_size
    position = self.bounds[direction][0] + distance

    old = self.plane.GetOrigin()
    self.plane.SetOrigin(position if direction == 'x' else old[0],
                         position if direction == 'y' else old[1],
                         position if direction == 'z' else old[2])

    for actor_name, actor in self.current_sideset_actors.items():
      actor.movePlane()

    for actor_name, actor in self.current_nodeset_actors.items():
      actor.movePlane()

    for actor_name, actor in self.current_block_actors.items():
      actor.movePlane()

    self.vtkwidget.repaint()

  def viewMeshCheckboxChanged(self, value):
    if value == QtCore.Qt.Checked:
      for actor_name, actor in self.current_sideset_actors.items():
        actor.showEdges()
      for actor_name, actor in self.current_nodeset_actors.items():
        actor.showEdges()
      for actor_name, actor in self.current_block_actors.items():
        actor.showEdges()
    else:
      for actor_name, actor in self.current_sideset_actors.items():
        actor.hideEdges()
      for actor_name, actor in self.current_nodeset_actors.items():
        actor.hideEdges()
      for actor_name, actor in self.current_block_actors.items():
        actor.hideEdges()
    self.vtkwidget.repaint()

  def clearBlockComboBox(self):
      self.highlight_block_combo.currentIndexChanged[str].disconnect(self.showBlockSelected)
      self.highlight_block_combo.setCurrentIndex(0)
      self.highlight_block_combo.currentIndexChanged[str].connect(self.showBlockSelected)

  def clearSidesetComboBox(self):
    self.highlight_sideset_combo.currentIndexChanged[str].disconnect(self.showSidesetSelected)
    self.highlight_sideset_combo.setCurrentIndex(0)
    self.highlight_sideset_combo.currentIndexChanged[str].connect(self.showSidesetSelected)

  def clearNodesetComboBox(self):
    self.highlight_nodeset_combo.currentIndexChanged[str].disconnect(self.showNodesetSelected)
    self.highlight_nodeset_combo.setCurrentIndex(0)
    self.highlight_nodeset_combo.currentIndexChanged[str].connect(self.showNodesetSelected)

  def showBlockSelected(self, block_name):
    if block_name != '':
      self.clearSidesetComboBox()
      self.clearNodesetComboBox()
      self.highlightBlock(str(block_name).split(' ')[0])
    else:
      self.clearActors()

  def showSidesetSelected(self, sideset_name):
    if sideset_name != '':
      self.clearBlockComboBox()
      self.clearNodesetComboBox()
      self.highlightBoundary(str(sideset_name).split(' ')[0])
    else:
      self.clearActors()

  def showNodesetSelected(self, nodeset_name):
    if nodeset_name != '':
      self.clearBlockComboBox()
      self.clearSidesetComboBox()
      self.highlightNodeset(str(nodeset_name).split(' ')[0])
    else:
      self.clearActors()

  def highlightBoundary(self, boundary):
    self.highlight_clear.setDisabled(False)
    # Turn off all sidesets
    for actor_name, actor in self.current_sideset_actors.items():
      actor.hide()

    # Turn off all nodesets
    for actor_name, actor in self.current_nodeset_actors.items():
      actor.hide()

    # Turn solids to only edges... but only if they are visible
    for actor_name, actor in self.current_block_actors.items():
      actor.setColor(black)
      actor.goWireframe()

    boundaries = boundary.strip("'").split(' ')
    for the_boundary in boundaries:
      if the_boundary in self.current_sideset_actors:
        self.current_sideset_actors[the_boundary].show()
      elif the_boundary in self.current_nodeset_actors:
        self.current_nodeset_actors[the_boundary].show()
      elif the_boundary in self.mesh_renderer.name_to_sideset_id:
        self.current_sideset_actors[str(self.mesh_renderer.name_to_sideset_id[the_boundary])].show()
      elif the_boundary in self.mesh_renderer.name_to_nodeset_id:
        self.current_nodeset_actors[str(self.mesh_renderer.name_to_nodeset_id[the_boundary])].show()

    self.vtkwidget.repaint()

  def highlightNodeset(self, boundary):
    self.highlight_clear.setDisabled(False)
    # Turn off all sidesets
    for actor_name, actor in self.current_sideset_actors.items():
      actor.hide()

    # Turn off all nodesets
    for actor_name, actor in self.current_nodeset_actors.items():
      actor.hide()

    # Turn solids to only edges... but only if they are visible
    for actor_name, actor in self.current_block_actors.items():
      actor.setColor(black)
      actor.goWireframe()

    boundaries = boundary.strip("'").split(' ')
    for the_boundary in boundaries:
      if the_boundary in self.current_nodeset_actors:
        self.current_nodeset_actors[the_boundary].show()
      elif the_boundary in self.mesh_renderer.name_to_nodeset_id:
        self.current_nodeset_actors[str(self.mesh_renderer.name_to_nodeset_id[the_boundary])].show()

    self.vtkwidget.repaint()

  def highlightBlock(self, block):
    self.highlight_clear.setDisabled(False)
    # Turn off all sidesets
    for actor_name, actor in self.current_sideset_actors.items():
      actor.hide()

    # Turn off all nodesets
    for actor_name, actor in self.current_nodeset_actors.items():
      actor.hide()

    # Turn solids to only edges...
    for actor_name, actor in self.current_block_actors.items():
      actor.setColor(black)
      actor.goWireframe()

    blocks = block.strip("'").split(' ')
    for the_block in blocks:
      if the_block in self.current_block_actors:
        self.current_block_actors[the_block].setColor(red)
        self.current_block_actors[the_block].goSolid()
      elif the_block in self.mesh_renderer.name_to_block_id:
        self.current_block_actors[str(self.mesh_renderer.name_to_block_id[the_block])].setColor(red)
        self.current_block_actors[str(self.mesh_renderer.name_to_block_id[the_block])].goSolid()

    self.vtkwidget.repaint()

  def clearActors(self):
    # Turn off all sidesets
    for actor_name, actor in self.current_sideset_actors.items():
      actor.hide()

    # Turn off all nodesets
    for actor_name, actor in self.current_nodeset_actors.items():
      actor.hide()

    # Show solids and edges - but only if something is visible
    for actor_name, actor in self.current_block_actors.items():
      actor.setColor(white)
      actor.goSolid()

    self.vtkwidget.repaint()

  def clearHighlight(self):
    self.highlight_block_combo.setCurrentIndex(0)
    self.highlight_sideset_combo.setCurrentIndex(0)
    self.highlight_nodeset_combo.setCurrentIndex(0)
    self.highlight_clear.setDisabled(True)
    self.clearActors()
Exemple #35
0
class ParallelCoordinatesWidget(QCellWidget):
    def __init__(self, parent=None):
        QCellWidget.__init__(self, parent)
        
        centralLayout = QtGui.QVBoxLayout()
        self.setLayout(centralLayout)
        centralLayout.setMargin(0)
        centralLayout.setSpacing(0)
                
        self.view = vtk.vtkContextView()
        self.widget = QVTKRenderWindowInteractor(self, 
                                                 rw=self.view.GetRenderWindow(),
                                                 iren=self.view.GetInteractor()
                                                )

        self.chart = vtk.vtkChartParallelCoordinates()
        self.view.GetScene().AddItem(self.chart)

        self.layout().addWidget(self.widget)

        # Create a annotation link to access selection in parallel coordinates view
        self.annotationLink = vtk.vtkAnnotationLink()
        # If you don't set the FieldType explicitly it ends up as UNKNOWN (as of 21 Feb 2010)
        # See vtkSelectionNode doc for field and content type enum values
        self.annotationLink.GetCurrentSelection().GetNode(0).SetFieldType(1)     # Point
        self.annotationLink.GetCurrentSelection().GetNode(0).SetContentType(4)   # Indices
        # Connect the annotation link to the parallel coordinates representation
        self.chart.SetAnnotationLink(self.annotationLink)
        self.annotationLink.AddObserver("AnnotationChangedEvent", self.selectionCallback)
        self.setFixedSize(400, 200)

    def updateContents(self, inputPorts):
        (self.coord, matrix) = inputPorts 
        if self.coord is not None: self.coord.register(self)
    
        self.createTable(matrix)
        self.widget.Initialize()
        
        # Capture window into history for playback
        # Call this at the end to capture the image after rendering
        QCellWidget.updateContents(self, inputPorts)
        
    def updateSelection(self, selectedIds):
        if len(selectedIds)==0: return

        Ids = VN.numpy_to_vtkIdTypeArray(np.array(selectedIds), deep=True)

        node = vtk.vtkSelectionNode()
        node.SetContentType(vtk.vtkSelectionNode.INDICES)
        node.SetFieldType(vtk.vtkSelectionNode.POINT)
        node.SetSelectionList(Ids)
        
        selection = vtk.vtkSelection()
        selection.AddNode(node)
        
        self.annotationLink.SetCurrentSelection(selection)
        self.widget.Render()
        
    def createTable(self, matrix):
        table = vtk.vtkTable()
        for col, attr in zip(matrix.values.T, matrix.attributes):
            column = VN.numpy_to_vtk(col.copy(), deep=True)
            column.SetName(attr)
            table.AddColumn(column)
        self.chart.GetPlot(0).SetInput(table)

        min_ = matrix.values.min()-0.01
        max_ = matrix.values.max()+0.01
        for i in range(self.chart.GetNumberOfAxes()):
            self.chart.GetAxis(i).SetRange(min_, max_)
            self.chart.GetAxis(i).SetBehavior(vtk.vtkAxis.FIXED);
#            self.chart.GetAxis(i).SetPosition(vtk.vtkAxis.LEFT)
#            self.chart.GetAxis(i).GetTitleProperties().SetOrientation(30)

    def selectionCallback(self, caller, event):
        if self.coord is None: return
        
        annSel = self.annotationLink.GetCurrentSelection()
        if annSel.GetNumberOfNodes() > 0:
            idxArr = annSel.GetNode(0).GetSelectionList()
            if idxArr.GetNumberOfTuples() > 0:
                self.coord.unregister(self)
                self.coord.notifyModules(VN.vtk_to_numpy(idxArr))
                self.coord.register(self)
Exemple #36
0
class AppWindow(QtGui.QMainWindow):
    def __init__(self, parent):
        self.parent = parent
        self.queue = Queue.Queue()
        self.processThread = ProcessingThread(self.queue)
        #self.processThread = threading.Thread(target=self.consumer.run())
        self.processThread.start()

        self.fileLoader = DicomLoader(self, "file")
        self.folderLoader = DicomLoader(self, "series")
        self.importSrc()
        self.initGUI()
        self.initToolbar()
        self.initConnections()


    def importSrc(self):
        # will be shown as errors in pyCharm
        pass

    def exit(self):
        self.close()

    def initConnections(self):
        self.connect(self.ui.actionLoad, QtCore.SIGNAL("triggered()"), self.loadSingleFile)
        self.connect(self.ui.actionExit, QtCore.SIGNAL("triggered()"), self.exit)

    def initGUI(self):
        QtGui.QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.setWindowTitle("Simple Dicom Viewer")

        #self.dicomReader = vtk.vtkDICOMImageReader()
        #self.dicomReader = vtkgdcm.vtkGDCMImageReader()
        self.show()

        self.figure = plt.figure()
        self.canvas = FigureCanvas(self.figure)
        self.toolbar = NavigationToolbar(self.canvas, self)
        self.ui.numpyLayout.addWidget(self.toolbar)
        self.ui.numpyLayout.addWidget(self.canvas)



        self.vtkWidget = QVTKRenderWindowInteractor(self.ui.imageFrame)
        self.vtkWidget.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
        #self.ui.imageLayout.removeWidget(self.ui.dicomSlider)
        self.ui.imageLayout.addWidget(self.vtkWidget)
        #self.ui.imageLayout.addWidget(self.ui.dicomSlider)

        self.disableSlider()

        self.viewer= vtk.vtkImageViewer()
        #self.viewer.SetupInteractor(MyInteractor())
        self.vtkWidget.GetRenderWindow().AddRenderer(self.viewer.GetRenderer())
        self.iren = self.vtkWidget.GetRenderWindow().GetInteractor()
        #self.iren.SetRenderWindow(self.vtkWidget.GetRenderWindow())


        self.drag = False
        self.measuring = False
        self.iren.AddObserver("LeftButtonPressEvent", self.leftClick)
        self.iren.AddObserver("LeftButtonReleaseEvent", self.leftRelease)
        self.iren.AddObserver("EnterEvent", self.mouseEntered)
        self.iren.AddObserver("LeaveEvent", self.mouseLeft)
        self.iren.AddObserver("MouseMoveEvent", self.mouseMoved)

    def mouseMoved(self, *args):
        if self.drag:
            self.temp = args[0].GetEventPosition()
            print(self.temp)
            print(self.begin)
            self.drawLine([self.begin, self.temp])
            return
            time.sleep(0.1)
            #print(args[0].GetEventPosition())
    def mouseEntered(self, *args):
        self.drag = False
        print("Entered")

    def mouseLeft(self, *args):
        self.drag = False
        print("Left")

    def leftClick(self, *args):
        if self.measuring:
            if self.drag == False:
                self.drag = True
                self.begin = args[0].GetEventPosition()
                print(self.begin)
                print(self.drag)
            else:
                self.drag = False
                self.end = args[0].GetEventPosition()
                self.drawLine([self.begin, self.end])
                self.printDistance(self.dist)

    def leftRelease(self, *args):
        #self.drag = False
        #print(self.drag)
        pass

    def printDistance(self, dist):
        box = QtGui.QMessageBox(self)
        box.setInformativeText("Distance: " + str(dist) + " cm.")
        box.show()



    def initToolbar(self):
        self.actions = Actions(self)

    def drawLine(self, points):
        try:
            self.viewer.GetRenderer().RemoveActor(self.actor)
            self.viewer.GetRenderer().Render()
        except:
            pass
        point1 = points[0]
        point2 = points[1]

        points = vtk.vtkPoints()
        points.SetNumberOfPoints(2)
        points.Allocate(2)

        points.InsertPoint(0, point1[0], point1[1], 0.001)
        points.InsertPoint(1, point2[0], point2[1], 0.001)

        dist = numpy.sqrt(numpy.square((point1[0]-point2[0])*0.028) + numpy.square((point1[1]-point2[1])*0.030))
        self.cells = vtk.vtkCellArray()
        self.cells.Initialize()

        line = vtk.vtkLine()
        line.GetPointIds().SetId(0,0)
        line.GetPointIds().SetId(1,1)
        self.cells.InsertNextCell(line)

        self.poly = vtk.vtkPolyData()
        self.poly.Initialize()
        self.poly.SetPoints(points)
        self.poly.SetLines(self.cells)
        self.poly.Modified()

        mapper = vtk.vtkPolyDataMapper2D()
        #print(dir(mapper))
        mapper.SetInput(self.poly)
        mapper.ScalarVisibilityOn()
        mapper.SetScalarModeToUsePointData()
        mapper.Update()

        self.actor = vtk.vtkActor2D()
        self.actor.SetMapper(mapper)
        self.viewer.GetRenderer().AddActor2D(self.actor)

        self.dist = dist



    def loadSingleFile(self):
        loader = self.fileLoader
        loader.loadFile()

        if loader.accepted:
            loader.setDir(os.path.dirname(str(loader.selectedFile)))
            self.disableSlider()
            self.dicomReader = vtkgdcm.vtkGDCMImageReader()
            self.dicomReader.SetFileName(str(loader.selectedFile))

            print(dir(self.dicomReader))
            print(self.dicomReader.GetScale())

            self.dicomReader.Update()
            imageData = self.dicomReader.GetOutput()
            size = imageData.GetDimensions()
            width = size[0]
            height = size[1]
            self.vtkWidget.setMaximumSize(QtCore.QSize(width, height))
            self.vtkWidget.setMinimumSize(QtCore.QSize(width, height))

            RefDs = dicom.read_file(str(loader.selectedFile))
            ConstPixelDims = (int(RefDs.Rows), int(RefDs.Columns), 1)

            pointData = imageData.GetPointData()
            arrayData = pointData.GetArray(0)
            arrayDicom = numpy_support.vtk_to_numpy(arrayData)
            arrayDicom = arrayDicom.reshape(ConstPixelDims, order='F')
            shape = arrayDicom.shape
            wtf = arrayDicom.reshape(shape[0], shape[1])
            wtf = numpy.fliplr(wtf).transpose()
            max = numpy.max(wtf)
            min = numpy.min(wtf)
            print(numpy.max(wtf))
            print(numpy.min(wtf))
            grad = numpy.gradient(wtf)

            print(wtf)
            computed = numpy.sqrt(numpy.square(grad[0]) + numpy.square(grad[1]))
            #self.proc.start()
            ax = self.figure.add_subplot(111)
            ax.imshow(wtf, interpolation="nearest", cmap=plt.get_cmap('gray'), vmin=0, vmax=max)
            self.canvas.draw()


            #points = vtk.vtkPoints()
            #points.SetNumberOfPoints(2)
            #points.Allocate(2)

            #points.InsertPoint(0, 100, 100, 0.001)
            #points.InsertPoint(0, 200, 200, 0.001)

            #cells = vtk.vtkCellArray()
            #cells.Initialize()

            #line = vtk.vtkLine()
            #line.GetPointIds().SetId(0,0)
            #line.GetPointIds().SetId(1,1)
            #cells.InsertNextCell(line)

            #poly = vtk.vtkPolyData()
            #poly.Initialize()
            #poly.SetPoints(points)
            #poly.SetLines(cells)
            #poly.Modified()

            #mapper = vtk.vtkPolyDataMapper2D()
            #print(dir(mapper))
            #mapper.SetInput(poly)
            #mapper.ScalarVisibilityOn()
            #mapper.SetScalarModeToUsePointData()
            #mapper.Update()

            #self.drawLine([(200,200), (300,300)])

            #actor = vtk.vtkActor2D()
            #actor.SetMapper(mapper)
            blend = vtk.vtkImageBlend()
            blend.AddInputConnection(self.dicomReader.GetOutputPort())
            #blend.AddInputConnection(actor.GetOutputPort())
            self.viewer.SetInputConnection(blend.GetOutputPort())
            #print(dir(self.viewer.GetRenderer()))
            #self.viewer.GetRenderer().AddActor2D(actor)


            #self.viewer.SetInputConnection(self.dicomReader.GetOutputPort())
            self.viewer.SetZSlice(0)
            self.getMedicalData()
            self.iren.ReInitialize()
            self.iren.Render()
            self.iren.Start()

            #actor = vtk.vtkImageActor()
            #self.viewer.GetRenderer().AddActor(actor)
            self.viewer.GetRenderer().Render()


    def getMedicalData(self):
        #print(self.dicomReader)
        splitter = "Medical Image Properties:"
        data = str(self.dicomReader).split(splitter)
        data = [x.strip() for x in data]
        data = data[1].split('\n')
        data = [x.split(":") for x in data if x]
        self.ui.dicomData.setRowCount(len(data))
        self.ui.dicomData.setColumnCount(1)
        self.ui.dicomData.setHorizontalHeaderItem(0, QtGui.QTableWidgetItem("Data"))
        for i in xrange(0, len(data)):
            self.ui.dicomData.setVerticalHeaderItem(i, QtGui.QTableWidgetItem((data[i][0])))
            self.ui.dicomData.setItem(i, 0, QtGui.QTableWidgetItem((data[i][1])))
        self.ui.dicomData.horizontalHeader().setResizeMode(QtGui.QHeaderView.Stretch)
        self.ui.dicomData.setSortingEnabled(False)
        #print(data)

    def disableSlider(self):
        self.ui.playButton.setDisabled(True)
        self.ui.dicomSlider.setDisabled(True)
        self.ui.dicomSlider.setValue(0)
        self.ui.dicomSlider.disconnect(self.ui.dicomSlider, QtCore.SIGNAL("valueChanged(int)"), self.sliderMoved)
        self.ui.playButton.disconnect(self.ui.playButton, QtCore.SIGNAL("clicked()"), self.playMovie)

    @QtCore.pyqtSlot(int)
    def sliderMoved(self, value):
        try:
            self.viewer.SetZSlice(value)
            self.iren.Render()
        except:
            raise ValueError

    @QtCore.pyqtSlot(int)
    def movieStep(self, value):
        self.ui.dicomSlider.setValue(value)
        self.ui.dicomSlider.setSliderDown(value)
        self.viewer.SetZSlice(value)
        self.iren.Render()

    @QtCore.pyqtSlot()
    def playMovie(self):
        self.ui.dicomSlider.disconnect(self.ui.dicomSlider, QtCore.SIGNAL("valueChanged(int)"), self.sliderMoved)
        self.viewer.SetZSlice(0)
        self.obj = Waiter()
        self.obj.trigger.connect(self.movieStep)
        self.obj.ended.connect(self.movieEnded)
        thr = ThreadWait(self.obj, self.ui.dicomSlider.maximum())
        self.queue.put((self.processThread.playMovie, thr, ))

    @QtCore.pyqtSlot()
    def movieEnded(self):
        self.ui.dicomSlider.connect(self.ui.dicomSlider, QtCore.SIGNAL("valueChanged(int)"), self.sliderMoved)

    def enableSlider(self, max):
        self.disableSlider()
        self.ui.playButton.setEnabled(True)
        self.ui.dicomSlider.setTracking(True)
        self.ui.dicomSlider.setEnabled(True)
        self.ui.dicomSlider.setValue(0)
        self.ui.dicomSlider.setMinimum(0)
        self.ui.dicomSlider.setMaximum(max)
        self.ui.dicomSlider.connect(self.ui.dicomSlider, QtCore.SIGNAL("valueChanged(int)"), self.sliderMoved)
        self.ui.playButton.connect(self.ui.playButton, QtCore.SIGNAL("clicked()"), self.playMovie)

    def loadFolder(self):
        loader = self.folderLoader
        loader.loadFile()

        if loader.accepted:
            loader.setDir(os.path.dirname(str(loader.selectedFolder)))
            self.dicomReader = vtkgdcm.vtkGDCMImageReader()
            regex = re.compile(r'.+\.dcm')
            files = [x for x in os.listdir(loader.selectedFolder) if re.match(regex, x)]
            self.seriesSize = len(files)
            temp = vtk.vtkStringArray()
            temp.SetNumberOfValues(len(files))
            i = 0
            for file in sorted(files):
                temp.SetValue(i, os.path.join(str(loader.selectedFolder), file))
                i = i + 1
            self.dicomReader.SetFileNames(temp)
            self.dicomReader.Update()

            imageData = self.dicomReader.GetOutput()
            size = imageData.GetDimensions()
            width = size[0]
            height = size[1]
            self.vtkWidget.setMaximumSize(QtCore.QSize(width, height))
            self.vtkWidget.setMinimumSize(QtCore.QSize(width, height))
            self.viewer.SetInputConnection(self.dicomReader.GetOutputPort())
            self.iren.ReInitialize()

            self.getMedicalData()

            self.enableSlider(self.seriesSize-1)
            self.ui.dicomSlider.setFocus()

    def undo(self):
        print("Undo")
    def redo(self):
        print("Redo")
    def magnify(self):
        print("Magnify")
    def cut(self):
        print("Cut")
    def measure(self):
        self.measuring = not self.measuring
Exemple #37
0
    def setup_ui(self, main_window):

        exitAction = QtGui.QAction(
            QtGui.QIcon('exit.png'), 'E&xit', main_window)
        exitAction.setShortcut('Ctrl+Q')
        exitAction.setStatusTip('Exit Application')
        exitAction.triggered.connect(main_window.close)

        # Menu
        self.menubar = QtGui.QMenuBar(main_window)
        self.menubar.setNativeMenuBar(False)
        self.file_menu = self.menubar.addMenu('&File')
        self.file_menu.addAction(exitAction)
        main_window.setMenuBar(self.menubar)

        # Status Bar
        self.statusbar = QtGui.QStatusBar(main_window)
        self.statusbar.showMessage('Ready')
        main_window.setStatusBar(self.statusbar)

        main_window.setObjectName('Main Window')
        main_window.resize(640, 480)

        self.central_widget = QtGui.QWidget(main_window)
        self.gridlayout = QtGui.QGridLayout(self.central_widget)
        self.gridlayout.setSpacing(5)

        # Widgets
        self.vtk_widget = QVTKRenderWindowInteractor(self.central_widget)
        self.vtk_widget.setStatusTip('VTK Rendering Pane')

        # QGroupBox with 2 Buttons. For file/folder open
        self.open_gbox = QtGui.QGroupBox('Open Image')
        self.open_folder_radio = QtGui.QRadioButton('Folder')
        self.open_folder_radio.setCheckable(True)
        self.open_folder_radio.setStatusTip('Open DICOM folder')
        self.open_file_radio = QtGui.QRadioButton('File')
        self.open_file_radio.setCheckable(True)
        self.open_file_radio.setStatusTip('Open single medical image')
        # hbox: Horizontal Box
        self.open_hboxlayout = QtGui.QHBoxLayout(self.open_gbox)
        self.open_hboxlayout.setSpacing(3)
        self.open_hboxlayout.addWidget(self.open_folder_radio)
        self.open_hboxlayout.addWidget(self.open_file_radio)

        # For 3 vtkImagePlaneWidget
        self.plane_gbox = QtGui.QGroupBox()
        # self.plane_gbox.setStyleSheet("QGroupBox {border: 0, solid;\
        #                                           }")
        self.plane_x_cbox = QtGui.QCheckBox('X')  # x-plane
        self.plane_y_cbox = QtGui.QCheckBox('Y')
        self.plane_z_cbox = QtGui.QCheckBox('Z')
        self.plane_hboxlayout = QtGui.QHBoxLayout(self.plane_gbox)
        # self.plane_hboxlayout.setSpacing(3)
        # self.plane_hboxlayout.addStretch(1)
        self.plane_hboxlayout.addWidget(self.plane_x_cbox)
        self.plane_hboxlayout.addWidget(self.plane_y_cbox)
        self.plane_hboxlayout.addWidget(self.plane_z_cbox)

        # QGroupBox with 3 QCheckBox. For rendering
        self.render_gbox = QtGui.QGroupBox('Rendering')  # gbox: Group Box
        self.vol_cbox = QtGui.QCheckBox('Volume')  # cbox: Check Box
        self.iso_cbox = QtGui.QCheckBox('Isosurface')
        self.plane_cbox = QtGui.QCheckBox('Planes')
        # vbox: Vertical Box
        self.render_vboxlayout = QtGui.QVBoxLayout(self.render_gbox)
        self.render_vboxlayout.addWidget(self.vol_cbox)
        self.render_vboxlayout.addWidget(self.iso_cbox)
        self.render_vboxlayout.addWidget(self.plane_cbox)
        # self.render_vboxlayout.addWidget(self.plane_gbox)

        # Reset Camera Button
        self.reset_camera_btn = QtGui.QPushButton('Reset Camera')

        # Layout of widgets
        self.gridlayout.addWidget(self.vtk_widget, 2, 0, 10, 1)
        self.gridlayout.addWidget(self.open_gbox, 2, 1)
        self.gridlayout.addWidget(self.render_gbox, 3, 1)

        self.gridlayout.addWidget(self.reset_camera_btn, 9, 1)

        # TEST
        self.test_btn = QtGui.QPushButton('Test Button')
        self.gridlayout.addWidget(self.test_btn, 10, 1)
        self.test_spin = QtGui.QSpinBox()
        self.gridlayout.addWidget(self.test_spin, 11, 1)

        main_window.setCentralWidget(self.central_widget)
class ExodusResultRenderWidget(QtGui.QWidget):
  def __init__(self, input_file_widget, execution_widget, qt_app, application):
    QtGui.QWidget.__init__(self)
    self.input_file_widget = input_file_widget
    self.qt_app = qt_app
    self.application = application

    self.plane = vtk.vtkPlane()
    self.plane.SetOrigin(-1000, 0, 0)
    self.plane.SetNormal(1, 0, 0)

    self.exodus_result = None

    # The multiple (from adaptivity)
    self.exodus_results = []

    self.timestep_to_exodus_result = {}

    self.file_name = None

    self.setupLuts()

    # The multiple (from adaptivity) file names we know of
    self.file_names = []

    self.current_max_timestep = 0

    # Whether or not there is new data to read
    self.new_stuff_to_read = False

    self.timer = QtCore.QTimer()
    self.timer.stop()
    self.timer.setInterval(100)
    self.timer.timeout.connect(self._updateData)

    self.execution_widget = execution_widget
    self.execution_widget.run_started.connect(self._runStarted)
    self.execution_widget.run_stopped.connect(self._runStopped)
    self.execution_widget.timestep_begin.connect(self._timestepBegin)
    self.execution_widget.timestep_end.connect(self._timestepEnd)

    self.main_layout = QtGui.QHBoxLayout()
#    self.main_layout.setSpacing(0)

    self.right_layout = QtGui.QVBoxLayout()

    self.left_layout = QtGui.QVBoxLayout()
    self.left_widget = QtGui.QWidget()
    self.left_widget.setMaximumWidth(1)

    self.left_widget.setLayout(self.left_layout)
    self.left_layout.setSizeConstraint(QtGui.QLayout.SetMinimumSize)

    self.main_layout.addWidget(self.left_widget)
    self.right_layout.setStretchFactor(self.left_layout, 0.01)
    self.main_layout.addLayout(self.right_layout)

#    self.setMinimumWidth(700)
    self.setLayout(self.main_layout)

    self.vtkwidget = QVTKRenderWindowInteractor(self)
#    self.vtkwidget.setMinimumHeight(300)

    # Create background, default to the gradient look
    self.renderer = vtk.vtkRenderer()
    self._showBlackBackgroundChanged(0)
    self.renderer.ResetCamera()

    self.right_layout.addWidget(self.vtkwidget)
    self.right_layout.setStretchFactor(self.vtkwidget, 100)

    self.vtkwidget.show()

    self.vtkwidget.GetRenderWindow().AddRenderer(self.renderer)
    self.vtkwidget.GetRenderWindow().GetInteractor().SetInteractorStyle(vtk.vtkInteractorStyleTrackballCamera())
    self.vtkwidget.Initialize()
    self.vtkwidget.Start()

    self.first = True

    self.exodus_result = None

    self.has_displacements = False
    self.current_displacement_magnitude = 1.0

    self.current_scale_x_magnitude = 1.0
    self.current_scale_y_magnitude = 1.0
    self.current_scale_z_magnitude = 1.0

    self.current_variable = None
    self.current_component = None

    # Holds a mapping of variable name to contour choices so they can be restored when variables are selected
    self.contour_choices = {}

    # If we are currently restoring contours then don't save the intermediate ones
    self.currently_restoring_contours = False
    self.setupControls()

    self.modifyUI()

  ''' This will be called after the interface is completely setup to allow an application to modify this tab '''
  def modifyUI(self):
    pass

  ''' Return the name to use for this tab '''
  def name(self):
    return 'Visualize'

  def setupControls(self):
    self.controls_widget = QtGui.QWidget()
    self.controls_layout = QtGui.QVBoxLayout()

    self.bottom_controls_layout = QtGui.QHBoxLayout()

    self.left_layout.addLayout(self.controls_layout)
    self.main_layout.setStretchFactor(self.left_layout, 0.1)

#    self.main_layout.addLayout(self.bottom_controls_layout)

    self.leftest_controls_layout = QtGui.QVBoxLayout()
    self.left_controls_layout = QtGui.QVBoxLayout()
    self.right_controls_layout = QtGui.QVBoxLayout()

    self.block_view_group_box = QtGui.QGroupBox('Show Blocks')
#    self.block_view_group_box.setMaximumWidth(200)
#    self.block_view_group_box.setMaximumHeight(200)

    self.block_view_layout = QtGui.QVBoxLayout()
    self.block_view_list = QtGui.QListView()
    self.block_view_model = QtGui.QStandardItemModel()
    self.block_view_model.itemChanged.connect(self._blockViewItemChanged)
    self.block_view_list.setModel(self.block_view_model)
    self.block_view_layout.addWidget(self.block_view_list)

    self.block_view_group_box.setLayout(self.block_view_layout)

    self.leftest_controls_layout.addWidget(self.block_view_group_box)

    self.controls_layout.addLayout(self.leftest_controls_layout)
    self.controls_layout.addLayout(self.left_controls_layout)
    self.controls_layout.addLayout(self.right_controls_layout)

    self.controls_layout.setStretchFactor(self.leftest_controls_layout,1.0)
    self.controls_layout.setStretchFactor(self.left_controls_layout,1.5)
    self.controls_layout.setStretchFactor(self.right_controls_layout,4.0)

    self.automatic_update_checkbox = QtGui.QCheckBox("Automatically Update")
    self.automatic_update_checkbox.setToolTip('Toggle automattically reading new timesteps as they finish computing')
    self.automatic_update_checkbox.setCheckState(QtCore.Qt.Checked)
    self.automatically_update = True
    self.automatic_update_checkbox.stateChanged[int].connect(self._automaticUpdateChanged)
#    self.left_controls_layout.addWidget(self.automatic_update_checkbox)

    # Create Group for viewer controls

    # Create the View Mesh toggle
    self.toggle_groupbox = QtGui.QGroupBox("View")
    self.toggle_groupbox.setMaximumHeight(70)
    self.toggle_layout = QtGui.QHBoxLayout()
    self.toggle_groupbox.setMaximumHeight(70)
    self.draw_edges_checkbox = QtGui.QCheckBox("View Mesh")
    self.draw_edges_checkbox.setToolTip('Show mesh elements')
    self.draw_edges_checkbox.stateChanged[int].connect(self._drawEdgesChanged)
    self.toggle_layout.addWidget(self.draw_edges_checkbox, alignment=QtCore.Qt.AlignHCenter)

    # Add a button for toggling the scalebar legend
    self.hide_scalebar_checkbox = QtGui.QCheckBox("Scalebar")
    self.hide_scalebar_checkbox.setToolTip('Toggle visibility of colorbar')
    self.hide_scalebar_checkbox.setCheckState(QtCore.Qt.Checked)
    self.hide_scalebar_checkbox.stateChanged[int].connect(self._hideScalebarChanged)
    self.toggle_layout.addWidget(self.hide_scalebar_checkbox, alignment=QtCore.Qt.AlignHCenter)

    # Add a button for toggling background to black
    self.show_black_background_checkbox = QtGui.QCheckBox("Black")
    self.show_black_background_checkbox.setToolTip('Toggle a black/gradient background')
    self.show_black_background_checkbox.stateChanged[int].connect(self._showBlackBackgroundChanged)
    self.toggle_layout.addWidget(self.show_black_background_checkbox, alignment=QtCore.Qt.AlignHCenter)

    # Create a vertical layout and add the toggles
    self.toggle_groupbox.setLayout(self.toggle_layout)
    self.reset_layout = QtGui.QVBoxLayout()
    self.reset_layout.addWidget(self.toggle_groupbox)

    self.displace_groupbox = QtGui.QGroupBox("Displace")
    self.displace_groupbox.setCheckable(True)
    self.displace_groupbox.setChecked(True)
    self.displace_groupbox.setDisabled(True)
    self.displace_groupbox.setMaximumHeight(70)
    self.displace_groupbox.toggled[bool].connect(self._displaceToggled)
    self.displace_layout = QtGui.QHBoxLayout()
    self.displace_layout.setSpacing(0)
    self.displace_groupbox.setLayout(self.displace_layout)

    self.displace_magnitude_label = QtGui.QLabel("Multiplier: ")
    self.displace_magnitude_text = QtGui.QLineEdit("1.0")
    self.displace_magnitude_text.setMaximumWidth(50)
    self.displace_magnitude_text.setMinimumWidth(10)
    self.displace_magnitude_text.returnPressed.connect(self._displaceMagnitudeTextReturn)

    self.displace_layout.addWidget(self.displace_magnitude_label, alignment=QtCore.Qt.AlignRight)
    self.displace_layout.addWidget(self.displace_magnitude_text, alignment=QtCore.Qt.AlignLeft)

    self.reset_layout.addWidget(self.displace_groupbox)

    self.scale_groupbox = QtGui.QGroupBox("Scale")
    self.scale_groupbox.setCheckable(True)
    self.scale_groupbox.setChecked(False)
    self.scale_groupbox.setDisabled(False)
    self.scale_groupbox.setMaximumHeight(70)
    self.scale_groupbox.toggled[bool].connect(self._scaleToggled)
    self.scale_layout = QtGui.QHBoxLayout()
    self.scale_layout.setSpacing(0)
    self.scale_groupbox.setLayout(self.scale_layout)

    self.scale_x_label = QtGui.QLabel("x: ")
    self.scale_x_text = QtGui.QLineEdit("1.0")
    self.scale_x_text.setMinimumWidth(10)
    self.scale_x_text.setMaximumWidth(50)

    self.scale_y_label = QtGui.QLabel("y: ")
    self.scale_y_text = QtGui.QLineEdit("1.0")
    self.scale_y_text.setMinimumWidth(10)
    self.scale_y_text.setMaximumWidth(50)

    self.scale_z_label = QtGui.QLabel("z: ")
    self.scale_z_text = QtGui.QLineEdit("1.0")
    self.scale_z_text.setMinimumWidth(10)
    self.scale_z_text.setMaximumWidth(50)

    self.scale_x_text.returnPressed.connect(self._scaleMagnitudeTextReturn)
    self.scale_y_text.returnPressed.connect(self._scaleMagnitudeTextReturn)
    self.scale_z_text.returnPressed.connect(self._scaleMagnitudeTextReturn)

    self.scale_layout.addWidget(self.scale_x_label, alignment=QtCore.Qt.AlignRight)
    self.scale_layout.addWidget(self.scale_x_text, alignment=QtCore.Qt.AlignLeft)

    self.scale_layout.addWidget(self.scale_y_label, alignment=QtCore.Qt.AlignRight)
    self.scale_layout.addWidget(self.scale_y_text, alignment=QtCore.Qt.AlignLeft)

    self.scale_layout.addWidget(self.scale_z_label, alignment=QtCore.Qt.AlignRight)
    self.scale_layout.addWidget(self.scale_z_text, alignment=QtCore.Qt.AlignLeft)

    self.reset_layout.addWidget(self.scale_groupbox)

    self.clip_groupbox = QtGui.QGroupBox("Clip")
    self.clip_groupbox.setToolTip('Toggle clipping mode where the solution can be sliced open')
    self.clip_groupbox.setCheckable(True)
    self.clip_groupbox.setChecked(False)
    self.clip_groupbox.setMaximumHeight(70)
    self.clip_groupbox.toggled[bool].connect(self._clippingToggled)
    clip_layout = QtGui.QHBoxLayout()

    self.clip_plane_combobox = QtGui.QComboBox()
    self.clip_plane_combobox.setToolTip('Direction of the normal for the clip plane')
    self.clip_plane_combobox.addItem('x')
    self.clip_plane_combobox.addItem('y')
    self.clip_plane_combobox.addItem('z')
    self.clip_plane_combobox.currentIndexChanged[str].connect(self._clipNormalChanged)

    clip_layout.addWidget(self.clip_plane_combobox)

    self.clip_plane_slider = QtGui.QSlider(QtCore.Qt.Horizontal)
    self.clip_plane_slider.setToolTip('Slide to change plane position')
    self.clip_plane_slider.setRange(0, 100)
    self.clip_plane_slider.setSliderPosition(50)
    self.clip_plane_slider.sliderReleased.connect(self._clipSliderReleased)
    self.clip_plane_slider.sliderMoved[int].connect(self._clipSliderMoved)
    clip_layout.addWidget(self.clip_plane_slider)
#     vbox->addStretch(1);
    self.clip_groupbox.setLayout(clip_layout)

    self.reset_layout.addWidget(self.clip_groupbox)



    self.view_layout = QtGui.QHBoxLayout()

    self.open_button = QtGui.QPushButton('Open')
    self.open_button.setMaximumWidth(100)
    self.open_button.setToolTip('Open an existing result')
    self.open_button.clicked.connect(self._clickedOpen)
    self.view_layout.addWidget(self.open_button, alignment=QtCore.Qt.AlignHCenter)

    self.save_button = QtGui.QPushButton('Save')
    self.save_button.setMaximumWidth(100)
    self.save_button.setToolTip('Save the current view to a file')
    self.save_button.clicked.connect(self._saveView)
    self.view_layout.addWidget(self.save_button, alignment=QtCore.Qt.AlignHCenter)

    self.reset_button = QtGui.QPushButton('Reset')
    self.reset_button.setMaximumWidth(100)
    self.reset_button.setToolTip('Recenter the camera on the current result')
    self.reset_button.clicked.connect(self._resetView)
    self.view_layout.addWidget(self.reset_button, alignment=QtCore.Qt.AlignHCenter)

    self.reset_layout.addLayout(self.view_layout)

    self.right_controls_layout.addLayout(self.reset_layout)


    self.contour_groupbox = QtGui.QGroupBox("Contour")
#    self.contour_groupbox.setMaximumHeight(10)
#    self.contour_groupbox.setMaximumHeight(70)
#    contour_groupbox_policy = QtGui.QSizePolicy()
    self.contour_groupbox.setSizePolicy(QtGui.QSizePolicy.Fixed,QtGui.QSizePolicy.Fixed)
    self.contour_layout = QtGui.QVBoxLayout()
    self.contour_groupbox.setLayout(self.contour_layout)

    self.variable_contour_layout = QtGui.QHBoxLayout()
    self.contour_layout.addLayout(self.variable_contour_layout)
    self.contour_label = QtGui.QLabel("Contour:")
    self.variable_contour = QtGui.QComboBox()
    self.variable_contour_is_nodal = {}
    self.variable_contour.setToolTip('Which variable to color by')
    self.variable_contour.currentIndexChanged[int].connect(self._contourVariableSelected)
#    self.variable_contour_layout.addWidget(self.contour_label, alignment=QtCore.Qt.AlignRight)
    self.variable_contour_layout.addWidget(self.variable_contour, alignment=QtCore.Qt.AlignHCenter)

#    self.component_layout = QtGui.QHBoxLayout()
    self.component_label = QtGui.QLabel("Component:")
    self.variable_component = QtGui.QComboBox()
    self.variable_component.setToolTip('If the variable is a vector this selects what component of that vector (or the Magnitude) to color by')
    self.variable_component.currentIndexChanged[str].connect(self._variableComponentSelected)
#    self.component_layout.addWidget(self.component_label, alignment=QtCore.Qt.AlignRight)
#    self.component_layout.addWidget(self.variable_component, alignment=QtCore.Qt.AlignLeft)
#    self.variable_contour_layout.addLayout(self.component_layout)
    self.variable_contour_layout.addWidget(self.variable_component, alignment=QtCore.Qt.AlignHCenter)


    self.minmax_contour_layout = QtGui.QVBoxLayout()
    self.contour_layout.addLayout(self.minmax_contour_layout)

    self.min_groupbox = QtGui.QGroupBox("Min")
    self.min_layout = QtGui.QHBoxLayout()
    self.min_groupbox.setLayout(self.min_layout)

    self.min_radio_layout = QtGui.QVBoxLayout()

    self.min_current_radio = QtGui.QRadioButton('Current')
    self.min_current_radio.setChecked(QtCore.Qt.Checked)
    self.min_current_radio.toggled.connect(self._updateContours)
    self.min_global_radio = QtGui.QRadioButton('Global')
    self.min_global_radio.toggled.connect(self._updateContours)
    self.min_radio_layout.addWidget(self.min_current_radio)
#    self.min_radio_layout.addWidget(self.min_global_radio)

    self.min_custom_layout = QtGui.QHBoxLayout()
    self.min_custom_layout.setSpacing(0)
    self.min_custom_radio = QtGui.QRadioButton()
    self.min_custom_radio.toggled.connect(self._updateContours)
    self.min_custom_text = QtGui.QLineEdit()
    self.min_custom_text.returnPressed.connect(self._updateContours)
    self.min_custom_text.setDisabled(True)
    self.min_custom_text.setMaximumWidth(100)
    self.min_custom_layout.addWidget(self.min_custom_radio, alignment=QtCore.Qt.AlignLeft)
    self.min_custom_layout.addWidget(self.min_custom_text, alignment=QtCore.Qt.AlignLeft)
    self.min_custom_layout.addStretch()

    self.min_layout.addLayout(self.min_radio_layout)
    self.min_layout.addLayout(self.min_custom_layout)

    self.minmax_contour_layout.addWidget(self.min_groupbox)



    self.max_groupbox = QtGui.QGroupBox("Max")
    self.max_layout = QtGui.QHBoxLayout()
    self.max_groupbox.setLayout(self.max_layout)

    self.max_radio_layout = QtGui.QVBoxLayout()

    self.max_current_radio = QtGui.QRadioButton('Current')
    self.max_current_radio.setChecked(QtCore.Qt.Checked)
    self.max_current_radio.toggled.connect(self._updateContours)
    self.max_global_radio = QtGui.QRadioButton('Global')
    self.max_global_radio.toggled.connect(self._updateContours)
    self.max_radio_layout.addWidget(self.max_current_radio)
#    self.max_radio_layout.addWidget(self.max_global_radio)

    self.max_custom_layout = QtGui.QHBoxLayout()
    self.max_custom_layout.setSpacing(0)
    self.max_custom_radio = QtGui.QRadioButton()
    self.max_custom_radio.toggled.connect(self._updateContours)
    self.max_custom_text = QtGui.QLineEdit()
    self.max_custom_text.returnPressed.connect(self._updateContours)
    self.max_custom_text.setDisabled(True)
    self.max_custom_text.setMaximumWidth(100)
    self.max_custom_layout.addWidget(self.max_custom_radio, alignment=QtCore.Qt.AlignLeft)
    self.max_custom_layout.addWidget(self.max_custom_text, alignment=QtCore.Qt.AlignLeft)
    self.max_custom_layout.addStretch()

    self.max_layout.addLayout(self.max_radio_layout)
    self.max_layout.addLayout(self.max_custom_layout)

    self.minmax_contour_layout.addWidget(self.max_groupbox)


#    self.component_layout = QtGui.QHBoxLayout()
    self.color_scheme_label = QtGui.QLabel("Color Scheme:")
    self.color_scheme_component = QtGui.QComboBox()
    self.color_scheme_component.addItem('HSV (Cool to Warm)')
    self.color_scheme_component.addItem('Diverging (Blue to Red)')
    self.color_scheme_component.addItem('Shock')
    self.color_scheme_component.setToolTip('The color scheme used byt the render view')
    self.color_scheme_component.currentIndexChanged[str].connect(self._colorSchemeSelected)

#    self.component_layout.addWidget(self.component_label, alignment=QtCore.Qt.AlignRight)
#    self.component_layout.addWidget(self.variable_component, alignment=QtCore.Qt.AlignLeft)
#    self.variable_contour_layout.addLayout(self.component_layout)

    self.minmax_contour_layout.addWidget(self.color_scheme_component)

    self.left_controls_layout.addWidget(self.contour_groupbox)


    self.beginning_button = QtGui.QToolButton()
    self.beginning_button.setToolTip('Go to first timestep')
    self.beginning_button.setIcon(QtGui.QIcon(pathname + '/resources/from_paraview/pqVcrFirst32.png'))
    self.beginning_button.clicked.connect(self._beginningClicked)

    self.back_button = QtGui.QToolButton()
    self.back_button.setToolTip('Previous timestep')
    self.back_button.setIcon(QtGui.QIcon(pathname + '/resources/from_paraview/pqVcrBack32.png'))
    self.back_button.clicked.connect(self._backClicked)

    self.play_button = QtGui.QToolButton()
    self.play_button.setToolTip('Play through the currently computed timesteps')
    self.play_button.setIcon(QtGui.QIcon(pathname + '/resources/from_paraview/pqVcrPlay32.png'))
    self.play_button.clicked.connect(self._playClicked)

    self.pause_button = QtGui.QToolButton()
    self.pause_button.setToolTip('If playing this will pause playback')
    self.pause_button.setDisabled(True)
    self.pause_button.setIcon(QtGui.QIcon(pathname + '/resources/from_paraview/pqVcrPause32.png'))
    self.pause_button.clicked.connect(self._pauseClicked)

    self.forward_button = QtGui.QToolButton()
    self.forward_button.setToolTip('Next timestep')
    self.forward_button.setIcon(QtGui.QIcon(pathname + '/resources/from_paraview/pqVcrForward32.png'))
    self.forward_button.clicked.connect(self._forwardClicked)

    self.last_button = QtGui.QToolButton()
    self.last_button.setToolTip('Go to last timestep')
    self.last_button.setIcon(QtGui.QIcon(pathname + '/resources/from_paraview/pqVcrLast32.png'))
    self.last_button.clicked.connect(self._lastClicked)

    self.loop_button = QtGui.QToolButton()
    self.loop_button.setToolTip('Toggle replaying all timesteps when the end is reached during playback.  Note that as new timesteps finish they will automatically be picked up and added to the end of the sequence.')
    self.loop_button.setCheckable(True)
    self.loop_button.setIcon(QtGui.QIcon(pathname + '/resources/from_paraview/pqVcrLoop24.png'))
    self.loop_button.toggled.connect(self._loopClicked)

    self.currently_looping = False

    self.time_slider_label = QtGui.QLabel("Timestep:")
    self.time_slider = QtGui.QSlider(QtCore.Qt.Horizontal)
    self.time_slider.setToolTip('Slide to select a timestep to display')
#    self.time_slider.setMaximumWidth(600)

    self.time_slider.valueChanged.connect(self._timeSliderChanged)
    self.time_slider.sliderReleased.connect(self._timeSliderReleased)

    self.time_slider_textbox = QtGui.QLineEdit()
    self.time_slider_textbox.setToolTip('Enter a number and press Enter to go to that timestep')
    self.time_slider_textbox.setMaximumWidth(30)
    self.time_slider_textbox.setMinimumWidth(30)
    self.time_slider_textbox.returnPressed.connect(self._sliderTextboxReturn)

    self.time_groupbox = QtGui.QGroupBox("Time")
    self.time_groupbox.setMaximumHeight(70)

    self.time_layout = QtGui.QHBoxLayout()
    self.time_layout.addWidget(self.beginning_button)
    self.time_layout.addWidget(self.back_button)
    self.time_layout.addWidget(self.play_button)
    self.time_layout.addWidget(self.pause_button)
    self.time_layout.addWidget(self.forward_button)
    self.time_layout.addWidget(self.last_button)
    self.time_layout.addWidget(self.loop_button)
    self.time_layout.addWidget(self.time_slider_label, alignment=QtCore.Qt.AlignRight)
    self.time_layout.addWidget(self.time_slider)
    self.time_layout.addWidget(self.time_slider_textbox, alignment=QtCore.Qt.AlignLeft)

    self.time_groupbox.setLayout(self.time_layout)

    self.right_layout.addWidget(self.time_groupbox)



  def _updateControls(self):
    self.old_contour = self.variable_contour.currentText()
    self.variable_contour.clear()
    self.has_displacements = False
    for variable in self.exodus_result.current_nodal_variables:
      if 'ObjectId' not in variable:
        self.variable_contour.addItem(variable)
        item_num = self.variable_contour.count()-1
        self.variable_contour.setItemIcon(item_num,QtGui.QIcon(pathname + '/resources/from_paraview/pqNodalData16.png'))
        self.variable_contour_is_nodal[item_num] = True
        if 'disp' in variable:
          self.has_displacements = True

    for variable in self.exodus_result.current_elemental_variables:
      if 'ObjectId' not in variable:
        self.variable_contour.addItem(variable)
        item_num = self.variable_contour.count()-1
        self.variable_contour.setItemIcon(item_num,QtGui.QIcon(pathname + '/resources/from_paraview/pqElemData16.png'))
        self.variable_contour_is_nodal[item_num] = False
        if 'disp' in variable:
          self.has_displacements = True

    if self.has_displacements:
      self.displace_groupbox.setDisabled(False)

    self.block_view_model.clear()
    for block in self.exodus_result.blocks:
      block_display_name = str(block)
      if block in self.exodus_result.block_to_name:
        block_display_name += ' : ' + self.exodus_result.block_to_name[block]

      item = QtGui.QStandardItem(str(block_display_name))
      item.exodus_block = block
      item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsUserCheckable)
      item.setCheckState(QtCore.Qt.Checked)
      self.block_view_model.appendRow(item)

    # Try to restore back to the view of the variable we were looking at
    found_index = self.variable_contour.findText(self.old_contour)
    if found_index != -1:
      self.variable_contour.setCurrentIndex(found_index)
    else: # If this variable doesn't exist then we are probably running a new simulation... try to reset the camera
      self._resetView()

    self.time_slider.setMinimum(0)
    self.time_slider.setMaximum(self.current_max_timestep)


  def setupLuts(self):
    self.luts = []

    # HSV (Blue to REd)  Default
    lut = vtk.vtkLookupTable()
    lut.SetHueRange(0.667, 0.0)
    lut.SetNumberOfColors(256)
    lut.Build()
    self.luts.append(lut)

    # Diverging (Cool to Warm) color scheme
    ctf = vtk.vtkColorTransferFunction()
    ctf.SetColorSpaceToDiverging()
    ctf.AddRGBPoint(0.0, 0.230, 0.299, 0.754)
    ctf.AddRGBPoint(1.0, 0.706, 0.016, 0.150)
    cc = list()
    for i in xrange(256):
      cc.append(ctf.GetColor(float(i) / 255.0))
    lut = vtk.vtkLookupTable()
    lut.SetNumberOfColors(256)
    for i, item in enumerate(cc):
      lut.SetTableValue(i, item[0], item[1], item[2], 1.0)
    lut.Build()
    self.luts.append(lut)

    # Shock
    ctf = vtk.vtkColorTransferFunction()
    min = 93698.4
    max = 230532
    ctf.AddRGBPoint(self._normalize(min, max,  93698.4),  0.0,         0.0,      1.0)
    ctf.AddRGBPoint(self._normalize(min, max, 115592.0),  0.0,         0.905882, 1.0)
    ctf.AddRGBPoint(self._normalize(min, max, 138853.0),  0.0941176,   0.733333, 0.027451)
    ctf.AddRGBPoint(self._normalize(min, max, 159378.0),  1.0,         0.913725, 0.00784314)
    ctf.AddRGBPoint(self._normalize(min, max, 181272.0),  1.0,         0.180392, 0.239216)
    ctf.AddRGBPoint(self._normalize(min, max, 203165.0),  1.0,         0.701961, 0.960784)
    ctf.AddRGBPoint(self._normalize(min, max, 230532.0),  1.0,         1.0,      1.0)
    cc = list()
    for i in xrange(256):
      cc.append(ctf.GetColor(float(i) / 255.0))
    lut = vtk.vtkLookupTable()
    lut.SetNumberOfColors(256)
    for i, item in enumerate(cc):
      lut.SetTableValue(i, item[0], item[1], item[2], 1.0)
    lut.Build()
    self.luts.append(lut)

    self.current_lut = self.luts[0]


  def _normalize(self, min, max, value):
    return (value - min) / (max - min)

  def _blockViewItemChanged(self, item):
    if item.checkState() == QtCore.Qt.Checked:
      self.exodus_result.showBlock(item.exodus_block)
      self.exodus_result.reader.Update()
      self.exodus_result.geom.Update()
      self.current_bounds = self.exodus_result.actor.GetBounds()
      self._updateContours()
    else:
      self.exodus_result.hideBlock(item.exodus_block)
      self.exodus_result.reader.Update()
      self.exodus_result.geom.Update()
      self.current_bounds = self.exodus_result.actor.GetBounds()
      self._updateContours()

  def _displaceToggled(self, value):
    self._timeSliderReleased()

  def _scaleToggled(self, value):
    self._timeSliderReleased()

  def _displaceMagnitudeTextReturn(self):
    self.current_displacement_magnitude = float(self.displace_magnitude_text.text())
    self._timeSliderReleased()

  def _scaleMagnitudeTextReturn(self):
    self.current_scale_x_magnitude = float(self.scale_x_text.text())
    self.current_scale_y_magnitude = float(self.scale_y_text.text())
    self.current_scale_z_magnitude = float(self.scale_z_text.text())
    self._timeSliderReleased()

  def _drawEdgesChanged(self, value):
    if value == QtCore.Qt.Checked:
      self.exodus_result.actor.GetProperty().EdgeVisibilityOn()
      self.exodus_result.clip_actor.GetProperty().EdgeVisibilityOn()
    else:
      self.exodus_result.actor.GetProperty().EdgeVisibilityOff()
      self.exodus_result.clip_actor.GetProperty().EdgeVisibilityOff()
    self.vtkwidget.repaint()

  ##
  # A method for toggling visiability of the scale bar legend, it is controlled
  # by the 'Hide Scalebar' toggle on the Visualize tab
  # @param value The interger value from the checkbox (1=checked)
  def _hideScalebarChanged(self, value):

    # Show when checked
    if value == QtCore.Qt.Checked:
      self.exodus_result.scalar_bar.VisibilityOn()

    # Hide when unchecked
    else:
      self.exodus_result.scalar_bar.VisibilityOff()

    # Update the GUI
    self.vtkwidget.repaint()

  ##
  # A method for toggling black background or gradient background, it is controlled
  # by the 'Black Background' toggle on the Visualize tab
  # @param value The interger value from the checkbox (1=checked)
  def _showBlackBackgroundChanged(self, value):

    # Black when checked
    if value == QtCore.Qt.Checked:
      self.renderer.SetBackground(0,0,0)
      self.renderer.SetGradientBackground(0)
      #self.renderer.ResetCamera()

    # Gradient when unchecked
    else:
      self.renderer.SetBackground(0,0,0)
      self.renderer.SetBackground(0.2,0.2,0.2)
      self.renderer.SetBackground2(1,1,1)
      self.renderer.SetGradientBackground(1)
      #self.renderer.ResetCamera()

    # Update thew GUI
    self.vtkwidget.repaint()

  def _fillComponentCombo(self, variable_name, components):
    self.variable_component.clear()
    self.variable_component.addItem('Magnitude')
    num_components = components[variable_name]
    if num_components > 1 and self.exodus_result.current_dim >= 2:
      self.variable_component.setDisabled(False)
      self.variable_component.addItem('X')
      self.variable_component.addItem('Y')
    else:
      self.variable_component.setDisabled(True)

    if num_components > 1 and  self.exodus_result.current_dim == 3:
      self.variable_component.addItem('Z')

  def _contourVariableSelected(self, index):

    value_string = str(self.variable_contour.itemText(index))
    self.current_variable = value_string
    self.current_variable_index = index

    if index in self.variable_contour_is_nodal:
      self.current_variable_is_nodal = self.variable_contour_is_nodal[index]
    else:
      self.current_variable_is_nodal = True

    self.currently_restoring_contours = True

    # Maybe results haven't been written yet...
    if not self.exodus_result.data.GetPointData().GetVectors(value_string) and not self.exodus_result.data.GetCellData().GetVectors(value_string):
      return

    if value_string in self.exodus_result.current_nodal_components:
      self._fillComponentCombo(value_string, self.exodus_result.current_nodal_components)
    elif value_string in self.exodus_result.current_elemental_components:
      self._fillComponentCombo(value_string, self.exodus_result.current_elemental_components)

    if self.current_variable not in self.contour_choices:
      self.contour_choices[self.current_variable] = ContourChoices()

    self.contour_choices[self.current_variable].restore(self)
    self.currently_restoring_contours = False


  def _variableComponentSelected(self, value):
    value_string = str(value)
    self.current_component = value_string
    if value_string == 'Magnitude':
      self.component_index = -1
    elif value_string == 'X':
      self.component_index = 0
    elif value_string == 'Y':
      self.component_index = 1
    elif value_string == 'Z':
      self.component_index = 2

    self._updateContours()

  def _updateContours(self):
    self.exodus_result.setColorScheme(self.current_lut)
    if self.component_index == -1:
      self.exodus_result.lut.SetVectorModeToMagnitude()
    elif self.component_index == 0:
      self.exodus_result.lut.SetVectorModeToComponent()
      self.exodus_result.lut.SetVectorComponent(0)
    elif self.component_index == 1:
      self.exodus_result.lut.SetVectorModeToComponent()
      self.exodus_result.lut.SetVectorComponent(1)
    elif self.component_index == 2:
      self.exodus_result.lut.SetVectorModeToComponent()
      self.exodus_result.lut.SetVectorComponent(2)

    if self.clip_groupbox.isChecked():
      self.exodus_result.clipper.Modified()
      self.exodus_result.clipper.Update()
      self.exodus_result.clip_geom.Update()
      self.exodus_result.clip_mapper.Update()

    data = None
    if self.current_variable_is_nodal and self.current_variable in self.exodus_result.current_nodal_components:
      data = self.exodus_result.data.GetPointData().GetVectors(self.current_variable)
      self.exodus_result.mapper.SetScalarModeToUsePointFieldData()
      self.exodus_result.clip_mapper.SetScalarModeToUsePointFieldData()
    elif self.current_variable in self.exodus_result.current_elemental_components:
      data = self.exodus_result.data.GetCellData().GetVectors(self.current_variable)
      self.exodus_result.mapper.SetScalarModeToUseCellFieldData()
      self.exodus_result.clip_mapper.SetScalarModeToUseCellFieldData()

    self.exodus_result.mapper.SelectColorArray(self.current_variable)
    self.exodus_result.clip_mapper.SelectColorArray(self.current_variable)

    if data:
      self.current_range = data.GetRange(self.component_index)

      if self.min_current_radio.isChecked():
        self.min_custom_text.setText(str(self.current_range[0]))
        self.min_custom_text.setCursorPosition(0)

      if self.max_current_radio.isChecked():
        self.max_custom_text.setText(str(self.current_range[1]))
        self.max_custom_text.setCursorPosition(0)

      if self.min_custom_radio.isChecked():
        self.min_custom_text.setDisabled(False)
      else:
        self.min_custom_text.setDisabled(True)

      if self.max_custom_radio.isChecked():
        self.max_custom_text.setDisabled(False)
      else:
        self.max_custom_text.setDisabled(True)

      min = 0.0
      try:
        min = float(self.min_custom_text.displayText())
      except:
        min = 0.0

      max = 0.0
      try:
        max = float(self.max_custom_text.displayText())
      except:
        max = 0.0

      if self.current_variable not in self.contour_choices:
        self.contour_choices[self.current_variable] = ContourChoices()

      if not self.currently_restoring_contours:
        self.contour_choices[self.current_variable].save(self)

      the_range = (min, max)

      if min <= max:
        self.exodus_result.mapper.SetScalarRange(the_range)
        self.exodus_result.clip_mapper.SetScalarRange(the_range)


    self.exodus_result.scalar_bar.SetTitle(self.current_variable)
    self.renderer.AddActor2D(self.exodus_result.scalar_bar)
    self.vtkwidget.repaint()

  def _colorSchemeSelected(self, value):
    self.current_lut = self.luts[self.color_scheme_component.currentIndex()]
    self._updateContours()

  def _openFile(self, file_name):
    self._clear()

    self.base_stamp = os.path.getmtime(file_name)
    self.file_name = str(file_name)

    self.new_stuff_to_read = True
    self._updateData()
    self._updateData() # Call it again to read any adaptive results

    self._lastClicked() # Go to the last timestep

    self._resetView() # Reset the camera

  def _clickedOpen(self):
    file_name = QtGui.QFileDialog.getOpenFileName(self, "Open Result", "~/", "Input Files (*.e)")

    if file_name:
      self._openFile(file_name)

  def _resetView(self):
    self.renderer.ResetCamera()
    fp = self.renderer.GetActiveCamera().GetFocalPoint()
    p = self.renderer.GetActiveCamera().GetPosition()
    dist = math.sqrt( (p[0]-fp[0])**2 + (p[1]-fp[1])**2 + (p[2]-fp[2])**2 )
    self.renderer.GetActiveCamera().SetPosition(fp[0], fp[1], fp[2]+dist)
    self.renderer.GetActiveCamera().SetViewUp(0.0, 1.0, 0.0)
    self.vtkwidget.repaint()

  def _saveView(self):
    file_name = QtGui.QFileDialog.getSaveFileName(self, "Image File Name", "~/", "Image Files (*.png)")

    if file_name != '':
      w2i = vtk.vtkWindowToImageFilter()
      writer = vtk.vtkPNGWriter()
      w2i.SetInput(self.vtkwidget.GetRenderWindow())
      w2i.Update()
      writer.SetInputConnection(w2i.GetOutputPort())
      writer.SetFileName(str(file_name))
      self.vtkwidget.GetRenderWindow().Render()
      writer.Write()

  def _automaticUpdateChanged(self, value):
    if value == QtCore.Qt.Checked:
      self.automatically_update = True
    else:
      self.automatically_update = False

  def _beginningClicked(self):
    self.time_slider.setSliderPosition(0)
    self._timeSliderReleased()

  def _backClicked(self):
    self.time_slider.setSliderPosition(self.time_slider.sliderPosition()-1)
    self._timeSliderReleased()

  def _playClicked(self):
    self.play_button.setDisabled(True)
    self.pause_button.setDisabled(False)
    self.currently_playing = True

    first = True
    while((first or self.currently_looping) and self.currently_playing):
      first = False

      # If the slider is at the end then start over
      self.qt_app.processEvents()
      time.sleep(0.02)
      self.qt_app.processEvents()
      if self.time_slider.sliderPosition() == self.time_slider.maximum():
        self.time_slider.setSliderPosition(0)

      while self.time_slider.sliderPosition() < self.time_slider.maximum():
        self.time_slider.setSliderPosition(self.time_slider.sliderPosition()+1)
        self.qt_app.processEvents()
        self._timeSliderReleased()
        time.sleep(0.02)
        self.qt_app.processEvents()
        if not self.currently_playing:
          break

    self.play_button.setDisabled(False)
    self.pause_button.setDisabled(True)

  def _pauseClicked(self):
    self.play_button.setDisabled(False)
    self.pause_button.setDisabled(True)
    self.currently_playing = False

  def _forwardClicked(self):
    self.time_slider.setSliderPosition(self.time_slider.sliderPosition()+1)
    self._timeSliderReleased()

  def _lastClicked(self):
    self.time_slider.setSliderPosition(self.time_slider.maximum())
    self._timeSliderReleased()

  def _loopClicked(self, state):
    if state:
      self.currently_looping = True
    else:
      self.currently_looping = False

  def _timeSliderChanged(self):
    self.time_slider_textbox.setText(str(self.time_slider.sliderPosition()))

  def _timeSliderReleased(self):
    textbox_string = self.time_slider_textbox.text()
    if textbox_string == '':
      textbox_string = str(self.exodus_result.min_timestep)

    if int(textbox_string) in self.timestep_to_exodus_result:
      for actor in self.exodus_result.current_actors:
        self.renderer.RemoveActor(actor)
      self.exodus_result = self.timestep_to_exodus_result[int(textbox_string)]

      if self.clip_groupbox.isChecked():
        self.renderer.AddActor(self.exodus_result.clip_actor)
        if self.draw_edges_checkbox.checkState() == QtCore.Qt.Checked:
          self.exodus_result.clip_actor.GetProperty().EdgeVisibilityOn()
        else:
          self.exodus_result.clip_actor.GetProperty().EdgeVisibilityOff()
      else:
        self.renderer.AddActor(self.exodus_result.actor)
        if self.draw_edges_checkbox.checkState() == QtCore.Qt.Checked:
          self.exodus_result.actor.GetProperty().EdgeVisibilityOn()
        else:
          self.exodus_result.actor.GetProperty().EdgeVisibilityOff()

      num_block_view_items = self.block_view_model.rowCount()
      for i in xrange(num_block_view_items):
        item = self.block_view_model.item(i)
        if item.checkState() == QtCore.Qt.Checked:
          self.exodus_result.showBlock(item.exodus_block)
        else:
          self.exodus_result.hideBlock(item.exodus_block)

      if self.has_displacements and self.displace_groupbox.isChecked():
        self.exodus_result.reader.SetApplyDisplacements(1)
        self.exodus_result.reader.SetDisplacementMagnitude(float(self.current_displacement_magnitude))
      else:
        self.exodus_result.reader.SetApplyDisplacements(0)

      if self.scale_groupbox.isChecked():
        self.exodus_result.actor.SetScale(self.current_scale_x_magnitude, self.current_scale_y_magnitude, self.current_scale_z_magnitude)
      else:
        self.exodus_result.actor.SetScale(1.0, 1.0, 1.0)

    if self.exodus_result.reader:
      self.exodus_result.reader.SetTimeStep(self.timestep_to_timestep[int(textbox_string)])
      self.exodus_result.reader.Update()
      self.exodus_result.geom.Update()
      self.current_bounds = self.exodus_result.actor.GetBounds()
      self._updateContours()

  def _sliderTextboxReturn(self):
    self.time_slider.setSliderPosition(int(self.time_slider_textbox.text()))
    self._timeSliderReleased()

  def _associateResultsWithTimesteps(self):
    self.timestep_to_exodus_result = {}
    self.timestep_to_timestep = {}
    self.current_max_timestep = -1
    for result in self.exodus_results:
      result.reader.UpdateTimeInformation()
      min = result.reader.GetTimeStepRange()[0]
      max = result.reader.GetTimeStepRange()[1]
      for timestep in xrange(min, max+1):
        self.current_max_timestep += 1
        self.timestep_to_exodus_result[self.current_max_timestep] = result
        self.timestep_to_timestep[self.current_max_timestep] = timestep

  def _updateData(self):
    # Check to see if there are new exodus files with adapted timesteps in them.
    if self.file_name and self.exodus_result:
      for file_name in sorted(glob.glob(self.file_name + '-s*')):
        file_stamp = os.path.getmtime(file_name)
        if int(file_stamp) >= int(self.base_stamp) and int(file_stamp) <= int(time.time() - 1) and file_name not in self.file_names:
          self.file_names.append(file_name)
          exodus_result = ExodusResult(self, self.plane)
          exodus_result.setFileName(file_name, self.current_lut)
          self.exodus_results.append(exodus_result)
          self.new_stuff_to_read = True

    if not self.exodus_result:
      if not self.file_name: # Might have been set by opening a file
        output_file_names = self.input_file_widget.getOutputFileNames()
      else:
        output_file_names = [self.file_name]

      output_file = ''

      for file_name in output_file_names:
        if '.e' in file_name and os.path.exists(file_name):
          file_stamp = os.path.getmtime(file_name)

          if int(file_stamp) >= int(self.base_stamp) and int(file_stamp) <= int(time.time() - 1) and file_name not in self.file_names:
            self.file_name = file_name
            self.exodus_result = ExodusResult(self, self.plane)
            self.exodus_result.setFileName(file_name, self.current_lut)
            self.exodus_results.append(self.exodus_result)
            self.current_max_timestep = self.exodus_result.max_timestep
            self.renderer.AddActor(self.exodus_result.actor)
            self._drawEdgesChanged(self.draw_edges_checkbox.checkState())

            if self.first:
              self.first = False
              self.renderer.ResetCamera()

            # Avoid z-buffer fighting
            vtk.vtkPolyDataMapper().SetResolveCoincidentTopologyToPolygonOffset()

            if self.clip_groupbox.isChecked():
              _clippingToggled(True)

            self.vtkwidget.repaint()
            self._updateControls()
            self.time_slider.setSliderPosition(self.current_max_timestep)

    if self.new_stuff_to_read and self.exodus_result and self.automatically_update:
      self._associateResultsWithTimesteps()
#      self.exodus_result.reader.UpdateTimeInformation()
#      range = self.exodus_result.reader.GetTimeStepRange()
#      self.exodus_result.min_timestep = range[0]
#      self.exodus_result.max_timestep = range[1]
      self.time_slider.setMinimum(0)

      # Only automatically move forward if they're on the current step
      if self.time_slider.sliderPosition() == self.time_slider.maximum():
        self.time_slider.setMaximum(self.current_max_timestep)
        self.time_slider.setSliderPosition(self.current_max_timestep)
        self._timeSliderReleased()
        if self.clip_groupbox.isChecked():
          self._clipSliderReleased()
        self.vtkwidget.repaint()
      else:
        self.time_slider.setMaximum(self.current_max_timestep)

    self.new_stuff_to_read = False

  def _timestepBegin(self):
    self.new_stuff_to_read = True

  def _timestepEnd(self):
    pass


  def _clear(self):
    self.application.addExodusResultActors(self.renderer)
    self.file_name = None
    self.file_names = []

    if not self.exodus_result:
      return

    for actor in self.exodus_result.current_actors:
      self.renderer.RemoveActor(actor)

    del self.exodus_result.current_actors[:]

    self.exodus_result = None
    self.exodus_results = []
    self.timestep_to_exodus_result = {}

  def _runStarted(self):
    # Set the base time
    self.base_stamp = time.time()
    self._clear()
    self.timer.start()

  def _finalRead(self):
    self.new_stuff_to_read = True # Set this to true so we get one more update
    # Do it twice in case of adapted results
    self._updateData()
    self._updateData()

  def _runStopped(self):
    self.timer.stop()
    self.run_stopped_timer = QtCore.QTimer()
    self.run_stopped_timer.setInterval(1000) # Wait a second before updating the plots one last time
    self.run_stopped_timer.setSingleShot(True)
    self.run_stopped_timer.timeout.connect(self._finalRead)
    self.run_stopped_timer.start()

  def _clippingToggled(self, value):
    if value:
      self.renderer.RemoveActor(self.exodus_result.current_actor)
      self.renderer.AddActor(self.exodus_result.clip_actor)
      self.exodus_result.current_actor = self.exodus_result.clip_actor
      self.clip_plane_slider.setSliderPosition(50)
      self._clipSliderMoved(50)
      self._clipSliderReleased()
    else:
      self.renderer.RemoveActor(self.exodus_result.current_actor)
      self.renderer.AddActor(self.exodus_result.actor)
      self.exodus_result.current_actor = self.exodus_result.actor

    self.vtkwidget.repaint()

  def _clipNormalChanged(self, value):
    self.plane.SetOrigin(self.current_bounds[0],
                         self.current_bounds[2],
                         self.current_bounds[4])
    if value == 'x':
      self.plane.SetNormal(1, 0, 0)
    elif value == 'y':
      self.plane.SetNormal(0, 1, 0)
    else:
      self.plane.SetNormal(0, 0, 1)

    self.clip_plane_slider.setSliderPosition(50)
    self._clipSliderMoved(50)

    self.vtkwidget.repaint()

  def _clipSliderReleased(self):
    self._updateContours()
    self.vtkwidget.repaint()

  def _clipSliderMoved(self, value):
    direction = str(self.clip_plane_combobox.currentText())

    min = 0
    max = 0

    if direction == 'x':
      min = self.current_bounds[0]
      max = self.current_bounds[1]
    elif direction == 'y':
      min = self.current_bounds[2]
      max = self.current_bounds[3]
    elif direction == 'z':
      min = self.current_bounds[4]
      max = self.current_bounds[5]

    step_size = (max - min)/100.0
    steps = value
    distance = float(steps)*step_size
    position = min + distance

    old = self.plane.GetOrigin()
    self.plane.SetOrigin(position if direction == 'x' else old[0],
                         position if direction == 'y' else old[1],
                         position if direction == 'z' else old[2])

    self._updateContours()
    self.vtkwidget.repaint()
Exemple #39
0
class Ui_MainWindow(QtGui.QMainWindow):
    def __init__(self):
		QtGui.QMainWindow.__init__(self)
		self.setupUi(self)

    def setupUi(self, MainWindow):
        MainWindow.setObjectName(_fromUtf8("MainWindow"))
        MainWindow.resize(912, 640)
        #centralWidget
        self.centralWidget = QtGui.QWidget(MainWindow)
        self.centralWidget.setObjectName(_fromUtf8("centralWidget"))

        self.m_label = QtGui.QLabel(self.centralWidget)
        self.m_label.setGeometry(QtCore.QRect(750, 70, 91, 17))
        self.m_label.setObjectName(_fromUtf8("m_label"))
        self.m_pushButton = QtGui.QPushButton(self.centralWidget)
        self.m_pushButton.setGeometry(QtCore.QRect(740, 110, 99, 27))
        self.m_pushButton.setObjectName(_fromUtf8("m_pushButton"))

        #vtkWidget
        self.m_widget = QVTKRenderWindowInteractor(self.centralWidget)
        self.m_widget.setGeometry(QtCore.QRect(60, 60, 591, 501))
        self.m_widget.setObjectName(_fromUtf8("m_widget"))
        self.setvtkWidget()

        MainWindow.setCentralWidget(self.centralWidget)

        #menuBar
        self.menuBar = QtGui.QMenuBar(MainWindow)
        self.menuBar.setGeometry(QtCore.QRect(0, 0, 912, 25))
        self.menuBar.setObjectName(_fromUtf8("menuBar"))
        MainWindow.setMenuBar(self.menuBar)

        #toolBar
        self.mainToolBar = QtGui.QToolBar(MainWindow)
        self.mainToolBar.setObjectName(_fromUtf8("mainToolBar"))
        MainWindow.addToolBar(QtCore.Qt.TopToolBarArea, self.mainToolBar)

        #statusBar
        self.statusBar = QtGui.QStatusBar(MainWindow)
        self.statusBar.setObjectName(_fromUtf8("statusBar"))
        MainWindow.setStatusBar(self.statusBar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
        self.m_label.setText(_translate("MainWindow", "Hello world", None))
        self.m_pushButton.setText(_translate("MainWindow", "Say Hi!", None))

    def setvtkWidget(self):
    	self.ren = vtk.vtkRenderer()
        self.m_widget.GetRenderWindow().AddRenderer(self.ren)
        self.iren = self.m_widget.GetRenderWindow().GetInteractor()
 
        # The car model (includes a plate, two poles and four wheel)
        # Plate of the car
        # Create source
        plate = vtk.vtkCubeSource()
        plate.SetXLength(100)
        plate.SetYLength(60)
        plate.SetZLength(6)
        plate.SetCenter(50, 0, -3)
 
        # Create a mapper
        plateMapper = vtk.vtkPolyDataMapper()
        plateMapper.SetInputConnection(plate.GetOutputPort())

        # Create a transform
        plateTransform = vtk.vtkTransform()
 
        # Create an actor
        self.plateActor = vtk.vtkActor()
        self.plateActor.SetMapper(plateMapper)
        self.plateActor.SetUserTransform(plateTransform)
        self.plateActor.GetProperty().SetColor(0.69, 0.77, 0.87)
 
        self.ren.AddActor(self.plateActor)

        # Two poles
        # Left pole
        # Create source
        poleL = vtk.vtkCylinderSource()
        poleL.SetRadius(1.0)
        poleL.SetHeight(50.0)
        poleL.SetCenter(10, 0, 0)
        poleL.SetResolution(100.0)

        # Create a mapper
        poleLMapper = vtk.vtkPolyDataMapper()
        poleLMapper.SetInputConnection(poleL.GetOutputPort())

        # Create a transform
        poleLTransform = vtk.vtkTransform()
        poleLTransform.SetInput(plateTransform)

        # Create an actor
        poleLActor = vtk.vtkActor()
        poleLActor.SetMapper(poleLMapper)
        poleLActor.SetUserTransform(poleLTransform)

        poleLTransform.RotateX(90.0)
        poleLTransform.Translate(0.0, 25.0, 0.0)

        self.ren.AddActor(poleLActor)

        # Right pole
        # Create source
        poleR = vtk.vtkCylinderSource()
        poleR.SetRadius(1.0)
        poleR.SetHeight(50.0)
        poleR.SetCenter(90, 0, 0)
        poleR.SetResolution(100.0)

        # Create a mapper
        poleRMapper = vtk.vtkPolyDataMapper()
        poleRMapper.SetInputConnection(poleR.GetOutputPort())

        # Create a transform
        poleRTransform = vtk.vtkTransform()
        poleRTransform.SetInput(plateTransform)

        # Create an actor
        poleRActor = vtk.vtkActor()
        poleRActor.SetMapper(poleRMapper)
        poleRActor.SetUserTransform(poleRTransform)

        poleRTransform.RotateX(90.0)
        poleRTransform.Translate(0.0, 25.0, 0.0)

        self.ren.AddActor(poleRActor)

        # 4 car's wheels
        wheel = []
        wheelMapper = []
        wheelTransform = []
        wheelActor = []
        for i in range(4):
        	# Create source
            wheel.append(vtk.vtkCylinderSource())
            wheel[i].SetRadius(6.0)
            wheel[i].SetHeight(3.0)
            wheel[i].SetResolution(100.0)

        	# Create a mapper
            wheelMapper.append(vtk.vtkPolyDataMapper())
            wheelMapper[i].SetInputConnection(wheel[i].GetOutputPort())

            # Create a transform
            wheelTransform.append(vtk.vtkTransform())
            wheelTransform[i].SetInput(plateTransform)

        	# Create an actor
            wheelActor.append(vtk.vtkActor())
            wheelActor[i].SetMapper(wheelMapper[i])
            wheelActor[i].SetUserTransform(wheelTransform[i])
            wheelActor[i].GetProperty().SetColor(1.0, 1.0, 0.6)

            self.ren.AddActor(wheelActor[i])
        
        wheel[0].SetCenter(10, 25, -9.0)
        wheel[1].SetCenter(90, 25, -9.0)
        wheel[2].SetCenter(10, -25, -9.0)
        wheel[3].SetCenter(90, -25, -9.0)


        # Two spheres' model
        # Left sphere
        # Create source
        sphereL = vtk.vtkSphereSource()
        sphereL.SetRadius(5)
        sphereL.SetCenter(0, 0, 30)

        # Create a mapper
        sphereLMapper = vtk.vtkPolyDataMapper()
        sphereLMapper.SetInputConnection(sphereL.GetOutputPort())

        # Create an actor
        sphereLActor = vtk.vtkActor()
        sphereLActor.SetMapper(sphereLMapper)
        sphereLActor.GetProperty().SetColor(1.0, 0.2, 0.2)

        self.ren.AddActor(sphereLActor)

        # Right sphere
        # Create source
        sphereR = vtk.vtkSphereSource()
        sphereR.SetRadius(5)
        sphereR.SetCenter(100, 0, 30)

        # Create a mapper
        sphereRMapper = vtk.vtkPolyDataMapper()
        sphereRMapper.SetInputConnection(sphereR.GetOutputPort())

        # Create an actor
        sphereRActor = vtk.vtkActor()
        sphereRActor.SetMapper(sphereRMapper)
        sphereRActor.GetProperty().SetColor(0.0, 0.5, 1.0)

        self.ren.AddActor(sphereRActor)

        # Create a camera
        #self.ren.ResetCamera()
        camera = vtk.vtkCamera()
        self.ren.SetActiveCamera(camera)
        self.ren.GetActiveCamera().SetPosition(50, -300, 100)
        self.ren.GetActiveCamera().SetFocalPoint(50, 0, 0)
        self.ren.GetActiveCamera().SetViewUp(0, 0, 1)
        self.ren.GetActiveCamera().UpdateViewport(self.ren)
Exemple #40
0
 def __init__(self, widget, app=None, parent = None):
     QVTKRenderWindowInteractor.__init__(self, widget)    
     self.app = app
     
Exemple #41
0
class Ui_MainWindow(QtGui.QMainWindow):
    """ The main window class"""

    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        
        # member variables definition
        self.M1 = 0.0
        self.M2 = 0.0
        self.L1 = 0.0
        self.L2 = 0.0

        self.th1 = 0.0
        self.th2 = 0.0
        self.w1 = 0.0
        self.w2 = 0.0

        self.ts = 0.0
        self.te = 0.0
        self.dt = 0.0

        # setup timer
        self.timer = QtCore.QTimer(self)
        self.timer.timeout.connect(self.timerCallback)
        self.timer_count = 0
        self.current_time = 0.0

        # dimension of the vtk view 
        self.len_convert_factor = 100.0   # length convert factor 1m = 100 pixels
        self.X_lim = 500.0
        self.Y_lim = 300.0

        # archive (history) of the results
        self.archive = archive()

        # Setup UI widgets
        self.setupUi(self)

    def setupUi(self, MainWindow):
        # mainwindow
        MainWindow.setObjectName(_fromUtf8("MainWindow"))
        MainWindow.resize(1203, 694)

        # centralWidget
        self.centralWidget = QtGui.QWidget(MainWindow)
        self.centralWidget.setObjectName(_fromUtf8("centralWidget"))
        MainWindow.setCentralWidget(self.centralWidget)

        # left setting panel

        # frame
        self.settingFrame = QtGui.QFrame(self.centralWidget)
        self.settingFrame.setGeometry(QtCore.QRect(10, 10, 301, 581))
        self.settingFrame.setFrameShape(QtGui.QFrame.StyledPanel)
        self.settingFrame.setFrameShadow(QtGui.QFrame.Raised)
        self.settingFrame.setObjectName(_fromUtf8("settingFrame"))

        # system parameter group
        self.groupBox_system = QtGui.QGroupBox(self.settingFrame)
        self.groupBox_system.setGeometry(QtCore.QRect(20, 20, 261, 121))
        self.groupBox_system.setStyleSheet(_fromUtf8("QGroupBox{border: 1px solid rgb(192, 192, 192); border-radius:9px; font: bold}+ QGroupBox::title{subcontrol-origin: margin; left: 10px; padding: 0px 3px 0 3px}"))
        self.groupBox_system.setObjectName(_fromUtf8("groupBox_system"))
        self.label_M1 = QtGui.QLabel(self.groupBox_system)
        self.label_M1.setGeometry(QtCore.QRect(10, 40, 21, 17))
        self.label_M1.setObjectName(_fromUtf8("label_M1"))
        self.label_M2 = QtGui.QLabel(self.groupBox_system)
        self.label_M2.setGeometry(QtCore.QRect(140, 40, 21, 17))
        self.label_M2.setObjectName(_fromUtf8("label_M2"))
        self.label_L1 = QtGui.QLabel(self.groupBox_system)
        self.label_L1.setGeometry(QtCore.QRect(10, 90, 21, 17))
        self.label_L1.setObjectName(_fromUtf8("label_L1"))
        self.label_L2 = QtGui.QLabel(self.groupBox_system)
        self.label_L2.setGeometry(QtCore.QRect(140, 90, 21, 17))
        self.label_L2.setObjectName(_fromUtf8("label_L2"))
        self.lineEdit_M1 = QtGui.QLineEdit(self.groupBox_system)
        self.lineEdit_M1.setGeometry(QtCore.QRect(40, 30, 71, 27))
        self.lineEdit_M1.setObjectName(_fromUtf8("lineEdit_M1"))
        self.lineEdit_M2 = QtGui.QLineEdit(self.groupBox_system)
        self.lineEdit_M2.setGeometry(QtCore.QRect(170, 30, 71, 27))
        self.lineEdit_M2.setObjectName(_fromUtf8("lineEdit_M2"))
        self.lineEdit_L1 = QtGui.QLineEdit(self.groupBox_system)
        self.lineEdit_L1.setGeometry(QtCore.QRect(40, 80, 71, 27))
        self.lineEdit_L1.setObjectName(_fromUtf8("lineEdit_L1"))
        self.lineEdit_L2 = QtGui.QLineEdit(self.groupBox_system)
        self.lineEdit_L2.setGeometry(QtCore.QRect(170, 80, 71, 27))
        self.lineEdit_L2.setObjectName(_fromUtf8("lineEdit_L2"))

        # initial condition group
        self.groupBox_init = QtGui.QGroupBox(self.settingFrame)
        self.groupBox_init.setGeometry(QtCore.QRect(20, 170, 261, 121))
        self.groupBox_init.setStyleSheet(_fromUtf8("QGroupBox{border: 1px solid rgb(192, 192, 192); border-radius:9px; font: bold}+ QGroupBox::title{subcontrol-origin: margin; left: 10px; padding: 0px 3px 0 3px}"))
        self.groupBox_init.setObjectName(_fromUtf8("groupBox_init"))
        self.label_th1 = QtGui.QLabel(self.groupBox_init)
        self.label_th1.setGeometry(QtCore.QRect(10, 40, 31, 17))
        self.label_th1.setObjectName(_fromUtf8("label_th1"))
        self.label_th2 = QtGui.QLabel(self.groupBox_init)
        self.label_th2.setGeometry(QtCore.QRect(140, 40, 31, 17))
        self.label_th2.setObjectName(_fromUtf8("label_th2"))
        self.label_w1 = QtGui.QLabel(self.groupBox_init)
        self.label_w1.setGeometry(QtCore.QRect(10, 90, 21, 17))
        self.label_w1.setObjectName(_fromUtf8("label_w1"))
        self.label_w2 = QtGui.QLabel(self.groupBox_init)
        self.label_w2.setGeometry(QtCore.QRect(140, 90, 21, 17))
        self.label_w2.setObjectName(_fromUtf8("label_w2"))
        self.lineEdit_th1 = QtGui.QLineEdit(self.groupBox_init)
        self.lineEdit_th1.setGeometry(QtCore.QRect(40, 30, 71, 27))
        self.lineEdit_th1.setObjectName(_fromUtf8("lineEdit_th1"))
        self.lineEdit_w1 = QtGui.QLineEdit(self.groupBox_init)
        self.lineEdit_w1.setGeometry(QtCore.QRect(40, 80, 71, 27))
        self.lineEdit_w1.setObjectName(_fromUtf8("lineEdit_w1"))
        self.lineEdit_th2 = QtGui.QLineEdit(self.groupBox_init)
        self.lineEdit_th2.setGeometry(QtCore.QRect(170, 30, 71, 27))
        self.lineEdit_th2.setObjectName(_fromUtf8("lineEdit_th2"))
        self.lineEdit_w2 = QtGui.QLineEdit(self.groupBox_init)
        self.lineEdit_w2.setGeometry(QtCore.QRect(170, 80, 71, 27))
        self.lineEdit_w2.setObjectName(_fromUtf8("lineEdit_w2"))

        # time setting group
        self.groupBox_time = QtGui.QGroupBox(self.settingFrame)
        self.groupBox_time.setGeometry(QtCore.QRect(20, 310, 261, 131))
        self.groupBox_time.setStyleSheet(_fromUtf8("QGroupBox{border: 1px solid rgb(192, 192, 192); border-radius:9px; font: bold}+ QGroupBox::title{subcontrol-origin: margin; left: 10px; padding: 0px 3px 0 3px}"))
        self.groupBox_time.setObjectName(_fromUtf8("groupBox_time"))
        self.label_ts = QtGui.QLabel(self.groupBox_time)
        self.label_ts.setGeometry(QtCore.QRect(20, 40, 41, 17))
        self.label_ts.setObjectName(_fromUtf8("label_ts"))
        self.label_te = QtGui.QLabel(self.groupBox_time)
        self.label_te.setGeometry(QtCore.QRect(20, 70, 41, 17))
        self.label_te.setObjectName(_fromUtf8("label_te"))
        self.label_dt = QtGui.QLabel(self.groupBox_time)
        self.label_dt.setGeometry(QtCore.QRect(20, 100, 41, 17))
        self.label_dt.setObjectName(_fromUtf8("label_dt"))
        self.lineEdit_ts = QtGui.QLineEdit(self.groupBox_time)
        self.lineEdit_ts.setGeometry(QtCore.QRect(70, 30, 71, 27))
        self.lineEdit_ts.setObjectName(_fromUtf8("lineEdit_ts"))
        self.lineEdit_te = QtGui.QLineEdit(self.groupBox_time)
        self.lineEdit_te.setGeometry(QtCore.QRect(70, 60, 71, 27))
        self.lineEdit_te.setObjectName(_fromUtf8("lineEdit_te"))
        self.lineEdit_dt = QtGui.QLineEdit(self.groupBox_time)
        self.lineEdit_dt.setGeometry(QtCore.QRect(70, 90, 71, 27))
        self.lineEdit_dt.setObjectName(_fromUtf8("lineEdit_dt"))

        # pushButton
        self.pushButton_clear = QtGui.QPushButton(self.settingFrame)
        self.pushButton_clear.setGeometry(QtCore.QRect(60, 480, 99, 27))
        self.pushButton_clear.setObjectName(_fromUtf8("pushButton_clear"))
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(
            _fromUtf8("Icon/clear.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.pushButton_clear.setIcon(icon)
        self.pushButton_clear.setIconSize(QtCore.QSize(20, 20))

        self.pushButton_init = QtGui.QPushButton(self.settingFrame)
        self.pushButton_init.setGeometry(QtCore.QRect(180, 480, 99, 27))
        self.pushButton_init.setObjectName(_fromUtf8("pushButton_init"))
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(
            _fromUtf8("Icon/init.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.pushButton_init.setIcon(icon)
        self.pushButton_init.setIconSize(QtCore.QSize(20, 20))

        self.pushButton_simulate = QtGui.QPushButton(self.settingFrame)
        self.pushButton_simulate.setGeometry(QtCore.QRect(180, 520, 99, 27))
        self.pushButton_simulate.setObjectName(_fromUtf8("pushButton_simulate"))
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(
            _fromUtf8("Icon/tick.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.pushButton_simulate.setIcon(icon)
        self.pushButton_simulate.setIconSize(QtCore.QSize(20, 20))

        # vtk widget
        self.vtk_widget = QVTKRenderWindowInteractor(self.centralWidget)
        self.vtk_widget.setGeometry(QtCore.QRect(320, 10, 431, 581))
        self.vtk_widget.setObjectName(_fromUtf8("vtk_widget"))
        self.setvtkWidget()


        # plot_widget
        # trajectory
        self.plot_trace = MyMplCanvas(
            self.centralWidget, width=1, height=1, dpi=50, Ndim=2)
        self.plot_trace.setGeometry(QtCore.QRect(760, 10, 431, 285))
        self.plot_trace.setObjectName(_fromUtf8("plot_trace"))
        self.plot_trace.axes.set_xlim(-5, 5)
        self.plot_trace.axes.set_ylim(0, 5)
        # self.plot_trace.lines[0].set_color('red')     # it doesn't work?
        # self.plot_trace.lines[1].set_color('blue')
        self.plot_trace.fig.legend((self.plot_trace.lines[0], self.plot_trace.lines[
                                   1]), ('upper', 'lower'), (0.15, 0.76))
        self.plot_trace.axes.set_title("Trace of the pendulums", fontsize = 25)
        self.plot_trace.axes.set_xlabel("x/m", fontsize = 15)
        self.plot_trace.axes.set_ylabel("y/m", fontsize = 15)

        # phase angle
        self.plot_angle = MyMplCanvas(
            self.centralWidget, width=1, height=1, dpi=50, Ndim=2)
        self.plot_angle.setGeometry(QtCore.QRect(760, 306, 431, 285))
        self.plot_angle.setObjectName(_fromUtf8("plot_angle"))
        self.plot_angle.axes.set_xlim(0, 10)
        self.plot_angle.axes.set_ylim(-1.6, 1.6)
        self.plot_angle.axes.set_title("Angle of the pendulums", fontsize = 25)
        self.plot_angle.axes.set_xlabel("Time/sec", fontsize = 15)
        self.plot_angle.axes.set_ylabel("Angle/rad", fontsize = 15)


        # menuBar
        self.menuBar = QtGui.QMenuBar(MainWindow)
        self.menuBar.setGeometry(QtCore.QRect(0, 0, 1203, 25))
        self.menuBar.setObjectName(_fromUtf8("menuBar"))
        MainWindow.setMenuBar(self.menuBar)

        # toolbar
        self.mainToolBar = QtGui.QToolBar(MainWindow)
        self.mainToolBar.setIconSize(QtCore.QSize(50, 50))
        self.mainToolBar.setObjectName(_fromUtf8("mainToolBar"))
        self.mainToolBar.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon)
        MainWindow.addToolBar(QtCore.Qt.TopToolBarArea, self.mainToolBar)

        self.actionImport = QtGui.QAction(MainWindow)
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(_fromUtf8("Icon/import.png")), QtGui.QIcon.Normal, QtGui.QIcon.On)
        self.actionImport.setIcon(icon)
        self.actionImport.setObjectName(_fromUtf8("actionImport"))

        self.actionExport = QtGui.QAction(MainWindow)
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(_fromUtf8("Icon/export.png")), QtGui.QIcon.Normal, QtGui.QIcon.On)
        self.actionExport.setIcon(icon)
        self.actionExport.setObjectName(_fromUtf8("actionExport"))

        self.actionInit = QtGui.QAction(MainWindow)
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(_fromUtf8("Icon/init.png")), QtGui.QIcon.Normal, QtGui.QIcon.On)
        self.actionInit.setIcon(icon)
        self.actionInit.setObjectName(_fromUtf8("actionInit"))

        self.actionSimulate = QtGui.QAction(MainWindow)
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(_fromUtf8("Icon/tick.png")), QtGui.QIcon.Normal, QtGui.QIcon.On)
        self.actionSimulate.setIcon(icon)
        self.actionSimulate.setObjectName(_fromUtf8("actionSimulate"))

        self.actionStart = QtGui.QAction(MainWindow)
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(_fromUtf8("Icon/start.png")), QtGui.QIcon.Normal, QtGui.QIcon.On)
        self.actionStart.setIcon(icon)
        self.actionStart.setObjectName(_fromUtf8("actionStart"))
        
        self.actionStop = QtGui.QAction(MainWindow)
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(_fromUtf8(
            "Icon/stop.png")), QtGui.QIcon.Normal, QtGui.QIcon.On)
        self.actionStop.setIcon(icon)
        self.actionStop.setObjectName(_fromUtf8("actionStop"))

        self.actionSave = QtGui.QAction(MainWindow)
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(_fromUtf8(
            "Icon/save.png")), QtGui.QIcon.Normal, QtGui.QIcon.On)
        self.actionSave.setIcon(icon)
        self.actionSave.setObjectName(_fromUtf8("actionSave"))

        self.actionInfo = QtGui.QAction(MainWindow)
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(_fromUtf8(
            "Icon/info.svg")), QtGui.QIcon.Normal, QtGui.QIcon.On)
        self.actionInfo.setIcon(icon)
        self.actionInfo.setObjectName(_fromUtf8("actionInfo"))
        
        self.actionExit = QtGui.QAction(MainWindow)
        icon = QtGui.QIcon()
        icon.addPixmap(
            QtGui.QPixmap(_fromUtf8("Icon/exit.png")), QtGui.QIcon.Normal, QtGui.QIcon.On)
        self.actionExit.setIcon(icon)
        self.actionExit.setObjectName(_fromUtf8("actionExit"))

        self.mainToolBar.addAction(self.actionImport)
        self.mainToolBar.addAction(self.actionExport)
        self.mainToolBar.addSeparator()
        self.mainToolBar.addAction(self.actionInit)
        self.mainToolBar.addAction(self.actionSimulate)
        self.mainToolBar.addSeparator()
        self.mainToolBar.addAction(self.actionStart)
        self.mainToolBar.addAction(self.actionStop)
        self.mainToolBar.addAction(self.actionSave)
        self.mainToolBar.addSeparator()
        self.mainToolBar.addAction(self.actionInfo)
        self.mainToolBar.addAction(self.actionExit)
        self.mainToolBar.addSeparator()

        # add lineText to the toolbar to display the current time
        self.label_currenttime = QtGui.QLabel(self.mainToolBar)
        self.label_currenttime.setGeometry(QtCore.QRect(800, 25, 60, 30))
        self.label_currenttime.setObjectName(_fromUtf8("label_currenttime"))
        self.label_currenttime.setStyleSheet(
            "QLabel{font-weight: bold; font-size: 22px}")

        self.lineEdit_timer = QtGui.QLineEdit(self.mainToolBar)
        self.lineEdit_timer.setGeometry(QtCore.QRect(870, 20, 100, 40))
        self.lineEdit_timer.setObjectName(_fromUtf8("lineEdit_timer"))
        self.lineEdit_timer.setReadOnly(True)
        self.lineEdit_timer.setFont(QtGui.QFont("Arial", 20, QtGui.QFont.Bold))

        # Layout management
        #self.gridLayout = QtGui.QGridLayout(self.centralWidget)
        #self.gridLayout.setMargin(11)
        #self.gridLayout.setSpacing(6)
        #self.gridLayout.setObjectName(_fromUtf8("gridLayout"))

        #self.gridLayout.addWidget(self.settingFrame, 0, 0, 1, 1)
        #self.gridLayout.addWidget(self.vtk_widget, 0, 1, 1, 1)
        #self.gridLayout.addWidget(self.plot_widget, 0, 2, 1, 1)


        #
        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        # mainwindow
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))

        # system parameter setting group
        self.groupBox_system.setTitle(_translate("MainWindow", "System parameters", None))
        self.label_M1.setText(_translate("MainWindow", "M1", None))
        self.label_M2.setText(_translate("MainWindow", "M2", None))
        self.label_L1.setText(_translate("MainWindow", "L1", None))
        self.label_L2.setText(_translate("MainWindow", "L2", None))

        # initial condition group
        self.groupBox_init.setTitle(_translate("MainWindow", "Initial conditions", None))
        self.label_th1.setText(_translate("MainWindow", "th1", None))
        self.label_th2.setText(_translate("MainWindow", "th2", None))
        self.label_w1.setText(_translate("MainWindow", "w1", None))
        self.label_w2.setText(_translate("MainWindow", "w2", None))

        # time advancement group
        self.groupBox_time.setTitle(_translate("MainWindow", "Time advancement", None))
        self.label_ts.setText(_translate("MainWindow", "tstart", None))
        self.label_te.setText(_translate("MainWindow", "tend", None))
        self.label_dt.setText(_translate("MainWindow", "tstep", None))

        # pushBotton
        self.pushButton_clear.setText(_translate("MainWindow", "Clear", None))
        self.pushButton_init.setText(_translate("MainWindow", "Initialize", None))
        self.pushButton_simulate.setText(_translate("MainWindow", "Simulate", None))

        # toolbar
        self.actionImport.setText(_translate("MainWindow", "Import input", None))
        self.actionImport.setToolTip(_translate("MainWindow", "Import input", None))

        self.actionExport.setText(_translate("MainWindow", "Export input", None))
        self.actionExport.setToolTip(_translate("MainWindow", "Export input", None))

        self.actionInit.setText(_translate("MainWindow", "Initialize", None))
        self.actionInit.setToolTip(_translate("MainWindow", "Initialize", None))

        self.actionSimulate.setText(_translate("MainWindow", "Simulate", None))
        self.actionSimulate.setToolTip(_translate("MainWindow", "Simulate", None))

        self.actionStart.setText(_translate("MainWindow", "Start", None))
        self.actionStart.setToolTip(_translate("MainWindow", "Start", None))

        self.actionStop.setText(_translate("MainWindow", "Stop", None))
        self.actionStop.setToolTip(_translate("MainWindow", "Stop", None))

        self.actionSave.setText(_translate("MainWindow", "Save", None))
        self.actionSave.setToolTip(_translate("MainWindow", "Save", None))

        self.actionInfo.setText(_translate("MainWindow", "Infomation", None))
        self.actionInfo.setToolTip(_translate("MainWindow", "Infomation", None))

        self.actionExit.setText(_translate("MainWindow", "Exit", None))
        self.actionExit.setToolTip(_translate("MainWindow", "Exit", None))

        self.label_currenttime.setText(_translate("MainWindow", "Time:", None))


    # other class member function
    def setvtkWidget(self):
        """ setup the vtk widget"""
        # Create renderer
        self.ren = vtk.vtkRenderer()
        self.ren.SetBackground(0.1, 0.2, 0.3)
        self.vtk_widget.GetRenderWindow().AddRenderer(self.ren)
        self.iren = self.vtk_widget.GetRenderWindow().GetInteractor()

        # Two spheres' model
        # upper sphere
        # Create source
        self.sphereU = vtk.vtkSphereSource()
        self.sphereU.SetRadius(10)
        self.sphereU.SetCenter(-10, 250, 0)

        # Create a mapper
        sphereUMapper = vtk.vtkPolyDataMapper()
        sphereUMapper.SetInputConnection(self.sphereU.GetOutputPort())

        # Create an actor
        self.sphereUActor = vtk.vtkActor()
        self.sphereUActor.SetMapper(sphereUMapper)
        self.sphereUActor.GetProperty().SetColor(1.0, 0.2, 0.2)

        self.ren.AddActor(self.sphereUActor)

        # lower sphere
        # Create source
        self.sphereL = vtk.vtkSphereSource()
        self.sphereL.SetRadius(15)
        self.sphereL.SetCenter(50, 100, 0)

        # Create a mapper
        sphereLMapper = vtk.vtkPolyDataMapper()
        sphereLMapper.SetInputConnection(self.sphereL.GetOutputPort())

        # Create an actor
        self.sphereLActor = vtk.vtkActor()
        self.sphereLActor.SetMapper(sphereLMapper)
        self.sphereLActor.GetProperty().SetColor(0.0, 0.5, 1.0)

        self.ren.AddActor(self.sphereLActor)

        # two ropes connected to the spheres
        # upper rope
        self.RopeU = vtk.vtkLineSource()
        self.RopeU.SetPoint1(0, self.Y_lim, 0)
        self.RopeU.SetPoint2(-10, 250, 0)

        RopeUMapper = vtk.vtkPolyDataMapper()
        RopeUMapper.SetInput(self.RopeU.GetOutput())

        RopeUActor = vtk.vtkActor()
        RopeUActor.SetMapper(RopeUMapper)
        # RopeUActor.GetProperty().SetColor(1.0, 0.0, 0.0)
        RopeUActor.GetProperty().SetLineWidth(5)

        self.ren.AddActor(RopeUActor)

        # lower rope
        self.RopeL = vtk.vtkLineSource()
        self.RopeL.SetPoint1(-10, 250, 0)
        self.RopeL.SetPoint2(50, 100, 0)

        RopeLMapper = vtk.vtkPolyDataMapper()
        RopeLMapper.SetInput(self.RopeL.GetOutput())

        RopeLActor = vtk.vtkActor()
        RopeLActor.SetMapper(RopeLMapper)
        # RopeLActor.GetProperty().SetColor(1.0, 0.0, 0.0)
        RopeLActor.GetProperty().SetLineWidth(5)

        self.ren.AddActor(RopeLActor)

        # Create a camera
        camera = vtk.vtkCamera()
        self.ren.SetActiveCamera(camera)
        self.ren.GetActiveCamera().SetPosition(0, 150, 1000)
        self.ren.GetActiveCamera().SetFocalPoint(0, 150, 0)
        self.ren.GetActiveCamera().SetViewUp(0, 1, 0)
        self.ren.GetActiveCamera().UpdateViewport(self.ren)

    def get_input(self):
        """ get input data from the GUI """
        # system parameters
        self.M1 = self.lineEdit_M1.text().toDouble()[0]
        self.M2 = self.lineEdit_M2.text().toDouble()[0]
        self.L1 = self.lineEdit_L1.text().toDouble()[0]
        self.L2 = self.lineEdit_L2.text().toDouble()[0]

        # initial conditions
        self.th1 = self.lineEdit_th1.text().toDouble()[0]
        self.th2 = self.lineEdit_th2.text().toDouble()[0]
        self.w1 = self.lineEdit_w1.text().toDouble()[0]
        self.w2 = self.lineEdit_w2.text().toDouble()[0]

        # time advancement setting
        self.ts = self.lineEdit_ts.text().toDouble()[0]
        self.te = self.lineEdit_te.text().toDouble()[0]
        self.dt = self.lineEdit_dt.text().toDouble()[0]

    def set_input(self):
        # system parameters
        self.lineEdit_M1.setText(str(self.M1))
        self.lineEdit_M2.setText(str(self.M2))
        self.lineEdit_L1.setText(str(self.L1))
        self.lineEdit_L2.setText(str(self.L2))

        # initial conditions
        self.lineEdit_th1.setText(str(self.th1))
        self.lineEdit_th2.setText(str(self.th2))
        self.lineEdit_w1.setText(str(self.w1))
        self.lineEdit_w2.setText(str(self.w2))

        # time advancement setting
        self.lineEdit_ts.setText(str(self.ts))
        self.lineEdit_te.setText(str(self.te))
        self.lineEdit_dt.setText(str(self.dt))


    def timerCallback(self):
        """ timer callback function """
        # update and display the current time
        self.timer_count += 1
        self.current_time = self.timer_count*self.dt
        self.lineEdit_timer.setText(str(self.current_time))

        # terminate the simulation when reaching the preset stop time
        if self.current_time > self.te:
            self.timer.stop()
            return

        # solve the governing system of equations at the current timestep
        t = np.array([self.current_time-self.dt, self.current_time])
        result = self.pendulum.ode_solve(t)
        # alternative euler method to solve the ODEs
        #result = self.pendulum.euler_ode(self.current_time, self.dt)

        # save results history to the archive
        self.archive.addData(np.insert(result, 0, t[-1]))

        # update the vtk view to display the results
        X1, Y1, X2, Y2, self.th1, self.th2 = result

        # two spheres
        self.sphereU.SetCenter(X1*self.len_convert_factor, self.Y_lim+Y1*self.len_convert_factor, 0.0)
        self.sphereL.SetCenter(X2*self.len_convert_factor, self.Y_lim+Y2*self.len_convert_factor, 0.0)

        # two ropes
        self.RopeU.SetPoint1(0.0 , self.Y_lim, 0.0)
        self.RopeU.SetPoint2(X1*self.len_convert_factor, self.Y_lim+Y1*self.len_convert_factor, 0.0)

        self.RopeL.SetPoint1(X1*self.len_convert_factor, self.Y_lim+Y1*self.len_convert_factor, 0.0)
        self.RopeL.SetPoint2(X2*self.len_convert_factor, self.Y_lim+Y2*self.len_convert_factor, 0.0)

        # upate the vtk view
        self.iren.GetRenderWindow().Render()

        # update the matplotlib plots
        # plot trace
        self.plot_trace.updateFig([[X1, Y1], [X2, Y2]])

        # plot_angle
        self.plot_angle.updateFig([[t[-1], self.th1], [t[-1], self.th2]])

    # toolbar slot function
    @QtCore.pyqtSlot() # signal with no arguments
    def on_actionImport_triggered(self):
        """Toolbar import input button slot"""
        filename = QtGui.QFileDialog.getOpenFileName(self, "Open Input file", "input files/")
        if filename == "":
            return
        read_data = []
        with open(filename, 'r') as f:
            for line in f.readlines():
                read_data.append(float(line.strip()))

        # system parameters
        self.M1 = read_data[0]
        self.L1 = read_data[1]
        self.M2 = read_data[2]
        self.L2 = read_data[3]
        # initial conditions
        self.th1 = read_data[4]
        self.th2 = read_data[5]
        self.w1 = read_data[6]
        self.w2 = read_data[7]
        # time advancement setting
        self.ts = read_data[8]
        self.te = read_data[9]
        self.dt = read_data[10]

        # update the GUI
        self.set_input()


    @QtCore.pyqtSlot() # signal with no arguments
    def on_actionExport_triggered(self):
        """Toolbar export input button slot"""
        self.get_input()
        filename = QtGui.QFileDialog.getSaveFileName(self, "Export Input file", "input files/")
        if filename == "":
            return
        with open(filename, 'wb') as f:
            # system parameters
            f.write("%f\n"%self.M1)
            f.write("%f\n"%self.L1)
            f.write("%f\n"%self.M2)
            f.write("%f\n"%self.L2)
            # initial conditions
            f.write("%f\n"%self.th1)
            f.write("%f\n"%self.th2)
            f.write("%f\n"%self.w1)
            f.write("%f\n"%self.w2)
            # time advancement setting
            f.write("%f\n"%self.ts)
            f.write("%f\n"%self.te)
            f.write("%f\n"%self.dt)       

    
    @QtCore.pyqtSlot() # signal with no arguments
    def on_actionInit_triggered(self):
        """Toolbar initialize button slot"""
        # get input data from the GUI
        self.get_input()

        # update the positions of the actors of the vtk based on the input
        X1 = self.L1*np.sin(self.th1)
        Y1 = -self.L1*np.cos(self.th1)
        X2 = X1 + self.L2*np.sin(self.th2)
        Y2 = Y1 - self.L2*np.cos(self.th2)

        # two spheres
        self.sphereU.SetCenter(X1*self.len_convert_factor, self.Y_lim+Y1*self.len_convert_factor, 0.0)
        self.sphereL.SetCenter(X2*self.len_convert_factor, self.Y_lim+Y2*self.len_convert_factor, 0.0)

        # two ropes
        self.RopeU.SetPoint1(0.0 , self.Y_lim, 0.0)
        self.RopeU.SetPoint2(X1*self.len_convert_factor, self.Y_lim+Y1*self.len_convert_factor, 0.0)

        self.RopeL.SetPoint1(X1*self.len_convert_factor, self.Y_lim+Y1*self.len_convert_factor, 0.0)
        self.RopeL.SetPoint2(X2*self.len_convert_factor, self.Y_lim+Y2*self.len_convert_factor, 0.0)

        # upate the vtk view
        self.iren.GetRenderWindow().Render()

        # initialize the time setting
        self.timer_count = 0
        self.current_time = 0.0
        self.lineEdit_timer.setText(str(self.current_time))

        # clean the plots view
        self.plot_trace.clearAxia()
        self.plot_angle.clearAxia()

        self.plot_trace.fig.legend((self.plot_trace.lines[0], self.plot_trace.lines[
                                   1]), ('upper', 'lower'), (0.15, 0.76))
        self.plot_trace.axes.set_title("Trace of the pendulums", fontsize = 25)
        self.plot_trace.axes.set_xlabel("x/m", fontsize = 15)
        self.plot_trace.axes.set_ylabel("y/m", fontsize = 15)

        self.plot_angle.axes.set_title("Angle of the pendulums", fontsize = 25)
        self.plot_angle.axes.set_xlabel("Time/sec", fontsize = 15)
        self.plot_angle.axes.set_ylabel("Angle/rad", fontsize = 15)



    @QtCore.pyqtSlot() # signal with no arguments
    def on_actionSimulate_triggered(self):
        """Toolbar simulate button slot"""
        # initialize the simulation
        self.on_actionInit_triggered()

        # create pendulum object and initialize the state
        self.pendulum = DoublePendulum(self.M1, self.M2, self.L1, self.L2)
        self.pendulum.status = np.array([self.th1, self.th2, self.w1, self.w2])

        # start time advancement process
        self.timer.start(self.dt*1000.0)     # convert time unit from s to ms

    @QtCore.pyqtSlot() # signal with no arguments
    def on_actionStart_triggered(self):
        """Toolbar start button slot"""
        self.timer.start(self.dt*1000.0)

    @QtCore.pyqtSlot() # signal with no arguments
    def on_actionStop_triggered(self):
        """Toolbar stop button slot"""
        self.timer.stop()

    @QtCore.pyqtSlot() # signal with no arguments
    def on_actionSave_triggered(self):
        """Toolbar save button slot"""
        filename = QtGui.QFileDialog.getSaveFileName(self, "Save result file", "results/")
        with open(filename, 'wb') as f:
            f.write("Time     X1     Y1     X2     Y2    th1     th2\n")
            N = self.archive.getLen()
            for i in range(N):
                f.write("%f     %f     %f      %f      %f     %f     %f\n"
                    %(self.archive.t[i], self.archive.X1[i], self.archive.Y1[i],
                        self.archive.X2[i], self.archive.Y2[i], self.archive.th1[i],
                        self.archive.th2[i]))

    @QtCore.pyqtSlot() # signal with no arguments
    def on_actionInfo_triggered(self):
        """Toolbar info button slot"""
        aboutDlg = Ui_AboutDialog()
        aboutDlg.setModal(True)
        aboutDlg.exec_()

    @QtCore.pyqtSlot() # signal with no arguments
    def on_actionExit_triggered(self):
        """Toolbar exit button slot"""
        self.close()

    # pushbutton slots
    @QtCore.pyqtSlot() # signal with no arguments
    def on_pushButton_clear_clicked(self):
        """pushBotton clear function"""
        # system parameters
        self.lineEdit_M1.setText(str(""))
        self.lineEdit_M2.setText(str(""))
        self.lineEdit_L1.setText(str(""))
        self.lineEdit_L2.setText(str(""))

        # initial conditions
        self.lineEdit_th1.setText(str(""))
        self.lineEdit_th2.setText(str(""))
        self.lineEdit_w1.setText(str(""))
        self.lineEdit_w2.setText(str(""))

        # time advancement setting
        self.lineEdit_ts.setText(str(""))
        self.lineEdit_te.setText(str(""))
        self.lineEdit_dt.setText(str(""))

    @QtCore.pyqtSlot() # signal with no arguments
    def on_pushButton_init_clicked(self):
        """pushBotton initialize function"""
        self.on_actionInit_triggered()

    @QtCore.pyqtSlot() # signal with no arguments
    def on_pushButton_simulate_clicked(self):
        """pushBotton simulate function"""
        self.on_actionSimulate_triggered()
Exemple #42
0
class VTKFrame(QtGui.QFrame):
    def __init__(self, parent=None):
        super(VTKFrame, self).__init__(parent)

        self.vtkWidget = QVTKRenderWindowInteractor(self)
        vl = QtGui.QVBoxLayout(self)
        vl.addWidget(self.vtkWidget)
        vl.setContentsMargins(0, 0, 0, 0)

        self.ren = vtk.vtkRenderer()
        self.ren.SetBackground(0.1, 0.2, 0.4)
        self.vtkWidget.GetRenderWindow().AddRenderer(self.ren)
        self.iren = self.vtkWidget.GetRenderWindow().GetInteractor()

        # Provide some geometry
        resolution = 8
        aPlane = vtk.vtkPlaneSource()
        aPlane.SetXResolution(resolution)
        aPlane.SetYResolution(resolution)

        # Create cell data
        cellData = vtk.vtkFloatArray()
        for i in range(resolution * resolution):
            cellData.InsertNextValue(i + 1)

        # Create a lookup table to map cell data to colors
        lut = vtk.vtkLookupTable()
        tableSize = max(resolution * resolution + 1, 10)
        lut.SetNumberOfTableValues(tableSize)
        lut.Build()

        # Fill in a few known colors, the rest will be generated if needed
        lut.SetTableValue(0, 0, 0, 0, 1)  # Black
        lut.SetTableValue(1, 0.8900, 0.8100, 0.3400, 1)  # Banana
        lut.SetTableValue(2, 1.0000, 0.3882, 0.2784, 1)  # Tomato
        lut.SetTableValue(3, 0.9608, 0.8706, 0.7020, 1)  # Wheat
        lut.SetTableValue(4, 0.9020, 0.9020, 0.9804, 1)  # Lavender
        lut.SetTableValue(5, 1.0000, 0.4900, 0.2500, 1)  # Flesh
        lut.SetTableValue(6, 0.5300, 0.1500, 0.3400, 1)  # Raspberry
        lut.SetTableValue(7, 0.9804, 0.5020, 0.4471, 1)  # Salmon
        lut.SetTableValue(8, 0.7400, 0.9900, 0.7900, 1)  # Mint
        lut.SetTableValue(9, 0.2000, 0.6300, 0.7900, 1)  # Peacock

        aPlane.Update()  #Force an update so we can set cell data
        aPlane.GetOutput().GetCellData().SetScalars(cellData)

        # Create a mapper
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(aPlane.GetOutputPort())
        mapper.SetScalarRange(0, tableSize - 1)
        mapper.SetLookupTable(lut)

        # Create an actor
        actor = vtk.vtkActor()
        actor.SetMapper(mapper)

        self.ren.AddActor(actor)
        self.ren.ResetCamera()

        self._initialized = False

    def showEvent(self, evt):
        if not self._initialized:
            self.iren.Initialize()
            self._initialized = True
class VTKChartWidget(object):
    def __init__(self, chart_frame):
        super(VTKChartWidget, self).__init__()
        vtk.vtkObject.GlobalWarningDisplayOff()

        self.line_colors = default_line_colors
        self.line_width = default_line_width
        self.line_types = default_line_types

        self._gui_callbacks = []

        self.chart_frame = chart_frame

        self.renderer = vtk.vtkRenderer()
        self.renderer.SetBackground(1.0, 1.0, 1.0)

        self.table = vtk.vtkTable()
        self.chart = vtk.vtkChartXY()
        self.chart_scene = vtk.vtkContextScene()
        self.chart_actor = vtk.vtkContextActor()
        self.chart_view = vtk.vtkContextView()

        self.chart_scene.AddItem(self.chart)
        self.chart_actor.SetScene(self.chart_scene)
        self.chart_view.SetScene(self.chart_scene)

        self.renderer.AddActor(self.chart_actor)
        self.chart_scene.SetRenderer(self.renderer)

        self.chart.SetShowLegend(True)
        legend = self.chart.GetLegend()
        legend.SetInline(False)
        legend.SetHorizontalAlignment(vtk.vtkChartLegend.RIGHT)
        legend.SetVerticalAlignment(vtk.vtkChartLegend.TOP)
        legend.SetLabelSize(20)
        title_prop = self.chart.GetTitleProperties()
        title_prop.SetFontSize(20)

        self.init_xy_data()
        self.set_up_view()

    @property
    def options_dict(self):
        options_dict = {}
        options_dict['x_min'] = self.chart.GetAxis(0).GetMinimum()
        options_dict['x_max'] = self.chart.GetAxis(0).GetMaximum()
        options_dict['y_min'] = self.chart.GetAxis(1).GetMinimum()
        options_dict['y_max'] = self.chart.GetAxis(1).GetMaximum()

        lines_options = []
        for i in range(self.chart.GetNumberOfPlots()):
            line = self.chart.GetPlot(i)
            rgb = [0.0, 0.0, 0.0]
            line.GetColor(rgb)
            width = line.GetWidth()
            line_type = line.GetPen().GetLineType()
            lines_options.append((rgb, width, line_type))
        options_dict['lines_options'] = lines_options

        return options_dict

    def apply_options(self, options_dict):
        self.chart.GetAxis(0).SetMinimum(options_dict['x_min'])
        self.chart.GetAxis(0).SetMaximum(options_dict['x_max'])
        self.chart.GetAxis(1).SetMinimum(options_dict['y_min'])
        self.chart.GetAxis(1).SetMaximum(options_dict['y_max'])

        lines_options = options_dict['lines_options']
        for i in range(self.chart.GetNumberOfPlots()):
            rgb = lines_options[i][0]
            width = lines_options[i][1]
            line_type = lines_options[i][2]

            _index1 = i % len(self.line_colors)
            _index2 = i % len(self.line_width)
            _index3 = i % len(self.line_types)

            self.line_colors[_index1] = rgb
            self.line_width[_index2] = width
            self.line_types[_index3] = line_type

            line = self.chart.GetPlot(i)
            line.SetColor(*rgb)
            width = line.SetWidth(width)
            line_type = line.GetPen().SetLineType(line_type)
            lines_options.append((rgb, width, line_type))
            self.render()

    def add_callback(self, callback):
        if callable(callback):
            self._gui_callbacks.append(callback)

    def refresh_gui(method):
        def wrapper(self, *args):
            method(self, *args)
            for i in range(len(self._gui_callbacks)):
                self._gui_callbacks[i]()

        return wrapper

    def init_xy_data(self):
        self.chart.SetTitle('N/A')
        self.chart.ClearPlots()
        self.chart.AddPlot(vtk.vtkChart.LINE)

    def set_up_view(self):
        self.interactor = QVTKRenderWindowInteractor(self.chart_frame)
        self.interactor.GetRenderWindow().AddRenderer(self.renderer)
        self.chart_frame.layout().addWidget(self.interactor, 1, 0, 1, 1)
        self.iren = self.interactor.GetRenderWindow().GetInteractor()

    @refresh_gui
    def set_xy_data(self, x_array, y_array, title):
        if not title:
            title = 'N/A'
        self.chart.SetTitle(title)
        self.chart.ClearPlots()

        self.table = vtk.vtkTable()

        self.table.AddColumn(x_array)
        self.table.AddColumn(y_array)

        line = self.chart.AddPlot(vtk.vtkChart.LINE)

        self.chart.GetAxis(1).SetTitle(x_array.GetName())
        self.chart.GetAxis(0).SetTitle(y_array.GetName())

        line.SetInputData(self.table, 0, 1)

        line.SetColor(*self.line_colors[0])
        line.SetWidth(self.line_width[0])
        line.GetPen().SetLineType(self.line_types[0])

        self.set_active()

        self.render()

    @refresh_gui
    def set_multiple_xy_data(self, x_array, y_arrays_list, title):
        if not title:
            title = 'N/A'
        self.chart.SetTitle(title)
        self.chart.ClearPlots()
        self.chart.GetAxis(0).SetTitle('')
        self.chart.GetAxis(1).SetTitle(x_array.GetName())

        self.table = vtk.vtkTable()

        self.table.AddColumn(x_array)
        for var_index, y_array in enumerate(y_arrays_list):
            self.table.AddColumn(y_array)
            line = self.chart.AddPlot(vtk.vtkChart.LINE)
            line.SetInputData(self.table, 0, var_index + 1)

            _index = var_index % len(self.line_colors)
            color_rgb = self.line_colors[_index]

            line.SetColor(*color_rgb)
            line.GetPen().SetLineType(self.line_types[_index])
            line.SetWidth(self.line_width[_index])

        self.set_active()
        self.render()

    def get_values_as_table(self):
        n_columns = self.table.GetNumberOfColumns()
        if not n_columns:
            return []

        n_rows = self.table.GetColumn(0).GetNumberOfTuples()
        if not n_rows:
            return []

        column_names = []
        for i in range(n_columns):
            column_names.append(self.table.GetColumn(i).GetName())

        table_values = [
            column_names,
        ]
        for i in range(n_rows):
            cur_row = []
            for j in range(n_columns):
                column = self.table.GetColumn(j)
                cur_row.append(column.GetValue(i))
            table_values.append(cur_row)
        return table_values

    @property
    def is_visible(self):
        return self.chart_frame.isVisible()

    def show(self):
        self.chart_frame.show()

    def hide(self):
        self.chart_frame.hide()

    def set_active(self):
        self.chart_frame.set_active()

    def render(self):
        self.interactor.GetRenderWindow().Render()
    def __init__(self, parent = None):
        super(VTKFrame, self).__init__(parent)

        self.vtkWidget = QVTKRenderWindowInteractor(self)
        self.iren = self.vtkWidget.GetRenderWindow().GetInteractor()
        vl = QtGui.QVBoxLayout(self)
        vl.addWidget(self.vtkWidget)
        vl.setContentsMargins(0, 0, 0, 0)
 
        # Create source
        parametricObjects = list()
        parametricObjects.append(vtk.vtkParametricBoy())
        parametricObjects.append(vtk.vtkParametricConicSpiral())
        parametricObjects.append(vtk.vtkParametricCrossCap())
        parametricObjects.append(vtk.vtkParametricDini())
 
        parametricObjects.append(vtk.vtkParametricEllipsoid())
        parametricObjects[-1].SetXRadius(0.5)
        parametricObjects[-1].SetYRadius(2.0)
        parametricObjects.append(vtk.vtkParametricEnneper())
        parametricObjects.append(vtk.vtkParametricFigure8Klein())
        parametricObjects.append(vtk.vtkParametricKlein())
 
        parametricObjects.append(vtk.vtkParametricMobius())
        parametricObjects[-1].SetRadius(2)
        parametricObjects[-1].SetMinimumV(-0.5)
        parametricObjects[-1].SetMaximumV(0.5)
        parametricObjects.append(vtk.vtkParametricRandomHills())
        parametricObjects[-1].AllowRandomGenerationOff()
        parametricObjects.append(vtk.vtkParametricRoman())
        parametricObjects.append(vtk.vtkParametricSuperEllipsoid())
        parametricObjects[-1].SetN1(0.5)
        parametricObjects[-1].SetN2(0.1)
 
        parametricObjects.append(vtk.vtkParametricSuperToroid())
        parametricObjects[-1].SetN1(0.2)
        parametricObjects[-1].SetN2(3.0)
        parametricObjects.append(vtk.vtkParametricTorus())
        parametricObjects.append(vtk.vtkParametricSpline())

        # Add some points to the parametric spline.
        inputPoints = vtk.vtkPoints()
        vtk.vtkMath.RandomSeed(8775070)
        for i in range(10):
            x = vtk.vtkMath.Random(0.0,1.0)
            y = vtk.vtkMath.Random(0.0,1.0)
            z = vtk.vtkMath.Random(0.0,1.0)
            inputPoints.InsertNextPoint(x, y, z)
        parametricObjects[-1].SetPoints(inputPoints)
 
        # There are only 15 objects.
        parametricFunctionSources = list()
        renderers = list()
        mappers = list()
        actors = list()
        textmappers = list()
        textactors = list()
 
        # Create a common text property.
        textProperty = vtk.vtkTextProperty()
        textProperty.SetFontSize(10)
        textProperty.SetJustificationToCentered()
 
        # Create a parametric function source, renderer, mapper
        # and actor for each object.
        for idx, item in enumerate(parametricObjects):
            parametricFunctionSources.append(vtk.vtkParametricFunctionSource())
            parametricFunctionSources[idx].SetParametricFunction(item)
            parametricFunctionSources[idx].Update()
 
            mappers.append(vtk.vtkPolyDataMapper())
            mappers[idx].SetInputConnection(parametricFunctionSources[idx].GetOutputPort())
 
            actors.append(vtk.vtkActor())
            actors[idx].SetMapper(mappers[idx])
 
            textmappers.append(vtk.vtkTextMapper())
            textmappers[idx].SetInput(item.GetClassName())
            textmappers[idx].SetTextProperty(textProperty)
 
            textactors.append(vtk.vtkActor2D())
            textactors[idx].SetMapper(textmappers[idx])
            textactors[idx].SetPosition(100, 16)
 
            renderers.append(vtk.vtkRenderer())
 
        gridDimensions = 4
 
        for idx in range(len(parametricObjects)):
            if idx < gridDimensions * gridDimensions:
                renderers.append(vtk.vtkRenderer)
 
        rendererSize = 200
 
        # setup the RenderWindow
        self.vtkWidget.GetRenderWindow().SetSize(rendererSize * gridDimensions, rendererSize * gridDimensions)
 
        # Add and position the renders to the render window.
        viewport = list()
        for row in range(gridDimensions):
            for col in range(gridDimensions):
                idx = row * gridDimensions + col
 
                viewport[:] = []
                viewport.append(float(col) * rendererSize / (gridDimensions * rendererSize))
                viewport.append(float(gridDimensions - (row+1)) * rendererSize / (gridDimensions * rendererSize))
                viewport.append(float(col+1)*rendererSize / (gridDimensions * rendererSize))
                viewport.append(float(gridDimensions - row) * rendererSize / (gridDimensions * rendererSize))
 
                if idx > (len(parametricObjects) - 1):
                    continue
 
                renderers[idx].SetViewport(viewport)
                self.vtkWidget.GetRenderWindow().AddRenderer(renderers[idx])
 
                renderers[idx].AddActor(actors[idx])
                renderers[idx].AddActor(textactors[idx])
                renderers[idx].SetBackground(0.2,0.3,0.4)
                renderers[idx].ResetCamera()
                renderers[idx].GetActiveCamera().Azimuth(30)
                renderers[idx].GetActiveCamera().Elevation(-30)
                renderers[idx].GetActiveCamera().Zoom(0.9)
                renderers[idx].ResetCameraClippingRange()
        
        self._initialized = False
class ExodusResultRenderWidget(QtGui.QWidget):
  def __init__(self, input_file_widget, execution_widget, qt_app, application):
    QtGui.QWidget.__init__(self)
    self.input_file_widget = input_file_widget
    self.qt_app = qt_app
    self.application = application

    self.plane = vtk.vtkPlane()
    self.plane.SetOrigin(-1000, 0, 0)
    self.plane.SetNormal(1, 0, 0)

    self.exodus_result = None

    # The multiple (from adaptivity)
    self.exodus_results = []

    self.timestep_to_exodus_result = {}

    self.file_name = None

    self.setupLuts()

    # The multiple (from adaptivity) file names we know of
    self.file_names = []

    self.current_max_timestep = 0

    # Whether or not there is new data to read
    self.new_stuff_to_read = False

    self.timer = QtCore.QTimer()
    self.timer.stop()
    self.timer.setInterval(100)
    self.timer.timeout.connect(self._updateData)

    self.execution_widget = execution_widget
    self.execution_widget.run_started.connect(self._runStarted)
    self.execution_widget.run_stopped.connect(self._runStopped)
    self.execution_widget.timestep_begin.connect(self._timestepBegin)
    self.execution_widget.timestep_end.connect(self._timestepEnd)

    self.main_layout = QtGui.QHBoxLayout()
#    self.main_layout.setSpacing(0)

    self.right_layout = QtGui.QVBoxLayout()

    self.left_layout = QtGui.QVBoxLayout()
    self.left_widget = QtGui.QWidget()
    self.left_widget.setMaximumWidth(1)

    self.left_widget.setLayout(self.left_layout)
    self.left_layout.setSizeConstraint(QtGui.QLayout.SetMinimumSize)

    self.main_layout.addWidget(self.left_widget)
    self.right_layout.setStretchFactor(self.left_layout, 0.01)
    self.main_layout.addLayout(self.right_layout)

#    self.setMinimumWidth(700)
    self.setLayout(self.main_layout)

    self.vtkwidget = QVTKRenderWindowInteractor(self)
#    self.vtkwidget.setMinimumHeight(300)

    # Create background, default to the gradient look
    self.renderer = vtk.vtkRenderer()
    self._showBlackBackgroundChanged(0)
    self.renderer.ResetCamera()

    self.right_layout.addWidget(self.vtkwidget)
    self.right_layout.setStretchFactor(self.vtkwidget, 100)

    self.vtkwidget.show()

    self.vtkwidget.GetRenderWindow().AddRenderer(self.renderer)
    self.vtkwidget.GetRenderWindow().GetInteractor().SetInteractorStyle(vtk.vtkInteractorStyleTrackballCamera())
    self.vtkwidget.Initialize()
    self.vtkwidget.Start()

    self.first = True

    self.exodus_result = None

    self.has_displacements = False
    self.current_displacement_magnitude = 1.0

    self.current_scale_x_magnitude = 1.0
    self.current_scale_y_magnitude = 1.0
    self.current_scale_z_magnitude = 1.0

    self.current_variable = None
    self.current_component = None

    # Holds a mapping of variable name to contour choices so they can be restored when variables are selected
    self.contour_choices = {}

    # If we are currently restoring contours then don't save the intermediate ones
    self.currently_restoring_contours = False
    self.setupControls()

    self.modifyUI()

  ''' This will be called after the interface is completely setup to allow an application to modify this tab '''
  def modifyUI(self):
    pass

  ''' Return the name to use for this tab '''
  def name(self):
    return 'Visualize'

  def setupControls(self):
    self.controls_widget = QtGui.QWidget()
    self.controls_layout = QtGui.QVBoxLayout()

    self.bottom_controls_layout = QtGui.QHBoxLayout()

    self.left_layout.addLayout(self.controls_layout)
    self.main_layout.setStretchFactor(self.left_layout, 0.1)

#    self.main_layout.addLayout(self.bottom_controls_layout)

    self.leftest_controls_layout = QtGui.QVBoxLayout()
    self.left_controls_layout = QtGui.QVBoxLayout()
    self.right_controls_layout = QtGui.QVBoxLayout()

    self.block_view_group_box = QtGui.QGroupBox('Show Blocks')
#    self.block_view_group_box.setMaximumWidth(200)
#    self.block_view_group_box.setMaximumHeight(200)

    self.block_view_layout = QtGui.QVBoxLayout()
    self.block_view_list = QtGui.QListView()
    self.block_view_model = QtGui.QStandardItemModel()
    self.block_view_model.itemChanged.connect(self._blockViewItemChanged)
    self.block_view_list.setModel(self.block_view_model)
    self.block_view_layout.addWidget(self.block_view_list)

    self.block_view_group_box.setLayout(self.block_view_layout)

    self.leftest_controls_layout.addWidget(self.block_view_group_box)

    self.controls_layout.addLayout(self.leftest_controls_layout)
    self.controls_layout.addLayout(self.left_controls_layout)
    self.controls_layout.addLayout(self.right_controls_layout)

    self.controls_layout.setStretchFactor(self.leftest_controls_layout,1.0)
    self.controls_layout.setStretchFactor(self.left_controls_layout,1.5)
    self.controls_layout.setStretchFactor(self.right_controls_layout,4.0)

    self.automatic_update_checkbox = QtGui.QCheckBox("Automatically Update")
    self.automatic_update_checkbox.setToolTip('Toggle automattically reading new timesteps as they finish computing')
    self.automatic_update_checkbox.setCheckState(QtCore.Qt.Checked)
    self.automatically_update = True
    self.automatic_update_checkbox.stateChanged[int].connect(self._automaticUpdateChanged)
#    self.left_controls_layout.addWidget(self.automatic_update_checkbox)

    # Create Group for viewer controls

    # Create the View Mesh toggle
    self.toggle_groupbox = QtGui.QGroupBox("View")
    self.toggle_groupbox.setMaximumHeight(70)
    self.toggle_layout = QtGui.QHBoxLayout()
    self.toggle_groupbox.setMaximumHeight(70)
    self.draw_edges_checkbox = QtGui.QCheckBox("View Mesh")
    self.draw_edges_checkbox.setToolTip('Show mesh elements')
    self.draw_edges_checkbox.stateChanged[int].connect(self._drawEdgesChanged)
    self.toggle_layout.addWidget(self.draw_edges_checkbox, alignment=QtCore.Qt.AlignHCenter)

    # Add a button for toggling the scalebar legend
    self.hide_scalebar_checkbox = QtGui.QCheckBox("Scalebar")
    self.hide_scalebar_checkbox.setToolTip('Toggle visibility of colorbar')
    self.hide_scalebar_checkbox.setCheckState(QtCore.Qt.Checked)
    self.hide_scalebar_checkbox.stateChanged[int].connect(self._hideScalebarChanged)
    self.toggle_layout.addWidget(self.hide_scalebar_checkbox, alignment=QtCore.Qt.AlignHCenter)

    # Add a button for toggling background to black
    self.show_black_background_checkbox = QtGui.QCheckBox("Black")
    self.show_black_background_checkbox.setToolTip('Toggle a black/gradient background')
    self.show_black_background_checkbox.stateChanged[int].connect(self._showBlackBackgroundChanged)
    self.toggle_layout.addWidget(self.show_black_background_checkbox, alignment=QtCore.Qt.AlignHCenter)

    # Create a vertical layout and add the toggles
    self.toggle_groupbox.setLayout(self.toggle_layout)
    self.reset_layout = QtGui.QVBoxLayout()
    self.reset_layout.addWidget(self.toggle_groupbox)

    self.displace_groupbox = QtGui.QGroupBox("Displace")
    self.displace_groupbox.setCheckable(True)
    self.displace_groupbox.setChecked(True)
    self.displace_groupbox.setDisabled(True)
    self.displace_groupbox.setMaximumHeight(70)
    self.displace_groupbox.toggled[bool].connect(self._displaceToggled)
    self.displace_layout = QtGui.QHBoxLayout()
    self.displace_layout.setSpacing(0)
    self.displace_groupbox.setLayout(self.displace_layout)

    self.displace_magnitude_label = QtGui.QLabel("Multiplier: ")
    self.displace_magnitude_text = QtGui.QLineEdit("1.0")
    self.displace_magnitude_text.setMaximumWidth(50)
    self.displace_magnitude_text.setMinimumWidth(10)
    self.displace_magnitude_text.returnPressed.connect(self._displaceMagnitudeTextReturn)

    self.displace_layout.addWidget(self.displace_magnitude_label, alignment=QtCore.Qt.AlignRight)
    self.displace_layout.addWidget(self.displace_magnitude_text, alignment=QtCore.Qt.AlignLeft)

    self.reset_layout.addWidget(self.displace_groupbox)

    self.scale_groupbox = QtGui.QGroupBox("Scale")
    self.scale_groupbox.setCheckable(True)
    self.scale_groupbox.setChecked(False)
    self.scale_groupbox.setDisabled(False)
    self.scale_groupbox.setMaximumHeight(70)
    self.scale_groupbox.toggled[bool].connect(self._scaleToggled)
    self.scale_layout = QtGui.QHBoxLayout()
    self.scale_layout.setSpacing(0)
    self.scale_groupbox.setLayout(self.scale_layout)

    self.scale_x_label = QtGui.QLabel("x: ")
    self.scale_x_text = QtGui.QLineEdit("1.0")
    self.scale_x_text.setMinimumWidth(10)
    self.scale_x_text.setMaximumWidth(50)

    self.scale_y_label = QtGui.QLabel("y: ")
    self.scale_y_text = QtGui.QLineEdit("1.0")
    self.scale_y_text.setMinimumWidth(10)
    self.scale_y_text.setMaximumWidth(50)

    self.scale_z_label = QtGui.QLabel("z: ")
    self.scale_z_text = QtGui.QLineEdit("1.0")
    self.scale_z_text.setMinimumWidth(10)
    self.scale_z_text.setMaximumWidth(50)

    self.scale_x_text.returnPressed.connect(self._scaleMagnitudeTextReturn)
    self.scale_y_text.returnPressed.connect(self._scaleMagnitudeTextReturn)
    self.scale_z_text.returnPressed.connect(self._scaleMagnitudeTextReturn)

    self.scale_layout.addWidget(self.scale_x_label, alignment=QtCore.Qt.AlignRight)
    self.scale_layout.addWidget(self.scale_x_text, alignment=QtCore.Qt.AlignLeft)

    self.scale_layout.addWidget(self.scale_y_label, alignment=QtCore.Qt.AlignRight)
    self.scale_layout.addWidget(self.scale_y_text, alignment=QtCore.Qt.AlignLeft)

    self.scale_layout.addWidget(self.scale_z_label, alignment=QtCore.Qt.AlignRight)
    self.scale_layout.addWidget(self.scale_z_text, alignment=QtCore.Qt.AlignLeft)

    self.reset_layout.addWidget(self.scale_groupbox)

    self.clip_groupbox = QtGui.QGroupBox("Clip")
    self.clip_groupbox.setToolTip('Toggle clipping mode where the solution can be sliced open')
    self.clip_groupbox.setCheckable(True)
    self.clip_groupbox.setChecked(False)
    self.clip_groupbox.setMaximumHeight(70)
    self.clip_groupbox.toggled[bool].connect(self._clippingToggled)
    clip_layout = QtGui.QHBoxLayout()

    self.clip_plane_combobox = QtGui.QComboBox()
    self.clip_plane_combobox.setToolTip('Direction of the normal for the clip plane')
    self.clip_plane_combobox.addItem('x')
    self.clip_plane_combobox.addItem('y')
    self.clip_plane_combobox.addItem('z')
    self.clip_plane_combobox.currentIndexChanged[str].connect(self._clipNormalChanged)

    clip_layout.addWidget(self.clip_plane_combobox)

    self.clip_plane_slider = QtGui.QSlider(QtCore.Qt.Horizontal)
    self.clip_plane_slider.setToolTip('Slide to change plane position')
    self.clip_plane_slider.setRange(0, 100)
    self.clip_plane_slider.setSliderPosition(50)
    self.clip_plane_slider.sliderReleased.connect(self._clipSliderReleased)
    self.clip_plane_slider.sliderMoved[int].connect(self._clipSliderMoved)
    clip_layout.addWidget(self.clip_plane_slider)
#     vbox->addStretch(1);
    self.clip_groupbox.setLayout(clip_layout)

    self.reset_layout.addWidget(self.clip_groupbox)



    self.view_layout = QtGui.QHBoxLayout()

    self.open_button = QtGui.QPushButton('Open')
    self.open_button.setMaximumWidth(100)
    self.open_button.setToolTip('Open an existing result')
    self.open_button.clicked.connect(self._clickedOpen)
    self.view_layout.addWidget(self.open_button, alignment=QtCore.Qt.AlignHCenter)

    self.save_button = QtGui.QPushButton('Save')
    self.save_button.setMaximumWidth(100)
    self.save_button.setToolTip('Save the current view to a file')
    self.save_button.clicked.connect(self._saveView)
    self.view_layout.addWidget(self.save_button, alignment=QtCore.Qt.AlignHCenter)

    self.reset_button = QtGui.QPushButton('Reset')
    self.reset_button.setMaximumWidth(100)
    self.reset_button.setToolTip('Recenter the camera on the current result')
    self.reset_button.clicked.connect(self._resetView)
    self.view_layout.addWidget(self.reset_button, alignment=QtCore.Qt.AlignHCenter)

    self.reset_layout.addLayout(self.view_layout)

    self.right_controls_layout.addLayout(self.reset_layout)


    self.contour_groupbox = QtGui.QGroupBox("Contour")
#    self.contour_groupbox.setMaximumHeight(10)
#    self.contour_groupbox.setMaximumHeight(70)
#    contour_groupbox_policy = QtGui.QSizePolicy()
    self.contour_groupbox.setSizePolicy(QtGui.QSizePolicy.Fixed,QtGui.QSizePolicy.Fixed)
    self.contour_layout = QtGui.QVBoxLayout()
    self.contour_groupbox.setLayout(self.contour_layout)

    self.variable_contour_layout = QtGui.QHBoxLayout()
    self.contour_layout.addLayout(self.variable_contour_layout)
    self.contour_label = QtGui.QLabel("Contour:")
    self.variable_contour = QtGui.QComboBox()
    self.variable_contour_is_nodal = {}
    self.variable_contour.setToolTip('Which variable to color by')
    self.variable_contour.currentIndexChanged[int].connect(self._contourVariableSelected)
#    self.variable_contour_layout.addWidget(self.contour_label, alignment=QtCore.Qt.AlignRight)
    self.variable_contour_layout.addWidget(self.variable_contour, alignment=QtCore.Qt.AlignHCenter)

#    self.component_layout = QtGui.QHBoxLayout()
    self.component_label = QtGui.QLabel("Component:")
    self.variable_component = QtGui.QComboBox()
    self.variable_component.setToolTip('If the variable is a vector this selects what component of that vector (or the Magnitude) to color by')
    self.variable_component.currentIndexChanged[str].connect(self._variableComponentSelected)
#    self.component_layout.addWidget(self.component_label, alignment=QtCore.Qt.AlignRight)
#    self.component_layout.addWidget(self.variable_component, alignment=QtCore.Qt.AlignLeft)
#    self.variable_contour_layout.addLayout(self.component_layout)
    self.variable_contour_layout.addWidget(self.variable_component, alignment=QtCore.Qt.AlignHCenter)


    self.minmax_contour_layout = QtGui.QVBoxLayout()
    self.contour_layout.addLayout(self.minmax_contour_layout)

    self.min_groupbox = QtGui.QGroupBox("Min")
    self.min_layout = QtGui.QHBoxLayout()
    self.min_groupbox.setLayout(self.min_layout)

    self.min_radio_layout = QtGui.QVBoxLayout()

    self.min_current_radio = QtGui.QRadioButton('Current')
    self.min_current_radio.setChecked(QtCore.Qt.Checked)
    self.min_current_radio.toggled.connect(self._updateContours)
    self.min_global_radio = QtGui.QRadioButton('Global')
    self.min_global_radio.toggled.connect(self._updateContours)
    self.min_radio_layout.addWidget(self.min_current_radio)
#    self.min_radio_layout.addWidget(self.min_global_radio)

    self.min_custom_layout = QtGui.QHBoxLayout()
    self.min_custom_layout.setSpacing(0)
    self.min_custom_radio = QtGui.QRadioButton()
    self.min_custom_radio.toggled.connect(self._updateContours)
    self.min_custom_text = QtGui.QLineEdit()
    self.min_custom_text.returnPressed.connect(self._updateContours)
    self.min_custom_text.setDisabled(True)
    self.min_custom_text.setMaximumWidth(100)
    self.min_custom_layout.addWidget(self.min_custom_radio, alignment=QtCore.Qt.AlignLeft)
    self.min_custom_layout.addWidget(self.min_custom_text, alignment=QtCore.Qt.AlignLeft)
    self.min_custom_layout.addStretch()

    self.min_layout.addLayout(self.min_radio_layout)
    self.min_layout.addLayout(self.min_custom_layout)

    self.minmax_contour_layout.addWidget(self.min_groupbox)



    self.max_groupbox = QtGui.QGroupBox("Max")
    self.max_layout = QtGui.QHBoxLayout()
    self.max_groupbox.setLayout(self.max_layout)

    self.max_radio_layout = QtGui.QVBoxLayout()

    self.max_current_radio = QtGui.QRadioButton('Current')
    self.max_current_radio.setChecked(QtCore.Qt.Checked)
    self.max_current_radio.toggled.connect(self._updateContours)
    self.max_global_radio = QtGui.QRadioButton('Global')
    self.max_global_radio.toggled.connect(self._updateContours)
    self.max_radio_layout.addWidget(self.max_current_radio)
#    self.max_radio_layout.addWidget(self.max_global_radio)

    self.max_custom_layout = QtGui.QHBoxLayout()
    self.max_custom_layout.setSpacing(0)
    self.max_custom_radio = QtGui.QRadioButton()
    self.max_custom_radio.toggled.connect(self._updateContours)
    self.max_custom_text = QtGui.QLineEdit()
    self.max_custom_text.returnPressed.connect(self._updateContours)
    self.max_custom_text.setDisabled(True)
    self.max_custom_text.setMaximumWidth(100)
    self.max_custom_layout.addWidget(self.max_custom_radio, alignment=QtCore.Qt.AlignLeft)
    self.max_custom_layout.addWidget(self.max_custom_text, alignment=QtCore.Qt.AlignLeft)
    self.max_custom_layout.addStretch()

    self.max_layout.addLayout(self.max_radio_layout)
    self.max_layout.addLayout(self.max_custom_layout)

    self.minmax_contour_layout.addWidget(self.max_groupbox)


#    self.component_layout = QtGui.QHBoxLayout()
    self.color_scheme_label = QtGui.QLabel("Color Scheme:")
    self.color_scheme_component = QtGui.QComboBox()
    self.color_scheme_component.addItem('HSV (Cool to Warm)')
    self.color_scheme_component.addItem('Diverging (Blue to Red)')
    self.color_scheme_component.addItem('Shock')
    self.color_scheme_component.setToolTip('The color scheme used byt the render view')
    self.color_scheme_component.currentIndexChanged[str].connect(self._colorSchemeSelected)

#    self.component_layout.addWidget(self.component_label, alignment=QtCore.Qt.AlignRight)
#    self.component_layout.addWidget(self.variable_component, alignment=QtCore.Qt.AlignLeft)
#    self.variable_contour_layout.addLayout(self.component_layout)

    self.minmax_contour_layout.addWidget(self.color_scheme_component)

    self.left_controls_layout.addWidget(self.contour_groupbox)


    self.beginning_button = QtGui.QToolButton()
    self.beginning_button.setToolTip('Go to first timestep')
    self.beginning_button.setIcon(QtGui.QIcon(pathname + '/resources/from_paraview/pqVcrFirst32.png'))
    self.beginning_button.clicked.connect(self._beginningClicked)

    self.back_button = QtGui.QToolButton()
    self.back_button.setToolTip('Previous timestep')
    self.back_button.setIcon(QtGui.QIcon(pathname + '/resources/from_paraview/pqVcrBack32.png'))
    self.back_button.clicked.connect(self._backClicked)

    self.play_button = QtGui.QToolButton()
    self.play_button.setToolTip('Play through the currently computed timesteps')
    self.play_button.setIcon(QtGui.QIcon(pathname + '/resources/from_paraview/pqVcrPlay32.png'))
    self.play_button.clicked.connect(self._playClicked)

    self.pause_button = QtGui.QToolButton()
    self.pause_button.setToolTip('If playing this will pause playback')
    self.pause_button.setDisabled(True)
    self.pause_button.setIcon(QtGui.QIcon(pathname + '/resources/from_paraview/pqVcrPause32.png'))
    self.pause_button.clicked.connect(self._pauseClicked)

    self.forward_button = QtGui.QToolButton()
    self.forward_button.setToolTip('Next timestep')
    self.forward_button.setIcon(QtGui.QIcon(pathname + '/resources/from_paraview/pqVcrForward32.png'))
    self.forward_button.clicked.connect(self._forwardClicked)

    self.last_button = QtGui.QToolButton()
    self.last_button.setToolTip('Go to last timestep')
    self.last_button.setIcon(QtGui.QIcon(pathname + '/resources/from_paraview/pqVcrLast32.png'))
    self.last_button.clicked.connect(self._lastClicked)

    self.loop_button = QtGui.QToolButton()
    self.loop_button.setToolTip('Toggle replaying all timesteps when the end is reached during playback.  Note that as new timesteps finish they will automatically be picked up and added to the end of the sequence.')
    self.loop_button.setCheckable(True)
    self.loop_button.setIcon(QtGui.QIcon(pathname + '/resources/from_paraview/pqVcrLoop24.png'))
    self.loop_button.toggled.connect(self._loopClicked)

    self.currently_looping = False

    self.time_slider_label = QtGui.QLabel("Timestep:")
    self.time_slider = QtGui.QSlider(QtCore.Qt.Horizontal)
    self.time_slider.setToolTip('Slide to select a timestep to display')
#    self.time_slider.setMaximumWidth(600)

    self.time_slider.valueChanged.connect(self._timeSliderChanged)
    self.time_slider.sliderReleased.connect(self._timeSliderReleased)

    self.time_slider_textbox = QtGui.QLineEdit()
    self.time_slider_textbox.setToolTip('Enter a number and press Enter to go to that timestep')
    self.time_slider_textbox.setMaximumWidth(30)
    self.time_slider_textbox.setMinimumWidth(30)
    self.time_slider_textbox.returnPressed.connect(self._sliderTextboxReturn)

    self.time_groupbox = QtGui.QGroupBox("Time")
    self.time_groupbox.setMaximumHeight(70)

    self.time_layout = QtGui.QHBoxLayout()
    self.time_layout.addWidget(self.beginning_button)
    self.time_layout.addWidget(self.back_button)
    self.time_layout.addWidget(self.play_button)
    self.time_layout.addWidget(self.pause_button)
    self.time_layout.addWidget(self.forward_button)
    self.time_layout.addWidget(self.last_button)
    self.time_layout.addWidget(self.loop_button)
    self.time_layout.addWidget(self.time_slider_label, alignment=QtCore.Qt.AlignRight)
    self.time_layout.addWidget(self.time_slider)
    self.time_layout.addWidget(self.time_slider_textbox, alignment=QtCore.Qt.AlignLeft)

    self.time_groupbox.setLayout(self.time_layout)

    self.right_layout.addWidget(self.time_groupbox)



  def _updateControls(self):
    self.old_contour = self.variable_contour.currentText()
    self.variable_contour.clear()
    self.has_displacements = False
    for variable in self.exodus_result.current_nodal_variables:
      if 'ObjectId' not in variable:
        self.variable_contour.addItem(variable)
        item_num = self.variable_contour.count()-1
        self.variable_contour.setItemIcon(item_num,QtGui.QIcon(pathname + '/resources/from_paraview/pqNodalData16.png'))
        self.variable_contour_is_nodal[item_num] = True
        if 'disp' in variable:
          self.has_displacements = True

    for variable in self.exodus_result.current_elemental_variables:
      if 'ObjectId' not in variable:
        self.variable_contour.addItem(variable)
        item_num = self.variable_contour.count()-1
        self.variable_contour.setItemIcon(item_num,QtGui.QIcon(pathname + '/resources/from_paraview/pqElemData16.png'))
        self.variable_contour_is_nodal[item_num] = False
        if 'disp' in variable:
          self.has_displacements = True

    if self.has_displacements:
      self.displace_groupbox.setDisabled(False)

    self.block_view_model.clear()
    for block in self.exodus_result.blocks:
      block_display_name = str(block)
      if block in self.exodus_result.block_to_name:
        block_display_name += ' : ' + self.exodus_result.block_to_name[block]

      item = QtGui.QStandardItem(str(block_display_name))
      item.exodus_block = block
      item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsUserCheckable)
      item.setCheckState(QtCore.Qt.Checked)
      self.block_view_model.appendRow(item)

    # Try to restore back to the view of the variable we were looking at
    found_index = self.variable_contour.findText(self.old_contour)
    if found_index != -1:
      self.variable_contour.setCurrentIndex(found_index)
    else: # If this variable doesn't exist then we are probably running a new simulation... try to reset the camera
      self._resetView()

    self.time_slider.setMinimum(0)
    self.time_slider.setMaximum(self.current_max_timestep)


  def setupLuts(self):
    self.luts = []

    # HSV (Blue to REd)  Default
    lut = vtk.vtkLookupTable()
    lut.SetHueRange(0.667, 0.0)
    lut.SetNumberOfColors(256)
    lut.Build()
    self.luts.append(lut)

    # Diverging (Cool to Warm) color scheme
    ctf = vtk.vtkColorTransferFunction()
    ctf.SetColorSpaceToDiverging()
    ctf.AddRGBPoint(0.0, 0.230, 0.299, 0.754)
    ctf.AddRGBPoint(1.0, 0.706, 0.016, 0.150)
    cc = list()
    for i in xrange(256):
      cc.append(ctf.GetColor(float(i) / 255.0))
    lut = vtk.vtkLookupTable()
    lut.SetNumberOfColors(256)
    for i, item in enumerate(cc):
      lut.SetTableValue(i, item[0], item[1], item[2], 1.0)
    lut.Build()
    self.luts.append(lut)

    # Shock
    ctf = vtk.vtkColorTransferFunction()
    min = 93698.4
    max = 230532
    ctf.AddRGBPoint(self._normalize(min, max,  93698.4),  0.0,         0.0,      1.0)
    ctf.AddRGBPoint(self._normalize(min, max, 115592.0),  0.0,         0.905882, 1.0)
    ctf.AddRGBPoint(self._normalize(min, max, 138853.0),  0.0941176,   0.733333, 0.027451)
    ctf.AddRGBPoint(self._normalize(min, max, 159378.0),  1.0,         0.913725, 0.00784314)
    ctf.AddRGBPoint(self._normalize(min, max, 181272.0),  1.0,         0.180392, 0.239216)
    ctf.AddRGBPoint(self._normalize(min, max, 203165.0),  1.0,         0.701961, 0.960784)
    ctf.AddRGBPoint(self._normalize(min, max, 230532.0),  1.0,         1.0,      1.0)
    cc = list()
    for i in xrange(256):
      cc.append(ctf.GetColor(float(i) / 255.0))
    lut = vtk.vtkLookupTable()
    lut.SetNumberOfColors(256)
    for i, item in enumerate(cc):
      lut.SetTableValue(i, item[0], item[1], item[2], 1.0)
    lut.Build()
    self.luts.append(lut)

    self.current_lut = self.luts[0]


  def _normalize(self, min, max, value):
    return (value - min) / (max - min)

  def _blockViewItemChanged(self, item):
    if item.checkState() == QtCore.Qt.Checked:
      self.exodus_result.showBlock(item.exodus_block)
      self.exodus_result.reader.Update()
      self.exodus_result.geom.Update()
      self.current_bounds = self.exodus_result.actor.GetBounds()
      self._updateContours()
    else:
      self.exodus_result.hideBlock(item.exodus_block)
      self.exodus_result.reader.Update()
      self.exodus_result.geom.Update()
      self.current_bounds = self.exodus_result.actor.GetBounds()
      self._updateContours()

  def _displaceToggled(self, value):
    self._timeSliderReleased()

  def _scaleToggled(self, value):
    self._timeSliderReleased()

  def _displaceMagnitudeTextReturn(self):
    self.current_displacement_magnitude = float(self.displace_magnitude_text.text())
    self._timeSliderReleased()

  def _scaleMagnitudeTextReturn(self):
    self.current_scale_x_magnitude = float(self.scale_x_text.text())
    self.current_scale_y_magnitude = float(self.scale_y_text.text())
    self.current_scale_z_magnitude = float(self.scale_z_text.text())
    self._timeSliderReleased()

  def _drawEdgesChanged(self, value):
    if value == QtCore.Qt.Checked:
      self.exodus_result.actor.GetProperty().EdgeVisibilityOn()
      self.exodus_result.clip_actor.GetProperty().EdgeVisibilityOn()
    else:
      self.exodus_result.actor.GetProperty().EdgeVisibilityOff()
      self.exodus_result.clip_actor.GetProperty().EdgeVisibilityOff()
    self.vtkwidget.repaint()

  ##
  # A method for toggling visiability of the scale bar legend, it is controlled
  # by the 'Hide Scalebar' toggle on the Visualize tab
  # @param value The interger value from the checkbox (1=checked)
  def _hideScalebarChanged(self, value):

    # Show when checked
    if value == QtCore.Qt.Checked:
      self.exodus_result.scalar_bar.VisibilityOn()

    # Hide when unchecked
    else:
      self.exodus_result.scalar_bar.VisibilityOff()

    # Update the GUI
    self.vtkwidget.repaint()

  ##
  # A method for toggling black background or gradient background, it is controlled
  # by the 'Black Background' toggle on the Visualize tab
  # @param value The interger value from the checkbox (1=checked)
  def _showBlackBackgroundChanged(self, value):

    # Black when checked
    if value == QtCore.Qt.Checked:
      self.renderer.SetBackground(0,0,0)
      self.renderer.SetGradientBackground(0)
      #self.renderer.ResetCamera()

    # Gradient when unchecked
    else:
      self.renderer.SetBackground(0,0,0)
      self.renderer.SetBackground(0.2,0.2,0.2)
      self.renderer.SetBackground2(1,1,1)
      self.renderer.SetGradientBackground(1)
      #self.renderer.ResetCamera()

    # Update thew GUI
    self.vtkwidget.repaint()

  def _fillComponentCombo(self, variable_name, components):
    self.variable_component.clear()
    self.variable_component.addItem('Magnitude')
    num_components = components[variable_name]
    if num_components > 1 and self.exodus_result.current_dim >= 2:
      self.variable_component.setDisabled(False)
      self.variable_component.addItem('X')
      self.variable_component.addItem('Y')
    else:
      self.variable_component.setDisabled(True)

    if num_components > 1 and  self.exodus_result.current_dim == 3:
      self.variable_component.addItem('Z')

  def _contourVariableSelected(self, index):

    value_string = str(self.variable_contour.itemText(index))
    self.current_variable = value_string
    self.current_variable_index = index

    if index in self.variable_contour_is_nodal:
      self.current_variable_is_nodal = self.variable_contour_is_nodal[index]
    else:
      self.current_variable_is_nodal = True

    self.currently_restoring_contours = True

    # Maybe results haven't been written yet...
    if not self.exodus_result.data.GetPointData().GetVectors(value_string) and not self.exodus_result.data.GetCellData().GetVectors(value_string):
      return

    if value_string in self.exodus_result.current_nodal_components:
      self._fillComponentCombo(value_string, self.exodus_result.current_nodal_components)
    elif value_string in self.exodus_result.current_elemental_components:
      self._fillComponentCombo(value_string, self.exodus_result.current_elemental_components)

    if self.current_variable not in self.contour_choices:
      self.contour_choices[self.current_variable] = ContourChoices()

    self.contour_choices[self.current_variable].restore(self)
    self.currently_restoring_contours = False


  def _variableComponentSelected(self, value):
    value_string = str(value)
    self.current_component = value_string
    if value_string == 'Magnitude':
      self.component_index = -1
    elif value_string == 'X':
      self.component_index = 0
    elif value_string == 'Y':
      self.component_index = 1
    elif value_string == 'Z':
      self.component_index = 2

    self._updateContours()

  def _updateContours(self):
    self.exodus_result.setColorScheme(self.current_lut)
    if self.component_index == -1:
      self.exodus_result.lut.SetVectorModeToMagnitude()
    elif self.component_index == 0:
      self.exodus_result.lut.SetVectorModeToComponent()
      self.exodus_result.lut.SetVectorComponent(0)
    elif self.component_index == 1:
      self.exodus_result.lut.SetVectorModeToComponent()
      self.exodus_result.lut.SetVectorComponent(1)
    elif self.component_index == 2:
      self.exodus_result.lut.SetVectorModeToComponent()
      self.exodus_result.lut.SetVectorComponent(2)

    if self.clip_groupbox.isChecked():
      self.exodus_result.clipper.Modified()
      self.exodus_result.clipper.Update()
      self.exodus_result.clip_geom.Update()
      self.exodus_result.clip_mapper.Update()

    data = None
    if self.current_variable_is_nodal and self.current_variable in self.exodus_result.current_nodal_components:
      data = self.exodus_result.data.GetPointData().GetVectors(self.current_variable)
      self.exodus_result.mapper.SetScalarModeToUsePointFieldData()
      self.exodus_result.clip_mapper.SetScalarModeToUsePointFieldData()
    elif self.current_variable in self.exodus_result.current_elemental_components:
      data = self.exodus_result.data.GetCellData().GetVectors(self.current_variable)
      self.exodus_result.mapper.SetScalarModeToUseCellFieldData()
      self.exodus_result.clip_mapper.SetScalarModeToUseCellFieldData()

    self.exodus_result.mapper.SelectColorArray(self.current_variable)
    self.exodus_result.clip_mapper.SelectColorArray(self.current_variable)

    if data:
      self.current_range = data.GetRange(self.component_index)

      if self.min_current_radio.isChecked():
        self.min_custom_text.setText(str(self.current_range[0]))
        self.min_custom_text.setCursorPosition(0)

      if self.max_current_radio.isChecked():
        self.max_custom_text.setText(str(self.current_range[1]))
        self.max_custom_text.setCursorPosition(0)

      if self.min_custom_radio.isChecked():
        self.min_custom_text.setDisabled(False)
      else:
        self.min_custom_text.setDisabled(True)

      if self.max_custom_radio.isChecked():
        self.max_custom_text.setDisabled(False)
      else:
        self.max_custom_text.setDisabled(True)

      min = 0.0
      try:
        min = float(self.min_custom_text.displayText())
      except:
        min = 0.0

      max = 0.0
      try:
        max = float(self.max_custom_text.displayText())
      except:
        max = 0.0

      if self.current_variable not in self.contour_choices:
        self.contour_choices[self.current_variable] = ContourChoices()

      if not self.currently_restoring_contours:
        self.contour_choices[self.current_variable].save(self)

      the_range = (min, max)

      if min <= max:
        self.exodus_result.mapper.SetScalarRange(the_range)
        self.exodus_result.clip_mapper.SetScalarRange(the_range)


    self.exodus_result.scalar_bar.SetTitle(self.current_variable)
    self.renderer.AddActor2D(self.exodus_result.scalar_bar)
    self.vtkwidget.repaint()

  def _colorSchemeSelected(self, value):
    self.current_lut = self.luts[self.color_scheme_component.currentIndex()]
    self._updateContours()

  def _openFile(self, file_name):
    self._clear()

    self.base_stamp = os.path.getmtime(file_name)
    self.file_name = str(file_name)

    self.new_stuff_to_read = True
    self._updateData()
    self._updateData() # Call it again to read any adaptive results

    self._lastClicked() # Go to the last timestep

    self._resetView() # Reset the camera

  def _clickedOpen(self):
    file_name = QtGui.QFileDialog.getOpenFileName(self, "Open Result", "~/", "Input Files (*.e)")

    if not isinstance(file_name, basestring): # This happens when using pyside
        file_name = file_name[0]

    if file_name:
      self._openFile(file_name)

  def _resetView(self):
    self.renderer.ResetCamera()
    fp = self.renderer.GetActiveCamera().GetFocalPoint()
    p = self.renderer.GetActiveCamera().GetPosition()
    dist = math.sqrt( (p[0]-fp[0])**2 + (p[1]-fp[1])**2 + (p[2]-fp[2])**2 )
    self.renderer.GetActiveCamera().SetPosition(fp[0], fp[1], fp[2]+dist)
    self.renderer.GetActiveCamera().SetViewUp(0.0, 1.0, 0.0)
    self.vtkwidget.repaint()

  def _saveView(self):
    file_name = QtGui.QFileDialog.getSaveFileName(self, "Image File Name", "~/", "Image Files (*.png)")

    if not isinstance(file_name, basestring): # This happens when using pyside
        file_name = file_name[0]

    if file_name != '':
      w2i = vtk.vtkWindowToImageFilter()
      writer = vtk.vtkPNGWriter()
      w2i.SetInput(self.vtkwidget.GetRenderWindow())
      w2i.Update()
      writer.SetInputConnection(w2i.GetOutputPort())
      writer.SetFileName(str(file_name))
      self.vtkwidget.GetRenderWindow().Render()
      writer.Write()

  def _automaticUpdateChanged(self, value):
    if value == QtCore.Qt.Checked:
      self.automatically_update = True
    else:
      self.automatically_update = False

  def _beginningClicked(self):
    self.time_slider.setSliderPosition(0)
    self._timeSliderReleased()

  def _backClicked(self):
    self.time_slider.setSliderPosition(self.time_slider.sliderPosition()-1)
    self._timeSliderReleased()

  def _playClicked(self):
    self.play_button.setDisabled(True)
    self.pause_button.setDisabled(False)
    self.currently_playing = True

    first = True
    while((first or self.currently_looping) and self.currently_playing):
      first = False

      # If the slider is at the end then start over
      self.qt_app.processEvents()
      time.sleep(0.02)
      self.qt_app.processEvents()
      if self.time_slider.sliderPosition() == self.time_slider.maximum():
        self.time_slider.setSliderPosition(0)

      while self.time_slider.sliderPosition() < self.time_slider.maximum():
        self.time_slider.setSliderPosition(self.time_slider.sliderPosition()+1)
        self.qt_app.processEvents()
        self._timeSliderReleased()
        time.sleep(0.02)
        self.qt_app.processEvents()
        if not self.currently_playing:
          break

    self.play_button.setDisabled(False)
    self.pause_button.setDisabled(True)

  def _pauseClicked(self):
    self.play_button.setDisabled(False)
    self.pause_button.setDisabled(True)
    self.currently_playing = False

  def _forwardClicked(self):
    self.time_slider.setSliderPosition(self.time_slider.sliderPosition()+1)
    self._timeSliderReleased()

  def _lastClicked(self):
    self.time_slider.setSliderPosition(self.time_slider.maximum())
    self._timeSliderReleased()

  def _loopClicked(self, state):
    if state:
      self.currently_looping = True
    else:
      self.currently_looping = False

  def _timeSliderChanged(self):
    self.time_slider_textbox.setText(str(self.time_slider.sliderPosition()))

  def _timeSliderReleased(self):
    textbox_string = self.time_slider_textbox.text()
    if textbox_string == '':
      textbox_string = str(self.exodus_result.min_timestep)

    if int(textbox_string) in self.timestep_to_exodus_result:
      for actor in self.exodus_result.current_actors:
        self.renderer.RemoveActor(actor)
      self.exodus_result = self.timestep_to_exodus_result[int(textbox_string)]

      if self.clip_groupbox.isChecked():
        self.renderer.AddActor(self.exodus_result.clip_actor)
        if self.draw_edges_checkbox.checkState() == QtCore.Qt.Checked:
          self.exodus_result.clip_actor.GetProperty().EdgeVisibilityOn()
        else:
          self.exodus_result.clip_actor.GetProperty().EdgeVisibilityOff()
      else:
        self.renderer.AddActor(self.exodus_result.actor)
        if self.draw_edges_checkbox.checkState() == QtCore.Qt.Checked:
          self.exodus_result.actor.GetProperty().EdgeVisibilityOn()
        else:
          self.exodus_result.actor.GetProperty().EdgeVisibilityOff()

      num_block_view_items = self.block_view_model.rowCount()
      for i in xrange(num_block_view_items):
        item = self.block_view_model.item(i)
        if item.checkState() == QtCore.Qt.Checked:
          self.exodus_result.showBlock(item.exodus_block)
        else:
          self.exodus_result.hideBlock(item.exodus_block)

      if self.has_displacements and self.displace_groupbox.isChecked():
        self.exodus_result.reader.SetApplyDisplacements(1)
        self.exodus_result.reader.SetDisplacementMagnitude(float(self.current_displacement_magnitude))
      else:
        self.exodus_result.reader.SetApplyDisplacements(0)

      if self.scale_groupbox.isChecked():
        self.exodus_result.actor.SetScale(self.current_scale_x_magnitude, self.current_scale_y_magnitude, self.current_scale_z_magnitude)
      else:
        self.exodus_result.actor.SetScale(1.0, 1.0, 1.0)

    if self.exodus_result.reader:
      self.exodus_result.reader.SetTimeStep(self.timestep_to_timestep[int(textbox_string)])
      self.exodus_result.reader.Update()
      self.exodus_result.geom.Update()
      self.current_bounds = self.exodus_result.actor.GetBounds()
      self._updateContours()

  def _sliderTextboxReturn(self):
    self.time_slider.setSliderPosition(int(self.time_slider_textbox.text()))
    self._timeSliderReleased()

  def _associateResultsWithTimesteps(self):
    self.timestep_to_exodus_result = {}
    self.timestep_to_timestep = {}
    self.current_max_timestep = -1
    for result in self.exodus_results:
      result.reader.UpdateTimeInformation()
      min = result.reader.GetTimeStepRange()[0]
      max = result.reader.GetTimeStepRange()[1]
      for timestep in xrange(min, max+1):
        self.current_max_timestep += 1
        self.timestep_to_exodus_result[self.current_max_timestep] = result
        self.timestep_to_timestep[self.current_max_timestep] = timestep

  def _updateData(self):
    # Check to see if there are new exodus files with adapted timesteps in them.
    if self.file_name and self.exodus_result:
      for file_name in sorted(glob.glob(self.file_name + '-s*')):
        file_stamp = os.path.getmtime(file_name)
        if int(file_stamp) >= int(self.base_stamp) and int(file_stamp) <= int(time.time() - 1) and file_name not in self.file_names:
          self.file_names.append(file_name)
          exodus_result = ExodusResult(self, self.plane)
          exodus_result.setFileName(file_name, self.current_lut)
          self.exodus_results.append(exodus_result)
          self.new_stuff_to_read = True

    if not self.exodus_result:
      if not self.file_name: # Might have been set by opening a file
        output_file_names = self.input_file_widget.getOutputFileNames()
      else:
        output_file_names = [self.file_name]

      output_file = ''

      for file_name in output_file_names:
        if '.e' in file_name and os.path.exists(file_name):
          file_stamp = os.path.getmtime(file_name)

          if int(file_stamp) >= int(self.base_stamp) and int(file_stamp) <= int(time.time() - 1) and file_name not in self.file_names:
            self.file_name = file_name
            self.exodus_result = ExodusResult(self, self.plane)
            self.exodus_result.setFileName(file_name, self.current_lut)
            self.exodus_results.append(self.exodus_result)
            self.current_max_timestep = self.exodus_result.max_timestep
            self.renderer.AddActor(self.exodus_result.actor)
            self._drawEdgesChanged(self.draw_edges_checkbox.checkState())

            if self.first:
              self.first = False
              self.renderer.ResetCamera()

            # Avoid z-buffer fighting
            vtk.vtkPolyDataMapper().SetResolveCoincidentTopologyToPolygonOffset()

            if self.clip_groupbox.isChecked():
              _clippingToggled(True)

            self.vtkwidget.repaint()
            self._updateControls()
            self.time_slider.setSliderPosition(self.current_max_timestep)

    if self.new_stuff_to_read and self.exodus_result and self.automatically_update:
      self._associateResultsWithTimesteps()
#      self.exodus_result.reader.UpdateTimeInformation()
#      range = self.exodus_result.reader.GetTimeStepRange()
#      self.exodus_result.min_timestep = range[0]
#      self.exodus_result.max_timestep = range[1]
      self.time_slider.setMinimum(0)

      # Only automatically move forward if they're on the current step
      if self.time_slider.sliderPosition() == self.time_slider.maximum():
        self.time_slider.setMaximum(self.current_max_timestep)
        self.time_slider.setSliderPosition(self.current_max_timestep)
        self._timeSliderReleased()
        if self.clip_groupbox.isChecked():
          self._clipSliderReleased()
        self.vtkwidget.repaint()
      else:
        self.time_slider.setMaximum(self.current_max_timestep)

    self.new_stuff_to_read = False

  def _timestepBegin(self):
    self.new_stuff_to_read = True

  def _timestepEnd(self):
    pass


  def _clear(self):
    self.application.addExodusResultActors(self.renderer)
    self.file_name = None
    self.file_names = []

    if not self.exodus_result:
      return

    for actor in self.exodus_result.current_actors:
      self.renderer.RemoveActor(actor)

    del self.exodus_result.current_actors[:]

    self.exodus_result = None
    self.exodus_results = []
    self.timestep_to_exodus_result = {}

  def _runStarted(self):
    # Set the base time
    self.base_stamp = time.time()
    self._clear()
    self.timer.start()

  def _finalRead(self):
    self.new_stuff_to_read = True # Set this to true so we get one more update
    # Do it twice in case of adapted results
    self._updateData()
    self._updateData()

  def _runStopped(self):
    self.timer.stop()
    self.run_stopped_timer = QtCore.QTimer()
    self.run_stopped_timer.setInterval(1000) # Wait a second before updating the plots one last time
    self.run_stopped_timer.setSingleShot(True)
    self.run_stopped_timer.timeout.connect(self._finalRead)
    self.run_stopped_timer.start()

  def _clippingToggled(self, value):
    if value:
      self.renderer.RemoveActor(self.exodus_result.current_actor)
      self.renderer.AddActor(self.exodus_result.clip_actor)
      self.exodus_result.current_actor = self.exodus_result.clip_actor
      self.clip_plane_slider.setSliderPosition(50)
      self._clipSliderMoved(50)
      self._clipSliderReleased()
    else:
      self.renderer.RemoveActor(self.exodus_result.current_actor)
      self.renderer.AddActor(self.exodus_result.actor)
      self.exodus_result.current_actor = self.exodus_result.actor

    self.vtkwidget.repaint()

  def _clipNormalChanged(self, value):
    self.plane.SetOrigin(self.current_bounds[0],
                         self.current_bounds[2],
                         self.current_bounds[4])
    if value == 'x':
      self.plane.SetNormal(1, 0, 0)
    elif value == 'y':
      self.plane.SetNormal(0, 1, 0)
    else:
      self.plane.SetNormal(0, 0, 1)

    self.clip_plane_slider.setSliderPosition(50)
    self._clipSliderMoved(50)

    self.vtkwidget.repaint()

  def _clipSliderReleased(self):
    self._updateContours()
    self.vtkwidget.repaint()

  def _clipSliderMoved(self, value):
    direction = str(self.clip_plane_combobox.currentText())

    min = 0
    max = 0

    if direction == 'x':
      min = self.current_bounds[0]
      max = self.current_bounds[1]
    elif direction == 'y':
      min = self.current_bounds[2]
      max = self.current_bounds[3]
    elif direction == 'z':
      min = self.current_bounds[4]
      max = self.current_bounds[5]

    step_size = (max - min)/100.0
    steps = value
    distance = float(steps)*step_size
    position = min + distance

    old = self.plane.GetOrigin()
    self.plane.SetOrigin(position if direction == 'x' else old[0],
                         position if direction == 'y' else old[1],
                         position if direction == 'z' else old[2])

    self._updateContours()
    self.vtkwidget.repaint()
Exemple #46
0
    def __init__(self, parent=None):
        super(VTKFrame, self).__init__(parent)

        self.vtkWidget = QVTKRenderWindowInteractor(self)
        vl = QtGui.QVBoxLayout(self)
        vl.addWidget(self.vtkWidget)
        vl.setContentsMargins(0, 0, 0, 0)

        self.ren = vtk.vtkRenderer()
        self.ren.SetBackground(0.1, 0.2, 0.4)
        self.vtkWidget.GetRenderWindow().AddRenderer(self.ren)
        self.iren = self.vtkWidget.GetRenderWindow().GetInteractor()

        g = vtk.vtkMutableDirectedGraph()
        v1 = g.AddVertex()
        v2 = g.AddVertex()
        v3 = g.AddVertex()

        ### g.AddEdge(v1, v2)
        g.AddGraphEdge(v1, v2)
        g.AddGraphEdge(v2, v3)
        g.AddGraphEdge(v3, v1)

        # Do layout manually before handing graph to the view.
        # This allows us to know the positions of edge arrows.
        graphLayoutView = vtk.vtkGraphLayoutView()

        layout = vtk.vtkGraphLayout()
        strategy = vtk.vtkSimple2DLayoutStrategy()
        layout.SetInput(g)
        layout.SetLayoutStrategy(strategy)

        # Tell the view to use the vertex layout we provide
        graphLayoutView.SetLayoutStrategyToPassThrough()
        # The arrows will be positioned on a straight line between two
        # vertices so tell the view not to draw arcs for parallel edges
        graphLayoutView.SetEdgeLayoutStrategyToPassThrough()

        # Add the graph to the view. This will render vertices and edges,
        # but not edge arrows.
        graphLayoutView.AddRepresentationFromInputConnection(
            layout.GetOutputPort())

        # Manually create an actor containing the glyphed arrows.
        graphToPoly = vtk.vtkGraphToPolyData()
        graphToPoly.SetInputConnection(layout.GetOutputPort())
        graphToPoly.EdgeGlyphOutputOn()

        # Set the position (0: edge start, 1:edge end) where
        # the edge arrows should go.
        graphToPoly.SetEdgeGlyphPosition(0.98)

        # Make a simple edge arrow for glyphing.
        arrowSource = vtk.vtkGlyphSource2D()
        arrowSource.SetGlyphTypeToEdgeArrow()
        arrowSource.SetScale(0.1)
        arrowSource.Update()

        # Use Glyph3D to repeat the glyph on all edges.
        arrowGlyph = vtk.vtkGlyph3D()
        arrowGlyph.SetInputConnection(0, graphToPoly.GetOutputPort(1))
        arrowGlyph.SetInputConnection(1, arrowSource.GetOutputPort())

        # Create a mapper
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(arrowGlyph.GetOutputPort())

        # Create an actor
        actor = vtk.vtkActor()
        actor.SetMapper(mapper)

        self.ren.AddActor(actor)
        self.ren.ResetCamera()

        self._initialized = False
  def __init__(self, input_file_widget, execution_widget, qt_app, application):
    QtGui.QWidget.__init__(self)
    self.input_file_widget = input_file_widget
    self.qt_app = qt_app
    self.application = application

    self.plane = vtk.vtkPlane()
    self.plane.SetOrigin(-1000, 0, 0)
    self.plane.SetNormal(1, 0, 0)

    self.exodus_result = None

    # The multiple (from adaptivity)
    self.exodus_results = []

    self.timestep_to_exodus_result = {}

    self.file_name = None

    self.setupLuts()

    # The multiple (from adaptivity) file names we know of
    self.file_names = []

    self.current_max_timestep = 0

    # Whether or not there is new data to read
    self.new_stuff_to_read = False

    self.timer = QtCore.QTimer()
    self.timer.stop()
    self.timer.setInterval(100)
    self.timer.timeout.connect(self._updateData)

    self.execution_widget = execution_widget
    self.execution_widget.run_started.connect(self._runStarted)
    self.execution_widget.run_stopped.connect(self._runStopped)
    self.execution_widget.timestep_begin.connect(self._timestepBegin)
    self.execution_widget.timestep_end.connect(self._timestepEnd)

    self.main_layout = QtGui.QHBoxLayout()
#    self.main_layout.setSpacing(0)

    self.right_layout = QtGui.QVBoxLayout()

    self.left_layout = QtGui.QVBoxLayout()
    self.left_widget = QtGui.QWidget()
    self.left_widget.setMaximumWidth(1)

    self.left_widget.setLayout(self.left_layout)
    self.left_layout.setSizeConstraint(QtGui.QLayout.SetMinimumSize)

    self.main_layout.addWidget(self.left_widget)
    self.right_layout.setStretchFactor(self.left_layout, 0.01)
    self.main_layout.addLayout(self.right_layout)

#    self.setMinimumWidth(700)
    self.setLayout(self.main_layout)

    self.vtkwidget = QVTKRenderWindowInteractor(self)
#    self.vtkwidget.setMinimumHeight(300)

    # Create background, default to the gradient look
    self.renderer = vtk.vtkRenderer()
    self._showBlackBackgroundChanged(0)
    self.renderer.ResetCamera()

    self.right_layout.addWidget(self.vtkwidget)
    self.right_layout.setStretchFactor(self.vtkwidget, 100)

    self.vtkwidget.show()

    self.vtkwidget.GetRenderWindow().AddRenderer(self.renderer)
    self.vtkwidget.GetRenderWindow().GetInteractor().SetInteractorStyle(vtk.vtkInteractorStyleTrackballCamera())
    self.vtkwidget.Initialize()
    self.vtkwidget.Start()

    self.first = True

    self.exodus_result = None

    self.has_displacements = False
    self.current_displacement_magnitude = 1.0

    self.current_scale_x_magnitude = 1.0
    self.current_scale_y_magnitude = 1.0
    self.current_scale_z_magnitude = 1.0

    self.current_variable = None
    self.current_component = None

    # Holds a mapping of variable name to contour choices so they can be restored when variables are selected
    self.contour_choices = {}

    # If we are currently restoring contours then don't save the intermediate ones
    self.currently_restoring_contours = False
    self.setupControls()

    self.modifyUI()
Exemple #48
0
class VTKFrame(QtGui.QFrame):
    def __init__(self, parent = None):
        super(VTKFrame, self).__init__(parent)

        self.vtkWidget = QVTKRenderWindowInteractor(self)
        vl = QtGui.QVBoxLayout(self)
        vl.addWidget(self.vtkWidget)
        vl.setContentsMargins(0, 0, 0, 0)
 
        self.ren = vtk.vtkRenderer()
        self.ren.SetBackground(0.2, 0.3, 0.4)
        self.vtkWidget.GetRenderWindow().AddRenderer(self.ren)
        self.iren = self.vtkWidget.GetRenderWindow().GetInteractor()
 
        # Create Spiral tube
        nV = 256 #No. of vertices
        nCyc = 5 #No. of spiral cycles
        rS = 2.0   #Spiral radius
        h = 10.0
        nTv = 8 #No. of surface elements for each tube vertex

        points = vtk.vtkPoints()
        for i in range(nV):
            vX = rS * math.cos(2 * math.pi * nCyc * i / (nV-1))
            vY = rS * math.sin(2 * math.pi * nCyc * i / (nV-1))
            vZ = h * i / nV
            points.InsertPoint(i, vX, vY, vZ)

        lines = vtk.vtkCellArray()
        lines.InsertNextCell(nV)
        for i in range(nV):
            lines.InsertCellPoint(i)

        polyData = vtk.vtkPolyData()
        polyData.SetPoints(points)
        polyData.SetLines(lines)

        tube = vtk.vtkTubeFilter()
        tube.SetInput(polyData)
        tube.SetNumberOfSides(nTv)
 
        # Create a mapper
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(tube.GetOutputPort())
 
        # Create an actor
        actor = vtk.vtkActor()
        actor.SetMapper(mapper)
 
        self.ren.AddActor(actor)
        self.ren.ResetCamera()

        self._initialized = False

    def showEvent(self, evt):
        if not self._initialized:
            self.iren.Initialize()
            #self.startTimer(30)
            self._initialized = True

    def timerEvent(self, evt):
        self.ren.GetActiveCamera().Azimuth(1)
        self.vtkWidget.GetRenderWindow().Render()
Exemple #49
0
    def __init__(self, parent=None):
        super(VTKFrame, self).__init__(parent)

        self.vtkWidget = QVTKRenderWindowInteractor(self)
        vl = QtGui.QVBoxLayout(self)
        vl.addWidget(self.vtkWidget)
        vl.setContentsMargins(0, 0, 0, 0)

        self.ren = vtk.vtkRenderer()
        self.ren.SetBackground(0.1, 0.2, 0.4)
        self.vtkWidget.GetRenderWindow().AddRenderer(self.ren)
        self.iren = self.vtkWidget.GetRenderWindow().GetInteractor()

        # Create source
        #Setup the coordinates of eight points
        #(the two faces must be in counter clockwise order as viewd from the outside)
        P0 = [0.0, 0.0, 0.0]
        P1 = [1.0, 0.0, 0.0]
        P2 = [1.0, 1.0, 0.0]
        P3 = [0.0, 1.0, 0.0]
        P4 = [0.0, 0.0, 1.0]
        P5 = [1.0, 0.0, 1.0]
        P6 = [1.0, 1.0, 1.0]
        P7 = [0.0, 1.0, 1.0]

        #Create the points
        points = vtk.vtkPoints()
        points.InsertNextPoint(P0)
        points.InsertNextPoint(P1)
        points.InsertNextPoint(P2)
        points.InsertNextPoint(P3)
        points.InsertNextPoint(P4)
        points.InsertNextPoint(P5)
        points.InsertNextPoint(P6)
        points.InsertNextPoint(P7)

        #Create a hexahedron from the points
        hexa = vtk.vtkHexahedron()
        hexa.GetPointIds().SetId(0, 0)
        hexa.GetPointIds().SetId(1, 1)
        hexa.GetPointIds().SetId(2, 2)
        hexa.GetPointIds().SetId(3, 3)
        hexa.GetPointIds().SetId(4, 4)
        hexa.GetPointIds().SetId(5, 5)
        hexa.GetPointIds().SetId(6, 6)
        hexa.GetPointIds().SetId(7, 7)

        #Add the hexahedron to a cell array
        hexs = vtk.vtkCellArray()
        hexs.InsertNextCell(hexa)

        #Add the points and hexahedron to an unstructured grid
        uGrid = vtk.vtkUnstructuredGrid()
        uGrid.SetPoints(points)
        uGrid.InsertNextCell(hexa.GetCellType(), hexa.GetPointIds())

        surface = vtk.vtkDataSetSurfaceFilter()
        surface.SetInput(uGrid)
        surface.Update()

        aBeamMapper = vtk.vtkDataSetMapper()
        aBeamMapper.SetInput(surface.GetOutput())
        #aBeamMapper.SetInput(uGrid)
        aBeamActor = vtk.vtkActor()
        aBeamActor.SetMapper(aBeamMapper)
        aBeamActor.AddPosition(0, 0, 0)
        aBeamActor.GetProperty().SetColor(1, 1, 0)
        aBeamActor.GetProperty().SetOpacity(0.60)
        aBeamActor.GetProperty().EdgeVisibilityOn()
        aBeamActor.GetProperty().SetEdgeColor(1, 1, 1)
        aBeamActor.GetProperty().SetLineWidth(1.5)

        #create a plane to cut,here it cuts in the XZ direction (xz normal=(1,0,0);XY =(0,0,1),YZ =(0,1,0)
        plane = vtk.vtkPlane()
        plane.SetOrigin(0.5, 0, 0)
        plane.SetNormal(1, 0, 0)

        #create cutter
        cutter = vtk.vtkCutter()
        cutter.SetCutFunction(plane)
        cutter.SetInput(aBeamActor.GetMapper().GetInput())
        cutter.Update()
        cutterMapper = vtk.vtkDataSetMapper()
        cutterMapper.SetInputConnection(cutter.GetOutputPort())

        #create plane actor
        planeActor = vtk.vtkActor()
        planeActor.GetProperty().SetColor(1, 0.5, 0.5)
        planeActor.GetProperty().SetLineWidth(2)
        planeActor.SetMapper(cutterMapper)

        #Add the actor to the scene
        self.ren.AddActor(aBeamActor)
        self.ren.AddActor(planeActor)
        self.ren.ResetCamera()

        self._initialized = False
Exemple #50
0
 tool2.toggled.connect(editSwc)
 toolbar1.addAction(tool2)
 tool3 = QtGui.QAction(toolbar1)
 tool3_icon = QtGui.QIcon()
 tool3_icon.addFile(r'G:\sulei\workplace\TraceTool\Resource\Science.png')
 tool3.setIcon(tool3_icon)
 tool3.triggered.connect(changeLineWidth)
 toolbar1.addAction(tool3)
 
 
 mainwin.addToolBar(toolbar1)
 mainwin.setMenuBar(menubar1)
 mainwin_location = QtCore.QRect(600, 300, 400, 400)
 mainwin.setMaximumSize(400, 400)
 mainwin.setGeometry(mainwin_location)
 central_widget = QtGui.QWidget(mainwin)
 mainwin.setCentralWidget(central_widget)
 layout1 = QtGui.QHBoxLayout()
 central_widget.setLayout(layout1)
 vtk_widget = QVTKRenderWindowInteractor(central_widget)
 vtk_widget.setMinimumSize(50, 50)
 layout1.addWidget(vtk_widget)
 vtk_widget.setSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
 ren = vtk.vtkRenderer()
 style1 = SwcEditStyle()
 iren = vtk_widget.GetRenderWindow().GetInteractor()
 iren.SetInteractorStyle(style1)
 vtk_widget.Initialize()
 vtk_widget.Start()
 mainwin.show()
 sys.exit(app.exec_())
Exemple #51
0
    def setupUi(self, Form):
        Form.setObjectName(_fromUtf8("Form"))
        Form.resize(1142, 672)
        self.horizontalLayout = QtGui.QHBoxLayout(Form)
        self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
        self.gridLayout_2 = QtGui.QGridLayout()
        self.gridLayout_2.setSizeConstraint(QtGui.QLayout.SetMinimumSize)
        self.gridLayout_2.setContentsMargins(0, -1, -1, 0)
        self.gridLayout_2.setHorizontalSpacing(6)
        self.gridLayout_2.setObjectName(_fromUtf8("gridLayout_2"))
        self.verticalLayout = QtGui.QVBoxLayout()
        self.verticalLayout.setSpacing(6)
        self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
        self.label = QtGui.QLabel(Form)
        font = QtGui.QFont()
        font.setFamily(_fromUtf8("Yu Gothic UI"))
        font.setPointSize(11)
        font.setBold(True)
        font.setWeight(75)
        self.label.setFont(font)
        self.label.setAlignment(QtCore.Qt.AlignCenter)
        self.label.setObjectName(_fromUtf8("label"))
        self.verticalLayout.addWidget(self.label)
        self.XYPlaneWidget = QVTKRenderWindowInteractor(Form)
        self.XYPlaneWidget.setObjectName(_fromUtf8("XYPlaneWidget"))
        self.verticalLayout.addWidget(self.XYPlaneWidget)
        self.XYSlider = QtGui.QSlider(Form)
        self.XYSlider.setOrientation(QtCore.Qt.Horizontal)
        self.XYSlider.setObjectName(_fromUtf8("XYSlider"))
        self.verticalLayout.addWidget(self.XYSlider)
        self.verticalLayout.setStretch(1, 1)
        self.gridLayout_2.addLayout(self.verticalLayout, 0, 0, 1, 1)
        self.verticalLayout_2 = QtGui.QVBoxLayout()
        self.verticalLayout_2.setObjectName(_fromUtf8("verticalLayout_2"))
        self.label_3 = QtGui.QLabel(Form)
        font = QtGui.QFont()
        font.setFamily(_fromUtf8("Yu Gothic UI"))
        font.setPointSize(11)
        font.setBold(True)
        font.setWeight(75)
        self.label_3.setFont(font)
        self.label_3.setAlignment(QtCore.Qt.AlignCenter)
        self.label_3.setObjectName(_fromUtf8("label_3"))
        self.verticalLayout_2.addWidget(self.label_3)
        self.YZPlaneWidget = QVTKRenderWindowInteractor(Form)
        self.YZPlaneWidget.setObjectName(_fromUtf8("YZPlaneWidget"))
        self.verticalLayout_2.addWidget(self.YZPlaneWidget)
        self.YZSlider = QtGui.QSlider(Form)
        self.YZSlider.setOrientation(QtCore.Qt.Horizontal)
        self.YZSlider.setObjectName(_fromUtf8("YZSlider"))
        self.verticalLayout_2.addWidget(self.YZSlider)
        self.verticalLayout_2.setStretch(1, 1)
        self.gridLayout_2.addLayout(self.verticalLayout_2, 0, 1, 1, 1)
        self.verticalLayout_3 = QtGui.QVBoxLayout()
        self.verticalLayout_3.setObjectName(_fromUtf8("verticalLayout_3"))
        self.label_2 = QtGui.QLabel(Form)
        font = QtGui.QFont()
        font.setFamily(_fromUtf8("Yu Gothic UI"))
        font.setPointSize(11)
        font.setBold(True)
        font.setWeight(75)
        self.label_2.setFont(font)
        self.label_2.setAlignment(QtCore.Qt.AlignCenter)
        self.label_2.setWordWrap(False)
        self.label_2.setObjectName(_fromUtf8("label_2"))
        self.verticalLayout_3.addWidget(self.label_2)
        self.XZPlaneWidget = QVTKRenderWindowInteractor(Form)
        self.XZPlaneWidget.setObjectName(_fromUtf8("XZPlaneWidget"))
        self.verticalLayout_3.addWidget(self.XZPlaneWidget)
        self.XZSlider = QtGui.QSlider(Form)
        self.XZSlider.setOrientation(QtCore.Qt.Horizontal)
        self.XZSlider.setObjectName(_fromUtf8("XZSlider"))
        self.verticalLayout_3.addWidget(self.XZSlider)
        self.verticalLayout_3.setStretch(1, 1)
        self.gridLayout_2.addLayout(self.verticalLayout_3, 1, 0, 1, 1)
        self.verticalLayout_5 = QtGui.QVBoxLayout()
        self.verticalLayout_5.setObjectName(_fromUtf8("verticalLayout_5"))
        self.label_4 = QtGui.QLabel(Form)
        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred,
                                       QtGui.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.label_4.sizePolicy().hasHeightForWidth())
        self.label_4.setSizePolicy(sizePolicy)
        font = QtGui.QFont()
        font.setFamily(_fromUtf8("Yu Gothic UI"))
        font.setPointSize(11)
        font.setBold(True)
        font.setWeight(75)
        self.label_4.setFont(font)
        self.label_4.setAlignment(QtCore.Qt.AlignCenter)
        self.label_4.setObjectName(_fromUtf8("label_4"))
        self.verticalLayout_5.addWidget(self.label_4)
        self.VolumeWidget = QVTKRenderWindowInteractor(Form)
        self.VolumeWidget.setEnabled(True)
        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred,
                                       QtGui.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.VolumeWidget.sizePolicy().hasHeightForWidth())
        self.VolumeWidget.setSizePolicy(sizePolicy)
        self.VolumeWidget.setMaximumSize(QtCore.QSize(16777215, 16777215))
        self.VolumeWidget.setObjectName(_fromUtf8("VolumeWidget"))
        self.verticalLayout_5.addWidget(self.VolumeWidget)
        self.gridLayout_2.addLayout(self.verticalLayout_5, 1, 1, 1, 1)
        self.horizontalLayout.addLayout(self.gridLayout_2)
        self.gridLayout = QtGui.QGridLayout()
        self.gridLayout.setSizeConstraint(QtGui.QLayout.SetDefaultConstraint)
        self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
        self.WindowWidthSlider = QtGui.QSlider(Form)
        self.WindowWidthSlider.setOrientation(QtCore.Qt.Horizontal)
        self.WindowWidthSlider.setObjectName(_fromUtf8("WindowWidthSlider"))
        self.gridLayout.addWidget(self.WindowWidthSlider, 3, 1, 1, 1)
        self.WindowWidthLabel = QtGui.QLabel(Form)
        self.WindowWidthLabel.setObjectName(_fromUtf8("WindowWidthLabel"))
        self.gridLayout.addWidget(self.WindowWidthLabel, 3, 0, 1, 1)
        self.WindowControlLabel = QtGui.QLabel(Form)
        self.WindowControlLabel.setFrameShape(QtGui.QFrame.NoFrame)
        self.WindowControlLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.WindowControlLabel.setObjectName(_fromUtf8("WindowControlLabel"))
        self.gridLayout.addWidget(self.WindowControlLabel, 0, 0, 1, 1)
        spacerItem = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum,
                                       QtGui.QSizePolicy.Expanding)
        self.gridLayout.addItem(spacerItem, 4, 0, 1, 1)
        self.WindowCenterLabel = QtGui.QLabel(Form)
        self.WindowCenterLabel.setObjectName(_fromUtf8("WindowCenterLabel"))
        self.gridLayout.addWidget(self.WindowCenterLabel, 1, 0, 1, 1)
        self.WindowCenterSlider = QtGui.QSlider(Form)
        self.WindowCenterSlider.setOrientation(QtCore.Qt.Horizontal)
        self.WindowCenterSlider.setObjectName(_fromUtf8("WindowCenterSlider"))
        self.gridLayout.addWidget(self.WindowCenterSlider, 1, 1, 1, 1)
        self.horizontalLayout.addLayout(self.gridLayout)
        self.horizontalLayout.setStretch(0, 3)
        self.horizontalLayout.setStretch(1, 1)

        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)
  def __init__(self, input_file_widget, execution_widget, qt_app, application):
    QtGui.QWidget.__init__(self)
    self.input_file_widget = input_file_widget
    self.qt_app = qt_app
    self.application = application

    self.plane = vtk.vtkPlane()
    self.plane.SetOrigin(-1000, 0, 0)
    self.plane.SetNormal(1, 0, 0)

    self.exodus_result = None

    # The multiple (from adaptivity)
    self.exodus_results = []

    self.timestep_to_exodus_result = {}

    self.file_name = None

    self.setupLuts()

    # The multiple (from adaptivity) file names we know of
    self.file_names = []

    self.current_max_timestep = 0

    # Whether or not there is new data to read
    self.new_stuff_to_read = False

    self.timer = QtCore.QTimer()
    self.timer.stop()
    self.timer.setInterval(100)
    self.timer.timeout.connect(self._updateData)

    self.execution_widget = execution_widget
    self.execution_widget.run_started.connect(self._runStarted)
    self.execution_widget.run_stopped.connect(self._runStopped)
    self.execution_widget.timestep_begin.connect(self._timestepBegin)
    self.execution_widget.timestep_end.connect(self._timestepEnd)

    self.main_layout = QtGui.QHBoxLayout()
#    self.main_layout.setSpacing(0)

    self.right_layout = QtGui.QVBoxLayout()

    self.left_layout = QtGui.QVBoxLayout()
    self.left_widget = QtGui.QWidget()
    self.left_widget.setMaximumWidth(1)

    self.left_widget.setLayout(self.left_layout)
    self.left_layout.setSizeConstraint(QtGui.QLayout.SetMinimumSize)

    self.main_layout.addWidget(self.left_widget)
    self.right_layout.setStretchFactor(self.left_layout, 0.01)
    self.main_layout.addLayout(self.right_layout)

#    self.setMinimumWidth(700)
    self.setLayout(self.main_layout)

    self.vtkwidget = QVTKRenderWindowInteractor(self)
#    self.vtkwidget.setMinimumHeight(300)

    # Create background, default to the gradient look
    self.renderer = vtk.vtkRenderer()
    self._showBlackBackgroundChanged(0)
    self.renderer.ResetCamera()

    self.right_layout.addWidget(self.vtkwidget)
    self.right_layout.setStretchFactor(self.vtkwidget, 100)

    self.vtkwidget.show()

    self.vtkwidget.GetRenderWindow().AddRenderer(self.renderer)
    self.vtkwidget.GetRenderWindow().GetInteractor().SetInteractorStyle(vtk.vtkInteractorStyleTrackballCamera())
    self.vtkwidget.Initialize()
    self.vtkwidget.Start()

    self.first = True

    self.exodus_result = None

    self.has_displacements = False
    self.current_displacement_magnitude = 1.0

    self.current_scale_x_magnitude = 1.0
    self.current_scale_y_magnitude = 1.0
    self.current_scale_z_magnitude = 1.0

    self.current_variable = None
    self.current_component = None

    # Holds a mapping of variable name to contour choices so they can be restored when variables are selected
    self.contour_choices = {}

    # If we are currently restoring contours then don't save the intermediate ones
    self.currently_restoring_contours = False
    self.setupControls()

    self.modifyUI()
Exemple #53
0
    def setupUi(self, MainWindow):
        '''
        Zde se vytvoří hlavní okno editoru. Nastaví se jeho velikost a název
        '''
        MainWindow.setObjectName(_fromUtf8("MainWindow"))
        MainWindow.resize(1000, 800)
        self.centralwidget = QtGui.QWidget(MainWindow)
        self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
        self.widget = QtGui.QWidget(self.centralwidget)
        self.widget.setGeometry(QtCore.QRect(370, 49, 401, 411))
        self.widget.setObjectName(_fromUtf8("widget"))
        '''
        Vytvoření tlačítka CUT, které při stisku spouští metodu liver_cut (zvolený resekční algoritmus)
        '''
        self.toolButton = QtGui.QPushButton(self.centralwidget)
        self.toolButton.setGeometry(QtCore.QRect(140, 140, 71, 41))
        self.toolButton.setObjectName(_fromUtf8("toolButton"))
        QtCore.QObject.connect(self.toolButton, QtCore.SIGNAL("clicked()"),
                               MainWindow.liver_cut)
        '''
        Vytvoření tlačítka PLANE, které při stisku volá metodu Plane
        '''
        self.toolButton_2 = QtGui.QPushButton(self.centralwidget)
        self.toolButton_2.setGeometry(QtCore.QRect(140, 280, 71, 41))
        self.toolButton_2.setObjectName(_fromUtf8("toolButton_2"))
        QtCore.QObject.connect(self.toolButton_2, QtCore.SIGNAL("clicked()"),
                               MainWindow.Plane)
        '''
        Vytvoření tlačítka POINT, které při stisku volá metodu Point
        '''
        self.toolButton_3 = QtGui.QPushButton(self.centralwidget)
        self.toolButton_3.setGeometry(QtCore.QRect(140, 210, 71, 41))
        self.toolButton_3.setObjectName(_fromUtf8("toolButton_3"))
        QtCore.QObject.connect(self.toolButton_3, QtCore.SIGNAL("clicked()"),
                               MainWindow.Point)
        '''
        Vytvoření textového pole pro uživatelské výpisy
        '''
        self.info_text = QtGui.QPlainTextEdit(self.centralwidget)
        self.info_text.setGeometry(QtCore.QRect(20, 350, 280, 100))
        self.info_text.setObjectName(_fromUtf8("lineEdit"))
        self.info_text.setReadOnly(True)
        '''
        Vytvoření textového pole pro výpisy informací o velikosti odstraněné části jater
        '''
        self.liver_text = QtGui.QPlainTextEdit(self.centralwidget)
        self.liver_text.setGeometry(QtCore.QRect(380, 490, 380, 50))
        self.liver_text.setObjectName(_fromUtf8("lineEdit"))
        self.liver_text.setReadOnly(True)
        '''
        Vytvoření vizualizačního okna
        '''
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtGui.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21))
        self.menubar.setObjectName(_fromUtf8("menubar"))
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtGui.QStatusBar(MainWindow)
        self.statusbar.setObjectName(_fromUtf8("statusbar"))
        MainWindow.setStatusBar(self.statusbar)
        self.gridlayout = QtGui.QGridLayout(self.widget)
        self.vtkWidget = QVTKRenderWindowInteractor(self.widget)

        self.gridlayout.addWidget(self.vtkWidget, 0, 0, 1, 1)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)
 def set_up_view(self):
     self.interactor = QVTKRenderWindowInteractor(self.chart_frame)
     self.interactor.GetRenderWindow().AddRenderer(self.renderer)
     self.chart_frame.layout().addWidget(self.interactor, 1, 0, 1, 1)
     self.iren = self.interactor.GetRenderWindow().GetInteractor()
Exemple #55
0
    def __init__(self, parent=None):
        #QtGui.QMainWindow.__init__(self, parent)

        self.dragging = False
        self.lasso_screen = [(0, 0), (100, 50)]

        if 0:
            self.frame = QtGui.QFrame()

            self.vl = QtGui.QVBoxLayout()
            self.vtkWidget = QVTKRenderWindowInteractor(self.frame)
            # monkey patch
            self.vtkWidget._original_mouseMoveEvent = self.vtkWidget.mouseMoveEvent
            self.vtkWidget.mouseMoveEvent = self.mouseMoveEvent

            self.vtkWidget._original_mousePressEvent = self.vtkWidget.mousePressEvent
            self.vtkWidget.mousePressEvent = self.mousePressEvent

            self.vtkWidget._original_mouseReleaseEvent = self.vtkWidget.mouseReleaseEvent
            self.vtkWidget.mouseReleaseEvent = self.mouseReleaseEvent

            if 0:
                self.vtkWidget._original_paintEvent = self.vtkWidget.paintEvent
                self.vtkWidget.paintEvent = self.paintEvent

                def test():
                    print QtGui.QPaintEngine.OpenGL
                    return 0

                self.vtkWidget.paintEngine = test

            self.vl.addWidget(self.vtkWidget)

            #self.overlay = Overlay(self.vtkWidget, self.frame)
            #self.vl.addWidget(self.overlay)
            #self.vl.addWidget(QtGui.QPushButton("test", self))
        else:
            window = vtk.vtkXOpenGLRenderWindow()
            window.SetOffScreenRendering(True)

        self.ren = vtk.vtkRenderer()
        window.AddRenderer(self.ren)
        #self.iren = self.vtkWidget.GetRenderWindow().GetInteractor()
        #self.iren.GetInteractorStyle().SetCurrentStyleToTrackballCamera()
        #self.iren.GetInteractorStyle().AddObserver("MouseMoveEvent", self.mouseMoveEvent)
        #self.interactorStyle = MyInteractorStyle(self)
        #self.iren.SetInteractorStyle(self.interactorStyle)
        #import pdb
        #pdb.set_trace()
        # Create source
        #source = vtk.vtkSphereSource()
        #source.SetCenter(0, 0, 0)
        #source.SetRadius(5.0)
        if 0:
            self.levelSlider = QtGui.QSlider(QtCore.Qt.Horizontal, self)
            self.levelSlider.setRange(0, 100)
            self.levelSlider.sliderReleased.connect(self.sliderReleased)
            self.isoCheckbox = QtGui.QCheckBox("Show isosurface", self)
            self.volumeCheckbox = QtGui.QCheckBox("Show volume rendering",
                                                  self)
            self.vl.addWidget(self.isoCheckbox)
            self.vl.addWidget(self.volumeCheckbox)
            self.vl.addWidget(self.levelSlider)

            self.isoCheckbox.setCheckState(QtCore.Qt.Checked)
            self.volumeCheckbox.setCheckState(QtCore.Qt.Checked)

        #self.formLayout = QtGui.QFormLayout(self)
        #self.formLayout.addRow("show isosurface", QCheckBox
        #self.vl.addItem(self.formLayout)

        imageData = createImageData()
        volumeMapper = vtk.vtkSmartVolumeMapper()
        volumeMapper = vtk.vtkVolumeTextureMapper3D()
        volumeMapper.SetBlendModeToComposite()

        #compositeFunction = vtk.vtkVolumeRayCastCompositeFunction()
        # We can finally create our volume. We also have to specify the data for it, as well as how the data will be rendered.
        #volumeMapper = vtk.vtkVolumeRayCastMapper()
        #volumeMapper.SetVolumeRayCastFunction(compositeFunction)

        volumeMapper.SetInputConnection(imageData.GetProducerPort())

        volumeProperty = vtk.vtkVolumeProperty()
        volumeProperty.ShadeOff()
        volumeProperty.SetInterpolationType(vtk.VTK_LINEAR_INTERPOLATION)

        compositeOpacity = vtk.vtkPiecewiseFunction()
        compositeOpacity.AddPoint(0., 0.0)
        compositeOpacity.AddPoint(1., 0.105)
        compositeOpacity.AddPoint(2., 0.101)
        compositeOpacity.AddPoint(3., 0.102)
        volumeProperty.SetScalarOpacity(compositeOpacity)

        color = vtk.vtkColorTransferFunction()
        #color.AddRGBPoint(1, 1.0, 0.0, 0.0)
        color.AddRGBPoint(2, 0.0, 1.0, 0.0)
        color.AddRGBPoint(3, 0.0, 0.0, 1.0)
        volumeProperty.SetColor(color)

        volume = vtk.vtkVolume()
        volume.SetMapper(volumeMapper)
        volume.SetProperty(volumeProperty)
        self.ren.AddViewProp(volume)

        outline = vtk.vtkOutlineFilter()
        outline.SetInput(imageData)
        outlineMapper = vtk.vtkPolyDataMapper()
        outlineMapper.SetInputConnection(outline.GetOutputPort())
        outlineActor = vtk.vtkActor()
        outlineActor.SetMapper(outlineMapper)
        outlineActor.GetProperty().SetColor(0, 0, 0)
        self.ren.AddActor(outlineActor)

        self.lasso = Lasso(self.lasso_screen)
        self.ren.AddActor(self.lasso.actor)

        if 0:

            def onVolume(state):
                checked = state == QtCore.Qt.Checked
                if checked:
                    volume.VisibilityOn()
                else:
                    volume.VisibilityOff()
                self.vtkWidget.GetRenderWindow().Render()

            self.volumeCheckbox.stateChanged.connect(onVolume)

        #self.ren.ResetCamera()

        if 0:
            self.surface = vtk.vtkMarchingCubes()
            self.surface.SetInput(imageData)
            self.surface.ComputeNormalsOn()
            self.surface.SetValue(0, 100)

            #print surface
            #print surface.GetOutput()
            #print surface.GetOutputPort()

            # Create a mapper
            mapper = vtk.vtkPolyDataMapper()
            mapper.SetInputConnection(self.surface.GetOutputPort())
            mapper.ScalarVisibilityOff()
            print mapper
            import pdb
            #pdb.set_trace()
            # Create an actor
            actor = vtk.vtkActor()
            actor.SetMapper(mapper)

            actor.GetProperty().SetColor(1, 0, 0)
            actor.GetProperty().SetOpacity(1)

            self.ren.AddActor(actor)

            def onIso(state):
                checked = state == QtCore.Qt.Checked
                if checked:
                    actor.VisibilityOn()
                else:
                    actor.VisibilityOff()
                self.vtkWidget.GetRenderWindow().Render()

            self.isoCheckbox.stateChanged.connect(onIso)

        self.ren.ResetCamera()

        #self.frame.setLayout(self.vl)
        #self.setCentralWidget(self.frame)
        self.ren.SetBackground(1, 1, 1)
        #self.ren.SetOffScreenRendering(True)
        arr = vtk.vtkUnsignedCharArray()
        print "size", arr.GetDataSize()
        window.Render()
        print window.GetPixelData(0, 0, 10, 10, 0, arr)
        print "size", arr.GetDataSize()

        self.show()
        self.raise_()
        print "aap"
        self.iren.Initialize()