def calculate(self):
        FreeCAD.FEM_dialog["results_type"] = "None"
        self.update()
        self.restore_result_dialog()
        # Convert existing values to numpy array
        P1 = np.array(self.result_object.PrincipalMax)
        P2 = np.array(self.result_object.PrincipalMed)
        P3 = np.array(self.result_object.PrincipalMin)
        Von = np.array(self.result_object.StressValues)
        T = np.array(self.result_object.Temperature)
        dispvectors = np.array(self.result_object.DisplacementVectors)
        x = np.array(dispvectors[:, 0])
        y = np.array(dispvectors[:, 1])
        z = np.array(dispvectors[:, 2])
        userdefined_eq = x + y + z + T + Von + P1 + P2 + P3  # Dummy equation to get around flake8, varibles not being used
        userdefined_eq = self.form.user_def_eq.toPlainText()  # Get equation to be used
        UserDefinedFormula = eval(userdefined_eq).tolist()
        minm = min(UserDefinedFormula)
        avg = sum(UserDefinedFormula) / len(UserDefinedFormula)
        maxm = max(UserDefinedFormula)

        QApplication.setOverrideCursor(Qt.WaitCursor)
        if self.suitable_results:
            self.MeshObject.ViewObject.setNodeColorByScalars(self.result_object.NodeNumbers, UserDefinedFormula)
        self.set_result_stats("", minm, avg, maxm)
        QtGui.qApp.restoreOverrideCursor()
    def calculixFinished(self, exitCode):
        print "calculixFinished()", exitCode
        print self.Calculix.state()

        # Restore previous cwd
        QtCore.QDir.setCurrent(self.cwd)

        self.printCalculiXstdout()
        self.Timer.stop()

        self.femConsoleMessage("Calculix done!", "#00AA00")

        self.form.pushButton_generate.setText("Re-run Calculix")
        print "Loading results...."
        self.femConsoleMessage("Loading result sets...")
        self.form.label_Time.setText('Time: {0:4.1f}: '.format(time.time() - self.Start))
        fea = FemTools()
        fea.reset_all()
        frd_result_file = os.path.splitext(self.inp_file_name)[0] + '.frd'
        if os.path.isfile(frd_result_file):
            QApplication.setOverrideCursor(Qt.WaitCursor)
            ccxFrdReader.importFrd(frd_result_file, FemGui.getActiveAnalysis())
            QApplication.restoreOverrideCursor()
            self.femConsoleMessage("Loading results done!", "#00AA00")
        else:
            self.femConsoleMessage("Loading results failed! Results file doesn\'t exist", "#FF0000")
        self.form.label_Time.setText('Time: {0:4.1f}: '.format(time.time() - self.Start))
    def typeChanged(self,typeName):
        if typeName == "None":
            self.MeshObject.ViewObject.NodeColor = {}
            self.MeshObject.ViewObject.ElementColor = {}
            return
            
        QApplication.setOverrideCursor(Qt.WaitCursor)
        
        if typeName[:2] == "Ua" and self.DisplacementObject:            
            (min,max,avg) = self.MeshObject.ViewObject.setNodeColorByResult(self.DisplacementObject)
        if typeName[:2] == "U1" and self.DisplacementObject:            
            (min,max,avg) = self.MeshObject.ViewObject.setNodeColorByResult(self.DisplacementObject,1)
        if typeName[:2] == "U2" and self.DisplacementObject:            
            (min,max,avg) = self.MeshObject.ViewObject.setNodeColorByResult(self.DisplacementObject,2)
        if typeName[:2] == "U3" and self.DisplacementObject:            
            (min,max,avg) = self.MeshObject.ViewObject.setNodeColorByResult(self.DisplacementObject,3)
        if typeName[:2] == "Sa" and self.StressObject:            
            (min,max,avg) = self.MeshObject.ViewObject.setNodeColorByResult(self.StressObject)
            
        self.form.lineEdit_Max.setText(str(max))
        self.form.lineEdit_Min.setText(str(min))
        self.form.lineEdit_Avg.setText(str(avg))

        print typeName

        QtGui.qApp.restoreOverrideCursor()
 def run_gmsh(self):
     QApplication.setOverrideCursor(Qt.WaitCursor)
     part = self.obj.Part
     if self.mesh_obj.MeshRegionList:
         if part.Shape.ShapeType == "Compound" and hasattr(part, "Proxy"):  # other part obj might not have a Proxy, thus an exception would be raised
             if (part.Proxy.Type == "FeatureBooleanFragments" or part.Proxy.Type == "FeatureSlice" or part.Proxy.Type == "FeatureXOR"):
                 error_message = "The mesh to shape is a boolean split tools Compound and the mesh has mesh region list. Gmsh could return unexpected meshes in such circumstances. It is strongly recommended to extract the shape to mesh from the Compound and use this one."
                 QtGui.QMessageBox.critical(None, "Shape to mesh is a BooleanFragmentsCompound and mesh regions are defined", error_message)
     self.Start = time.time()
     self.form.l_time.setText('Time: {0:4.1f}: '.format(time.time() - self.Start))
     self.console_message_gmsh = ''
     self.gmsh_runs = True
     self.console_log("We are going to start ...")
     self.get_active_analysis()
     import femmesh.gmshtools as gmshtools
     gmsh_mesh = gmshtools.GmshTools(self.obj, self.analysis)
     self.console_log("Start Gmsh ...")
     error = ''
     try:
         error = gmsh_mesh.create_mesh()
     except:
         import sys
         print("Unexpected error when creating mesh: ", sys.exc_info()[0])
     if error:
         print(error)
         self.console_log('Gmsh had warnings ...')
         self.console_log(error, '#FF0000')
     else:
         self.console_log('Clean run of Gmsh')
     self.console_log("Gmsh done!")
     self.form.l_time.setText('Time: {0:4.1f}: '.format(time.time() - self.Start))
     self.Timer.stop()
     self.update()
     QApplication.restoreOverrideCursor()
    def calculixFinished(self,exitCode):
        print "calculixFinished()",exitCode
        print self.Calculix.state()
        out = self.Calculix.readAllStandardOutput()
        print out
        if out:
            self.femConsoleMessage(unicode(out).replace('\n','<br>'))

        self.Timer.stop()
        
        self.femConsoleMessage("Calculix done!", "#00FF00")

        self.form.pushButton_generate.setText("Re-run Calculix")
        print "Loading results...."
        self.femConsoleMessage("Loading result sets...")
        self.form.label_Time.setText('Time: {0:4.1f}: '.format(time.time() - self.Start) )

        if os.path.isfile(self.Basename + '.frd'):
            QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
            CalculixLib.importFrd(self.Basename + '.frd',FemGui.getActiveAnalysis() )
            QApplication.restoreOverrideCursor()
            self.femConsoleMessage("Loading results done!", "#00FF00")
        else:
            self.femConsoleMessage("Loading results failed! Results file doesn\'t exist", "#FF0000")
        self.form.label_Time.setText('Time: {0:4.1f}: '.format(time.time() - self.Start) )
    def __init__(self, theScene, parent):
        """
        Default class constructor.

        :param `theScene`: TOWRITE
        :type `theScene`: `QGraphicsScene`_
        :param `parent`: Pointer to a parent widget instance.
        :type `parent`: `QWidget`_
        """
        super(EmbDetailsDialog, self).__init__(parent)

        self.setMinimumSize(750, 550)

        self.getInfo()
        mainWidget = self.createMainWidget()

        buttonBox = QDialogButtonBox(QDialogButtonBox.Ok)
        buttonBox.accepted.connect(self.accept)

        vboxLayoutMain = QVBoxLayout(self)
        vboxLayoutMain.addWidget(mainWidget)
        vboxLayoutMain.addWidget(buttonBox)
        self.setLayout(vboxLayoutMain)

        self.setWindowTitle(self.tr("Embroidery Design Details"))

        QApplication.setOverrideCursor(Qt.ArrowCursor)
 def vm_stress_selected(self, state):
     FreeCAD.FEM_dialog["results_type"] = "Sabs"
     QApplication.setOverrideCursor(Qt.WaitCursor)
     self.MeshObject.ViewObject.setNodeColorByScalars(self.result_object.ElementNumbers, self.result_object.StressValues)
     (minm, avg, maxm) = self.get_result_stats("Sabs")
     self.set_result_stats("MPa", minm, avg, maxm)
     QtGui.qApp.restoreOverrideCursor()
 def mousePressEvent(self, event):
     if event.button() == Qt.MidButton:
         QApplication.setOverrideCursor(QCursor(Qt.SizeHorCursor))
         self._pan_pos = event.globalPos()
         event.accept()
     else:
         event.ignore()
    def typeChanged(self, index):
        selected = self.form.comboBox_Type.itemData(index)
        if selected[0] == "None":
            self.MeshObject.ViewObject.NodeColor = {}
            self.MeshObject.ViewObject.ElementColor = {}
            self.form.lineEdit_Max.setProperty("unit", "mm")
            self.form.lineEdit_Max.setText(" 0 mm")
            self.form.lineEdit_Min.setProperty("unit", "mm")
            self.form.lineEdit_Min.setText(" 0 mm")
            self.form.lineEdit_Avg.setProperty("unit", "mm")
            self.form.lineEdit_Avg.setText(" 0 mm")
            return

        QApplication.setOverrideCursor(Qt.WaitCursor)
        if self.DisplacementObject:
            if selected[0] in ("U1", "U2", "U3", "Uabs"):
                (minm, maxm, avg) = self.MeshObject.ViewObject.setNodeColorByResult(self.DisplacementObject, selected[1])
                unit = "mm"
        if self.StressObject:
            if selected[0] in ("Sabs"):
                (minm, maxm, avg) = self.MeshObject.ViewObject.setNodeColorByResult(self.StressObject)
                unit = "MPa"

        self.form.lineEdit_Max.setProperty("unit", unit)
        self.form.lineEdit_Max.setText("{:.6} {}".format(maxm, unit))
        self.form.lineEdit_Min.setProperty("unit", unit)
        self.form.lineEdit_Min.setText("{:.6} {}".format(minm, unit))
        self.form.lineEdit_Avg.setProperty("unit", unit)
        self.form.lineEdit_Avg.setText("{:.6} {}".format(avg, unit))

        QtGui.qApp.restoreOverrideCursor()
 def run_gmsh(self):
     QApplication.setOverrideCursor(Qt.WaitCursor)
     self.Start = time.time()
     self.form.l_time.setText('Time: {0:4.1f}: '.format(time.time() - self.Start))
     self.console_message_gmsh = ''
     self.gmsh_runs = True
     self.console_log("We gone start ...")
     self.get_active_analysis()
     self.set_mesh_params()
     import FemGmshTools
     gmsh_mesh = FemGmshTools.FemGmshTools(self.obj, self.analysis)
     self.console_log("Start GMSH ...")
     error = ''
     try:
         error = gmsh_mesh.create_mesh()
     except:
         import sys
         print("Unexpected error when creating mesh: ", sys.exc_info()[0])
     if error:
         print(error)
         self.console_log('GMSH had warnings ...')
         self.console_log(error, '#FF0000')
     else:
         self.console_log('Clean run of GMSH')
     self.console_log("GMSH done!")
     self.form.l_time.setText('Time: {0:4.1f}: '.format(time.time() - self.Start))
     self.Timer.stop()
     self.update()
     QApplication.restoreOverrideCursor()
    def calculixFinished(self,exitCode):
        print "calculixFinished()",exitCode
        print self.Calculix.state()
        out = self.Calculix.readAllStandardOutput()
        print out
        if out:
            self.OutStr = self.OutStr + unicode(out).replace('\n','<br>')
            self.form.textEdit_Output.setText(self.OutStr)

        self.Timer.stop()
        
        self.OutStr = self.OutStr + '<font color="#0000FF">{0:4.1f}:</font> '.format(time.time() - self.Start) + '<font color="#00FF00">Calculix done!</font><br>'
        self.form.textEdit_Output.setText(self.OutStr)

        self.form.pushButton_generate.setText("Re-run Calculix")
        print "Loading results...."
        self.OutStr = self.OutStr + '<font color="#0000FF">{0:4.1f}:</font> '.format(time.time() - self.Start) + 'Loading result sets...<br>'
        self.form.textEdit_Output.setText(self.OutStr)
        self.form.label_Time.setText('Time: {0:4.1f}: '.format(time.time() - self.Start) )

        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        CalculixLib.importFrd(self.Basename + '.frd',FemGui.getActiveAnalysis() )
        QApplication.restoreOverrideCursor()
        self.OutStr = self.OutStr + '<font color="#0000FF">{0:4.1f}:</font> '.format(time.time() - self.Start) + '<font color="#00FF00">Loading results done!</font><br>'
        self.form.textEdit_Output.setText(self.OutStr)
        self.form.label_Time.setText('Time: {0:4.1f}: '.format(time.time() - self.Start) )
Exemple #12
0
    def update_max_min(self):
        """
        Updates the max and min boxes in colorbar dialog.

        There should be code in here which stops this process on large cubes...
        The time taken in this case is too large for the small reward.

        """
        QApplication.setOverrideCursor(QtCore.Qt.WaitCursor)
        scheme = self.colorbar_dialog.get_colorbar_scheme()

        if scheme is "auto":
            colorbar_max, colorbar_min = cl.find_max_min(self.plotted_cube)
            self.colorbar_dialog.set_max_min(colorbar_max, colorbar_min)

        elif scheme is "fixed":
            # want to fix the colorbar across all of the slices.
            cube = self.cube
            dim_1_index = self.select_dimension_1.currentIndex()
            dim_2_index = self.select_dimension_2.currentIndex()
            sliced_dim_index = self.select_sliced_dim.currentIndex()
            dim_indices = {'dim 1 index': dim_1_index,
                           'dim 2 index': dim_2_index,
                           'sliced dim index': sliced_dim_index}
            collapsed_indices = []
            for i in xrange(self.ndim - 3):
                box_name = "select_slice_index_" + str(i+1)
                box = self.findChild(QtGui.QComboBox, box_name)
                collapsed_indices.append(box.currentIndex())

            colorbar_max, colorbar_min = cl.set_fixed_colorbar(
                cube, dim_indices, collapsed_indices)
            self.colorbar_dialog.set_max_min(colorbar_max, colorbar_min)

        QApplication.restoreOverrideCursor()
Exemple #13
0
  def showOpenDialog(self):
    """
    Handles the loading of a file, and calls functions to set up the GUI accordingly and then display the cube
    """
    
    self.filename, _ = QtGui.QFileDialog.getOpenFileName(self, 'Open File', '/project/avd/iris/resources/public_sample_data_1.0')
    self.clearAll()
    
    QApplication.setOverrideCursor(QtCore.Qt.WaitCursor)
    self.statusBar().showMessage('Loading Cube')
    try:
      self.cubes = iris.load(self.filename)
    except ValueError as e:
      flags = QtGui.QMessageBox.StandardButton.Ok
      response = QtGui.QMessageBox.critical(self, 'Unable to Load Cube: File type could not be read', str(e), flags) 
      self.statusBar().showMessage('Load Failed')
      QApplication.restoreOverrideCursor()
    QApplication.restoreOverrideCursor()
    
    for self.cube in self.cubes:
      self.selectCube.addItem(self.cube.name())        #fills the selectCube combo box with the cubes from the file
    if len(self.cubes) == 1:
      self.selectCube.setEnabled(False)
    else:
      self.selectCube.setEnabled(True)
    self.cubeLoaded = True
    
    self.printCubeBrowser.setText(str(self.cube))

    self.setDimensionCombos()
    self.update()
Exemple #14
0
  def update(self):
    
    QApplication.setOverrideCursor(QtCore.Qt.WaitCursor)
    
    self.updateButton.setEnabled(False)
    
    cube = self.getCurrentCube()
    plotType = self.selectPlotType.currentText()
    projection = self.selectProjection.currentText()
    cmap = self.selectColormap.currentText()
    Ncontours = self.contourSlider.value()
    coastlines = self.actionCoastlines.isChecked()
    gridlines = self.actionGridlines.isChecked()
    contourLabels = self.actionContour_Labels.isChecked()
    countries = self.actionCountry_Boundaries.isChecked()
    rivers = self.actionRivers_and_Lakes.isChecked()
    dim1_name = self.selectDimension1.currentText()
    dim1_index = self.selectDimension1.currentIndex()
    dim2_name = self.selectDimension2.currentText()
    dim2_index = self.selectDimension2.currentIndex()
    slicedDimName = self.selectSlicedDim.currentText()
    slicedDimIndex = self.selectSlicedDim.currentIndex()
    sliceIndex = self.selectSliceScroll.value()
    collapsedNames = []
    collapsedIndices = []
    for i in range(cube.ndim - 3):
      exec("collapsedNames.append(self.collapsedDim{}.text())".format(i+1))
      exec("collapsedIndices.append(self.selectSliceIndex{}.currentIndex())".format(i+1))
    if self.cbDialog.autoselectRange.isChecked():
      cbMax = None
      cbMin = None
    elif self.cbDialog.fixedColorbar.isChecked():
      if self.fixedCb == False:
	self.Max, self.Min = cc.setFixedColorbar(cube, dim1_name, dim2_name, slicedDimName, dim1_index, dim2_index, slicedDimIndex, collapsedIndices)
	self.fixedCb == True
      cbMax = self.Max
      cbMin = self.Min
    else:
      cbMax = self.cbDialog.maxContour.value()
      cbMin = self.cbDialog.minContour.value()
    
    self.clearFig()
    
    self.statusBar().showMessage('Plotting Cube')
    try:
      self.plotted_cube = cc.update(cube, plotType, projection, cmap, Ncontours, coastlines, gridlines, contourLabels, countries, rivers,
		cbMax, cbMin, dim1_name, dim1_index, dim2_name, dim2_index, slicedDimName,
		slicedDimIndex, sliceIndex, collapsedNames, collapsedIndices)
    
    except Exception as e:
      flags = QtGui.QMessageBox.StandardButton.Ok
      response = QtGui.QMessageBox.critical(self, 'Unable to plot cube!', str(e), flags)
      self.statusBar().showMessage('Failed to Plot Cube')
      QApplication.restoreOverrideCursor()
    
    self.statusBar().showMessage('Drawing Plot')
    self.display()
    self.printCubeSliceBrowser.setText(str(self.plotted_cube))
    self.statusBar().showMessage('Ready')
    QApplication.restoreOverrideCursor()
    def calculixFinished(self, exitCode):
        print("calculixFinished() {}".format(exitCode))
        print(self.Calculix.state())

        # Restore previous cwd
        QtCore.QDir.setCurrent(self.cwd)

        self.printCalculiXstdout()
        self.Timer.stop()

        self.femConsoleMessage("CalculiX done!", "#00AA00")

        self.form.pb_run_ccx.setText("Re-run CalculiX")
        self.femConsoleMessage("Loading result sets...")
        self.form.l_time.setText('Time: {0:4.1f}: '.format(time.time() - self.Start))
        fea = ccxtools.FemToolsCcx(None, self.solver_object)
        fea.reset_mesh_purge_results_checked()
        fea.inp_file_name = self.inp_file_name
        QApplication.setOverrideCursor(Qt.WaitCursor)
        try:
            fea.load_results()
        except:
            QApplication.restoreOverrideCursor()
            majorVersion, minorVersion = fea.get_ccx_version()
            if majorVersion == 2 and minorVersion <= 10:
                message = "The used CalculiX version {}.{} creates broken output files.\n" \
                    "Please upgrade to a newer version.".format(majorVersion, minorVersion)
                QtGui.QMessageBox.warning(None, "Upgrade CalculiX", message)
            raise
        else:
            QApplication.restoreOverrideCursor()
            self.form.l_time.setText('Time: {0:4.1f}: '.format(time.time() - self.Start))
 def networkpressure_selected(self, state):
     FreeCAD.FEM_dialog["results_type"] = "NPress"
     QApplication.setOverrideCursor(Qt.WaitCursor)
     if self.suitable_results:
         self.mesh_obj.ViewObject.setNodeColorByScalars(self.result_obj.NodeNumbers, self.result_obj.NetworkPressure)
     (minm, avg, maxm) = self.get_result_stats("NPress")
     self.set_result_stats("MPa", minm, avg, maxm)
     QtGui.qApp.restoreOverrideCursor()
 def massflowrate_selected(self, state):
     FreeCAD.FEM_dialog["results_type"] = "MFlow"
     QApplication.setOverrideCursor(Qt.WaitCursor)
     if self.suitable_results:
         self.mesh_obj.ViewObject.setNodeColorByScalars(self.result_obj.NodeNumbers, self.result_obj.MassFlowRate)
     (minm, avg, maxm) = self.get_result_stats("MFlow")
     self.set_result_stats("kg/s", minm, avg, maxm)
     QtGui.QApplication.restoreOverrideCursor()
 def peeq_selected(self, state):
     FreeCAD.FEM_dialog["results_type"] = "Peeq"
     QApplication.setOverrideCursor(Qt.WaitCursor)
     if self.suitable_results:
         self.mesh_obj.ViewObject.setNodeColorByScalars(self.result_obj.NodeNumbers, self.result_obj.Peeq)
     (minm, avg, maxm) = self.get_result_stats("Peeq")
     self.set_result_stats("", minm, avg, maxm)
     QtGui.QApplication.restoreOverrideCursor()
 def min_prin_selected(self, state):
     FreeCAD.FEM_dialog["results_type"] = "MinPrin"
     QApplication.setOverrideCursor(Qt.WaitCursor)
     if self.suitable_results:
         self.MeshObject.ViewObject.setNodeColorByScalars(self.result_object.NodeNumbers, self.result_object.PrincipalMin)
     (minm, avg, maxm) = self.get_result_stats("MinPrin")
     self.set_result_stats("MPa", minm, avg, maxm)
     QtGui.qApp.restoreOverrideCursor()
 def select_displacement_type(self, disp_type):
     QApplication.setOverrideCursor(Qt.WaitCursor)
     (minm, avg, maxm) = (0.0, 0.0, 0.0)
     if self.DisplacementObject:
         match = {"Uabs": 0, "U1": 1, "U2": 2, "U3": 3}
         self.MeshObject.ViewObject.setNodeColorByResult(self.DisplacementObject, match[disp_type])
         (minm, avg, maxm) = self.get_result_stats(disp_type)
     self.set_result_stats("mm", minm, avg, maxm)
     QtGui.qApp.restoreOverrideCursor()
 def show_displacement(self, checked):
     QApplication.setOverrideCursor(Qt.WaitCursor)
     FreeCAD.FEM_dialog["show_disp"] = checked
     factor = 0.0
     if checked:
         factor = self.form.hsb_displacement_factor.value()
     self.MeshObject.ViewObject.setNodeDisplacementByVectors(self.result_object.ElementNumbers, self.result_object.DisplacementVectors)
     self.MeshObject.ViewObject.applyDisplacement(factor)
     QtGui.qApp.restoreOverrideCursor()
 def vm_stress_selected(self, state):
     FreeCAD.FEM_dialog["results_type"] = "Sabs"
     QApplication.setOverrideCursor(Qt.WaitCursor)
     (minm, avg, maxm) = (0.0, 0.0, 0.0)
     if self.StressObject:
         self.MeshObject.ViewObject.setNodeColorByResult(self.StressObject)
         (minm, avg, maxm) = self.get_result_stats("Sabs")
     self.set_result_stats("MPa", minm, avg, maxm)
     QtGui.qApp.restoreOverrideCursor()
 def show_displacement(self, checked):
     QApplication.setOverrideCursor(Qt.WaitCursor)
     FreeCAD.FEM_dialog["show_disp"] = checked
     if "result_object" in FreeCAD.FEM_dialog:
         if FreeCAD.FEM_dialog["result_object"] != self.result_object:
             self.update_displacement()
     FreeCAD.FEM_dialog["result_object"] = self.result_object
     self.MeshObject.ViewObject.setNodeDisplacementByVectors(self.result_object.ElementNumbers, self.result_object.DisplacementVectors)
     self.update_displacement()
     QtGui.qApp.restoreOverrideCursor()
Exemple #24
0
    def mousePressEvent( self, event ):
        # handle a scroll event
        if event.button() == Qt.LeftButton and self.canScroll():
            self._scrolling = True
            self._scrollInitY = event.globalY()
            self._scrollInitVal = self.verticalScrollBar().value()

            QApplication.setOverrideCursor(Qt.ClosedHandCursor)

        event.accept()
 def temperature_selected(self, state):
     FreeCAD.FEM_dialog["results_type"] = "Temp"
     QApplication.setOverrideCursor(Qt.WaitCursor)
     if self.suitable_results:
         self.MeshObject.ViewObject.setNodeColorByScalars(self.result_object.NodeNumbers, self.result_object.Temperature)
     minm = min(self.result_object.Temperature)
     avg = sum(self.result_object.Temperature) / len(self.result_object.Temperature)
     maxm = max(self.result_object.Temperature)
     self.set_result_stats("K", minm, avg, maxm)
     QtGui.qApp.restoreOverrideCursor()
Exemple #26
0
def main():
    pid_file = 'av-control.pid'
    fp = open(pid_file, 'w')
    try:
        fcntl.lockf(fp, fcntl.LOCK_EX | fcntl.LOCK_NB)
    except IOError:
        # another instance is running
        print "av-control is already running."
        sys.exit(1)

    logging.basicConfig(format='%(asctime)s %(levelname)s: %(message)s',
                        level=logging.INFO)
    app = QApplication(sys.argv)

    parser = argparse.ArgumentParser()
    parser.add_argument("-f", "--fullscreen",
                        help="Run in fullscreen mode and hide the mouse cursor",
                        action="store_true")
    parser.add_argument("-c",
                        help="Specify the controller ID to connect to",
                        metavar="CONTROLLERID",
                        default="")
    args = parser.parse_args()

    try:
        ssf = QFile(":/stylesheet")
        ssf.open(QFile.ReadOnly)
        styleSheet = str(ssf.readAll())
        app.setStyleSheet(styleSheet)
    except IOError:
        # never mind
        logging.warn("Cannot find stylesheet, using default system styles.")

    try:
        controller = Controller.fromPyro(args.c)

        myapp = MainWindow(controller)

        client = AvControlClient(myapp)
        client.setDaemon(True)
        client.start()
        client.started.wait()
        atexit.register(lambda: controller.unregisterClient(client.uri))

        controller.registerClient(client.uri)

        if args.fullscreen:
            QApplication.setOverrideCursor(Qt.BlankCursor)
            myapp.showFullScreen()
        else:
            myapp.show()
        sys.exit(app.exec_())

    except VersionMismatchError as e:
        Dialogs.errorBox(str(e))
 def show_displacement(self, checked):
     QApplication.setOverrideCursor(Qt.WaitCursor)
     FreeCAD.FEM_dialog["show_disp"] = checked
     if "result_obj" in FreeCAD.FEM_dialog:
         if FreeCAD.FEM_dialog["result_obj"] != self.result_obj:
             self.update_displacement()
     FreeCAD.FEM_dialog["result_obj"] = self.result_obj
     if self.suitable_results:
         self.mesh_obj.ViewObject.setNodeDisplacementByVectors(self.result_obj.NodeNumbers, self.result_obj.DisplacementVectors)
     self.update_displacement()
     QtGui.QApplication.restoreOverrideCursor()
 def select_displacement_type(self, disp_type):
     QApplication.setOverrideCursor(Qt.WaitCursor)
     if disp_type == "Uabs":
         self.MeshObject.ViewObject.setNodeColorByScalars(self.result_object.ElementNumbers, self.result_object.DisplacementLengths)
     else:
         match = {"U1": 0, "U2": 1, "U3": 2}
         d = zip(*self.result_object.DisplacementVectors)
         displacements = list(d[match[disp_type]])
         self.MeshObject.ViewObject.setNodeColorByScalars(self.result_object.ElementNumbers, displacements)
     (minm, avg, maxm) = self.get_result_stats(disp_type)
     self.set_result_stats("mm", minm, avg, maxm)
     QtGui.qApp.restoreOverrideCursor()
Exemple #29
0
def busy_cursor(widget=None, cursor=Qt.WaitCursor):
    if widget:
        widget.setCursor(cursor)
    else:
        QApplication.setOverrideCursor(cursor)
    try:
        yield
    finally:
        if widget:
            widget.unsetCursor()
        else:
            QApplication.restoreOverrideCursor()
 def write_input_file_handler(self):
     QApplication.restoreOverrideCursor()
     if self.check_prerequisites():
         QApplication.setOverrideCursor(Qt.WaitCursor)
         try:
             self.write_calculix_input_file()
         except:
             print "Unexpected error when writing CalculiX input file:", sys.exc_info()[0]
             raise
         finally:
             QApplication.restoreOverrideCursor()
         self.form.pushButton_edit.setEnabled(True)
         self.form.pushButton_generate.setEnabled(True)
Exemple #31
0
    def calculate(self):
        FreeCAD.FEM_dialog["results_type"] = "None"
        self.update()
        self.restore_result_dialog()
        # Convert existing values to numpy array
        P1 = np.array(self.result_obj.PrincipalMax)
        P2 = np.array(self.result_obj.PrincipalMed)
        P3 = np.array(self.result_obj.PrincipalMin)
        Von = np.array(self.result_obj.StressValues)
        Peeq = np.array(self.result_obj.Peeq)
        T = np.array(self.result_obj.Temperature)
        MF = np.array(self.result_obj.MassFlowRate)
        NP = np.array(self.result_obj.NetworkPressure)
        dispvectors = np.array(self.result_obj.DisplacementVectors)
        x = np.array(dispvectors[:, 0])
        y = np.array(dispvectors[:, 1])
        z = np.array(dispvectors[:, 2])
        stressvectors = np.array(self.result_obj.StressVectors)
        sx = np.array(stressvectors[:, 0])
        sy = np.array(stressvectors[:, 1])
        sz = np.array(stressvectors[:, 2])
        strainvectors = np.array(self.result_obj.StrainVectors)
        ex = np.array(strainvectors[:, 0])
        ey = np.array(strainvectors[:, 1])
        ez = np.array(strainvectors[:, 2])
        userdefined_eq = self.form.user_def_eq.toPlainText()  # Get equation to be used
        UserDefinedFormula = eval(userdefined_eq).tolist()
        self.result_obj.UserDefined = UserDefinedFormula
        minm = min(UserDefinedFormula)
        avg = sum(UserDefinedFormula) / len(UserDefinedFormula)
        maxm = max(UserDefinedFormula)

        QApplication.setOverrideCursor(Qt.WaitCursor)
        if self.suitable_results:
            self.mesh_obj.ViewObject.setNodeColorByScalars(self.result_obj.NodeNumbers, UserDefinedFormula)
        self.set_result_stats("", minm, avg, maxm)
        QtGui.QApplication.restoreOverrideCursor()
        del x, y, z, T, Von, Peeq, P1, P2, P3, sx, sy, sz, ex, ey, ez, MF, NP  # Dummy use of the variables to get around flake8 error
    def runSolverProcess(self):
        self.Start = time.time()

        solverDirectory = os.path.join(self.working_dir, self.solver_object.InputCaseName)
        solverDirectory = os.path.abspath(solverDirectory)
        cmd = self.solver_runner.get_solver_cmd(solverDirectory)
        FreeCAD.Console.PrintMessage(' '.join(cmd) + '\n')
        self.consoleMessage("Starting solver command:")
        self.consoleMessage(' '.join(cmd))
        envVars = self.solver_runner.getRunEnvironment()
        QApplication.setOverrideCursor(Qt.WaitCursor)
        self.solver_run_process.start(cmd, env_vars=envVars)
        if self.solver_run_process.waitForStarted():
            # Setting solve button to inactive to ensure that two instances of the same simulation aren't started
            # simultaneously
            self.form.pb_write_inp.setEnabled(False)
            self.form.pb_run_solver.setEnabled(False)
            self.form.terminateSolver.setEnabled(True)
            self.form.pb_paraview.setEnabled(True)
            self.consoleMessage("Solver started")
        else:
            self.consoleMessage("Error starting solver")
        QApplication.restoreOverrideCursor()
    def OnSaveFilePath(self, filePath):
        """"""
        file = QFile(filePath)
        if not file.open(QFile.WriteOnly | QFile.Text):
            QMessageBox.warning(
                self, self.tr('Warning'),
                self.tr('Cannot write file') + ' %s:\n%s.' %
                (filePath, file.errorString()))
            return False

        outf = QTextStream(file)
        QApplication.setOverrideCursor(Qt.WaitCursor)
        outf << self.toPlainText()
        QApplication.restoreOverrideCursor()

        self.DoSetCurrentFilePath(filePath)

        # Clear the Modified Flag.
        self.document().setModified(False)
        self.setWindowModified(False)
        self.setWindowTitle('%s[*]' % self.fileName)

        return True
Exemple #34
0
    def openParaview(self):
        self.Start = time.time()
        QApplication.setOverrideCursor(Qt.WaitCursor)

        paraview_cmd = "paraview"
        # If using blueCFD, use paraview supplied
        if CfdTools.getFoamRuntime() == 'BlueCFD':
            paraview_cmd = '{}\\..\\AddOns\\ParaView\\bin\\paraview.exe'.format(
                CfdTools.getFoamDir())
        # Otherwise, the command 'paraview' must be in the path. Possibly make path user-settable.
        # Test to see if it exists, as the exception thrown is cryptic on Windows if it doesn't
        import distutils.spawn
        if distutils.spawn.find_executable(paraview_cmd) is None:
            raise IOError("Paraview executable " + paraview_cmd +
                          " not found in path.")

        self.paraviewScriptName = os.path.join(self.meshCaseDir,
                                               'pvScriptMesh.py')
        arg = '--script={}'.format(self.paraviewScriptName)

        self.console_log("Running " + paraview_cmd + " " + arg)
        self.open_paraview.start(paraview_cmd, [arg])
        QApplication.restoreOverrideCursor()
Exemple #35
0
 def __init__(self, state, parent=None):
     super().__init__(parent)
     Lib.prepareModalDialog(self)
     self.state = state
     self.setWindowTitle("Combine Overlapping Pages — {}".format(
         QApplication.applicationName()))
     self.createWidgets()
     self.layoutWidgets()
     self.createConnections()
     self.entry = None
     QApplication.setOverrideCursor(Qt.WaitCursor)
     try:
         self.eids = list(
             self.state.model.filteredEntries(
                 filter=FilterKind.HAS_OVERLAPPING_PAGES,
                 match=None,
                 offset=0,
                 limit=UNLIMITED,
                 entryData=EntryDataKind.EID))
     finally:
         QApplication.restoreOverrideCursor()
     self.eidIndex = -1 if self.eids else None
     if self.eids:
         self.skip()
         self.combineButton.setFocus()
         say(
             "Found {:,} entries with overlapping pages".format(
                 len(self.eids)), SAY_TIMEOUT)
     else:
         say("No overlapping pages found", SAY_TIMEOUT)
     self.updateUi()
     settings = QSettings()
     self.updateToolTips(
         bool(
             int(
                 settings.value(Gopt.Key.ShowDialogToolTips,
                                Gopt.Default.ShowDialogToolTips))))
    def run_gmsh(self):
        QApplication.setOverrideCursor(Qt.WaitCursor)
        part = self.mesh_obj.Part
        if self.mesh_obj.MeshRegionList:
            if part.Shape.ShapeType == "Compound" and hasattr(
                    part, "Proxy"
            ):  # other part obj might not have a Proxy, thus an exception would be raised
                if (part.Proxy.Type == "FeatureBooleanFragments"
                        or part.Proxy.Type == "FeatureSlice"
                        or part.Proxy.Type == "FeatureXOR"):
                    error_message = "The mesh to shape is a boolean split tools Compound and the mesh has mesh region list. GMSH could return unexpected meshes in such circumstances. It is strongly recommended to extract the shape to mesh from the Compound and use this one."
                    QtGui.QMessageBox.critical(
                        None,
                        "Shape to mesh is a BooleanFragmentsCompound and mesh regions are defined",
                        error_message)
        self.Start = time.time()
        self.form.l_time.setText('Time: {0:4.1f}: '.format(time.time() -
                                                           self.Start))
        self.console_message_gmsh = ''
        self.gmsh_runs = True
        self.console_log("We are going to start ...")
        self.get_active_analysis()

        self.console_log("Start GMSH ...")
        error = CfdTools.runGmsh(self.mesh_obj, self.analysis)
        if error:
            print(error)
            self.console_log('GMSH had warnings ...')
            self.console_log(error, '#FF0000')
        else:
            self.console_log('Clean run of GMSH')
        self.console_log("GMSH done!")
        self.form.l_time.setText('Time: {0:4.1f}: '.format(time.time() -
                                                           self.Start))
        self.Timer.stop()
        self.update()
        QApplication.restoreOverrideCursor()
Exemple #37
0
    def addRelation(self, qnode):
        """ Adds a relation or save a starting point
        
        """
        if self.startRelation != None:  # yeah a new relation
            self.log.info("Add relation from " + self.startRelation.node +
                          " to " + qnode.node)
            if self.relations.currentText() == "---":
                msg = QMessageBox()
                msg.setText("Please choose a valid variant.")
                msg.exec_()
                return
            addstr = "\n(" + self.relations.currentText(
            ) + " " + self.startRelation.node + " " + qnode.node + ")\n"
            self.startRelation = None
            ontology = None
            for i in self.getIndexAbstractor().ontologies:
                if i.name == self.activeOntology.currentText():
                    ontology = i

            if ontology is None:
                msg = QMessageBox()
                msg.setText("Please choose a valid Ontology to write to.")
                msg.exec_()
                return
            self.lineEdit.setText(qnode.node)
            x = self.getIndexAbstractor().get_ontology_file(ontology)
            x.seek(0, 2)
            x.write(addstr)
            QApplication.setOverrideCursor(Qt.BusyCursor)
            self.SyntaxController.add_ontology(ontology,
                                               newversion=x.getvalue())
            QApplication.setOverrideCursor(Qt.ArrowCursor)
            self.commit()
        else:
            self.log.info("Starting node is " + qnode.node)
            self.startRelation = qnode
Exemple #38
0
    def calculate(self):
        FreeCAD.FEM_dialog["results_type"] = "None"
        self.update()
        self.restore_result_dialog()
        # Convert existing values to numpy array
        P1 = np.array(self.result_object.PrincipalMax)
        P2 = np.array(self.result_object.PrincipalMed)
        P3 = np.array(self.result_object.PrincipalMin)
        Von = np.array(self.result_object.StressValues)
        T = np.array(self.result_object.Temperature)
        dispvectors = np.array(self.result_object.DisplacementVectors)
        x = np.array(dispvectors[:, 0])
        y = np.array(dispvectors[:, 1])
        z = np.array(dispvectors[:, 2])
        stressvectors = np.array(self.result_object.StressVectors)
        sx = np.array(stressvectors[:, 0])
        sy = np.array(stressvectors[:, 1])
        sz = np.array(stressvectors[:, 2])
        strainvectors = np.array(self.result_object.StrainVectors)
        ex = np.array(strainvectors[:, 0])
        ey = np.array(strainvectors[:, 1])
        ez = np.array(strainvectors[:, 2])
        userdefined_eq = x + y + z + T + Von + P1 + P2 + P3 + sx + sy + sz + ex + ey + ez  # Dummy equation to get around flake8, varibles not being used
        userdefined_eq = self.form.user_def_eq.toPlainText(
        )  # Get equation to be used
        UserDefinedFormula = eval(userdefined_eq).tolist()
        self.result_object.UserDefined = UserDefinedFormula
        minm = min(UserDefinedFormula)
        avg = sum(UserDefinedFormula) / len(UserDefinedFormula)
        maxm = max(UserDefinedFormula)

        QApplication.setOverrideCursor(Qt.WaitCursor)
        if self.suitable_results:
            self.MeshObject.ViewObject.setNodeColorByScalars(
                self.result_object.NodeNumbers, UserDefinedFormula)
        self.set_result_stats("", minm, avg, maxm)
        QtGui.qApp.restoreOverrideCursor()
    def calculixFinished(self, exitCode):
        print("calculixFinished() {}".format(exitCode))
        print(self.Calculix.state())

        # Restore previous cwd
        QtCore.QDir.setCurrent(self.cwd)

        self.printCalculiXstdout()
        self.Timer.stop()

        self.femConsoleMessage("CalculiX done!", "#00AA00")

        self.form.pb_run_ccx.setText("Re-run CalculiX")
        self.femConsoleMessage("Loading result sets...")
        self.form.l_time.setText('Time: {0:4.1f}: '.format(time.time() -
                                                           self.Start))
        fea = FemToolsCcx.FemToolsCcx(None, self.solver_object)
        fea.reset_mesh_purge_results_checked()
        fea.inp_file_name = self.inp_file_name
        QApplication.setOverrideCursor(Qt.WaitCursor)
        fea.load_results()
        QApplication.restoreOverrideCursor()
        self.form.l_time.setText('Time: {0:4.1f}: '.format(time.time() -
                                                           self.Start))
    def calculixFinished(self, exitCode):
        print("calculixFinished() {}".format(exitCode))
        print(self.Calculix.state())

        # Restore previous cwd
        QtCore.QDir.setCurrent(self.cwd)

        self.Timer.stop()

        if self.printCalculiXstdout():
            self.calculixNoError()
        else:
            self.calculixError()

        self.form.pb_run_ccx.setText("Re-run CalculiX")
        self.femConsoleMessage("Loading result sets...")
        self.form.l_time.setText('Time: {0:4.1f}: '.format(time.time() -
                                                           self.Start))
        fea = ccxtools.FemToolsCcx(None, self.solver_object)
        fea.reset_mesh_purge_results_checked()
        fea.inp_file_name = self.inp_file_name
        QApplication.setOverrideCursor(Qt.WaitCursor)
        try:
            fea.load_results()
        except:
            QApplication.restoreOverrideCursor()
            majorVersion, minorVersion = fea.get_ccx_version()
            if majorVersion == 2 and minorVersion <= 10:
                message = "The used CalculiX version {}.{} creates broken output files.\n" \
                    "Please upgrade to a newer version.".format(majorVersion, minorVersion)
                QtGui.QMessageBox.warning(None, "Upgrade CalculiX", message)
            raise
        else:
            QApplication.restoreOverrideCursor()
            self.form.l_time.setText('Time: {0:4.1f}: '.format(time.time() -
                                                               self.Start))
Exemple #41
0
    def analysePlugins(self):
        if self.check2to3Script():
            self._ui.label_2.setText('2to3.py script not found.\nPlease locate it in the Options tab.')
            return
        else:
            self._pluginUpdater._pluginUpdateDict = {}
            QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
            package = reload(sys.modules[PLUGINS_PACKAGE_NAME])
#             try:
#                 package = imp.reload(sys.modules['mapclientplugins'])
#             except Exception:
#                 package = importlib.reload(sys.modules['mapclientplugins'])
            for _, modname, ispkg in pkgutil.iter_modules(package.__path__):
                if ispkg and modname != 'imagesourcestep' and modname != 'pointcloudserializerstep':
                    self._pluginUpdater._directory = _.path
                    (plugin_init_update, plugin_resources_update, plugin_syntax_update, plugin_tabbed_indentation, resourcesDirs, tabbed_modules) = performPluginAnalysis(_.path, modname, self._resourceFiles)
                    self._pluginUpdater.pluginUpdateDict(modname, plugin_init_update, plugin_resources_update, plugin_syntax_update, \
                                                        plugin_tabbed_indentation, os.path.join(_.path, modname, '__init__.py'), resourcesDirs, tabbed_modules)
            self.fillUpdatesList()

            if self._ui.listWidget.count() == 0:
                self._ui.label_2.setText('None of your plugins require updates at this time.')
            else:
                self._ui.label_2.setText('Tip: Update a single plugin by double-clicking!')
Exemple #42
0
 def runMeshProcess(self):
     self.console_message_cart = ''
     self.Start = time.time()
     self.Timer.start()
     # Re-initialise CfdMeshTools with new parameters
     self.set_mesh_params()
     self.cart_mesh = CfdMeshTools.CfdMeshTools(self.mesh_obj)
     self.consoleMessage("Starting meshing ...")
     try:
         QApplication.setOverrideCursor(Qt.WaitCursor)
         self.get_active_analysis()
         self.set_mesh_params()
         cart_mesh = self.cart_mesh
         setInputFieldQuantity(self.form.if_max, str(cart_mesh.get_clmax()))
         print("\nStarting meshing ...\n")
         print('  Part to mesh: Name --> ' + cart_mesh.part_obj.Name +
               ',  Label --> ' + cart_mesh.part_obj.Label +
               ', ShapeType --> ' + cart_mesh.part_obj.Shape.ShapeType)
         print('  CharacteristicLengthMax: ' + str(cart_mesh.clmax))
         cart_mesh.get_dimension()
         cart_mesh.get_file_paths(CfdTools.getOutputPath(self.analysis))
         cart_mesh.setup_mesh_case_dir()
         self.consoleMessage("Exporting mesh region data ...")
         cart_mesh.get_region_data(
         )  # Writes region stls so need file structure
         cart_mesh.write_mesh_case()
         self.consoleMessage("Exporting the part surfaces ...")
         cart_mesh.write_part_file()
         self.consoleMessage("Running {} ...".format(self.utility))
         self.runCart(cart_mesh)
     except Exception as ex:
         self.consoleMessage("Error: " + str(ex), '#FF0000')
         self.Timer.stop()
         raise
     finally:
         QApplication.restoreOverrideCursor()
Exemple #43
0
    def __init__(self, theScene, parent=None):
        """
        Default class constructor.

        :param `theScene`: TOWRITE
        :type `theScene`: `QGraphicsScene`_
        :param `parent`: Pointer to a parent widget instance.
        :type `parent`: `QWidget`_
        """
        super(EmbDetailsDialog, self).__init__(parent)

        self.setMinimumSize(750, 550)

        self.getInfo()
        self.mainWidget = self.createMainWidget()

        self.buttonBox = QDialogButtonBox(QDialogButtonBox.Ok)
        self.buttonBox.accepted.connect(self.accept)

        vboxLayoutMain = QVBoxLayout(self)
        vboxLayoutMain.addWidget(self.mainWidget)
        vboxLayoutMain.addWidget(self.buttonBox)
        self.setLayout(vboxLayoutMain)

        self.setWindowTitle(self.tr("Embroidery Design Details"))

        QApplication.setOverrideCursor(Qt.ArrowCursor)

        self.stitchesTotal = int()
        self.stitchesReal = int()
        self.stitchesJump = int()
        self.stitchesTrim = int()
        self.colorTotal = int
        self.colorChanges = int()

        self.boundingRect = QRectF()
Exemple #44
0
 def run_gmsh(self):
     QApplication.setOverrideCursor(Qt.WaitCursor)
     partsh = self.obj.Part
     if partsh.Shape.ShapeType == "Compound":
         error_message = "The mesh to shape is a Compound, GMSH could return unexpected meshes for Compounds. It is strongly recommended to extract the shape to mesh from the Compound and use this one."
         FreeCAD.Console.PrintError(error_message + "\n")
         if hasattr(partsh, "Proxy") and (partsh.Proxy.Type == "FeatureBooleanFragments" or partsh.Proxy.Type == "FeatureSlice" or partsh.Proxy.Type == "FeatureXOR"):  # other part obj might not have a Proxy
             error_message = "The mesh to shape is a boolean split tools Compound, GMSH could return unexpected meshes for a boolean split tools Compound. It is strongly recommended to extract the shape to mesh from the Compound and use this one."
             FreeCAD.Console.PrintError(error_message + "\n")
             QtGui.QMessageBox.critical(None, "Shape to mesh is a Compound", error_message)
     self.Start = time.time()
     self.form.l_time.setText('Time: {0:4.1f}: '.format(time.time() - self.Start))
     self.console_message_gmsh = ''
     self.gmsh_runs = True
     self.console_log("We gone start ...")
     self.get_active_analysis()
     import FemGmshTools
     gmsh_mesh = FemGmshTools.FemGmshTools(self.obj, self.analysis)
     self.console_log("Start GMSH ...")
     error = ''
     try:
         error = gmsh_mesh.create_mesh()
     except:
         import sys
         print("Unexpected error when creating mesh: ", sys.exc_info()[0])
     if error:
         print(error)
         self.console_log('GMSH had warnings ...')
         self.console_log(error, '#FF0000')
     else:
         self.console_log('Clean run of GMSH')
     self.console_log("GMSH done!")
     self.form.l_time.setText('Time: {0:4.1f}: '.format(time.time() - self.Start))
     self.Timer.stop()
     self.update()
     QApplication.restoreOverrideCursor()
 def write_input_file_handler(self):
     self.Start = time.time()
     if self.check_prerequisites_helper():
         self.consoleMessage("{} case writer is called".format(
             self.solver_object.SolverName))
         self.form.pb_paraview.setEnabled(False)
         self.form.pb_edit_inp.setEnabled(False)
         self.form.pb_run_solver.setEnabled(False)
         QApplication.setOverrideCursor(Qt.WaitCursor)
         try:
             self.solver_runner.writer.writeCase()
         except Exception as e:
             self.consoleMessage("Error writing case:", "#FF0000")
             self.consoleMessage(str(e), "#FF0000")
             self.consoleMessage("Write case setup file failed", "#FF0000")
             raise
         finally:
             QApplication.restoreOverrideCursor()
         self.consoleMessage("Write {} case is completed".format(
             self.solver_object.SolverName))
         self.updateUI()
         self.form.pb_run_solver.setEnabled(True)
     else:
         self.consoleMessage("Case check failed", "#FF0000")
Exemple #46
0
    def keyPressEvent(self, event):
        super(myCodeWidget, self).keyPressEvent(event)

        if event.modifiers() & Qt.ControlModifier:
            QApplication.setOverrideCursor(QCursor(Qt.PointingHandCursor))
Exemple #47
0
 def showDisplacementClicked(self, bool):
     QApplication.setOverrideCursor(Qt.WaitCursor)
     self.setDisplacement()
     QtGui.qApp.restoreOverrideCursor()
    def run(self):
        self.Start = time.time()

        #dirName = self.formUi.lineEdit_outputDir.text()
        dirName = self.TempDir
        print 'run() dir:', dirName
        self.OutStr = self.OutStr + '<font color="#0000FF">{0:4.1f}:</font> '.format(
            time.time() - self.Start) + 'Check dependencies...<br>'
        self.formUi.textEdit_Output.setText(self.OutStr)
        self.formUi.label_Time.setText('Time: {0:4.1f}: '.format(time.time() -
                                                                 self.Start))
        MeshObject = None
        if FemGui.getActiveAnalysis():
            for i in FemGui.getActiveAnalysis().Member:
                if i.isDerivedFrom("Fem::FemMeshObject"):
                    MeshObject = i
        else:
            QtGui.QMessageBox.critical(None, "Missing prerequisit",
                                       "No active Analysis")
            return

        if not MeshObject:
            QtGui.QMessageBox.critical(None, "Missing prerequisit",
                                       "No mesh object in the Analysis")
            return

        MathObject = None
        for i in FemGui.getActiveAnalysis().Member:
            if i.isDerivedFrom("App::MaterialObjectPython"):
                MathObject = i
        if not MathObject:
            QtGui.QMessageBox.critical(None, "Missing prerequisit",
                                       "No material object in the Analysis")
            return
        matmap = MathObject.Material

        FixedObject = None
        for i in FemGui.getActiveAnalysis().Member:
            if i.isDerivedFrom("Fem::ConstraintFixed"):
                FixedObject = i
        if not FixedObject:
            QtGui.QMessageBox.critical(
                None, "Missing prerequisit",
                "No fixed-constraint nodes defined in the Analysis")
            return

        ForceObject = None
        for i in FemGui.getActiveAnalysis().Member:
            if i.isDerivedFrom("Fem::ConstraintForce"):
                ForceObject = i
        if not ForceObject:
            QtGui.QMessageBox.critical(
                None, "Missing prerequisit",
                "No force-constraint nodes defined in the Analysis")
            return

        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))

        self.Basename = self.TempDir + '/' + MeshObject.Name
        filename = self.Basename + '.inp'

        self.OutStr = self.OutStr + '<font color="#0000FF">{0:4.1f}:</font> '.format(
            time.time() - self.Start) + self.Basename + '<br>'
        self.formUi.textEdit_Output.setText(self.OutStr)

        self.OutStr = self.OutStr + '<font color="#0000FF">{0:4.1f}:</font> '.format(
            time.time() - self.Start) + 'Write mesh...<br>'
        self.formUi.textEdit_Output.setText(self.OutStr)

        MeshObject.FemMesh.writeABAQUS(filename)
        # reopen file with "append" and add the analysis definition
        inpfile = open(filename, 'a')
        inpfile.write('\n\n')

        self.OutStr = self.OutStr + '<font color="#0000FF">{0:4.1f}:</font> '.format(
            time.time() - self.Start) + 'Write loads & Co...<br>'
        self.formUi.textEdit_Output.setText(self.OutStr)

        # write the fixed node set
        NodeSetName = FixedObject.Name
        inpfile.write('*NSET,NSET=' + NodeSetName + '\n')
        for o, f in FixedObject.References:
            fo = o.Shape.getElement(f)
            n = MeshObject.FemMesh.getNodesByFace(fo)
            for i in n:
                inpfile.write(str(i) + ',\n')
        inpfile.write('\n\n')

        # write the load node set
        NodeSetNameForce = ForceObject.Name
        inpfile.write('*NSET,NSET=' + NodeSetNameForce + '\n')
        NbrForceNods = 0
        for o, f in ForceObject.References:
            fo = o.Shape.getElement(f)
            n = MeshObject.FemMesh.getNodesByFace(fo)
            for i in n:
                inpfile.write(str(i) + ',\n')
                NbrForceNods = NbrForceNods + 1
        inpfile.write('\n\n')

        # get the material properties
        YM = FreeCAD.Units.Quantity(
            MathObject.Material['Mechanical_youngsmodulus'])
        if YM.Unit.Type == '':
            print 'Material "Mechanical_youngsmodulus" has no Unit, asuming kPa!'
            YM = FreeCAD.Units.Quantity(YM.Value, FreeCAD.Units.Unit('Pa'))

        print YM

        PR = float(MathObject.Material['FEM_poissonratio'])
        print PR

        # now open again and write the setup:
        inpfile.write('*MATERIAL, Name=' + matmap['General_name'] + '\n')
        inpfile.write('*ELASTIC \n')
        inpfile.write('{0:.3f}, '.format(YM.Value))
        inpfile.write('{0:.3f}\n'.format(PR))
        inpfile.write('*SOLID SECTION, Elset=Eall, Material=' +
                      matmap['General_name'] + '\n')
        inpfile.write('*INITIAL CONDITIONS, TYPE=STRESS, USER\n')
        inpfile.write('*STEP\n')
        inpfile.write('*STATIC\n')
        inpfile.write('*BOUNDARY\n')
        inpfile.write(NodeSetName + ',1,3,0.0\n')
        #inpfile.write('*DLOAD\n')
        #inpfile.write('Eall,NEWTON\n')

        Force = (ForceObject.Force * 1000.0) / NbrForceNods
        vec = ForceObject.NormalDirection
        inpfile.write('*CLOAD\n')
        inpfile.write(NodeSetNameForce + ',1,' + ` vec.x * Force ` + '\n')
        inpfile.write(NodeSetNameForce + ',2,' + ` vec.y * Force ` + '\n')
        inpfile.write(NodeSetNameForce + ',3,' + ` vec.z * Force ` + '\n')

        inpfile.write('*NODE FILE\n')
        inpfile.write('U\n')
        inpfile.write('*EL FILE\n')
        inpfile.write('S, E\n')
        inpfile.write('*NODE PRINT , NSET=Nall \n')
        inpfile.write('U \n')
        inpfile.write('*EL PRINT , ELSET=Eall \n')
        inpfile.write('S \n')
        inpfile.write('*END STEP \n')

        self.OutStr = self.OutStr + '<font color="#0000FF">{0:4.1f}:</font> '.format(
            time.time() - self.Start) + self.CalculixBinary + '<br>'
        self.formUi.textEdit_Output.setText(self.OutStr)

        self.OutStr = self.OutStr + '<font color="#0000FF">{0:4.1f}:</font> '.format(
            time.time() - self.Start) + 'Run Calculix...<br>'
        self.formUi.textEdit_Output.setText(self.OutStr)

        # run Claculix
        print 'run Calclulix at:', self.CalculixBinary, '  with: ', self.Basename
        self.Calculix.start(self.CalculixBinary, ['-i', self.Basename])

        QApplication.restoreOverrideCursor()
 def runDependencyChecker(self):
     self.thread.task = DEPENDENCY_CHECK
     self.startThread()
     QApplication.setOverrideCursor(Qt.WaitCursor)
Exemple #50
0
    def writeCalculixInputFile(self):
        print 'writeCalculixInputFile'
        self.Start = time.time()

        #dirName = self.form.lineEdit_outputDir.text()
        dirName = self.TempDir
        print 'CalculiX run directory: ', dirName
        self.femConsoleMessage("Check dependencies...")
        self.form.label_Time.setText('Time: {0:4.1f}: '.format(time.time() -
                                                               self.Start))
        MeshObject = None
        if FemGui.getActiveAnalysis():
            for i in FemGui.getActiveAnalysis().Member:
                if i.isDerivedFrom("Fem::FemMeshObject"):
                    MeshObject = i
        else:
            QtGui.QMessageBox.critical(None, "Missing prerequisit",
                                       "No active Analysis")
            return

        if not MeshObject:
            QtGui.QMessageBox.critical(None, "Missing prerequisit",
                                       "No mesh object in the Analysis")
            return

        MathObject = None
        for i in FemGui.getActiveAnalysis().Member:
            if i.isDerivedFrom("App::MaterialObjectPython"):
                MathObject = i
        if not MathObject:
            QtGui.QMessageBox.critical(None, "Missing prerequisit",
                                       "No material object in the Analysis")
            return
        matmap = MathObject.Material

        FixedObject = None
        for i in FemGui.getActiveAnalysis().Member:
            if i.isDerivedFrom("Fem::ConstraintFixed"):
                FixedObject = i
        if not FixedObject:
            QtGui.QMessageBox.critical(
                None, "Missing prerequisit",
                "No fixed-constraint nodes defined in the Analysis")
            return

        ForceObject = None
        for i in FemGui.getActiveAnalysis().Member:
            if i.isDerivedFrom("Fem::ConstraintForce"):
                ForceObject = i
        if not ForceObject:
            QtGui.QMessageBox.critical(
                None, "Missing prerequisit",
                "No force-constraint nodes defined in the Analysis")
            return

        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))

        self.Basename = self.TempDir + '/' + MeshObject.Name
        filename = self.Basename + '.inp'

        self.femConsoleMessage(self.Basename)
        self.femConsoleMessage("Write mesh...")

        # write mesh
        MeshObject.FemMesh.writeABAQUS(filename)

        # reopen file with "append" and add the analysis definition
        inpfile = open(filename, 'a')

        self.femConsoleMessage("Write loads & Co...")

        # write fixed node set
        NodeSetName = FixedObject.Name
        inpfile.write(
            '\n\n\n\n***********************************************************\n'
        )
        inpfile.write('** node set for fixed constraint\n')
        inpfile.write('*NSET,NSET=' + NodeSetName + '\n')
        for o, f in FixedObject.References:
            fo = o.Shape.getElement(f)
            if fo.ShapeType == 'Face':
                FixedObjectType = 'AreaSupport'
                n = MeshObject.FemMesh.getNodesByFace(fo)
                for i in n:
                    inpfile.write(str(i) + ',\n')
            elif fo.ShapeType == 'Edge':
                FixedObjectType = 'LineSupport'
                print 'Line Supports are not yet implemented to export to CalculiX'
                # getNodesByEdge(fo) # not implemented yet
            elif fo.ShapeType == 'Vertex':
                FixedObjectType = 'PointSupport'
                print 'Point Supports are not yet implemented to export to CalculiX'

        # write load node set
        NodeSetNameForce = ForceObject.Name
        inpfile.write(
            '\n\n\n\n***********************************************************\n'
        )
        inpfile.write('** node set for load\n')
        inpfile.write('*NSET,NSET=' + NodeSetNameForce + '\n')
        NbrForceNods = 0
        for o, f in ForceObject.References:
            fo = o.Shape.getElement(f)
            if fo.ShapeType == 'Face':
                ForceObjectType = 'AreaLoad'
                n = MeshObject.FemMesh.getNodesByFace(fo)
                for i in n:
                    inpfile.write(str(i) + ',\n')
                    NbrForceNods = NbrForceNods + 1
            elif fo.ShapeType == 'Edge':
                ForceObjectType = 'LineLoad'
                print 'Line Loads are not yet implemented to export to CalculiX'
                # getNodesByEdge(fo) # not implemented yet
            elif fo.ShapeType == 'Vertex':
                ForceObjectType = 'PointLoad'
                print 'Point Loads are not yet implemented to export to CalculiX'

        # get material properties
        YM = FreeCAD.Units.Quantity(
            MathObject.Material['Mechanical_youngsmodulus'])
        if YM.Unit.Type == '':
            print 'Material "Mechanical_youngsmodulus" has no Unit, asuming kPa!'
            YM = FreeCAD.Units.Quantity(YM.Value, FreeCAD.Units.Unit('Pa'))
        else:
            print 'YM unit: ', YM.Unit.Type
        print 'YM = ', YM

        PR = float(MathObject.Material['FEM_poissonratio'])
        print 'PR = ', PR

        # write material properties
        inpfile.write(
            '\n\n\n\n***********************************************************\n'
        )
        inpfile.write('** material\n')
        inpfile.write('** unit is MPa = N/mm2\n')
        inpfile.write('*MATERIAL, Name=' + matmap['General_name'] + '\n')
        inpfile.write('*ELASTIC \n')
        inpfile.write('{0:.3f}, '.format(YM.Value * 1E-3))
        inpfile.write('{0:.3f}\n'.format(PR))
        inpfile.write('*SOLID SECTION, Elset=Eall, Material=' +
                      matmap['General_name'] + '\n')

        # write step beginn
        inpfile.write(
            '\n\n\n\n***********************************************************\n'
        )
        inpfile.write(
            '** one step is needed to calculate the mechanical analysis of FreeCAD\n'
        )
        inpfile.write(
            '** loads are applied quasi-static, means without involving the time dimension\n'
        )
        inpfile.write('*STEP\n')
        inpfile.write('*STATIC\n')

        # write constaints
        inpfile.write('\n\n** constaints\n')
        if FixedObjectType == 'AreaSupport':
            inpfile.write('*BOUNDARY\n')
            inpfile.write(NodeSetName + ',1,3,0.0\n')
        elif FixedObjectType == 'LineSupport':
            pass  # ToDo
        elif FixedObjectType == 'PointSupport':
            pass  # ToDo

        # write loads
        #inpfile.write('*DLOAD\n')
        #inpfile.write('Eall,NEWTON\n')
        inpfile.write('\n\n** loads\n')
        if ForceObjectType == 'AreaLoad':
            Force = ForceObject.Force / NbrForceNods
            vec = ForceObject.DirectionVector
            inpfile.write('** direction: ' + str(vec) + '\n')
            inpfile.write(
                '** concentrated load [N] distributed on the area of the given faces.\n'
            )
            inpfile.write('** ' + str(ForceObject.Force) + ' N / ' +
                          str(NbrForceNods) + ' Nodes = ' + str(Force) +
                          ' N on each node\n')
            inpfile.write('*CLOAD\n')
            inpfile.write(NodeSetNameForce + ',1,' + ` vec.x * Force ` + '\n')
            inpfile.write(NodeSetNameForce + ',2,' + ` vec.y * Force ` + '\n')
            inpfile.write(NodeSetNameForce + ',3,' + ` vec.z * Force ` + '\n')
        elif ForceObjectType == 'LineLoad':
            pass  # ToDo
        elif ForceObjectType == 'PointLoad':
            pass  # ToDo

        # write outputs, both are needed by FreeCAD
        inpfile.write('\n\n** outputs --> frd file\n')
        inpfile.write('*NODE FILE\n')
        inpfile.write('U\n')
        inpfile.write('*EL FILE\n')
        inpfile.write('S, E\n')
        inpfile.write('** outputs --> dat file\n')
        inpfile.write('*NODE PRINT , NSET=Nall \n')
        inpfile.write('U \n')
        inpfile.write('*EL PRINT , ELSET=Eall \n')
        inpfile.write('S \n')
        inpfile.write('\n\n')

        # write step end
        inpfile.write('*END STEP \n')

        # write some informations
        FcVersionInfo = FreeCAD.Version()
        inpfile.write(
            '\n\n\n\n***********************************************************\n'
        )
        inpfile.write('**\n')
        inpfile.write('**   CalculiX Inputfile\n')
        inpfile.write('**\n')
        inpfile.write('**   written by    --> FreeCAD ' + FcVersionInfo[0] +
                      '.' + FcVersionInfo[1] + '.' + FcVersionInfo[2] + '\n')
        inpfile.write('**   written on    --> ' + time.ctime() + '\n')
        inpfile.write('**   file name     --> ' +
                      os.path.basename(FreeCAD.ActiveDocument.FileName) + '\n')
        inpfile.write('**   analysis name --> ' +
                      FemGui.getActiveAnalysis().Name + '\n')
        inpfile.write('**\n')
        inpfile.write('**\n')
        inpfile.write('**   Units\n')
        inpfile.write('**\n')
        inpfile.write('**   Geometry (mesh data)        --> mm\n')
        inpfile.write("**   Materials (young's modulus) --> N/mm2 = MPa\n")
        inpfile.write('**   Loads (nodal loads)         --> N\n')
        inpfile.write('**\n')
        inpfile.write('**\n')

        inpfile.close()

        QApplication.restoreOverrideCursor()
    def calculate(self):
        FreeCAD.FEM_dialog["results_type"] = "None"
        self.update()
        self.restore_result_dialog()
        # Convert existing values to numpy array
        P1 = np.array(self.result_obj.PrincipalMax)
        P2 = np.array(self.result_obj.PrincipalMed)
        P3 = np.array(self.result_obj.PrincipalMin)
        Von = np.array(self.result_obj.StressValues)
        Peeq = np.array(self.result_obj.Peeq)
        T = np.array(self.result_obj.Temperature)
        MF = np.array(self.result_obj.MassFlowRate)
        NP = np.array(self.result_obj.NetworkPressure)
        dispvectors = np.array(self.result_obj.DisplacementVectors)
        x = np.array(dispvectors[:, 0])
        y = np.array(dispvectors[:, 1])
        z = np.array(dispvectors[:, 2])
        sxx = np.array(self.result_obj.NodeStressXX)
        syy = np.array(self.result_obj.NodeStressYY)
        szz = np.array(self.result_obj.NodeStressZZ)
        sxy = np.array(self.result_obj.NodeStressXY)
        sxz = np.array(self.result_obj.NodeStressXZ)
        syz = np.array(self.result_obj.NodeStressYZ)
        exx = np.array(self.result_obj.NodeStrainXX)
        eyy = np.array(self.result_obj.NodeStrainYY)
        ezz = np.array(self.result_obj.NodeStrainZZ)
        exy = np.array(self.result_obj.NodeStrainXY)
        exz = np.array(self.result_obj.NodeStrainXZ)
        eyz = np.array(self.result_obj.NodeStrainYZ)

        # Display of Reinforcement Ratios and Mohr Coulomb Criterion
        rx = np.array(self.result_obj.ReinforcementRatio_x)
        ry = np.array(self.result_obj.ReinforcementRatio_y)
        rz = np.array(self.result_obj.ReinforcementRatio_z)
        mc = np.array(self.result_obj.MohrCoulomb)

        ps1vector = np.array(self.result_obj.PS1Vector)
        s1x = np.array(ps1vector[:, 0])
        s1y = np.array(ps1vector[:, 1])
        s1z = np.array(ps1vector[:, 2])

        ps2vector = np.array(self.result_obj.PS2Vector)
        s2x = np.array(ps2vector[:, 0])
        s2y = np.array(ps2vector[:, 1])
        s2z = np.array(ps2vector[:, 2])

        ps3vector = np.array(self.result_obj.PS1Vector)
        s3x = np.array(ps3vector[:, 0])
        s3y = np.array(ps3vector[:, 1])
        s3z = np.array(ps3vector[:, 2])

        userdefined_eq = self.form.user_def_eq.toPlainText()  # Get equation to be used
        UserDefinedFormula = eval(userdefined_eq).tolist()
        self.result_obj.UserDefined = UserDefinedFormula
        minm = min(UserDefinedFormula)
        avg = sum(UserDefinedFormula) / len(UserDefinedFormula)
        maxm = max(UserDefinedFormula)

        QApplication.setOverrideCursor(Qt.WaitCursor)
        if self.suitable_results:
            self.mesh_obj.ViewObject.setNodeColorByScalars(
                self.result_obj.NodeNumbers,
                UserDefinedFormula
            )
        self.set_result_stats("", minm, avg, maxm)
        QtGui.QApplication.restoreOverrideCursor()
        # Dummy use of the variables to get around flake8 error
        del x, y, z, T, Von, Peeq, P1, P2, P3
        del sxx, syy, szz, sxy, sxz, syz
        del exx, eyy, ezz, exy, exz, eyz
        del MF, NP, rx, ry, rz, mc
        del s1x, s1y, s1z, s2x, s2y, s2z, s3x, s3y, s3z
Exemple #52
0
    def plot_dataset_list(self, dataset_list, data_layout, append=False):
        ''' plots a list of datasets to a data layout'''
        QApplication.setOverrideCursor(QtCore.Qt.WaitCursor)
        data_layout.clear()
        if not append:
            self.subplots = []
        toes = []
        t = time.time()
        unplotable = []
        for dataset in dataset_list:
            if 'datatype' not in dataset.attrs.keys():
                unplotable.append(''.join(
                    [dataset.file.filename, dataset.name]))
                continue
            '''sampled data'''
            if dataset.attrs.get('datatype') < 1000:  # sampled data
                if (self.settings_panel.oscillogram_check.checkState() ==
                        QtCore.Qt.Checked):

                    pl = downsamplePlot(dataset, name=str(len(self.subplots)))
                    pl.setLabel('left', dataset.name.split('/')[-1])
                    data_layout.addItem(pl, row=len(self.subplots), col=0)
                    # max_default_range = 20
                    # xmax = min(dataset.size/float(dataset.attrs['sampling_rate']),
                    #            maxb_default_range)
                    # xrange = pl.dataItems[0].dataBounds(0)
                    # yrange = pl.dataItems[0].dataBounds(1)
                    # pl.setXRange(*xrange,padding=0)
                    # pl.setYRange(*yrange,padding=0)
                    self.subplots.append(pl)
                    pl.showGrid(x=True, y=True)
                ''' simple events '''
            elif utils.is_simple_event(dataset):
                if dataset.attrs.get('units') == 'ms':
                    data = dataset.value / 1000.
                elif dataset.attrs.get('units') == 'samples':
                    data = dataset.value / dataset.attrs['sampling_rate']
                else:
                    data = dataset.value
                if (self.settings_panel.raster_check.checkState()
                        == QtCore.Qt.Checked
                        or self.settings_panel.psth_check.checkState()
                        == QtCore.Qt.Checked
                        or self.settings_panel.isi_check.checkState()
                        == QtCore.Qt.Checked):
                    toes.append(data)
                continue
                ''' complex event '''
            elif utils.is_complex_event(dataset):
                if (self.settings_panel.label_check.checkState() ==
                        QtCore.Qt.Checked):
                    pl = labelPlot(dataset.file,
                                   dataset.name,
                                   name=str(len(self.subplots)))
                    pl.setLabel('left', dataset.name.split('/')[-1])
                    data_layout.addItem(pl, row=len(self.subplots), col=0)
                    #pl.showLabel('left', show=False)
                    pl.sigLabelSelected.connect(self.label_selected)
                    pl.sigNoLabelSelected.connect(self.label_unselected)
                    self.deleteLabelAction.triggered.connect(
                        pl.delete_selected_labels)
                    self.subplots.append(pl)

            else:
                unplotable.append(''.join(
                    [dataset.file.filename, dataset.name]))
                continue
            '''adding spectrograms'''
            if dataset.attrs.get('datatype') in (0, 1, 23):  # show spectrogram
                if (self.settings_panel.spectrogram_check.checkState() ==
                        QtCore.Qt.Checked):
                    pl = spectrogram.fromSettingsPanel(dataset,
                                                       self.settings_panel)
                    pl.selection_made.connect(self.spectrogramSelection)
                    data_layout.addItem(pl, row=len(self.subplots), col=0)
                    self.subplots.append(pl)


#end for loop
        if toes:
            if self.settings_panel.raster_check.checkState(
            ) == QtCore.Qt.Checked:
                pl = rasterPlot(toes)
                data_layout.addItem(pl, row=len(self.subplots), col=0)
                pl.showLabel('left', show=False)
                self.subplots.append(pl)

            if self.settings_panel.psth_check.checkState(
            ) == QtCore.Qt.Checked:
                all_toes = np.zeros(sum(len(t) for t in toes))
                k = 0
                for t in toes:
                    all_toes[k:k + len(t)] = t
                    k += len(t)
                if self.settings_panel.psth_bin_size.text():
                    bin_size = float(
                        self.settings_panel.psth_bin_size.text()) / 1000.
                else:
                    bin_size = .01
                bins = np.arange(all_toes.min(),
                                 all_toes.max() + bin_size, bin_size)
                y, x = np.histogram(all_toes, bins=bins)
                psth = pg.PlotCurveItem(x,
                                        y,
                                        stepMode=True,
                                        fillLevel=0,
                                        brush=(0, 0, 255, 80))

                pl = data_layout.addPlot(row=len(self.subplots), col=0)
                pl.addItem(psth)
                pl.setMouseEnabled(y=False)
                self.subplots.append(pl)

        if self.settings_panel.isi_check.checkState() == QtCore.Qt.Checked:
            isis = np.zeros(sum(len(t) - 1 for t in toes))
            k = 0
            for t in toes:
                isis[k:k + len(t) - 1] = np.diff(t)
                k += len(t) - 1
            if self.settings_panel.psth_bin_size.text():
                bin_size = float(
                    self.settings_panel.psth_bin_size.text()) / 1000.
            else:
                bin_size = .01
            bins = np.arange(isis.min(), isis.max() + bin_size, bin_size)
            y, x = np.histogram(isis, bins=bins, normed=True)
            isi_hist = pg.PlotCurveItem(x,
                                        y,
                                        stepMode=True,
                                        fillLevel=0,
                                        brush=(0, 0, 255, 80))

            pl = data_layout.addPlot(row=len(self.subplots), col=0)
            pl.addItem(isi_hist)
            pl.setMouseEnabled(y=False)
            self.subplots.append(pl)
        '''linking x axes'''
        minPlotHeight = 100
        masterXLink = None
        for pl in self.subplots:
            if not masterXLink:
                masterXLink = pl
            pl.setXLink(masterXLink)
            pl.setMinimumHeight(minPlotHeight)

        if any(isinstance(pl, spectrogram) for pl in self.subplots):
            self.exportSelectionAction.setVisible(True)
        else:
            self.exportSelectionAction.setVisible(False)

        spacing = 5
        self.data_layout.centralWidget.layout.setSpacing(spacing)
        self.data_layout.setMinimumHeight(
            len(self.subplots) * (minPlotHeight + spacing))
        QApplication.restoreOverrideCursor()
        if unplotable:
            self.error_message.showMessage(
                "Could not plot the following datasets: %s" %
                ('\n'.join(unplotable)), "plot_error")
 def enterEvent(self, *args, **kwargs):
     self.highlighted = True
     QApplication.setOverrideCursor(Qt.PointingHandCursor)
     self.repaint()
Exemple #54
0
    def set_dimension_combos(self):
        """
        This method is responisble for ensuring that all of the revelant
        combo boxes are filled with the correct coordinate names. It is
        called whenever the cube is changed.

        """
        QApplication.setOverrideCursor(QtCore.Qt.WaitCursor)

        self.clear_dims()

        # Cube is set and the summary is printed to the information tab.
        self.cube = self.get_current_cube()
        self.print_cube_browser.setText(str(self.cube))

        # we check to see if we need to add or remove collapsed dim slots
        old_ndim = self.ndim if self.ndim > 3 else 3
        new_ndim = self.cube.ndim if self.cube.ndim > 3 else 3

        difference = new_ndim - old_ndim

        # adds more slots until there are enough.
        if difference > 0:
            for i in xrange(difference):
                self.num_collapsed_dims += 1
                self.add_collapsed_dim(self.num_collapsed_dims)

        # removes slots until there are the correct amount.
        if difference < 0:
            for _ in xrange(abs(difference)):
                self.remove_collapsed_dim(self.num_collapsed_dims)
                self.num_collapsed_dims -= 1

        # Set some instance variables about the cube.
        self.dim_names = gl.get_dim_names(self.cube)
        self.ndim = self.cube.ndim

        # Fill the combo boxes
        self.fill_combo("select_dimension_1", self.dim_names, True)

        if self.ndim >= 2:
            self.fill_combo("select_dimension_2", self.dim_names, True)

        if self.ndim >= 3:
            self.fill_combo("select_sliced_dim", self.dim_names, True)

            # get data on the coord points, and fill the combo box.
            dim = self.select_sliced_dim.currentText()
            data = gl.get_coord_values(self.cube, dim, self.dim_names)
            self.fill_combo("select_slice_combo", data, True)
            self.set_slice_scroll()
            self.select_slice_scroll.setEnabled(True)
            self.action_next_slice.setEnabled(True)
            self.action_previous_slice.setEnabled(True)

        self.set_initial_index()
        self.set_collapsed_dims()

        # Collapsed dims refers to all dimensions above 3. these dimensions
        # are not the plotted dimensions, nor are they the dimension in which
        # slices are to be taken... They are simply collapsed as chosen by the
        # user.

        self.set_enabled()

        # These placeholder variables keep a record of the current state of
        # the selectCoordinate combo boxes.
        self.dim_1 = self.select_dimension_1.currentIndex()
        self.dim_2 = self.select_dimension_2.currentIndex()
        self.dim_3 = self.select_sliced_dim.currentIndex()

        QApplication.restoreOverrideCursor()
Exemple #55
0
def main():
    pid_file = 'av-control.pid'
    fp = open(pid_file, 'w')
    try:
        fcntl.lockf(fp, fcntl.LOCK_EX | fcntl.LOCK_NB)
    except IOError:
        # another instance is running
        print "av-control is already running."
        sys.exit(1)

    logging.basicConfig(format='%(asctime)s %(levelname)s: %(message)s',
                        level=logging.INFO)
    app = QApplication(sys.argv)

    parser = argparse.ArgumentParser()
    parser.add_argument(
        "-f",
        "--fullscreen",
        help="Run in fullscreen mode and hide the mouse cursor",
        action="store_true")
    parser.add_argument("-c",
                        help="Specify the controller ID to connect to",
                        metavar="CONTROLLERID",
                        default="")
    parser.add_argument(
        "-j",
        "--joystick",
        help="Path to joystick device to use for camera control")
    args = parser.parse_args()

    try:
        ssf = QFile(":/stylesheet")
        ssf.open(QFile.ReadOnly)
        styleSheet = str(ssf.readAll())
        app.setStyleSheet(styleSheet)
    except IOError:
        # never mind
        logging.warn("Cannot find stylesheet, using default system styles.")

    try:
        controller = Controller.fromPyro(args.c)

        js = None
        joystickDevice = args.joystick
        print args
        try:
            if args.joystick:
                if os.path.exists(joystickDevice):
                    logging.info(
                        "Configuring joystick {}".format(joystickDevice))
                    js = Joystick(joystickDevice)
                    js.start()
                else:
                    logging.error(
                        "Specified joystick device {} does not exist!".format(
                            joystickDevice))
        except IOError:
            logging.exception("Unable to configure joystick")
            pass

        jsa = SensitivityPrefsCameraJoystickAdapter(js)
        jsa.start()
        myapp = MainWindow(controller, jsa)

        client = AvControlClient(myapp)
        client.setDaemon(True)
        client.start()
        client.started.wait()
        atexit.register(lambda: controller.unregisterClient(client.uri))

        controller.registerClient(client.uri)

        if args.fullscreen:
            QApplication.setOverrideCursor(Qt.BlankCursor)
            myapp.showFullScreen()
        else:
            myapp.show()
        sys.exit(app.exec_())

    except VersionMismatchError as e:
        Dialogs.errorBox(str(e))
    def runSolverProcess(self):
        self.Start = time.time()

        # Check for changes that require remesh
        if FreeCAD.GuiUp and (self.analysis_object.NeedsMeshRewrite
                              or self.analysis_object.NeedsCaseRewrite
                              or self.analysis_object.NeedsMeshRerun):

            if self.analysis_object.NeedsCaseRewrite:
                if self.analysis_object.NeedsMeshRewrite or self.analysis_object.NeedsMeshRerun:
                    text = "The case may need to be re-meshed and the case setup re-written based on changes " + \
                           "you have made to the model.\n\nRe-mesh and re-write case setup first?"
                else:
                    text = "The case setup may need to be re-written based on changes " + \
                           "you have made to the model.\n\nRe-write case setup first?"
            else:
                if self.analysis_object.NeedsMeshRewrite or self.analysis_object.NeedsMeshRerun:
                    text = "The case may need to be re-meshed based on changes " + \
                           "you have made to the model.\n\nRe-mesh case first?"

            if QtGui.QMessageBox.question(None,
                                          "CfdOF Workbench",
                                          text,
                                          defaultButton=QtGui.QMessageBox.Yes
                                          ) == QtGui.QMessageBox.Yes:
                self.Start = time.time()

                if self.analysis_object.NeedsMeshRewrite or self.analysis_object.NeedsMeshRerun:
                    from CfdOF.Mesh import CfdMeshTools
                    mesh_obj = CfdTools.getMeshObject(self.analysis_object)
                    cart_mesh = CfdMeshTools.CfdMeshTools(mesh_obj)
                    cart_mesh.progressCallback = self.consoleMessage
                    if self.analysis_object.NeedsMeshRewrite:
                        #Write mesh
                        cart_mesh.writeMesh()
                        self.analysis_object.NeedsMeshRewrite = False
                        self.analysis_object.NeedsMeshRerun = True

                if self.analysis_object.NeedsCaseRewrite:
                    self.write_input_file_handler()

                if self.analysis_object.NeedsMeshRerun:
                    # Run mesher
                    self.solver_object.Proxy.solver_process = CfdConsoleProcess(
                        finished_hook=self.mesherFinished,
                        stdout_hook=self.gotOutputLines,
                        stderr_hook=self.gotErrorLines)

                    cart_mesh.error = False
                    cmd = CfdTools.makeRunCommand('./Allmesh',
                                                  cart_mesh.meshCaseDir,
                                                  source_env=False)
                    FreeCAD.Console.PrintMessage('Executing: ' +
                                                 ' '.join(cmd) + '\\n')
                    env_vars = CfdTools.getRunEnvironment()
                    self.solver_object.Proxy.solver_process.start(
                        cmd, env_vars=env_vars)
                    if self.solver_object.Proxy.solver_process.waitForStarted(
                    ):
                        # Setting solve button to inactive to ensure that two instances of the same simulation aren't started
                        # simultaneously
                        self.form.pb_write_inp.setEnabled(False)
                        self.form.pb_run_solver.setEnabled(False)
                        self.form.terminateSolver.setEnabled(True)
                        self.consoleMessage("Mesher started ...")
                        return
            else:
                self.Start = time.time()

        QApplication.setOverrideCursor(Qt.WaitCursor)
        FreeCADGui.doCommand("from CfdOF import CfdTools")
        FreeCADGui.doCommand("from CfdOF import CfdConsoleProcess")
        self.solver_object.Proxy.solver_runner = self.solver_runner
        FreeCADGui.doCommand("proxy = FreeCAD.ActiveDocument." +
                             self.solver_object.Name + ".Proxy")
        # This is a workaround to emit code into macro without actually running it
        FreeCADGui.doCommand("proxy.running_from_macro = True")
        self.solver_object.Proxy.running_from_macro = False
        FreeCADGui.doCommand(
            "if proxy.running_from_macro:\n" +
            "  analysis_object = FreeCAD.ActiveDocument." +
            self.analysis_object.Name + "\n" +
            "  solver_object = FreeCAD.ActiveDocument." +
            self.solver_object.Name + "\n" +
            "  working_dir = CfdTools.getOutputPath(analysis_object)\n" +
            "  case_name = solver_object.InputCaseName\n" +
            "  solver_directory = os.path.abspath(os.path.join(working_dir, case_name))\n"
            + "  import CfdRunnableFoam\n" +
            "  solver_runner = CfdRunnableFoam.CfdRunnableFoam(analysis_object, solver_object)\n"
            + "  cmd = solver_runner.get_solver_cmd(solver_directory)\n" +
            "  FreeCAD.Console.PrintMessage(' '.join(cmd) + '\\n')\n" +
            "  env_vars = solver_runner.getRunEnvironment()\n" +
            "  solver_process = CfdConsoleProcess.CfdConsoleProcess(stdout_hook=solver_runner.process_output)\n"
            + "  solver_process.start(cmd, env_vars=env_vars)\n" +
            "  solver_process.waitForFinished()\n")
        working_dir = CfdTools.getOutputPath(self.analysis_object)
        case_name = self.solver_object.InputCaseName
        solver_directory = os.path.abspath(os.path.join(
            working_dir, case_name))
        cmd = self.solver_runner.get_solver_cmd(solver_directory)
        FreeCAD.Console.PrintMessage(' '.join(cmd) + '\\n')
        env_vars = self.solver_runner.getRunEnvironment()
        self.solver_object.Proxy.solver_process = CfdConsoleProcess(
            finished_hook=self.solverFinished,
            stdout_hook=self.gotOutputLines,
            stderr_hook=self.gotErrorLines)
        self.solver_object.Proxy.solver_process.start(cmd, env_vars=env_vars)
        if self.solver_object.Proxy.solver_process.waitForStarted():
            # Setting solve button to inactive to ensure that two instances of the same simulation aren't started
            # simultaneously
            self.form.pb_write_inp.setEnabled(False)
            self.form.pb_run_solver.setEnabled(False)
            self.form.terminateSolver.setEnabled(True)
            self.form.pb_paraview.setEnabled(True)
            self.consoleMessage("Solver started")
        else:
            self.consoleMessage("Error starting solver")
        QApplication.restoreOverrideCursor()
Exemple #57
0
    def contextMenuEvent(self, event):
        """
        Handles the ``contextMenuEvent`` event for :class:`StatusBarButton`.

        :param `event`: A `QContextMenuEvent`_ to be processed.
        """
        QApplication.setOverrideCursor(Qt.ArrowCursor)
        menu = QMenu(self)
        objName = self.objectName()
        themeDir = gIconDir + os.sep + '..' + os.sep + self.mainWin.getSettingsGeneralIconTheme(
        ) + os.sep
        s = "&Settings..."
        if objName == "StatusBarButtonSNAP":

            settingsSnapAction = QAction(
                QIcon(themeDir + "gridsnapsettings.png"), s, menu)
            settingsSnapAction.triggered.connect(self.settingsSnap)
            menu.addAction(settingsSnapAction)

        elif objName == "StatusBarButtonGRID":

            settingsGridAction = QAction(QIcon(themeDir + "gridsettings.png"),
                                         s, menu)
            settingsGridAction.triggered.connect(self.settingsGrid)
            menu.addAction(settingsGridAction)

        elif objName == "StatusBarButtonRULER":

            settingsRulerAction = QAction(
                QIcon(themeDir + "rulersettings.png"), s, menu)
            settingsRulerAction.triggered.connect(self.settingsRuler)
            menu.addAction(settingsRulerAction)

        elif objName == "StatusBarButtonORTHO":

            settingsOrthoAction = QAction(
                QIcon(themeDir + "orthosettings.png"), s, menu)
            settingsOrthoAction.triggered.connect(self.settingsOrtho)
            menu.addAction(settingsOrthoAction)

        elif objName == "StatusBarButtonPOLAR":

            settingsPolarAction = QAction(
                QIcon(themeDir + "polarsettings.png"), s, menu)
            settingsPolarAction.triggered.connect(self.settingsPolar)
            menu.addAction(settingsPolarAction)

        elif objName == "StatusBarButtonQSNAP":

            settingsQSnapAction = QAction(
                QIcon(themeDir + "qsnapsettings.png"), s, menu)
            settingsQSnapAction.triggered.connect(self.settingsQSnap)
            menu.addAction(settingsQSnapAction)

        elif objName == "StatusBarButtonQTRACK":

            settingsQTrackAction = QAction(
                QIcon(themeDir + "qtracksettings.png"), s, menu)
            settingsQTrackAction.triggered.connect(self.settingsQTrack)
            menu.addAction(settingsQTrackAction)

        elif objName == "StatusBarButtonLWT":

            gview = self.mainWin.activeView()
            if gview:

                enableRealAction = QAction(QIcon(themeDir + "realrender.png"),
                                           "&RealRender On", menu)
                enableRealAction.setEnabled(not gview.isRealEnabled())
                enableRealAction.triggered.connect(self.enableReal)
                menu.addAction(enableRealAction)

                disableRealAction = QAction(QIcon(themeDir + "realrender.png"),
                                            "&RealRender Off", menu)
                disableRealAction.setEnabled(gview.isRealEnabled())
                disableRealAction.triggered.connect(self.disableReal)
                menu.addAction(disableRealAction)

            settingsLwtAction = QAction(
                QIcon(themeDir + "lineweightsettings" + ".png"), s, menu)
            settingsLwtAction.triggered.connect(self.settingsLwt)
            menu.addAction(settingsLwtAction)

        menu.exec_(event.globalPos())
        QApplication.restoreOverrideCursor()
        self.statusbar.clearMessage()
Exemple #58
0
    def runMesh(self):
        self.Start = time.time()

        # Check for changes that require mesh re-write
        self.store()
        if self.analysis_obj.NeedsMeshRewrite:
            if FreeCAD.GuiUp:
                if QtGui.QMessageBox.question(
                        None,
                        "CfdOF Workbench",
                        "The case setup for the mesher may need to be re-written based on changes you have made to the "
                        "model.\n\nWrite mesh case first?",
                        defaultButton=QtGui.QMessageBox.Yes
                ) == QtGui.QMessageBox.Yes:
                    self.Start = time.time()
                    self.writeMesh()
                else:
                    self.Start = time.time()

        try:
            QApplication.setOverrideCursor(Qt.WaitCursor)
            self.consoleMessage("Initializing {} ...".format(
                self.mesh_obj.MeshUtility))
            FreeCADGui.doCommand("from CfdOF.Mesh import CfdMeshTools")
            FreeCADGui.doCommand("from CfdOF import CfdTools")
            FreeCADGui.doCommand("from CfdOF import CfdConsoleProcess")
            FreeCADGui.doCommand(
                "cart_mesh = "
                "CfdMeshTools.CfdMeshTools(FreeCAD.ActiveDocument." +
                self.mesh_obj.Name + ")")
            FreeCADGui.doCommand("proxy = FreeCAD.ActiveDocument." +
                                 self.mesh_obj.Name + ".Proxy")
            FreeCADGui.doCommand("proxy.cart_mesh = cart_mesh")
            FreeCADGui.doCommand("cart_mesh.error = False")
            FreeCADGui.doCommand(
                "cmd = CfdTools.makeRunCommand('./Allmesh', cart_mesh.meshCaseDir, source_env=False)"
            )
            FreeCADGui.doCommand(
                "FreeCAD.Console.PrintMessage('Executing: ' + ' '.join(cmd) + '\\n')"
            )
            FreeCADGui.doCommand("env_vars = CfdTools.getRunEnvironment()")
            FreeCADGui.doCommand("proxy.running_from_macro = True")
            self.mesh_obj.Proxy.running_from_macro = False
            FreeCADGui.doCommand(
                "if proxy.running_from_macro:\n" +
                "  mesh_process = CfdConsoleProcess.CfdConsoleProcess()\n" +
                "  mesh_process.start(cmd, env_vars=env_vars)\n" +
                "  mesh_process.waitForFinished()\n" + "else:\n" +
                "  proxy.mesh_process.start(cmd, env_vars=env_vars)")
            if self.mesh_obj.Proxy.mesh_process.waitForStarted():
                self.form.pb_run_mesh.setEnabled(
                    False)  # Prevent user running a second instance
                self.form.pb_stop_mesh.setEnabled(True)
                self.form.pb_write_mesh.setEnabled(False)
                self.form.pb_check_mesh.setEnabled(False)
                self.form.pb_paraview.setEnabled(False)
                self.form.pb_load_mesh.setEnabled(False)
                self.consoleMessage("Mesher started ...")
            else:
                self.consoleMessage("Error starting meshing process",
                                    "#FF0000")
                self.mesh_obj.Proxy.cart_mesh.error = True
        except Exception as ex:
            self.consoleMessage("Error " + type(ex).__name__ + ": " + str(ex),
                                '#FF0000')
            raise
        finally:
            QApplication.restoreOverrideCursor()
Exemple #59
0
 def set_cursor(self, cursor):
     QApplication.restoreOverrideCursor()
     qcursor = QCursor()
     qcursor.setShape(cursord[cursor])
     QApplication.setOverrideCursor(qcursor)
    def __init__(self, mw, parent=None):
        """
        Default class constructor.

        :param `mw`: The application's MainWindow instance.
        :type `mw`: `QMainWindow`_
        :param `parent`: Pointer to a parent widget instance.
        :type `parent`: `QWidget`_
        """
        super(LayerManager, self).__init__(parent)

        tr = self.tr

        self.layerModel = layerModel = QStandardItemModel(0, 8, self)

        self.layerModelSorted = layerModelSorted = QSortFilterProxyModel()
        layerModelSorted.setDynamicSortFilter(True)
        layerModelSorted.setSourceModel(layerModel)

        self.treeView = treeView = QTreeView()
        treeView.setRootIsDecorated(False)
        treeView.setAlternatingRowColors(True)
        treeView.setModel(layerModelSorted)
        treeView.setSortingEnabled(True)
        treeView.sortByColumn(0, Qt.AscendingOrder)

        mainLayout = QVBoxLayout()
        mainLayout.addWidget(treeView)
        self.setLayout(mainLayout)

        self.setWindowTitle(tr("Layer Manager"))
        self.setMinimumSize(750, 550)

        ## layerModel.setHeaderData(0, Qt.Horizontal, self.tr("Name"))
        ## layerModel.setHeaderData(1, Qt.Horizontal, self.tr("Visible"))
        ## layerModel.setHeaderData(2, Qt.Horizontal, self.tr("Frozen"))
        ## layerModel.setHeaderData(3, Qt.Horizontal, self.tr("Z Value"))
        ## layerModel.setHeaderData(4, Qt.Horizontal, self.tr("Color"))
        ## layerModel.setHeaderData(5, Qt.Horizontal, self.tr("Linetype"))
        ## layerModel.setHeaderData(6, Qt.Horizontal, self.tr("Lineweight"))
        ## layerModel.setHeaderData(7, Qt.Horizontal, self.tr("Print"))
        localMeth = layerModel.setHeaderData
        localQtHorizontal = Qt.Horizontal
        [
            localMeth(i, localQtHorizontal, tr(strng))
            for i, strng in ((0, "Name"), (1, "Visible"), (2, "Frozen"),
                             (3, "Z Value"), (4, "Color"), (5, "Linetype"),
                             (6, "Lineweight"), (7, "Print"))
        ]

        ## addLayer = self.addLayer  # local optimization
        ## addLayer("0", True, False, 0.0, qRgb(0, 0, 0), "Continuous", "Default", True)
        ## addLayer("1", True, False, 1.0, qRgb(0, 0, 0), "Continuous", "Default", True)
        ## addLayer("2", True, False, 2.0, qRgb(0, 0, 0), "Continuous", "Default", True)
        ## addLayer("3", True, False, 3.0, qRgb(0, 0, 0), "Continuous", "Default", True)
        ## addLayer("4", True, False, 4.0, qRgb(0, 0, 0), "Continuous", "Default", True)
        ## addLayer("5", True, False, 5.0, qRgb(0, 0, 0), "Continuous", "Default", True)
        ## addLayer("6", True, False, 6.0, qRgb(0, 0, 0), "Continuous", "Default", True)
        ## addLayer("7", True, False, 7.0, qRgb(0, 0, 0), "Continuous", "Default", True)
        ## addLayer("8", True, False, 8.0, qRgb(0, 0, 0), "Continuous", "Default", True)
        ## addLayer("9", True, False, 9.0, qRgb(0, 0, 0), "Continuous", "Default", True)
        addLayer = self.addLayer
        [
            addLayer("%s" % i, True, False, float(i), qRgb(0, 0, 0),
                     "Continuous", "Default", True) for i in range(0, 10)
        ]

        ## for i in range(0, layerModel.columnCount()):
        ##     treeView.resizeColumnToContents(i)
        localtreeViewMeth = treeView.resizeColumnToContents
        [localtreeViewMeth(i) for i in range(0, layerModel.columnCount())]

        QApplication.setOverrideCursor(Qt.ArrowCursor)