コード例 #1
0
def run_elmergrid(export_path, mesh_object):
    """
    Run ElmerGrid as an external process if it found in the operating system.

    :param export_path: path where the result is written
    :param mesh_object: FreeCAD mesh object that is to be exported 
    """
    #Export to UNV file for Elmer
    export_objects = []
    export_objects.append(mesh_object)
    Fem.export(export_objects, export_path)

    optional_path_to_elmer = ''  # optional path to ElmerGrid
    elmerGrid_command = optional_path_to_elmer + 'ElmerGrid 8 2 ' + export_path + ' -autoclean -names'
    #print elmerGrid_command

    from PySide import QtCore, QtGui
    from platform import system
    import os
    process = QtCore.QProcess()
    try:
        process = QtCore.QProcess()
        process.startDetached(elmerGrid_command)
        FreeCAD.Console.PrintMessage('Running ' + elmerGrid_command + '\n')
        FreeCAD.Console.PrintMessage('Finished ' + elmerGrid_command + '\n')
    except:
        FreeCAD.Console.PrintError('Error')
        QtGui.QMessageBox.critical(None, 'Error', 'Error!!',
                                   QtGui.QMessageBox.Abort)
コード例 #2
0
    def __init__(self, analysis=None, solver=None, test_mode=False):
        if analysis:
            ## @var analysis
            #  FEM analysis - the core object. Has to be present.
            #  It's set to analysis passed in "__init__" or set to current active analysis by default if nothing has been passed to "__init__".
            self.analysis = analysis
        else:
            import FemGui
            self.analysis = FemGui.getActiveAnalysis()
        if solver:
            ## @var solver
            #  solver of the analysis. Used to store the active solver and analysis parameters
            self.solver = solver
        else:
            self.solver = None
        if self.analysis:
            self.update_objects()
            self.base_name = ""
            if self.solver:
                self.set_analysis_type()
                self.setup_working_dir()
                self.setup_z88()
            else:
                raise Exception('FEM: No solver found!')
        else:
            raise Exception('FEM: No active analysis found!')

        self.z88_is_running = False
        self.z88_testrun = QtCore.QProcess()
        self.z88_solverun = QtCore.QProcess()
        QtCore.QObject.connect(self.z88_testrun, QtCore.SIGNAL("started()"), self.z88_testrun_started)
        QtCore.QObject.connect(self.z88_testrun, QtCore.SIGNAL("finished(int)"), self.z88_testrun_finished)
        QtCore.QObject.connect(self.z88_solverun, QtCore.SIGNAL("started()"), self.z88_solverun_started)
        QtCore.QObject.connect(self.z88_solverun, QtCore.SIGNAL("finished(int)"), self.z88_solverun_finished)
コード例 #3
0
    def __init__(self, obj):
        self.mesh_obj = obj
        self.form = FreeCADGui.PySideUic.loadUi(
            os.path.join(os.path.dirname(__file__), "TaskPanelCfdMeshCart.ui"))

        self.mesh_process = QtCore.QProcess()
        self.Timer = QtCore.QTimer()
        self.console_message_cart = ''
        self.error_message = ''
        self.cart_mesh = []
        self.paraviewScriptName = ""

        QtCore.QObject.connect(self.mesh_process,
                               QtCore.SIGNAL("readyReadStandardOutput()"),
                               self.readOutput)
        QtCore.QObject.connect(self.mesh_process,
                               QtCore.SIGNAL("readyReadStandardError()"),
                               self.readOutput)
        QtCore.QObject.connect(self.mesh_process,
                               QtCore.SIGNAL("finished(int)"),
                               self.meshFinished)

        QtCore.QObject.connect(self.form.if_max,
                               QtCore.SIGNAL("valueChanged(Base::Quantity)"),
                               self.max_changed)
        # QtCore.QObject.connect(self.form.if_min, QtCore.SIGNAL("valueChanged(Base::Quantity)"), self.min_changed)
        QtCore.QObject.connect(self.form.cb_dimension,
                               QtCore.SIGNAL("activated(int)"),
                               self.choose_dimension)
        QtCore.QObject.connect(self.form.cb_utility,
                               QtCore.SIGNAL("activated(int)"),
                               self.choose_utility)
        QtCore.QObject.connect(self.Timer, QtCore.SIGNAL("timeout()"),
                               self.update_timer_text)

        self.open_paraview = QtCore.QProcess()

        QtCore.QObject.connect(self.form.pb_run_mesh,
                               QtCore.SIGNAL("clicked()"), self.runMeshProcess)
        QtCore.QObject.connect(self.form.pb_stop_mesh,
                               QtCore.SIGNAL("clicked()"),
                               self.killMeshProcess)
        QtCore.QObject.connect(self.form.pb_paraview,
                               QtCore.SIGNAL("clicked()"), self.openParaview)
        self.form.pb_stop_mesh.setEnabled(False)
        self.form.pb_paraview.setEnabled(False)
        self.form.snappySpecificProperties.setVisible(False)

        # Limit mesh dimensions to 3D solids
        self.form.cb_dimension.addItems(
            _CfdMeshCart._CfdMeshCart.known_element_dimensions)
        self.form.cb_utility.addItems(
            _CfdMeshCart._CfdMeshCart.known_mesh_utility)

        self.get_mesh_params()
        self.order = '1st'  # Force first order for CFD mesh
        self.get_active_analysis()
        self.update()
コード例 #4
0
    def __init__(self, obj):
        self.mesh_obj = obj
        self.form = FreeCADGui.PySideUic.loadUi(os.path.join(os.path.dirname(__file__), "TaskPanelCfdMeshCart.ui"))

        self.mesh_process = QtCore.QProcess()
        self.Timer = QtCore.QTimer()
        self.console_message_cart = ''
        self.error_message = ''
        self.cart_mesh = []
        self.paraviewScriptName = ""

        QtCore.QObject.connect(self.mesh_process, QtCore.SIGNAL("readyReadStandardOutput()"), self.read_output)
        QtCore.QObject.connect(self.mesh_process, QtCore.SIGNAL("readyReadStandardError()"), self.read_output)
        QtCore.QObject.connect(self.mesh_process, QtCore.SIGNAL("finished(int)"), self.mesh_finished)

        QtCore.QObject.connect(self.form.if_max, QtCore.SIGNAL("valueChanged(Base::Quantity)"), self.max_changed)
        QtCore.QObject.connect(self.form.if_pointInMeshX, QtCore.SIGNAL("valueChanged(Base::Quantity)"),
                               self.pointInMeshX_changed)
        QtCore.QObject.connect(self.form.if_pointInMeshY, QtCore.SIGNAL("valueChanged(Base::Quantity)"),
                               self.pointInMeshY_changed)
        QtCore.QObject.connect(self.form.if_pointInMeshZ, QtCore.SIGNAL("valueChanged(Base::Quantity)"),
                               self.pointInMeshZ_changed)
        QtCore.QObject.connect(self.form.if_cellsbetweenlevels, QtCore.SIGNAL("valueChanged(int)"),
                               self.cellsbetweenlevels_changed)
        QtCore.QObject.connect(self.form.if_edgerefine, QtCore.SIGNAL("valueChanged(int)"), self.edgerefine_changed)
        QtCore.QObject.connect(self.form.cb_dimension, QtCore.SIGNAL("activated(int)"), self.choose_dimension)
        QtCore.QObject.connect(self.form.cb_utility, QtCore.SIGNAL("activated(int)"), self.choose_utility)
        QtCore.QObject.connect(self.Timer, QtCore.SIGNAL("timeout()"), self.update_timer_text)

        self.open_paraview = QtCore.QProcess()

        QtCore.QObject.connect(self.form.pb_run_mesh, QtCore.SIGNAL("clicked()"), self.runMeshProcess)
        QtCore.QObject.connect(self.form.pb_stop_mesh, QtCore.SIGNAL("clicked()"), self.killMeshProcess)
        QtCore.QObject.connect(self.form.pb_paraview, QtCore.SIGNAL("clicked()"), self.openParaview)
        QtCore.QObject.connect(self.form.pb_searchPointInMesh, QtCore.SIGNAL("clicked()"), self.searchPointInMesh)
        self.form.pb_stop_mesh.setEnabled(False)
        self.form.pb_paraview.setEnabled(False)
        self.form.snappySpecificProperties.setVisible(False)

        # Limit mesh dimensions to 3D solids
        self.form.cb_dimension.addItems(_CfdMeshCart._CfdMeshCart.known_element_dimensions)
        self.form.cb_utility.addItems(_CfdMeshCart._CfdMeshCart.known_mesh_utility)

        self.form.if_max.setToolTip("Select 0 to use default value")
        self.form.pb_searchPointInMesh.setToolTip("Specify below a point vector inside of the mesh or press 'Search' "
                                                  "to try and automatically find a point")
        self.form.if_cellsbetweenlevels.setToolTip("Number of cells between each of level of refinement.")
        self.form.if_edgerefine.setToolTip("Number of refinement levels for all edges.")

        tmpdir = tempfile.gettempdir()
        self.meshCaseDir = os.path.join(tmpdir, 'meshCase')

        self.get_mesh_params()
        self.order = '1st'  # Default to first order for CFD mesh
        self.get_active_analysis()
        self.update()
コード例 #5
0
    def __init__(self, obj):
        self.obj = obj

        self.Timer = QtCore.QTimer()
        self.conversion_process = QtCore.QProcess()
        self.conversion_process.finished.connect(self.mesh_finished)
        self.conversion_process.readyReadStandardOutput.connect(
            self.read_output)
        self.conversion_process.readyReadStandardError.connect(
            self.read_output)

        self.console_message_cart = ''
        self.form = FreeCADGui.PySideUic.loadUi(
            os.path.join(os.path.dirname(__file__),
                         "TaskPanelCfdConvertTo2D.ui"))

        descriptionText = (
            "Convert 3D mesh into 2D OpenFOAM mesh (single element through the thickness)."
        )

        usageDescriptor = ("1.) Create 3D mesh. \n" \
            "2.) Create boundary conditions for front and back faces \n"\
            "3.) Select corresponding boundary conditions \n"\
            "4.) Selected boundaries will automitically be changed to Type='Empty'.")

        self.form.labelDescription.setText(descriptionText)
        self.form.labelUsageDescription.setText(usageDescriptor)

        self.form.paraviewButton.setEnabled(False)
        self.form.paraviewButton.clicked.connect(self.openParaview)
        self.open_paraview = QtCore.QProcess()

        self.listOfBoundaryLabels = []
        self.listOfBoundaryNames = []
        doc_name = str(self.obj.Document.Name)
        doc = FreeCAD.getDocument(doc_name)
        for doc_objs in doc.Objects:
            #if "CfdFluidBoundary"
            if "CfdFluidBoundary" in doc_objs.Name:
                self.listOfBoundaryLabels.append(doc_objs.Label)
                self.listOfBoundaryNames.append(doc_objs.Name)

        self.form.comboBoxFront.addItems(self.listOfBoundaryLabels)
        self.form.comboBoxBack.addItems(self.listOfBoundaryLabels)

        self.form.convertButton.clicked.connect(self.convertClicked)

        self.initialiseUponReload()
コード例 #6
0
ファイル: utilities.py プロジェクト: cti-gr/avgui
 def run(self):
     self.finished.connect(self.onThreadTermination)
     self.avgUpdateProc = QtCore.QProcess()
     # self.avgUpdateProc.open(QtCore.QIODevice.Unbuffered)
     self.avgUpdateProc.destroyed.connect(self.avgProcDestroyed)
     self.avgUpdateProc.readyRead.connect(self.printOut)
     self.avgUpdateProc.finished.connect(self.onAVGProcFinish)
     self.avgUpdateProc.start("gksu", [
         "--description=" + langmodule.avgUpdate,
         "--message=" + langmodule.mustSudo, "avgupdate"
     ])
     try:
         startLocker = QtCore.QMutexLocker(mutexStartCheck)
         while not self.avgUpdateProc.waitForStarted(msecs=2000):
             print(" - avgupdate failed to start - ")
             #self.avgUpdateProc.readyRead.disconnect()
             #self.avgUpdateProc.kill()
             #self.avgUpdateProc.close()
             self.exitCode = 1
             self.avgUpdateProc.finished.emit(self.exitCode)
             #self.avgUpdateProc.start("gksu", ["avgupdate"])
             self.exit()
             return
     except Exception as err:
         print("Failed to initialize Update Process" + str(err))
         return
     self.exec_()
コード例 #7
0
 def run(self):
     # If using docker, need to make and set the foam, bin & etc directories if they don't already exist
     usedocker = CfdTools.DockerContainer.usedocker
     if usedocker:
         prefs = CfdTools.getPreferencesLocation()
         foam_dir =  FreeCAD.ParamGet(prefs).GetString("InstallationPath", "")
         cmd = 'mkdir -p {0}/bin ; mkdir -p {0}/etc'.format(foam_dir)
         proc = QtCore.QProcess()
         proc.start(cmd)
         if not proc.waitForFinished():
             self.signals.status.emit("Could not create directories")
             self.signals.finished.emit(False)
             return
     try:
         if self.task == DOWNLOAD_BLUECFD:
             self.downloadBlueCFD()
         elif self.task == DOWNLOAD_CFMESH:
             self.downloadCfMesh()
         elif self.task == DOWNLOAD_HISA:
             self.downloadHisa()
         elif self.task == DOWNLOAD_DOCKER:
             self.downloadDocker()            
     except Exception as e:
         self.signals.error.emit(str(e))
         self.signals.finished.emit(False)
         raise
     self.signals.finished.emit(True)
コード例 #8
0
ファイル: CfdPreferencePage.py プロジェクト: zhjzhang/CfdOF
 def downloadOpenFoam(self):
     filename = self.download(self.openfoam_url, OPENFOAM_FILE_EXT, "OpenFOAM")
     if QtCore.QProcess().startDetached(filename):
         self.signals.status.emit("OpenFOAM installer launched - please complete the installation")
         self.signals.status.emit("NB: OF_Env_Create desktop shortcut must be run after installation")
     else:
         raise Exception("Failed to launch OpenFOAM installer")
コード例 #9
0
    def __init__(self):
        super(MenuManager, self).__init__()

        self.contentsDoc = None
        self.assistantProcess = QtCore.QProcess()
        self.helpRootUrl = ''
        self.docDir = QtCore.QDir()
        self.imgDir = QtCore.QDir()

        self.info = {}
        self.window = None

        self.ticker = None
        self.tickerInAnim = None
        self.upButton = None
        self.downButton = None
        self.helpEngine = None
        self.score = Score()
        self.currentMenu = "[no menu visible]"
        self.currentCategory = "[no category visible]"
        self.currentMenuButtons = "[no menu buttons visible]"
        self.currentInfo = "[no info visible]"
        self.currentMenuCode = -1
        self.readXmlDocument()
        self.initHelpEngine()
コード例 #10
0
 def collect(self):
     self.weather = QtCore.QProcess()
     self.twitter = QtCore.QProcess()
     self.weather.readyReadStandardOutput.connect(self.read_out)
     self.twitter.readyReadStandardOutput.connect(self.read_out_2)
     self.weather.start('python "weather_collect.py"')
     self.twitter.start('python "stream_starter.py"')
     #self.pt = Popen([sys.executable, 'twitter_stream.py'], cwd=r"C:\Users\Karolina\OneDrive - Imperial College London\Year 4\Sensing\Coursework\code")
     #self.pw = Popen([sys.executable, 'weather_collect.py'], cwd=r"C:\Users\Karolina\OneDrive - Imperial College London\Year 4\Sensing\Coursework\code")
     #for line in self.pt.stdout.readlines():
     #    print line
     self.pushButton.hide()
     self.pushButton_3.show()
     time=str(datetime.datetime.now())
     self.textBrowser.setText('STARTED ' + time)
     self.textBrowser_2.setText('STARTED ' + time)
コード例 #11
0
ファイル: guiutils.py プロジェクト: thushiyang/DesignSPHysics
    def on_flowtool_browse():
        filedialog = QtGui.QFileDialog()
        # noinspection PyArgumentList
        file_name, _ = filedialog.getOpenFileName(setup_window,
                                                  "Select FlowTool path",
                                                  QtCore.QDir.homePath())
        if file_name != "":
            # Verify if exe is indeed measuretool
            process = QtCore.QProcess(FreeCADGui.getMainWindow())
            process.start('"{}"'.format(file_name))
            process.waitForFinished()
            output = str(process.readAllStandardOutput())

            if "flowtool" in output[0:22].lower():
                flowtool_input.setText(file_name)
            else:
                utils.error(
                    "I can't recognize FlowTool in that executable.! "
                    "Check that the file corresponds with the appropriate tool and that you have permissions to execute it"
                )
                warning_dialog(
                    "I can't recognize FlowTool in that executable.! "
                    "Check that the file corresponds with the appropriate tool and that you have permissions to execute it",
                    detailed_text="If you're working with GNU/Linux, you can give permissions to an executable from the terminal "
                                  "with: chmod +x /path/to/the/executable"
                )
コード例 #12
0
ファイル: guiutils.py プロジェクト: thushiyang/DesignSPHysics
 def on_dualsphysics_browse():
     filedialog = QtGui.QFileDialog()
     # noinspection PyArgumentList
     file_name, _ = filedialog.getOpenFileName(setup_window,
                                               "Select DualSPHysics path",
                                               QtCore.QDir.homePath())
     if file_name != "":
         # Verify if exe is indeed dualsphysics
         process = QtCore.QProcess(FreeCADGui.getMainWindow())
         if platform == "linux" or platform == "linux2":
             os.environ["LD_LIBRARY_PATH"] = "{}/".format(
                 "/".join(file_name.split("/")[:-1]))
             process.start('"{}"'.format(file_name))
         else:
             process.start('"{}"'.format(file_name))
         process.waitForFinished()
         output = str(process.readAllStandardOutput())
         if "dualsphysics" in output[0:20].lower():
             dsphpath_input.setText(file_name)
         else:
             utils.error(
                 "I can't recognize DualSPHysics in that executable.! "
                 "Check that the file corresponds with the appropriate tool and that you have permissions to execute it"
             )
             warning_dialog(
                 "I can't recognize DualSPHysics in that executable.! "
                 "Check that the file corresponds with the appropriate tool and that you have permissions to execute it",
                 detailed_text="If you're working with GNU/Linux, you can give permissions to an executable from the terminal "
                               "with: chmod +x /path/to/the/executable"
             )
コード例 #13
0
    def __init__(self, solver_runner_obj):
        ui_path = os.path.dirname(__file__) + os.path.sep + "TaskPanelCfdSolverControl.ui"
        self.form = FreeCADGui.PySideUic.loadUi(ui_path)
        self.fem_prefs = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Fem")

        self.analysis_object = FemGui.getActiveAnalysis()

        self.solver_runner = solver_runner_obj
        self.solver_object = solver_runner_obj.solver
        # test if Proxy instance is not None and correct type, or create a new python instance
        #self.solver_python_object = CfdTools.getSolverPythonFromAnalysis(self.analysis_object)

        self.SolverProcess = QtCore.QProcess()
        self.Timer = QtCore.QTimer()
        self.Timer.start(3000)

        # update UI
        self.fem_console_message = ''

        # Connect Signals and Slots
        QtCore.QObject.connect(self.form.tb_choose_working_dir, QtCore.SIGNAL("clicked()"), self.choose_working_dir)
        QtCore.QObject.connect(self.form.pb_write_inp, QtCore.SIGNAL("clicked()"), self.write_input_file_handler)
        QtCore.QObject.connect(self.form.pb_edit_inp, QtCore.SIGNAL("clicked()"), self.editSolverInputFile)
        QtCore.QObject.connect(self.form.pb_run_solver, QtCore.SIGNAL("clicked()"), self.runSolverProcess)
        QtCore.QObject.connect(self.form.pb_show_result, QtCore.SIGNAL("clicked()"), self.showResult)
        #
        QtCore.QObject.connect(self.SolverProcess, QtCore.SIGNAL("started()"), self.solverProcessStarted)
        QtCore.QObject.connect(self.SolverProcess, QtCore.SIGNAL("stateChanged(QProcess::ProcessState)"), self.solverProcessStateChanged)
        QtCore.QObject.connect(self.SolverProcess, QtCore.SIGNAL("error(QProcess::ProcessError)"), self.solverProcessError)
        QtCore.QObject.connect(self.SolverProcess, QtCore.SIGNAL("finished(int)"), self.solverProcessFinished)

        QtCore.QObject.connect(self.Timer, QtCore.SIGNAL("timeout()"), self.updateText)
        self.form.pb_show_result.setEnabled(True)
        self.Start = time.time() #debug tobe removed, it is not used in this taskpanel
        self.update()  # update UI from FemSolverObject, like WorkingDir
コード例 #14
0
ファイル: CfdPreferencePage.py プロジェクト: wkangholy/CfdOF
    def downloadBlueCFD(self):
        self.signals.status.emit("Downloading blueCFD-Core, please wait...")
        try:
            if hasattr(ssl, 'create_default_context'):
                context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
            else:
                context = None
            # Download
            (filename,
             header) = self.downloadFile(self.bluecfd_url,
                                         suffix=BLUECFD_FILE_EXT,
                                         reporthook=self.downloadStatus,
                                         context=context)
        except Exception as ex:
            raise Exception("Error downloading blueCFD-Core: {}".format(
                str(ex)))

        self.signals.status.emit(
            "blueCFD-Core downloaded to {}".format(filename))

        if QtCore.QProcess().startDetached(filename):
            self.signals.status.emit(
                "blueCFD-Core installer launched - please complete the installation"
            )
        else:
            raise Exception("Failed to launch blueCFD-Core installer")
コード例 #15
0
ファイル: utilities.py プロジェクト: cti-gr/avgui
    def run(self):
        #print("CURRENT THREAD WHEN STARTING: " +  str(self.currentThreadId()))
        #print("Starting scan with scanPath: " + str(self.scanPath) + " and with scanParams: " + str(self.scanParams))
        #self.finished.connect(self.onThreadFinish)
        self.avgscanProc = QtCore.QProcess()
        self.avgscanProc.open(QtCore.QIODevice.Unbuffered)
        self.avgscanProc.destroyed.connect(self.procDestroyed)
        self.avgscanProc.readyRead.connect(self.printOut)
        self.avgscanProc.finished.connect(self.onAVGProcessFinish)
        if (self.avgscanProc.state() != QtCore.QProcess.ProcessState.Running
            ) & (self.avgscanProc.state() !=
                 QtCore.QProcess.ProcessState.Starting):

            #print("---- STARTING AVG SCAN ----")
            if self.scanParams:
                try:
                    print("Within try1 " + str(self.scanParams))
                    self.avgscanProc.start("avgscan",
                                           [self.scanPath] + self.scanParams)
                    self.exec_()
                    #while not self.avgscanProc.waitForStarted():
                    #print("Waiting avgscanProc to start")
                except Exception as errinit1:
                    print("Σφάλμα κατά την εκκίνηση της σάρωσης: " +
                          str(errinit2))
            else:
                try:
                    print("Within try2")
                    self.avgscanProc.start("avgscan", [self.scanPath])
                    self.exec_()
                    #while not self.avgscanProc.waitForStarted():
                    #	 print("Waiting avgscanProc to start")
                except Exception as errinit2:
                    print("Σφάλμα κατά την εκκίνηση της σάρωσης: " +
                          str(errinit2))
コード例 #16
0
def startParaview(case_path, script_name, consoleMessageFn):
    proc = QtCore.QProcess()
    # If using blueCFD, use paraview supplied
    if getFoamRuntime() == 'BlueCFD':
        paraview_cmd = '{}\\..\\AddOns\\ParaView\\bin\\paraview.exe'.format(
            getFoamDir())
    else:
        paraview_cmd = "paraview"
    arg = '--script={}'.format(script_name)
    # 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:
        # If not found, try to run from the OpenFOAM environment, in case a bundled version is available from there
        paraview_cmd = "$(which paraview)"  # 'which' required due to mingw weirdness(?) on Windows
        try:
            consoleMessageFn("Running " + paraview_cmd + " " + arg)
            proc = startFoamApplication([paraview_cmd, arg],
                                        case_path,
                                        log_name=None)
            consoleMessageFn("Paraview started")
        except QtCore.QProcess.ProcessError:
            consoleMessageFn("Error starting paraview")
    else:
        arg = '--script={}'.format(script_name)
        consoleMessageFn("Running " + paraview_cmd + " " + arg)
        proc.setWorkingDirectory(case_path)
        proc.start(paraview_cmd, [arg])
        if proc.waitForStarted():
            consoleMessageFn("Paraview started")
        else:
            consoleMessageFn("Error starting paraview")
    return proc
コード例 #17
0
ファイル: utilities.py プロジェクト: cti-gr/avgui
 def run(self):
     self.theOutput = ""
     result = None
     #self.avgchkupProc = QtCore.QProcess()
     self.avgchkupProc = QtCore.QProcess()
     self.avgchkupProc.started.connect(self.emitProcStarted)
     self.avgchkupProc.setStandardErrorFile("errfile.txt")
     self.avgchkupProc.open(QtCore.QIODevice.Unbuffered)
     self.avgchkupProc.destroyed.connect(self.procDestroyed)
     self.avgchkupProc.readyRead.connect(self.parseOutput)
     self.avgchkupProc.finished.connect(self.onAVGprocFinish)
     self.finished.connect(self.onThreadTermination)
     #self.avgchkupProc.set
     try:
         startLocker = QtCore.QMutexLocker(mutexStartCheck)
         #print("starting AVGUPDATE process with EUID: " + str(os.geteuid()))
         #print("Now EUID is: " + str(os.geteuid()))
         QtGui.QApplication.processEvents()
         # self.avgchkupProc.start("gksu", ["avgupdate -c"])
         self.avgchkupProc.start("gksu", [
             "--description=" + langmodule.chkUpdate,
             "--message=" + langmodule.mustSudo, "avgupdate -c"
         ])
         #print("started UPDATE PROCESS with state: " + str(self.avgchkupProc.state()))
         if not self.avgchkupProc.waitForStarted(msecs=3000):
             print("SOS: " + str(self.avgchkupProc.state()))
             self.sigFailed.emit(True, "")
             self.exit()
             return
         self.exec_()
         QtGui.QApplication.processEvents()
     except Exception as err:
         print("Failed to initialize QProcess: " + str(err))
         return
コード例 #18
0
def run_elmergrid(export_path, mesh_object, out_dir=None):
    """
    Run ElmerGrid as an external process if it found in the operating system.

    :param export_path: path where the result is written
    :param mesh_object: FreeCAD mesh object that is to be exported
    :param out_dir: directory where to write mesh files (if not given unv file name is used)
    """
    # Export to UNV file for Elmer
    export_objects = [mesh_object]
    Fem.export(export_objects, export_path)

    optional_path_to_elmer = ''  # optional path to ElmerGrid
    elmerGrid_command = optional_path_to_elmer + 'ElmerGrid 8 2 ' + export_path + ' -autoclean -names'
    if out_dir is not None:
        elmerGrid_command += ' -out ' + out_dir

    from PySide import QtCore, QtGui
    try:
        process = QtCore.QProcess()
        process.startDetached(elmerGrid_command)
        FreeCAD.Console.PrintMessage('Running ' + elmerGrid_command + '\n')
        FreeCAD.Console.PrintMessage('Finished ' + elmerGrid_command + '\n')
    except:
        FreeCAD.Console.PrintError('Error')
        QtGui.QMessageBox.critical(None, 'Error', 'Error!!',
                                   QtGui.QMessageBox.Abort)
コード例 #19
0
    def __init__(self, obj):
        self.mesh_obj = obj
        self.form = FreeCADGui.PySideUic.loadUi(os.path.join(os.path.dirname(__file__), "TaskPanelCfdMeshGmsh.ui"))

        self.mesh_process = QtCore.QProcess()
        self.Timer = QtCore.QTimer()
        self.Start = time.time()
        self.console_message_gmsh = ''
        self.error_message = ''
        self.gmsh_mesh = []

        QtCore.QObject.connect(self.mesh_process, QtCore.SIGNAL("readyReadStandardOutput()"), self.readOutput)
        QtCore.QObject.connect(self.mesh_process, QtCore.SIGNAL("readyReadStandardError()"), self.readOutput)
        QtCore.QObject.connect(self.mesh_process, QtCore.SIGNAL("finished(int)"), self.meshFinished)

        QtCore.QObject.connect(self.form.if_max, QtCore.SIGNAL("valueChanged(Base::Quantity)"), self.max_changed)
        QtCore.QObject.connect(self.form.if_min, QtCore.SIGNAL("valueChanged(Base::Quantity)"), self.min_changed)
        QtCore.QObject.connect(self.form.cb_dimension, QtCore.SIGNAL("activated(int)"), self.choose_dimension)
        QtCore.QObject.connect(self.Timer, QtCore.SIGNAL("timeout()"), self.update_timer_text)

        QtCore.QObject.connect(self.form.pb_run_mesh, QtCore.SIGNAL("clicked()"), self.runMeshProcess)
        QtCore.QObject.connect(self.form.pb_stop_mesh, QtCore.SIGNAL("clicked()"), self.killMeshProcess)
        self.form.pb_stop_mesh.setEnabled(False)

        self.form.cb_dimension.addItems(_FemMeshGmsh._FemMeshGmsh.known_element_dimensions)

        self.get_mesh_params()
        self.order = '1st'  # Force first order for CFD mesh
        self.get_active_analysis()
        self.update()
コード例 #20
0
def startParaview(case_path, script_name, consoleMessageFn):
    proc = QtCore.QProcess()
    paraview_cmd = getParaviewExecutable()
    arg = '--script={}'.format(script_name)

    if not paraview_cmd:
        # If not found, try to run from the OpenFOAM environment, in case a bundled version is available from there
        paraview_cmd = "$(which paraview)"  # 'which' required due to mingw weirdness(?) on Windows
        try:
            consoleMessageFn("Running " + paraview_cmd + " " + arg)
            proc = startFoamApplication([paraview_cmd, arg],
                                        case_path,
                                        log_name=None)
            consoleMessageFn("Paraview started")
        except QtCore.QProcess.ProcessError:
            consoleMessageFn("Error starting paraview")
    else:
        consoleMessageFn("Running " + paraview_cmd + " " + arg)
        proc.setWorkingDirectory(case_path)
        proc.start(paraview_cmd, [arg])
        if proc.waitForStarted():
            consoleMessageFn("Paraview started")
        else:
            consoleMessageFn("Error starting paraview")
    return proc
コード例 #21
0
    def __init__(self, solver_object):
        self.form = FreeCADGui.PySideUic.loadUi(
            FreeCAD.getHomePath() + "Mod/Fem/Resources/ui/SolverCalculix.ui")

        from femtools.ccxtools import CcxTools as ccx
        # we do not need to pass the analysis, it will be found on fea init
        # TODO: if there is not analysis object in document init of fea
        # will fail with an exception and task panel will not open
        # handle more smart by a pop up error message and still open
        # task panel, may be deactivate write and run button.
        self.fea = ccx(solver_object)
        self.fea.setup_working_dir()
        self.fea.setup_ccx()

        self.Calculix = QtCore.QProcess()
        self.Timer = QtCore.QTimer()
        self.Timer.start(300)

        self.fem_console_message = ""

        # Connect Signals and Slots
        QtCore.QObject.connect(self.form.tb_choose_working_dir,
                               QtCore.SIGNAL("clicked()"),
                               self.choose_working_dir)
        QtCore.QObject.connect(self.form.pb_write_inp,
                               QtCore.SIGNAL("clicked()"),
                               self.write_input_file_handler)
        QtCore.QObject.connect(self.form.pb_edit_inp,
                               QtCore.SIGNAL("clicked()"),
                               self.editCalculixInputFile)
        QtCore.QObject.connect(self.form.pb_run_ccx,
                               QtCore.SIGNAL("clicked()"), self.runCalculix)
        QtCore.QObject.connect(self.form.rb_static_analysis,
                               QtCore.SIGNAL("clicked()"),
                               self.select_static_analysis)
        QtCore.QObject.connect(self.form.rb_frequency_analysis,
                               QtCore.SIGNAL("clicked()"),
                               self.select_frequency_analysis)
        QtCore.QObject.connect(self.form.rb_thermomech_analysis,
                               QtCore.SIGNAL("clicked()"),
                               self.select_thermomech_analysis)
        QtCore.QObject.connect(self.form.rb_check_mesh,
                               QtCore.SIGNAL("clicked()"),
                               self.select_check_mesh)
        QtCore.QObject.connect(self.Calculix, QtCore.SIGNAL("started()"),
                               self.calculixStarted)
        QtCore.QObject.connect(
            self.Calculix,
            QtCore.SIGNAL("stateChanged(QProcess::ProcessState)"),
            self.calculixStateChanged)
        QtCore.QObject.connect(self.Calculix,
                               QtCore.SIGNAL("error(QProcess::ProcessError)"),
                               self.calculixError)
        QtCore.QObject.connect(self.Calculix, QtCore.SIGNAL("finished(int)"),
                               self.calculixFinished)
        QtCore.QObject.connect(self.Timer, QtCore.SIGNAL("timeout()"),
                               self.UpdateText)

        self.update()
コード例 #22
0
    def on_execute_gencase(self):
        """ Saves data into disk and uses GenCase to generate the case files."""
        self.on_save_case()
        if not Case.the().executable_paths.gencase:
            warning_dialog(__("GenCase executable is not set."))
            return

        gencase_full_path = path.abspath(Case.the().executable_paths.gencase)
        arguments = [
            "{path}/{name}_Def".format(path=Case.the().path,
                                       name=Case.the().name),
            "{path}/{name}_out/{name}".format(path=Case.the().path,
                                              name=Case.the().name),
            "-save:+all"
        ]
        cmd_string = "{} {}".format(gencase_full_path, " ".join(arguments))

        refocus_cwd()
        process = QtCore.QProcess(get_fc_main_window())
        process.setWorkingDirectory(Case.the().path)
        ensure_process_is_executable_or_fail(gencase_full_path)
        process.start(gencase_full_path, arguments)
        debug("Executing -> {}".format(cmd_string))
        process.waitForFinished()

        try:
            output = str(process.readAllStandardOutput().data(),
                         encoding='utf-8')
        except UnicodeDecodeError:
            output = str(process.readAllStandardOutput().data(),
                         encoding='latin1')

        if process.exitCode():
            Case.the().info.is_gencase_done = False
            error_dialog(
                __("Error executing GenCase. Did you add objects to the case?. Another reason could be memory issues. View details for more info."
                   ), output)
        else:
            try:
                total_particles_text = output[
                    output.index("Total particles: "):output.index(" (bound=")]
                total_particles = int(
                    total_particles_text[total_particles_text.index(": ") +
                                         2:])
                Case.the().info.particle_number = total_particles
                GencaseCompletedDialog(particle_count=total_particles,
                                       detail_text=output,
                                       cmd_string=cmd_string,
                                       parent=get_fc_main_window()).show()
                Case.the().info.is_gencase_done = True
                self.on_save_case()
                Case.the().info.needs_to_run_gencase = False
            except ValueError:
                print_exc()
                Case.the().info.is_gencase_done = False
                Case.the().info.needs_to_run_gencase = True

        # Refresh widget enable/disable status as GenCase finishes
        self.gencase_completed.emit(Case.the().info.is_gencase_done)
コード例 #23
0
ファイル: _TaskPanelCfdMesh.py プロジェクト: zhishang80/CfdOF
    def __init__(self, obj):
        self.mesh_obj = obj
        self.form = FreeCADGui.PySideUic.loadUi(os.path.join(os.path.dirname(__file__), "TaskPanelCfdMesh.ui"))

        self.Timer = QtCore.QTimer()
        self.Start = time.time()
        self.console_message_cart = ''
        self.error_message = ''
        self.cart_mesh = CfdMeshTools.CfdMeshTools(self.mesh_obj)
        self.paraviewScriptName = ""

        self.mesh_process = CfdConsoleProcess(finishedHook=self.meshFinished,
                                              stdoutHook=self.gotOutputLines,
                                              stderrHook=self.gotErrorLines)
        self.edit_prcess = None

        QtCore.QObject.connect(self.form.if_max, QtCore.SIGNAL("valueChanged(Base::Quantity)"), self.max_changed)
        QtCore.QObject.connect(self.form.if_pointInMeshX, QtCore.SIGNAL("valueChanged(Base::Quantity)"),
                               self.pointInMeshX_changed)
        QtCore.QObject.connect(self.form.if_pointInMeshY, QtCore.SIGNAL("valueChanged(Base::Quantity)"),
                               self.pointInMeshY_changed)
        QtCore.QObject.connect(self.form.if_pointInMeshZ, QtCore.SIGNAL("valueChanged(Base::Quantity)"),
                               self.pointInMeshZ_changed)
        QtCore.QObject.connect(self.form.if_cellsbetweenlevels, QtCore.SIGNAL("valueChanged(int)"),
                               self.cellsbetweenlevels_changed)
        QtCore.QObject.connect(self.form.if_edgerefine, QtCore.SIGNAL("valueChanged(int)"), self.edgerefine_changed)
        QtCore.QObject.connect(self.form.cb_dimension, QtCore.SIGNAL("activated(int)"), self.choose_dimension)
        QtCore.QObject.connect(self.form.cb_utility, QtCore.SIGNAL("activated(int)"), self.choose_utility)
        QtCore.QObject.connect(self.Timer, QtCore.SIGNAL("timeout()"), self.update_timer_text)

        self.open_paraview = QtCore.QProcess()

        self.form.pb_write_mesh.clicked.connect(self.writeMesh)
        self.form.pb_edit_mesh.clicked.connect(self.editMesh)
        self.form.pb_run_mesh.clicked.connect(self.runMesh)
        self.form.pb_stop_mesh.clicked.connect(self.killMeshProcess)
        self.form.pb_paraview.clicked.connect(self.openParaview)
        self.form.pb_load_mesh.clicked.connect(self.pbLoadMeshClicked)
        self.form.pb_clear_mesh.clicked.connect(self.pbClearMeshClicked)
        self.form.pb_searchPointInMesh.clicked.connect(self.searchPointInMesh)
        self.form.pb_stop_mesh.setEnabled(False)
        self.form.pb_paraview.setEnabled(False)
        self.form.snappySpecificProperties.setVisible(False)

        self.form.cb_dimension.addItems(_CfdMesh._CfdMesh.known_element_dimensions)
        self.form.cb_utility.addItems(_CfdMesh._CfdMesh.known_mesh_utility)

        self.form.if_max.setToolTip("Select 0 to use default value")
        self.form.pb_searchPointInMesh.setToolTip("Specify below a point vector inside of the mesh or press 'Search' "
                                                  "to try and automatically find a point")
        self.form.if_cellsbetweenlevels.setToolTip("Number of cells between each of level of refinement.")
        self.form.if_edgerefine.setToolTip("Number of refinement levels for all edges.")

        self.get_mesh_params()
        self.order = '1st'  # Default to first order for CFD mesh
        self.get_active_analysis()
        self.update()

        self.updateUI()
コード例 #24
0
ファイル: CfdConsoleProcess.py プロジェクト: jacojvr/CfdOF
 def __init__(self, finishedHook=None, stdoutHook=None, stderrHook=None):
     self.process = QtCore.QProcess()
     self.finishedHook = finishedHook
     self.stdoutHook = stdoutHook
     self.stderrHook = stderrHook
     self.process.finished.connect(self.finished)
     self.process.readyReadStandardOutput.connect(self.readStdout)
     self.process.readyReadStandardError.connect(self.readStderr)
コード例 #25
0
ファイル: MechanicalAnalysis.py プロジェクト: mthayne/FreeCAD
    def __init__(self, analysis_object):
        self.form = FreeCADGui.PySideUic.loadUi(
            FreeCAD.getHomePath() + "Mod/Fem/MechanicalAnalysis.ui")
        self.fem_prefs = FreeCAD.ParamGet(
            "User parameter:BaseApp/Preferences/Mod/Fem")
        ccx_binary = self.fem_prefs.GetString("ccxBinaryPath", "")
        if ccx_binary:
            self.CalculixBinary = ccx_binary
            print "Using ccx binary path from FEM preferences: {}".format(
                ccx_binary)
        else:
            from platform import system
            if system() == 'Linux':
                self.CalculixBinary = 'ccx'
            elif system() == 'Windows':
                self.CalculixBinary = FreeCAD.getHomePath() + 'bin/ccx.exe'
            else:
                self.CalculixBinary = 'ccx'
        self.fem_prefs = FreeCAD.ParamGet(
            "User parameter:BaseApp/Preferences/Mod/Fem")
        self.working_dir = self.fem_prefs.GetString("WorkingDir", '/tmp')

        self.analysis_object = analysis_object
        self.Calculix = QtCore.QProcess()
        self.Timer = QtCore.QTimer()
        self.Timer.start(300)

        self.fem_console_message = ''

        #Connect Signals and Slots
        QtCore.QObject.connect(self.form.tb_choose_working_dir,
                               QtCore.SIGNAL("clicked()"),
                               self.choose_working_dir)
        QtCore.QObject.connect(self.form.pushButton_write,
                               QtCore.SIGNAL("clicked()"),
                               self.write_input_file_handler)
        QtCore.QObject.connect(self.form.pushButton_edit,
                               QtCore.SIGNAL("clicked()"),
                               self.editCalculixInputFile)
        QtCore.QObject.connect(self.form.pushButton_generate,
                               QtCore.SIGNAL("clicked()"), self.runCalculix)

        QtCore.QObject.connect(self.Calculix, QtCore.SIGNAL("started()"),
                               self.calculixStarted)
        QtCore.QObject.connect(
            self.Calculix,
            QtCore.SIGNAL("stateChanged(QProcess::ProcessState)"),
            self.calculixStateChanged)
        QtCore.QObject.connect(self.Calculix,
                               QtCore.SIGNAL("error(QProcess::ProcessError)"),
                               self.calculixError)
        QtCore.QObject.connect(self.Calculix, QtCore.SIGNAL("finished(int)"),
                               self.calculixFinished)

        QtCore.QObject.connect(self.Timer, QtCore.SIGNAL("timeout()"),
                               self.UpdateText)

        self.update()
コード例 #26
0
 def run_process(self):
     if not self.processes:
         return None
     index, filepath = self.processes.pop(0)
     self.ui.tableWidget.setItem(
         index, 1, self.make_cell("Processando...", (255, 255, 100)))
     process = QtCore.QProcess(self.parent)
     process.finished.connect(finished_signal_factory(self, index, process))
     process.start(self.parent.CMD, [filepath])
コード例 #27
0
    def __init__(self, object):
        # the panel has a tree widget that contains categories
        # for the subcomponents, such as additions, subtractions.
        # the categories are shown only if they are not empty.
        self.form = FreeCADGui.PySideUic.loadUi(
            FreeCAD.getHomePath() + "Mod/Fem/MechanicalAnalysis.ui")
        from platform import system
        if system() == 'Linux':
            self.CalculixBinary = 'ccx'
        elif system() == 'Windows':
            self.CalculixBinary = FreeCAD.getHomePath() + 'bin/ccx.exe'
        else:
            self.CalculixBinary = 'ccx'
        self.TempDir = FreeCAD.ActiveDocument.TransientDir.replace(
            '\\', '/') + '/FemAnl_' + object.Uid[-4:]
        if not os.path.isdir(self.TempDir):
            os.mkdir(self.TempDir)

        self.obj = object
        #self.params = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Fem")
        self.fem_prefs = FreeCAD.ParamGet(
            "User parameter:BaseApp/Preferences/Mod/Fem")
        self.Calculix = QtCore.QProcess()
        self.Timer = QtCore.QTimer()
        self.Timer.start(300)

        self.fem_console_meaasge = ''

        #Connect Signals and Slots
        QtCore.QObject.connect(self.form.toolButton_chooseOutputDir,
                               QtCore.SIGNAL("clicked()"),
                               self.chooseOutputDir)
        QtCore.QObject.connect(self.form.pushButton_write,
                               QtCore.SIGNAL("clicked()"),
                               self.writeCalculixInputFile)
        QtCore.QObject.connect(self.form.pushButton_edit,
                               QtCore.SIGNAL("clicked()"),
                               self.editCalculixInputFile)
        QtCore.QObject.connect(self.form.pushButton_generate,
                               QtCore.SIGNAL("clicked()"), self.runCalculix)

        QtCore.QObject.connect(self.Calculix, QtCore.SIGNAL("started()"),
                               self.calculixStarted)
        QtCore.QObject.connect(
            self.Calculix,
            QtCore.SIGNAL("stateChanged(QProcess::ProcessState)"),
            self.calculixStateChanged)
        QtCore.QObject.connect(self.Calculix,
                               QtCore.SIGNAL("error(QProcess::ProcessError)"),
                               self.calculixError)
        QtCore.QObject.connect(self.Calculix, QtCore.SIGNAL("finished(int)"),
                               self.calculixFinished)

        QtCore.QObject.connect(self.Timer, QtCore.SIGNAL("timeout()"),
                               self.UpdateText)

        self.update()
コード例 #28
0
ファイル: CfdPreferencePage.py プロジェクト: yupeng08/CfdOF
 def downloadParaview(self):
     filename = self.download(self.paraview_url, PARAVIEW_FILE_EXT,
                              "ParaView")
     if QtCore.QProcess().startDetached(filename):
         self.signals.status.emit(
             "ParaView installer launched - please complete the installation"
         )
     else:
         raise Exception("Failed to launch ParaView installer")
コード例 #29
0
    def __init__(self, solver_runner_obj):
        ui_path = os.path.join(os.path.dirname(__file__),
                               "TaskPanelCfdSolverControl.ui")
        self.form = FreeCADGui.PySideUic.loadUi(ui_path)

        self.analysis_object = FemGui.getActiveAnalysis()

        self.solver_runner = solver_runner_obj
        self.solver_object = solver_runner_obj.solver

        self.writer_thread = QtCore.QThreadPool()
        self.writer_thread.setMaxThreadCount(
            1)  # Only allow one concurrent case writer to be triggered
        self.solver_runner.writer.setAutoDelete(
            False)  # Don't delete object once writer is run
        self.solver_runner.writer.signals.error.connect(self.writerError)
        self.solver_runner.writer.signals.finished.connect(self.writerFinished)

        # update UI
        self.console_message = ''

        self.solver_run_process = CfdConsoleProcess(
            finishedHook=self.solverFinished,
            stdoutHook=self.gotOutputLines,
            stderrHook=self.gotErrorLines)
        self.Timer = QtCore.QTimer()
        self.Timer.start(100)

        self.form.terminateSolver.clicked.connect(self.killSolverProcess)
        self.form.terminateSolver.setEnabled(False)

        self.open_paraview = QtCore.QProcess()

        # Connect Signals and Slots
        QtCore.QObject.connect(self.form.tb_choose_working_dir,
                               QtCore.SIGNAL("clicked()"),
                               self.choose_working_dir)
        QtCore.QObject.connect(self.form.pb_write_inp,
                               QtCore.SIGNAL("clicked()"),
                               self.write_input_file_handler)
        QtCore.QObject.connect(self.form.pb_edit_inp,
                               QtCore.SIGNAL("clicked()"),
                               self.editSolverInputFile)
        QtCore.QObject.connect(self.form.pb_run_solver,
                               QtCore.SIGNAL("clicked()"),
                               self.runSolverProcess)
        # QtCore.QObject.connect(self.form.pb_show_result, QtCore.SIGNAL("clicked()"), self.showResult)
        QtCore.QObject.connect(self.form.pb_paraview,
                               QtCore.SIGNAL("clicked()"), self.openParaview)
        # self.form.pb_show_result.setEnabled(False)

        QtCore.QObject.connect(self.Timer, QtCore.SIGNAL("timeout()"),
                               self.updateText)
        self.Start = time.time()
        self.update()  # update UI from FemSolverObject, like WorkingDir
コード例 #30
0
ファイル: CfdPreferencePage.py プロジェクト: kliberty/CfdOF
    def downloadBlueCFD(self):
        self.signals.status.emit("Downloading blueCFD-Core, please wait...")
        try:
            (filename, headers) = urlrequest.urlretrieve(self.bluecfd_url, reporthook=self.downloadStatus)
        except Exception as ex:
            raise Exception("Error downloading blueCFD-Core: {}".format(str(ex)))
        self.signals.status.emit("blueCFD-Core downloaded to {}".format(filename))

        if QtCore.QProcess().startDetached(filename):
            self.signals.status.emit("blueCFD-Core installer launched - please complete the installation")
        else:
            raise Exception("Failed to launch blueCFD-Core installer")