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.
        form_class, base_class = uic.loadUiType(FreeCAD.getHomePath() + "Mod/Fem/MechanicalAnalysis.ui")
        
        self.CalculixBinary = FreeCAD.getHomePath() +'bin/ccx.exe'
        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.formUi = form_class()
        self.form = QtGui.QWidget()
        self.formUi.setupUi(self.form)
        #self.params = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Fem")
        self.Calculix = QtCore.QProcess()
        self.Timer = QtCore.QTimer()
        self.Timer.start(300)
        
        self.OutStr = ''
        
        #Connect Signals and Slots
        QtCore.QObject.connect(self.formUi.toolButton_chooseOutputDir, QtCore.SIGNAL("clicked()"), self.chooseOutputDir)
        QtCore.QObject.connect(self.formUi.pushButton_generate, QtCore.SIGNAL("clicked()"), self.run)

        QtCore.QObject.connect(self.Calculix, QtCore.SIGNAL("started()"), self.calculixStarted)
        QtCore.QObject.connect(self.Calculix, QtCore.SIGNAL("finished(int)"), self.calculixFinished)

        QtCore.QObject.connect(self.Timer, QtCore.SIGNAL("timeout()"), self.UpdateText)
        
        self.update()
Example #2
0
 def get_gmsh_command(self):
     self.gmsh_bin = None
     gmsh_std_location = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Fem/Gmsh").GetBool("UseStandardGmshLocation")
     if gmsh_std_location:
         if system() == "Windows":
             gmsh_path = FreeCAD.getHomePath() + "bin/gmsh.exe"
             FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Fem/Gmsh").SetString("gmshBinaryPath", gmsh_path)
             self.gmsh_bin = gmsh_path
         elif system() == "Linux":
             p1 = subprocess.Popen(['which', 'gmsh'], stdout=subprocess.PIPE)
             if p1.wait() == 0:
                 gmsh_path = p1.stdout.read().split('\n')[0]
             elif p1.wait() == 1:
                 error_message = "GMSH binary gmsh not found in standard system binary path. Please install gmsh or set path to binary in FEM preferences tab GMSH.\n"
                 FreeCAD.Console.PrintError(error_message)
                 raise Exception(error_message)
             self.gmsh_bin = gmsh_path
         else:
             error_message = "No standard location implemented for your operating system. Set GMHS binary path in FEM preferences.\n"
             FreeCAD.Console.PrintError(error_message)
             raise Exception(error_message)
     else:
         if not self.gmsh_bin:
             self.gmsh_bin = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Fem/Gmsh").GetString("gmshBinaryPath", "")
         if not self.gmsh_bin:  # in prefs not set, we will try to use something reasonable
             if system() == "Linux":
                 self.gmsh_bin = "gmsh"
             elif system() == "Windows":
                 self.gmsh_bin = FreeCAD.getHomePath() + "bin/gmsh.exe"
             else:
                 self.gmsh_bin = "gmsh"
     print('  ' + self.gmsh_bin)
Example #3
0
    def Activated(self):
        pol=np.loadtxt(FreeCAD.getHomePath()+'Mod/glider/examples/p.dat', dtype=int)
        nod=np.loadtxt(FreeCAD.getHomePath()+'Mod/glider/examples/n.dat', dtype=float)
        planarMesh = []
        for i in pol:
            planarMesh.append(nod[i[0]])
            planarMesh.append(nod[i[1]])
            planarMesh.append(nod[i[2]])
            planarMesh.append(nod[i[0]])
            planarMesh.append(nod[i[2]])
            planarMesh.append(nod[i[3]])

        planarMeshObject = Mesh.Mesh(planarMesh)
        Mesh.show(planarMeshObject)
Example #4
0
    def start_gnu_plot(self,list,lc_coeff,ltc_coeff):
        gnu_plot_input_file = open(str(self.dirname + "/gnu_plot_input.txt"),"wb")
        gnu_plot_input_file.write(
                                    "set term png\n" +
                                    "set output \"max_disp_z.png\"\n"+
                                    "set surface\n" +
                                    "set grid\n"+
                                    "set hidden3d\n"+
                                    "set dgrid3d " + str(len(list)-1) + "," + str(len(list)-1) + ",100\n" +
                                    "set view 80,05,1.3,1.0\n"+
                                    "set title \"Abs Displacement in Z vs. Z-Level Offset and Rotation around Z-Axis\" 0,-2\n"+
                                    "show title\n"+
                                    "set label \"L Coefficients used for the calculation:" + lc_coeff[0] + "," + lc_coeff[1] + "," + lc_coeff[2] + "," + lc_coeff[3] + "," + lc_coeff[4] + "," + lc_coeff[5][:-1] + "\" at screen 0.1, screen 0.95 left font \"Arial,8\"\n"+ 
                                    "set label \"LT Coefficients used for the calculation:" + ltc_coeff[0] + "," + ltc_coeff[1] + "," + ltc_coeff[2] + "," + ltc_coeff[3] + "," + ltc_coeff[4] + "," + ltc_coeff[5][:-1] + "\" at screen 0.1, screen 0.93 left font \"Arial,8\"\n"+
                                    "set label \"Z-Offset\\nin [mm]\" at screen 0.5, screen 0.1 center rotate by 0\n"+ 
                                    "set label \"Rotation around Z-Axis\\nin [" + str(chr(248)) +"]\" at screen 0.91, screen 0.2 center rotate by 50\n"+ 
                                    "set label \"Max Displacement Z direction\\nin [mm]\" at screen 0.03, screen 0.5 center rotate by 90\n"+ 
                                    "set xtics in nomirror offset character 0,-0.5\n"+
                                    "splot \"postprocessing_input.txt\" u 1:4:14 with pm3d title \"\"\n" + 
                                    "exit" )
                                    

                                    
        gnu_plot_input_file.close()
        os.chdir(str(self.dirname))
        fnull = open(os.devnull, 'w')
        commandline = FreeCAD.getHomePath() + "bin/gnuplot/gnuplot gnu_plot_input.txt"
        result = subprocess.call(commandline, shell = True, stdout = fnull, stderr = fnull)
        fnull.close()
    def __init__(self, obj):

        self.obj = obj

        # parameter widget
        self.parameterWidget = FreeCADGui.PySideUic.loadUi(
            FreeCAD.getHomePath() + "Mod/Fem/Resources/ui/MeshGroup.ui"
        )
        QtCore.QObject.connect(
            self.parameterWidget.rb_name,
            QtCore.SIGNAL("toggled(bool)"),
            self.choose_exportidentifier_name
        )
        QtCore.QObject.connect(
            self.parameterWidget.rb_label,
            QtCore.SIGNAL("toggled(bool)"),
            self.choose_exportidentifier_label
        )
        self.init_parameter_widget()

        # geometry selection widget
        # start with Solid in list!
        self.selectionWidget = FemSelectionWidgets.GeometryElementsSelection(
            obj.References,
            ['Solid', 'Face', 'Edge', 'Vertex']
        )

        # form made from param and selection widget
        self.form = [self.parameterWidget, self.selectionWidget]
    def __init__(self, solver_object):
        self.form = FreeCADGui.PySideUic.loadUi(FreeCAD.getHomePath() + "Mod/Fem/Resources/ui/SolverCalculix.ui")

        # since open the task panel is only possible with an active analysis, we do not need to pass the analysis. it will be found
        self.fea = ccxtools.FemToolsCcx(None, 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()
Example #7
0
    def __init__(self, obj, mode):
        self.obj = obj

        self.form = FreeCADGui.PySideUic.loadUi(FreeCAD.getHomePath() + "Mod/PartDesign/InvoluteGearFeature.ui")
        self.form.setWindowIcon(QtGui.QIcon(":/icons/PartDesign_InternalExternalGear.svg"))

        QtCore.QObject.connect(self.form.Quantity_Modules, QtCore.SIGNAL("valueChanged(double)"), self.modulesChanged)
        QtCore.QObject.connect(
            self.form.Quantity_PressureAngle, QtCore.SIGNAL("valueChanged(double)"), self.angleChanged
        )
        QtCore.QObject.connect(
            self.form.spinBox_NumberOfTeeth, QtCore.SIGNAL("valueChanged(int)"), self.numTeethChanged
        )
        QtCore.QObject.connect(
            self.form.comboBox_HighPrecision, QtCore.SIGNAL("currentIndexChanged(int)"), self.numCurvesChanged
        )
        # QtCore.QObject.connect(self.form.comboBox_ExternalGear, QtCore.SIGNAL("activated(QString)"), self.externalGearChanged)
        # QtCore.QObject.connect(self.form.comboBox_ExternalGear, QtCore.SIGNAL("currentIndexChanged(int)"), self.externalGearChanged)
        QtCore.QObject.connect(
            self.form.comboBox_ExternalGear, QtCore.SIGNAL("currentIndexChanged(int)"), self.externalGearChanged
        )

        self.update()

        if mode == 0:  # fresh created
            self.obj.Proxy.execute(self.obj)  # calculate once
            FreeCAD.Gui.SendMsgToActiveView("ViewFit")
    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.
        form_class, base_class = uic.loadUiType(FreeCAD.getHomePath() + "Mod/Fem/ShowDisplacement.ui")

        self.obj = object
        self.formUi = form_class()
        self.form = QtGui.QWidget()
        self.formUi.setupUi(self.form)

        #Connect Signals and Slots
        QtCore.QObject.connect(self.formUi.radioButton_Displacement, QtCore.SIGNAL("clicked(bool)"), self.displacementClicked)
        QtCore.QObject.connect(self.formUi.radioButton_Stress, QtCore.SIGNAL("clicked(bool)"), self.stressClicked)
        QtCore.QObject.connect(self.formUi.radioButton_NoColor, QtCore.SIGNAL("clicked(bool)"), self.noColorClicked)
        QtCore.QObject.connect(self.formUi.checkBox_ShowDisplacement, QtCore.SIGNAL("clicked(bool)"), self.showDisplacementClicked)

        QtCore.QObject.connect(self.formUi.verticalScrollBar_Factor, QtCore.SIGNAL("valueChanged(int)"), self.sliderValue)

        QtCore.QObject.connect(self.formUi.spinBox_SliderFactor, QtCore.SIGNAL("valueChanged(double)"), self.sliderMaxValue)
        QtCore.QObject.connect(self.formUi.spinBox_DisplacementFactor, QtCore.SIGNAL("valueChanged(double)"), self.displacementFactorValue)

        self.DisplacementObject = None
        self.StressObject = None

        self.update()
Example #9
0
    def __init__(self, obj):
        self.obj = obj

        self.form = FreeCADGui.PySideUic.loadUi(FreeCAD.getHomePath() + "Mod/Fem/MechanicalMaterial.ui")

        QtCore.QObject.connect(self.form.pushButton_MatWeb, QtCore.SIGNAL("clicked()"), self.goMatWeb)
        QtCore.QObject.connect(self.form.cb_materials, QtCore.SIGNAL("activated(int)"), self.choose_material)
        QtCore.QObject.connect(self.form.input_fd_young_modulus, QtCore.SIGNAL("valueChanged(double)"), self.ym_changed)
        QtCore.QObject.connect(self.form.spinBox_poisson_ratio, QtCore.SIGNAL("valueChanged(double)"), self.pr_changed)
        QtCore.QObject.connect(self.form.input_fd_density, QtCore.SIGNAL("valueChanged(double)"), self.density_changed)
        self.material = self.obj.Material
        self.import_materials()
        previous_mat_path = self.get_material_path(self.material)
        if not previous_mat_path:
            print("Previously used material cannot be found in material directories. Using transient material.")
            material_name = self.get_material_name(self.material)
            if material_name != "None":
                self.add_transient_material(self.material)
                index = self.form.cb_materials.findData(material_name)
            else:
                index = self.form.cb_materials.findText(material_name)
            self.choose_material(index)
        else:
            index = self.form.cb_materials.findData(previous_mat_path)
            self.choose_material(index)
    def __init__(self, obj):

        self.obj = obj

        # parameter widget
        self.parameterWidget = FreeCADGui.PySideUic.loadUi(
            FreeCAD.getHomePath() + "Mod/Fem/Resources/ui/MeshBoundaryLayer.ui"
        )
        QtCore.QObject.connect(
            self.parameterWidget.bl_number_of_layers,
            QtCore.SIGNAL("valueChanged(int)"),
            self.bl_number_of_layers_changed
        )
        QtCore.QObject.connect(
            self.parameterWidget.bl_min_thickness,
            QtCore.SIGNAL("valueChanged(Base::Quantity)"),
            self.bl_min_thickness_changed
        )
        # be careful of signal signature for QDoubleSpinbox
        QtCore.QObject.connect(
            self.parameterWidget.bl_growth_rate,
            QtCore.SIGNAL("valueChanged(double)"),
            self.bl_growth_rate_changed
        )
        self.init_parameter_widget()

        # geometry selection widget
        # start with Solid in list!
        self.selectionWidget = FemSelectionWidgets.GeometryElementsSelection(
            obj.References,
            ['Solid', 'Face', 'Edge', 'Vertex']
        )

        # form made from param and selection widget
        self.form = [self.parameterWidget, self.selectionWidget]
    def __init__(self, obj):
        FreeCADGui.Selection.clearSelection()
        self.sel_server = None
        self.obj = obj
        self.material = self.obj.Material
        self.references = self.obj.References
        self.references_shape_type = None

        self.form = FreeCADGui.PySideUic.loadUi(FreeCAD.getHomePath() + "Mod/Fem/TaskPanelMechanicalMaterial.ui")
        QtCore.QObject.connect(self.form.pushButton_MatWeb, QtCore.SIGNAL("clicked()"), self.goMatWeb)
        QtCore.QObject.connect(self.form.cb_materials, QtCore.SIGNAL("activated(int)"), self.choose_material)
        QtCore.QObject.connect(self.form.input_fd_young_modulus, QtCore.SIGNAL("valueChanged(double)"), self.ym_changed)
        QtCore.QObject.connect(self.form.spinBox_poisson_ratio, QtCore.SIGNAL("valueChanged(double)"), self.pr_changed)
        QtCore.QObject.connect(self.form.input_fd_density, QtCore.SIGNAL("valueChanged(double)"), self.density_changed)
        QtCore.QObject.connect(self.form.pushButton_Reference, QtCore.SIGNAL("clicked()"), self.add_references)
        self.form.list_References.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
        self.form.list_References.connect(self.form.list_References, QtCore.SIGNAL("customContextMenuRequested(QPoint)"), self.references_list_right_clicked)

        self.import_materials()
        previous_mat_path = self.get_material_path(self.material)
        if not previous_mat_path:
            FreeCAD.Console.PrintMessage("Previously used material cannot be found in material directories. Using transient material.\n")
            material_name = self.get_material_name(self.material)
            if material_name != 'None':
                self.add_transient_material(self.material)
                index = self.form.cb_materials.findData(material_name)
            else:
                index = self.form.cb_materials.findText(material_name)
            self.choose_material(index)
        else:
            index = self.form.cb_materials.findData(previous_mat_path)
            self.choose_material(index)
        self.has_equal_references_shape_types()
        self.rebuild_list_References()
Example #12
0
def get_fem_test_defs(inout='out'):
    test_path = join(FreeCAD.getHomePath(), 'Mod', 'Fem', 'femtest')
    collected_test_modules = []
    collected_test_methods = []
    for tfile in sorted(os.listdir(test_path)):
        if tfile.startswith("test") and tfile.endswith(".py"):
            collected_test_modules.append(join(test_path, tfile))
    for f in collected_test_modules:
        tfile = open(f, 'r')
        module_name = os.path.splitext(os.path.basename(f))[0]
        class_name = ''
        for ln in tfile:
            ln = ln.lstrip()
            ln = ln.rstrip()
            if ln.startswith('class '):
                ln = ln.lstrip('class ')
                ln = ln.split('(')[0]
                class_name = ln
            if ln.startswith('def test'):
                ln = ln.lstrip('def ')
                ln = ln.split('(')[0]
                collected_test_methods.append('femtest.{}.{}.{}'.format(module_name, class_name, ln))
        tfile.close()
    print('')
    for m in collected_test_methods:
        run_outside_fc = './bin/FreeCADCmd --run-test "{}"'.format(m)
        run_inside_fc = 'unittest.TextTestRunner().run(unittest.TestLoader().loadTestsFromName("{}"))'.format(m)
        if inout == 'in':
            print('\nimport unittest')
            print(run_inside_fc)
        else:
            print(run_outside_fc)
    def __init__(self):
        self.form = FreeCADGui.PySideUic.loadUi(FreeCAD.getHomePath() + "Mod/Fem/TaskPanelShowResult.ui")
        self.fem_prefs = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Fem/General")
        self.restore_result_settings_in_dialog = self.fem_prefs.GetBool("RestoreResultDialog", True)

        # Connect Signals and Slots
        QtCore.QObject.connect(self.form.rb_none, QtCore.SIGNAL("toggled(bool)"), self.none_selected)
        QtCore.QObject.connect(self.form.rb_x_displacement, QtCore.SIGNAL("toggled(bool)"), self.x_displacement_selected)
        QtCore.QObject.connect(self.form.rb_y_displacement, QtCore.SIGNAL("toggled(bool)"), self.y_displacement_selected)
        QtCore.QObject.connect(self.form.rb_z_displacement, QtCore.SIGNAL("toggled(bool)"), self.z_displacement_selected)
        QtCore.QObject.connect(self.form.rb_abs_displacement, QtCore.SIGNAL("toggled(bool)"), self.abs_displacement_selected)
        QtCore.QObject.connect(self.form.rb_vm_stress, QtCore.SIGNAL("toggled(bool)"), self.vm_stress_selected)

        QtCore.QObject.connect(self.form.rb_max_shear_stress, QtCore.SIGNAL("toggled(bool)"), self.max_shear_selected)
        QtCore.QObject.connect(self.form.rb_maxprin, QtCore.SIGNAL("toggled(bool)"), self.max_prin_selected)
        QtCore.QObject.connect(self.form.rb_minprin, QtCore.SIGNAL("toggled(bool)"), self.min_prin_selected)
        QtCore.QObject.connect(self.form.rb_temperature, QtCore.SIGNAL("toggled(bool)"), self.temperature_selected)
        QtCore.QObject.connect(self.form.user_def_eq, QtCore.SIGNAL("textchanged()"), self.user_defined_text)
        QtCore.QObject.connect(self.form.calculate, QtCore.SIGNAL("clicked()"), self.calculate)

        QtCore.QObject.connect(self.form.cb_show_displacement, QtCore.SIGNAL("clicked(bool)"), self.show_displacement)
        QtCore.QObject.connect(self.form.hsb_displacement_factor, QtCore.SIGNAL("valueChanged(int)"), self.hsb_disp_factor_changed)
        QtCore.QObject.connect(self.form.sb_displacement_factor, QtCore.SIGNAL("valueChanged(int)"), self.sb_disp_factor_changed)
        QtCore.QObject.connect(self.form.sb_displacement_factor_max, QtCore.SIGNAL("valueChanged(int)"), self.sb_disp_factor_max_changed)

        self.update()
        if self.restore_result_settings_in_dialog:
            self.restore_result_dialog()
        else:
            self.restore_initial_result_dialog()
    def __init__(self, fem_mesh_obj, fileString):
        self.form = FreeCADGui.PySideUic.loadUi(FreeCAD.getHomePath() + "Mod/Fem/Resources/ui/MeshGroupXDMFExport.ui")
        self.result_dict = {}
        self.fem_mesh_obj = fem_mesh_obj
        self.fileString = fileString

        self.convert_fem_mesh_obj_to_table()
Example #15
0
def addToJob(obj, jobname = None):
    if jobname is not None:
        jobs = GetJobs(jobname)
        if len(jobs) == 1:
            job = jobs[0]
        else:
            FreeCAD.Console.PrintError("Didn't find the job")
            return None

    else:
        jobs = GetJobs()
        if len(jobs) == 0:
            job = PathJob.CommandJob.Create()

        elif len(jobs) == 1:
            job = jobs[0]
        else:
            form = FreeCADGui.PySideUic.loadUi(FreeCAD.getHomePath() + "Mod/Path/DlgJobChooser.ui")
            mylist = [i.Name for i in jobs]
            form.cboProject.addItems(mylist)
            r = form.exec_()
            if r is False:
                return None
            else:
                print form.cboProject.currentText()
                job = [i for i in jobs if i.Name == form.cboProject.currentText()][0]

    g = job.Group
    g.append(obj)
    job.Group = g
    return job
    def __init__(self):
        self.form = FreeCADGui.PySideUic.loadUi(FreeCAD.getHomePath() + "Mod/Fem/ShowDisplacement.ui")

        # Connect Signals and Slots
        QtCore.QObject.connect(self.form.rb_none, QtCore.SIGNAL("toggled(bool)"), self.none_selected)
        QtCore.QObject.connect(
            self.form.rb_x_displacement, QtCore.SIGNAL("toggled(bool)"), self.x_displacement_selected
        )
        QtCore.QObject.connect(
            self.form.rb_y_displacement, QtCore.SIGNAL("toggled(bool)"), self.y_displacement_selected
        )
        QtCore.QObject.connect(
            self.form.rb_z_displacement, QtCore.SIGNAL("toggled(bool)"), self.z_displacement_selected
        )
        QtCore.QObject.connect(
            self.form.rb_abs_displacement, QtCore.SIGNAL("toggled(bool)"), self.abs_displacement_selected
        )
        QtCore.QObject.connect(self.form.rb_vm_stress, QtCore.SIGNAL("toggled(bool)"), self.vm_stress_selected)

        QtCore.QObject.connect(self.form.cb_show_displacement, QtCore.SIGNAL("clicked(bool)"), self.show_displacement)
        QtCore.QObject.connect(
            self.form.hsb_displacement_factor, QtCore.SIGNAL("valueChanged(int)"), self.hsb_disp_factor_changed
        )
        QtCore.QObject.connect(
            self.form.sb_displacement_factor, QtCore.SIGNAL("valueChanged(int)"), self.sb_disp_factor_changed
        )
        QtCore.QObject.connect(
            self.form.sb_displacement_factor_max, QtCore.SIGNAL("valueChanged(int)"), self.sb_disp_factor_max_changed
        )

        self.update()
        self.restore_result_dialog()
    def testLinuxCNC(self):
        # first create something to generate a path for
        box = self.doc.addObject("Part::Box", "Box")

        # Create job and setup tool library + default tool
        job = self.doc.addObject("Path::FeatureCompoundPython", "Job")
        PathScripts.PathJob.ObjectPathJob(job)
        job.Base = self.doc.Box
        PathScripts.PathLoadTool.CommandPathLoadTool.Create(job.Name, False)
        toolLib = job.Group[0]
        tool1 = Path.Tool()
        tool1.Diameter = 5.0
        tool1.Name = "Default Tool"
        tool1.CuttingEdgeHeight = 15.0
        tool1.ToolType = "EndMill"
        tool1.Material = "HighSpeedSteel"
        job.Tooltable.addTools(tool1)
        toolLib.ToolNumber = 1
        self.failUnless(True)

        self.doc.getObject("TC").ToolNumber = 2
        self.doc.recompute()

        contour = self.doc.addObject("Path::FeaturePython", "Contour")
        PathScripts.PathContour.ObjectContour(contour)
        contour.Active = True
        contour.ClearanceHeight = 20.0
        contour.StepDown = 1.0
        contour.StartDepth= 10.0
        contour.FinalDepth=0.0
        contour.SafeHeight = 12.0
        contour.OffsetExtra = 0.0
        contour.Direction = 'CW'
        contour.UseComp = True
        contour.PlungeAngle = 90.0
        PathScripts.PathUtils.addToJob(contour)
        PathScripts.PathContour.ObjectContour.setDepths(contour.Proxy, contour)
        self.doc.recompute()

        job.PostProcessor = 'linuxcnc'
        job.PostProcessorArgs = '--no-header --no-line-numbers --no-comments --no-show-editor'

        post = PathScripts.PathPost.CommandPathPost()
        (fail, gcode) = post.exportObjectsWith([job], job, False)
        self.assertFalse(fail)

        referenceFile = FreeCAD.getHomePath() + 'Mod/Path/PathTests/test_linuxcnc_00.ngc'
        with open(referenceFile, 'r') as fp:
            refGCode = fp.read()

        # Use if this test fails in order to have a real good look at the changes
        if False:
            with open('tab.tmp', 'w') as fp:
                fp.write(gcode)


        if gcode != refGCode:
            msg = ''.join(difflib.ndiff(gcode.splitlines(True), refGCode.splitlines(True)))
            self.fail("linuxcnc output doesn't match: " + msg)
    def __init__(self, solver_object):
        self.form = FreeCADGui.PySideUic.loadUi(FreeCAD.getHomePath() + "Mod/Fem/TaskPanelFemSolverCalculix.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 CalculiX 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.solver_object = solver_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.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.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()
Example #19
0
    def setup_ccx(self, ccx_binary=None, ccx_binary_sig="CalculiX"):
        from platform import system
        ccx_std_location = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Fem/Ccx").GetBool("UseStandardCcxLocation", True)
        if ccx_std_location:
            if system() == "Windows":
                ccx_path = FreeCAD.getHomePath() + "bin/ccx.exe"
                FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Fem/Ccx").SetString("ccxBinaryPath", ccx_path)
                self.ccx_binary = ccx_path
        else:
            if not ccx_binary:
                self.ccx_prefs = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Fem/Ccx")
                ccx_binary = self.ccx_prefs.GetString("ccxBinaryPath", "")
            if not ccx_binary:
                if system() == "Linux":
                    ccx_binary = "ccx"
                elif system() == "Windows":
                    ccx_binary = FreeCAD.getHomePath() + "bin/ccx.exe"
                else:
                    ccx_binary = "ccx"
            self.ccx_binary = ccx_binary

        import subprocess
        startup_info = None
        if system() == "Windows":
            # Windows workaround to avoid blinking terminal window
            startup_info = subprocess.STARTUPINFO()
            startup_info.dwFlags = subprocess.STARTF_USESHOWWINDOW
        ccx_stdout = None
        ccx_stderr = None
        try:
            p = subprocess.Popen([self.ccx_binary], stdout=subprocess.PIPE,
                                 stderr=subprocess.PIPE, shell=False,
                                 startupinfo=startup_info)
            ccx_stdout, ccx_stderr = p.communicate()
            if ccx_binary_sig in ccx_stdout:
                self.ccx_binary_present = True
        except OSError as e:
            FreeCAD.Console.PrintError(e.message)
            if e.errno == 2:
                raise Exception("FEM: CalculiX binary ccx \'{}\' not found. Please set it in FEM preferences.".format(ccx_binary))
        except Exception as e:
            FreeCAD.Console.PrintError(e.message)
            raise Exception("FEM: CalculiX ccx \'{}\' output \'{}\' doesn't contain expected phrase \'{}\'. Please use ccx 2.6 or newer".
                            format(ccx_binary, ccx_stdout, ccx_binary_sig))
    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")
        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.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.Calculix = QtCore.QProcess()
        self.Timer = QtCore.QTimer()
        self.Timer.start(300)

        self.fem_console_message = ''

        #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.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()
 def initPage(self, obj):
     self.opImagePath = "{}Mod/Path/Images/Ops/{}".format(FreeCAD.getHomePath(), 'chamfer.svg')
     self.opImage = QtGui.QPixmap(self.opImagePath)
     self.form.opImage.setPixmap(self.opImage)
     iconMiter = QtGui.QIcon(':/icons/edge-join-miter-not.svg')
     iconMiter.addFile(':/icons/edge-join-miter.svg', state=QtGui.QIcon.On)
     iconRound = QtGui.QIcon(':/icons/edge-join-round-not.svg')
     iconRound.addFile(':/icons/edge-join-round.svg', state=QtGui.QIcon.On)
     self.form.joinMiter.setIcon(iconMiter)
     self.form.joinRound.setIcon(iconRound)
    def __init__(self,obj):
        self.obj = obj
        
        self.form=FreeCADGui.PySideUic.loadUi(FreeCAD.getHomePath() + "Mod/Fem/MechanicalMaterial.ui")
        self.params = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Fem")

        QtCore.QObject.connect(self.form.pushButton_MatWeb, QtCore.SIGNAL("clicked()"), self.goMatWeb)
        QtCore.QObject.connect(self.form.comboBox_MaterialsInDir, QtCore.SIGNAL("currentIndexChanged(int)"), self.chooseMat)
        
        self.update()
Example #23
0
    def Initialize(self):

        from gearfunc import CreateCycloideGear, CreateInvoluteGear, CreateBevelGear

        self.appendToolbar("Gear", ["CreateInvoluteGear", "CreateCycloideGear", "CreateBevelGear"])
        self.appendMenu("Gear", ["CreateInvoluteGear", "CreateCycloideGear","CreateBevelGear"])
        Gui.addIconPath(FreeCAD.getHomePath()+"Mod/gear/icons/")
        Gui.addCommand('CreateInvoluteGear', CreateInvoluteGear())
        Gui.addCommand('CreateCycloideGear', CreateCycloideGear())
        Gui.addCommand('CreateBevelGear', CreateBevelGear())
Example #24
0
    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()
Example #25
0
 def setup_z88(self, z88_binary=None):
     from platform import system
     z88_std_location = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Fem/Z88").GetBool("UseStandardZ88Location")
     print(z88_std_location)
     if z88_std_location:
         if system() == "Windows":
             z88_path = FreeCAD.getHomePath() + "bin/z88r.exe"
             FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Fem/Z88").SetString("z88BinaryPath", z88_path)
             self.z88_binary = z88_path
     else:
         if not z88_binary:
             z88_binary = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Fem/Z88").GetString("z88BinaryPath", "")
         if not z88_binary:
             if system() == "Linux":
                 z88_binary = "z88r"
             elif system() == "Windows":
                 z88_binary = FreeCAD.getHomePath() + "bin/z88r.exe"
             else:
                 z88_binary = "z88r"
         self.z88_binary = z88_binary
    def __init__(self, obj):

        self.obj = obj

        # parameter widget
        self.parameterWidget = FreeCADGui.PySideUic.loadUi(
            FreeCAD.getHomePath() + "Mod/Fem/Resources/ui/ElementGeometry1D.ui"
        )
        QtCore.QObject.connect(
            self.parameterWidget.cb_crosssectiontype,
            QtCore.SIGNAL("activated(int)"),
            self.sectiontype_changed
        )
        QtCore.QObject.connect(
            self.parameterWidget.if_rec_height,
            QtCore.SIGNAL("valueChanged(Base::Quantity)"),
            self.rec_height_changed
        )
        QtCore.QObject.connect(
            self.parameterWidget.if_rec_width,
            QtCore.SIGNAL("valueChanged(Base::Quantity)"),
            self.rec_width_changed
        )
        QtCore.QObject.connect(
            self.parameterWidget.if_circ_diameter,
            QtCore.SIGNAL("valueChanged(Base::Quantity)"),
            self.circ_diameter_changed
        )
        QtCore.QObject.connect(
            self.parameterWidget.if_pipe_diameter,
            QtCore.SIGNAL("valueChanged(Base::Quantity)"),
            self.pipe_diameter_changed
        )
        QtCore.QObject.connect(
            self.parameterWidget.if_pipe_thickness,
            QtCore.SIGNAL("valueChanged(Base::Quantity)"),
            self.pipe_thickness_changed
        )

        # it is inside the class thus double _FemElementGeometry1D
        self.parameterWidget.cb_crosssectiontype.addItems(
            _FemElementGeometry1D._FemElementGeometry1D.known_beam_types
        )
        self.get_beamsection_props()
        self.updateParameterWidget()

        # geometry selection widget
        self.selectionWidget = FemSelectionWidgets.GeometryElementsSelection(
            obj.References,
            ['Edge']
        )

        # form made from param and selection widget
        self.form = [self.parameterWidget, self.selectionWidget]
Example #27
0
 def Initialize(self):
     from .commands import CreateCycloideGear, CreateInvoluteGear
     from .commands import CreateBevelGear, CreateInvoluteRack, CreateCrownGear
     self.appendToolbar("Gear", self.commands)
     self.appendMenu("Gear", self.commands)
     Gui.addIconPath(App.getHomePath()+"Mod/gear/icons/")
     Gui.addCommand('CreateInvoluteGear', CreateInvoluteGear())
     Gui.addCommand('CreateCycloideGear', CreateCycloideGear())
     Gui.addCommand('CreateBevelGear', CreateBevelGear())
     Gui.addCommand('CreateInvoluteRack', CreateInvoluteRack())
     Gui.addCommand('CreateCrownGear', CreateCrownGear())
 def __init__(self, obj):
     self._obj = obj
     self._paramWidget = FreeCADGui.PySideUic.loadUi(
         FreeCAD.getHomePath() + "Mod/Fem/Resources/ui/InitialFlowVelocity.ui")
     self._initParamWidget()
     self.form = [self._paramWidget]
     analysis = FemUtils.findAnalysisOfMember(obj)
     self._mesh = FemUtils.getSingleMember(analysis, "Fem::FemMeshObject")
     self._part = self._mesh.Part if self._mesh is not None else None
     self._partVisible = None
     self._meshVisible = None
Example #29
0
    def __init__(self, obj):
        FreeCADGui.Selection.clearSelection()
        self.sel_server = None
        self.obj = obj
        self.references = self.obj.References

        self.form = FreeCADGui.PySideUic.loadUi(FreeCAD.getHomePath() + "Mod/Fem/FemBeamSection.ui")
        QtCore.QObject.connect(self.form.pushButton_Reference, QtCore.SIGNAL("clicked()"), self.add_references)
        self.form.list_References.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
        self.form.list_References.connect(self.form.list_References, QtCore.SIGNAL("customContextMenuRequested(QPoint)"), self.references_list_right_clicked)

        self.rebuild_list_References()
Example #30
0
def get_defmake_count():
    '''
    count the def make in module ObjectsFem
    could also be done in bash with
    grep -c  "def make" src/Mod/Fem/ObjectsFem.py
    '''
    name_modfile = FreeCAD.getHomePath() + 'Mod/Fem/ObjectsFem.py'
    modfile = open(name_modfile, 'r')
    lines_modefile = modfile.readlines()
    modfile.close()
    lines_defmake = [l for l in lines_modefile if l.startswith('def make')]
    return len(lines_defmake)
Example #31
0
def pathDefaultToolsPath(sub=None):
    if sub:
        return os.path.join(FreeCAD.getHomePath(), "Mod/Path/Tools/", sub)
    return os.path.join(FreeCAD.getHomePath(), "Mod/Path/Tools/")
Example #32
0
#***************************************************************************/

import FreeCAD, Part, os, FreeCADGui, __builtin__
from FreeCAD import Base
from math import *
import ImportGui

##########################################################
# Script version dated 19-Jan-2012                       #
##########################################################
#Configuration parameters below - use standard slashes / #
##########################################################

## path to table file (simple comma separated values)

model_tab_filename = FreeCAD.getHomePath(
) + "Mod/Idf/Idflibs/footprints_models.csv"

## path to directory containing step models

step_path = FreeCAD.getHomePath() + "Mod/Idf/Idflibs/"

ignore_hole_size = 0.5  # size in MM to prevent huge number of drilled holes
EmpDisplayMode = 2  # 0='Flat Lines', 1='Shaded', 2='Wireframe', 3='Points'; recommended 2 or 0

IDF_sort = 0  # 0-sort per refdes [1 - part number (not preffered)/refdes] 2-sort per footprint/refdes

IDF_diag = 0  # 0/1=disabled/enabled output (footprint.lst/missing_models.lst)
IDF_diag_path = "/tmp"  # path for output of footprint.lst and missing_models.lst

########################################################################################
#              End config section do not touch code below                              #
Example #33
0
def InitApplications():
    # Checking on FreeCAD module path ++++++++++++++++++++++++++++++++++++++++++
    ModDir = FreeCAD.getHomePath() + 'Mod'
    ModDir = os.path.realpath(ModDir)
    ExtDir = FreeCAD.getHomePath() + 'Ext'
    ExtDir = os.path.realpath(ExtDir)
    BinDir = FreeCAD.getHomePath() + 'bin'
    BinDir = os.path.realpath(BinDir)
    libpaths = []
    LibDir = FreeCAD.getHomePath() + 'lib'
    LibDir = os.path.realpath(LibDir)
    if os.path.exists(LibDir):
        libpaths.append(LibDir)
    Lib64Dir = FreeCAD.getHomePath() + 'lib64'
    Lib64Dir = os.path.realpath(Lib64Dir)
    if os.path.exists(Lib64Dir):
        libpaths.append(Lib64Dir)
    if sys.version_info[0] == 3:
        LibPyDir = FreeCAD.getHomePath() + 'lib-py3'
    else:
        LibPyDir = FreeCAD.getHomePath() + 'lib-py2'
    LibPyDir = os.path.realpath(LibPyDir)
    if (os.path.exists(LibPyDir)):
        libpaths.append(LibPyDir)
    AddPath = FreeCAD.ConfigGet("AdditionalModulePaths").split(";")
    HomeMod = FreeCAD.getUserAppDataDir() + "Mod"
    HomeMod = os.path.realpath(HomeMod)
    MacroDir = FreeCAD.ParamGet(
        "User parameter:BaseApp/Preferences/Macro").GetString("MacroPath")
    MacroMod = os.path.realpath(MacroDir + "/Mod")
    SystemWideMacroDir = FreeCAD.getHomePath() + 'Macro'
    SystemWideMacroDir = os.path.realpath(SystemWideMacroDir)

    #print FreeCAD.getHomePath()
    if os.path.isdir(FreeCAD.getHomePath() + 'src\\Tools'):
        sys.path.append(FreeCAD.getHomePath() + 'src\\Tools')

    # Searching for module dirs +++++++++++++++++++++++++++++++++++++++++++++++++++
    # Use dict to handle duplicated module names
    ModDict = {}
    if os.path.isdir(ModDir):
        ModDirs = os.listdir(ModDir)
        for i in ModDirs:
            ModDict[i.lower()] = os.path.join(ModDir, i)
    else:
        Wrn("No modules found in " + ModDir + "\n")
    # Search for additional modules in the home directory
    if os.path.isdir(HomeMod):
        HomeMods = os.listdir(HomeMod)
        for i in HomeMods:
            ModDict[i.lower()] = os.path.join(HomeMod, i)
    # Search for additional modules in the macro directory
    if os.path.isdir(MacroMod):
        MacroMods = os.listdir(MacroMod)
        for i in MacroMods:
            key = i.lower()
            if key not in ModDict: ModDict[key] = os.path.join(MacroMod, i)
    # Search for additional modules in command line
    for i in AddPath:
        if os.path.isdir(i): ModDict[i] = i
    #AddModPaths = App.ParamGet("System parameter:AdditionalModulePaths")
    #Err( AddModPaths)
    # add also this path so that all modules search for libraries
    # they depend on first here
    PathExtension = []
    PathExtension.append(BinDir)

    # prepend all module paths to Python search path
    Log('Init:   Searching for modules...\n')

    # to have all the module-paths available in FreeCADGuiInit.py:
    FreeCAD.__ModDirs__ = list(ModDict.values())

    # this allows importing with:
    # from FreeCAD.Module import package
    FreeCAD.__path__ = [ModDir] + libpaths + [HomeMod]

    # also add these directories to the sys.path to
    # not change the old behaviour. once we have moved to
    # proper python modules this can eventuelly be removed.
    sys.path = [ModDir] + libpaths + [ExtDir] + sys.path

    for Dir in ModDict.values():
        if ((Dir != '') & (Dir != 'CVS') & (Dir != '__init__.py')):
            sys.path.insert(0, Dir)
            PathExtension.append(Dir)
            InstallFile = os.path.join(Dir, "Init.py")
            if (os.path.exists(InstallFile)):
                try:
                    # XXX: This looks scary securitywise...

                    with open(InstallFile) as f:
                        exec(f.read())
                except Exception as inst:
                    Log('Init:      Initializing ' + Dir + '... failed\n')
                    Log('-' * 100 + '\n')
                    Log(traceback.format_exc())
                    Log('-' * 100 + '\n')
                    Err('During initialization the error "' + str(inst) +
                        '" occurred in ' + InstallFile + '\n')
                    Err('Please look into the log file for further information\n'
                        )
                else:
                    Log('Init:      Initializing ' + Dir + '... done\n')
            else:
                Log('Init:      Initializing ' + Dir +
                    '(Init.py not found)... ignore\n')

    extension_modules = []

    try:
        import pkgutil
        import importlib
        import freecad
        for _, freecad_module_name, freecad_module_ispkg in pkgutil.iter_modules(
                freecad.__path__, "freecad."):
            if freecad_module_ispkg:
                Log('Init: Initializing ' + freecad_module_name + '\n')
                try:
                    freecad_module = importlib.import_module(
                        freecad_module_name)
                    extension_modules += [freecad_module_name]
                    if any(module_name == 'init' for _, module_name, ispkg in
                           pkgutil.iter_modules(freecad_module.__path__)):
                        importlib.import_module(freecad_module_name + '.init')
                        Log('Init: Initializing ' + freecad_module_name +
                            '... done\n')
                    else:
                        Log('Init: No init module found in ' +
                            freecad_module_name + ', skipping\n')
                except Exception as inst:
                    Err('During initialization the error "' + str(inst) +
                        '" occurred in ' + freecad_module_name + '\n')
                    Err('-' * 80 + '\n')
                    Err(traceback.format_exc())
                    Err('-' * 80 + '\n')
                    Log('Init:      Initializing ' + freecad_module_name +
                        '... failed\n')
                    Log('-' * 80 + '\n')
                    Log(traceback.format_exc())
                    Log('-' * 80 + '\n')
    except ImportError as inst:
        Err('During initialization the error "' + str(inst) + '" occurred\n')

    Log("Using " + ModDir + " as module path!\n")
    # In certain cases the PathExtension list can contain invalid strings. We concatenate them to a single string
    # but check that the output is a valid string
    PathEnvironment = PathExtension.pop(0) + os.pathsep
    for path in PathExtension:
        try:
            PathEnvironment += path + os.pathsep
        except UnicodeDecodeError:
            Wrn('Filter invalid module path: u{}\n'.format(repr(path)))

    # new paths must be prepended to avoid to load a wrong version of a library
    try:
        os.environ["PATH"] = PathEnvironment + os.environ["PATH"]
    except UnicodeDecodeError:
        # See #0002238. FIXME: check again once ported to Python 3.x
        Log('UnicodeDecodeError was raised when concatenating unicode string with PATH. Try to remove non-ascii paths...\n'
            )
        path = os.environ["PATH"].split(os.pathsep)
        cleanpath = []
        for i in path:
            if test_ascii(i):
                cleanpath.append(i)
        os.environ["PATH"] = PathEnvironment + os.pathsep.join(cleanpath)
        Log('done\n')
    except UnicodeEncodeError:
        Log('UnicodeEncodeError was raised when concatenating unicode string with PATH. Try to replace non-ascii chars...\n'
            )
        os.environ["PATH"] = PathEnvironment.encode(
            errors='replace') + os.environ["PATH"]
        Log('done\n')
    except KeyError:
        os.environ["PATH"] = PathEnvironment
    path = os.environ["PATH"].split(os.pathsep)
    Log("System path after init:\n")
    for i in path:
        Log("   " + i + "\n")
    # add MacroDir to path (RFE #0000504)
    sys.path.append(MacroDir)
    # add SystemWideMacroDir to path
    sys.path.append(SystemWideMacroDir)
    # add special path for MacOSX (bug #0000307)
    import platform
    if len(platform.mac_ver()[0]) > 0:
        sys.path.append(
            os.path.expanduser('~/Library/Application Support/FreeCAD/Mod'))
Example #34
0
 def setUp(self):
     self.clone = None
     self.doc = FreeCAD.open(FreeCAD.getHomePath() +
                             'Mod/Path/PathTests/test_holes00.fcstd')
     self.job = PathJob.Create('Job', [self.doc.Body])
Example #35
0
    def setup_ccx(self, ccx_binary=None, ccx_binary_sig="CalculiX"):
        """Set Calculix binary path and validate its execution.

        Parameters
        ----------
        ccx_binary : str, optional
            It defaults to `None`. The path to the `ccx` binary. If it is `None`,
            the path is guessed.
        ccx_binary_sig : str, optional
            Defaults to 'CalculiX'. Expected output from `ccx` when run empty.

        """
        error_title = "No or wrong CalculiX binary ccx"
        error_message = ""
        from platform import system
        ccx_std_location = FreeCAD.ParamGet(
            "User parameter:BaseApp/Preferences/Mod/Fem/Ccx"
        ).GetBool("UseStandardCcxLocation", True)
        if ccx_std_location:
            if system() == "Windows":
                ccx_path = FreeCAD.getHomePath() + "bin/ccx.exe"
                FreeCAD.ParamGet(
                    "User parameter:BaseApp/Preferences/Mod/Fem/Ccx"
                ).SetString("ccxBinaryPath", ccx_path)
                self.ccx_binary = ccx_path
            elif system() in ("Linux", "Darwin"):
                p1 = subprocess.Popen(["which", "ccx"], stdout=subprocess.PIPE)
                if p1.wait() == 0:
                    if sys.version_info.major >= 3:
                        ccx_path = p1.stdout.read().decode("utf8").split("\n")[0]
                    else:
                        ccx_path = p1.stdout.read().split("\n")[0]
                elif p1.wait() == 1:
                    error_message = (
                        "FEM: CalculiX binary ccx not found in "
                        "standard system binary path. "
                        "Please install ccx or set path to binary "
                        "in FEM preferences tab CalculiX.\n"
                    )
                    if FreeCAD.GuiUp:
                        QtGui.QMessageBox.critical(None, error_title, error_message)
                    raise Exception(error_message)
                self.ccx_binary = ccx_path
        else:
            if not ccx_binary:
                self.ccx_prefs = FreeCAD.ParamGet(
                    "User parameter:BaseApp/Preferences/Mod/Fem/Ccx"
                )
                ccx_binary = self.ccx_prefs.GetString("ccxBinaryPath", "")
                if not ccx_binary:
                    FreeCAD.ParamGet(
                        "User parameter:BaseApp/Preferences/Mod/Fem/Ccx"
                    ).SetBool("UseStandardCcxLocation", True)
                    error_message = (
                        "FEM: CalculiX binary ccx path not set at all. "
                        "The use of standard path was activated in "
                        "FEM preferences tab CalculiX. Please try again!\n"
                    )
                    if FreeCAD.GuiUp:
                        QtGui.QMessageBox.critical(None, error_title, error_message)
                    FreeCAD.Console.PrintError(error_message)
            self.ccx_binary = ccx_binary

        startup_info = None
        if system() == "Windows":
            # Windows workaround to avoid blinking terminal window
            startup_info = subprocess.STARTUPINFO()
            startup_info.dwFlags = subprocess.STARTF_USESHOWWINDOW
        ccx_stdout = None
        ccx_stderr = None
        try:
            p = subprocess.Popen(
                [self.ccx_binary],
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                shell=False,
                startupinfo=startup_info
            )
            ccx_stdout, ccx_stderr = p.communicate()
            if ccx_binary_sig in str(ccx_stdout):
                self.ccx_binary_present = True
            else:
                error_message = "FEM: wrong ccx binary\n"
                if FreeCAD.GuiUp:
                    QtGui.QMessageBox.critical(None, error_title, error_message)
                FreeCAD.Console.PrintError(error_message)
                # TODO: I'm still able to break it.
                # If user doesn't give a file but a path without a file or
                # a file which is not a binary no exception at all is raised.
        except OSError as e:
            FreeCAD.Console.PrintError("{}\n".format(e))
            if e.errno == 2:
                error_message = (
                    "FEM: CalculiX binary ccx \'{}\' not found. "
                    "Please set the CalculiX binary ccx path in "
                    "FEM preferences tab CalculiX.\n"
                    .format(ccx_binary)
                )
                if FreeCAD.GuiUp:
                    QtGui.QMessageBox.critical(None, error_title, error_message)
                FreeCAD.Console.PrintError(error_message)

        except Exception as e:
            FreeCAD.Console.PrintError("{}\n".format(e))
            error_message = (
                "FEM: CalculiX ccx \'{}\' output \'{}\' doesn't "
                "contain expected phrase \'{}\'. "
                "There are some problems when running the ccx binary. "
                "Check if ccx runs standalone without FreeCAD.\n"
                .format(ccx_binary, ccx_stdout, ccx_binary_sig)
            )
            if FreeCAD.GuiUp:
                QtGui.QMessageBox.critical(None, error_title, error_message)
            FreeCAD.Console.PrintError(error_message)
    def __init__(self, obj):

        self.obj = obj

        # parameter widget
        self.parameterWidget = FreeCADGui.PySideUic.loadUi(
            FreeCAD.getHomePath() + "Mod/Fem/Resources/ui/ElementFluid1D.ui")
        QtCore.QObject.connect(self.parameterWidget.cb_section_type,
                               QtCore.SIGNAL("activated(int)"),
                               self.sectiontype_changed)
        QtCore.QObject.connect(self.parameterWidget.cb_liquid_section_type,
                               QtCore.SIGNAL("activated(int)"),
                               self.liquidsectiontype_changed)
        QtCore.QObject.connect(self.parameterWidget.if_manning_area,
                               QtCore.SIGNAL("valueChanged(Base::Quantity)"),
                               self.manning_area_changed)
        QtCore.QObject.connect(self.parameterWidget.if_manning_radius,
                               QtCore.SIGNAL("valueChanged(Base::Quantity)"),
                               self.manning_radius_changed)
        QtCore.QObject.connect(self.parameterWidget.sb_manning_coefficient,
                               QtCore.SIGNAL("valueChanged(double)"),
                               self.manning_coefficient_changed)
        QtCore.QObject.connect(self.parameterWidget.if_enlarge_area1,
                               QtCore.SIGNAL("valueChanged(Base::Quantity)"),
                               self.enlarge_area1_changed)
        QtCore.QObject.connect(self.parameterWidget.if_enlarge_area2,
                               QtCore.SIGNAL("valueChanged(Base::Quantity)"),
                               self.enlarge_area2_changed)
        QtCore.QObject.connect(self.parameterWidget.if_contract_area1,
                               QtCore.SIGNAL("valueChanged(Base::Quantity)"),
                               self.contract_area1_changed)
        QtCore.QObject.connect(self.parameterWidget.if_contract_area2,
                               QtCore.SIGNAL("valueChanged(Base::Quantity)"),
                               self.contract_area2_changed)
        QtCore.QObject.connect(self.parameterWidget.if_inletpressure,
                               QtCore.SIGNAL("valueChanged(Base::Quantity)"),
                               self.inlet_pressure_changed)
        QtCore.QObject.connect(self.parameterWidget.if_outletpressure,
                               QtCore.SIGNAL("valueChanged(Base::Quantity)"),
                               self.outlet_pressure_changed)
        QtCore.QObject.connect(self.parameterWidget.if_inletflowrate,
                               QtCore.SIGNAL("valueChanged(Base::Quantity)"),
                               self.inlet_flowrate_changed)
        QtCore.QObject.connect(self.parameterWidget.if_outletflowrate,
                               QtCore.SIGNAL("valueChanged(Base::Quantity)"),
                               self.outlet_flowrate_changed)
        QtCore.QObject.connect(self.parameterWidget.gb_inletpressure,
                               QtCore.SIGNAL("clicked(bool)"),
                               self.inlet_pressure_active)
        QtCore.QObject.connect(self.parameterWidget.gb_outletpressure,
                               QtCore.SIGNAL("clicked(bool)"),
                               self.outlet_pressure_active)
        QtCore.QObject.connect(self.parameterWidget.gb_inletflowrate,
                               QtCore.SIGNAL("clicked(bool)"),
                               self.inlet_flowrate_active)
        QtCore.QObject.connect(self.parameterWidget.gb_outletflowrate,
                               QtCore.SIGNAL("clicked(bool)"),
                               self.outlet_flowrate_active)
        QtCore.QObject.connect(self.parameterWidget.if_entrance_pipe_area,
                               QtCore.SIGNAL("valueChanged(Base::Quantity)"),
                               self.entrance_pipe_area_changed)
        QtCore.QObject.connect(self.parameterWidget.if_entrance_area,
                               QtCore.SIGNAL("valueChanged(Base::Quantity)"),
                               self.entrance_area_changed)
        QtCore.QObject.connect(self.parameterWidget.if_diaphragm_pipe_area,
                               QtCore.SIGNAL("valueChanged(Base::Quantity)"),
                               self.diaphragm_pipe_area_changed)
        QtCore.QObject.connect(self.parameterWidget.if_diaphragm_area,
                               QtCore.SIGNAL("valueChanged(Base::Quantity)"),
                               self.diaphragm_area_changed)
        QtCore.QObject.connect(self.parameterWidget.if_bend_pipe_area,
                               QtCore.SIGNAL("valueChanged(Base::Quantity)"),
                               self.bend_pipe_area_changed)
        QtCore.QObject.connect(self.parameterWidget.sb_bradius_pdiameter,
                               QtCore.SIGNAL("valueChanged(double)"),
                               self.bradius_pdiameter_changed)
        QtCore.QObject.connect(self.parameterWidget.sb_bend_angle,
                               QtCore.SIGNAL("valueChanged(double)"),
                               self.bend_angle_changed)
        QtCore.QObject.connect(self.parameterWidget.sb_bend_loss_coefficient,
                               QtCore.SIGNAL("valueChanged(double)"),
                               self.bend_loss_coefficient_changed)
        QtCore.QObject.connect(self.parameterWidget.if_gatevalve_pipe_area,
                               QtCore.SIGNAL("valueChanged(Base::Quantity)"),
                               self.gatevalve_pipe_area_changed)
        QtCore.QObject.connect(self.parameterWidget.sb_gatevalve_closing_coeff,
                               QtCore.SIGNAL("valueChanged(double)"),
                               self.gatevalve_closing_coeff_changed)
        QtCore.QObject.connect(self.parameterWidget.if_colebrooke_pipe_area,
                               QtCore.SIGNAL("valueChanged(Base::Quantity)"),
                               self.colebrooke_pipe_area_changed)
        QtCore.QObject.connect(self.parameterWidget.if_colebrooke_radius,
                               QtCore.SIGNAL("valueChanged(Base::Quantity)"),
                               self.colebrooke_radius_changed)
        QtCore.QObject.connect(
            self.parameterWidget.if_colebrooke_grain_diameter,
            QtCore.SIGNAL("valueChanged(Base::Quantity)"),
            self.colebrooke_grain_diameter_changed)
        QtCore.QObject.connect(self.parameterWidget.sb_colebrooke_form_factor,
                               QtCore.SIGNAL("valueChanged(double)"),
                               self.colebrooke_form_factor_changed)
        QtCore.QObject.connect(self.parameterWidget.tw_pump_characteristics,
                               QtCore.SIGNAL("cellChanged(int, int)"),
                               self.pump_characteristics_changed)
        self.parameterWidget.cb_section_type.addItems(
            _FemElementFluid1D._FemElementFluid1D.known_fluid_types)
        self.parameterWidget.cb_liquid_section_type.addItems(
            _FemElementFluid1D._FemElementFluid1D.known_liquid_types)
        self.parameterWidget.cb_gas_section_type.addItems(
            _FemElementFluid1D._FemElementFluid1D.known_gas_types)
        self.parameterWidget.cb_channel_section_type.addItems(
            _FemElementFluid1D._FemElementFluid1D.known_channel_types)
        self.get_fluidsection_props()
        self.updateParameterWidget()

        # geometry selection widget
        self.selectionWidget = FemSelectionWidgets.GeometryElementsSelection(
            obj.References, ['Edge'])

        # form made from param and selection widget
        self.form = [self.parameterWidget, self.selectionWidget]
    def __init__(self, obj):
        FreeCADGui.Selection.clearSelection()
        self.sel_server = None
        self.obj = obj
        self.obj_notvisible = []

        self.form = FreeCADGui.PySideUic.loadUi(
            FreeCAD.getHomePath() +
            "Mod/Fem/PyGui/TaskPanelFemElementFluid1D.ui")
        QtCore.QObject.connect(self.form.btn_add, QtCore.SIGNAL("clicked()"),
                               self.add_references)
        QtCore.QObject.connect(self.form.btn_remove,
                               QtCore.SIGNAL("clicked()"),
                               self.remove_reference)
        QtCore.QObject.connect(self.form.cb_section_type,
                               QtCore.SIGNAL("activated(int)"),
                               self.sectiontype_changed)
        QtCore.QObject.connect(self.form.cb_liquid_section_type,
                               QtCore.SIGNAL("activated(int)"),
                               self.liquidsectiontype_changed)
        QtCore.QObject.connect(self.form.if_manning_area,
                               QtCore.SIGNAL("valueChanged(Base::Quantity)"),
                               self.manning_area_changed)
        QtCore.QObject.connect(self.form.if_manning_radius,
                               QtCore.SIGNAL("valueChanged(Base::Quantity)"),
                               self.manning_radius_changed)
        QtCore.QObject.connect(self.form.sb_manning_coefficient,
                               QtCore.SIGNAL("valueChanged(double)"),
                               self.manning_coefficient_changed)
        QtCore.QObject.connect(self.form.if_enlarge_area1,
                               QtCore.SIGNAL("valueChanged(Base::Quantity)"),
                               self.enlarge_area1_changed)
        QtCore.QObject.connect(self.form.if_enlarge_area2,
                               QtCore.SIGNAL("valueChanged(Base::Quantity)"),
                               self.enlarge_area2_changed)
        QtCore.QObject.connect(self.form.if_contract_area1,
                               QtCore.SIGNAL("valueChanged(Base::Quantity)"),
                               self.contract_area1_changed)
        QtCore.QObject.connect(self.form.if_contract_area2,
                               QtCore.SIGNAL("valueChanged(Base::Quantity)"),
                               self.contract_area2_changed)
        QtCore.QObject.connect(self.form.if_inletpressure,
                               QtCore.SIGNAL("valueChanged(Base::Quantity)"),
                               self.inlet_pressure_changed)
        QtCore.QObject.connect(self.form.if_outletpressure,
                               QtCore.SIGNAL("valueChanged(Base::Quantity)"),
                               self.outlet_pressure_changed)
        QtCore.QObject.connect(self.form.if_inletflowrate,
                               QtCore.SIGNAL("valueChanged(Base::Quantity)"),
                               self.inlet_flowrate_changed)
        QtCore.QObject.connect(self.form.if_outletflowrate,
                               QtCore.SIGNAL("valueChanged(Base::Quantity)"),
                               self.outlet_flowrate_changed)
        QtCore.QObject.connect(self.form.gb_inletpressure,
                               QtCore.SIGNAL("clicked(bool)"),
                               self.inlet_pressure_active)
        QtCore.QObject.connect(self.form.gb_outletpressure,
                               QtCore.SIGNAL("clicked(bool)"),
                               self.outlet_pressure_active)
        QtCore.QObject.connect(self.form.gb_inletflowrate,
                               QtCore.SIGNAL("clicked(bool)"),
                               self.inlet_flowrate_active)
        QtCore.QObject.connect(self.form.gb_outletflowrate,
                               QtCore.SIGNAL("clicked(bool)"),
                               self.outlet_flowrate_active)
        QtCore.QObject.connect(self.form.if_entrance_pipe_area,
                               QtCore.SIGNAL("valueChanged(Base::Quantity)"),
                               self.entrance_pipe_area_changed)
        QtCore.QObject.connect(self.form.if_entrance_area,
                               QtCore.SIGNAL("valueChanged(Base::Quantity)"),
                               self.entrance_area_changed)
        QtCore.QObject.connect(self.form.if_diaphragm_pipe_area,
                               QtCore.SIGNAL("valueChanged(Base::Quantity)"),
                               self.diaphragm_pipe_area_changed)
        QtCore.QObject.connect(self.form.if_diaphragm_area,
                               QtCore.SIGNAL("valueChanged(Base::Quantity)"),
                               self.diaphragm_area_changed)
        QtCore.QObject.connect(self.form.if_bend_pipe_area,
                               QtCore.SIGNAL("valueChanged(Base::Quantity)"),
                               self.bend_pipe_area_changed)
        QtCore.QObject.connect(self.form.sb_bradius_pdiameter,
                               QtCore.SIGNAL("valueChanged(double)"),
                               self.bradius_pdiameter_changed)
        QtCore.QObject.connect(self.form.sb_bend_angle,
                               QtCore.SIGNAL("valueChanged(double)"),
                               self.bend_angle_changed)
        QtCore.QObject.connect(self.form.sb_bend_loss_coefficient,
                               QtCore.SIGNAL("valueChanged(double)"),
                               self.bend_loss_coefficient_changed)
        QtCore.QObject.connect(self.form.if_gatevalve_pipe_area,
                               QtCore.SIGNAL("valueChanged(Base::Quantity)"),
                               self.gatevalve_pipe_area_changed)
        QtCore.QObject.connect(self.form.sb_gatevalve_closing_coeff,
                               QtCore.SIGNAL("valueChanged(double)"),
                               self.gatevalve_closing_coeff_changed)
        QtCore.QObject.connect(self.form.if_colebrooke_pipe_area,
                               QtCore.SIGNAL("valueChanged(Base::Quantity)"),
                               self.colebrooke_pipe_area_changed)
        QtCore.QObject.connect(self.form.if_colebrooke_radius,
                               QtCore.SIGNAL("valueChanged(Base::Quantity)"),
                               self.colebrooke_radius_changed)
        QtCore.QObject.connect(self.form.if_colebrooke_grain_diameter,
                               QtCore.SIGNAL("valueChanged(Base::Quantity)"),
                               self.colebrooke_grain_diameter_changed)
        QtCore.QObject.connect(self.form.sb_colebrooke_form_factor,
                               QtCore.SIGNAL("valueChanged(double)"),
                               self.colebrooke_form_factor_changed)
        QtCore.QObject.connect(self.form.tw_pump_characteristics,
                               QtCore.SIGNAL("cellChanged(int, int)"),
                               self.pump_characteristics_changed)
        self.form.list_References.itemSelectionChanged.connect(
            self.select_clicked_reference_shape)
        self.form.list_References.setContextMenuPolicy(
            QtCore.Qt.CustomContextMenu)
        self.form.list_References.connect(
            self.form.list_References,
            QtCore.SIGNAL("customContextMenuRequested(QPoint)"),
            self.references_list_right_clicked)
        self.form.cb_section_type.addItems(
            PyObjects._FemElementFluid1D._FemElementFluid1D.known_fluid_types)
        self.form.cb_liquid_section_type.addItems(
            PyObjects._FemElementFluid1D._FemElementFluid1D.known_liquid_types)
        self.form.cb_gas_section_type.addItems(
            PyObjects._FemElementFluid1D._FemElementFluid1D.known_gas_types)
        self.form.cb_channel_section_type.addItems(
            PyObjects._FemElementFluid1D._FemElementFluid1D.known_channel_types
        )

        self.get_fluidsection_props()
        self.update()
Example #38
0
 def setUp(self):
     self.test_dir = join(FreeCAD.getHomePath(), "Mod", "OpenSCAD", "OpenSCADTest", "data")
Example #39
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
        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()
Example #40
0
    def __init__(self, obj):
        self.result_obj = obj
        self.mesh_obj = self.result_obj.Mesh
        # task panel should be started by use of setEdit of view provider
        # in view provider checks: Mesh, active analysis and if Mesh and result are in active analysis

        self.form = FreeCADGui.PySideUic.loadUi(
            FreeCAD.getHomePath() + "Mod/Fem/Resources/ui/ResultShow.ui")
        self.fem_prefs = FreeCAD.ParamGet(
            "User parameter:BaseApp/Preferences/Mod/Fem/General")
        self.restore_result_settings_in_dialog = self.fem_prefs.GetBool(
            "RestoreResultDialog", True)

        # Connect Signals and Slots
        # result type radio buttons
        QtCore.QObject.connect(self.form.rb_none,
                               QtCore.SIGNAL("toggled(bool)"),
                               self.none_selected)
        QtCore.QObject.connect(self.form.rb_abs_displacement,
                               QtCore.SIGNAL("toggled(bool)"),
                               self.abs_displacement_selected)
        QtCore.QObject.connect(self.form.rb_x_displacement,
                               QtCore.SIGNAL("toggled(bool)"),
                               self.x_displacement_selected)
        QtCore.QObject.connect(self.form.rb_y_displacement,
                               QtCore.SIGNAL("toggled(bool)"),
                               self.y_displacement_selected)
        QtCore.QObject.connect(self.form.rb_z_displacement,
                               QtCore.SIGNAL("toggled(bool)"),
                               self.z_displacement_selected)
        QtCore.QObject.connect(self.form.rb_temperature,
                               QtCore.SIGNAL("toggled(bool)"),
                               self.temperature_selected)
        QtCore.QObject.connect(self.form.rb_vm_stress,
                               QtCore.SIGNAL("toggled(bool)"),
                               self.vm_stress_selected)
        QtCore.QObject.connect(self.form.rb_maxprin,
                               QtCore.SIGNAL("toggled(bool)"),
                               self.max_prin_selected)
        QtCore.QObject.connect(self.form.rb_minprin,
                               QtCore.SIGNAL("toggled(bool)"),
                               self.min_prin_selected)
        QtCore.QObject.connect(self.form.rb_max_shear_stress,
                               QtCore.SIGNAL("toggled(bool)"),
                               self.max_shear_selected)
        QtCore.QObject.connect(self.form.rb_massflowrate,
                               QtCore.SIGNAL("toggled(bool)"),
                               self.massflowrate_selected)
        QtCore.QObject.connect(self.form.rb_networkpressure,
                               QtCore.SIGNAL("toggled(bool)"),
                               self.networkpressure_selected)
        QtCore.QObject.connect(self.form.rb_peeq,
                               QtCore.SIGNAL("toggled(bool)"),
                               self.peeq_selected)

        # displacement
        QtCore.QObject.connect(self.form.cb_show_displacement,
                               QtCore.SIGNAL("clicked(bool)"),
                               self.show_displacement)
        QtCore.QObject.connect(self.form.hsb_displacement_factor,
                               QtCore.SIGNAL("valueChanged(int)"),
                               self.hsb_disp_factor_changed)
        QtCore.QObject.connect(self.form.sb_displacement_factor,
                               QtCore.SIGNAL("valueChanged(int)"),
                               self.sb_disp_factor_changed)
        QtCore.QObject.connect(self.form.sb_displacement_factor_max,
                               QtCore.SIGNAL("valueChanged(int)"),
                               self.sb_disp_factor_max_changed)

        # user defined equation
        QtCore.QObject.connect(self.form.user_def_eq,
                               QtCore.SIGNAL("textchanged()"),
                               self.user_defined_text)
        QtCore.QObject.connect(self.form.calculate, QtCore.SIGNAL("clicked()"),
                               self.calculate)

        self.update()
        if self.restore_result_settings_in_dialog:
            self.restore_result_dialog()
        else:
            self.restore_initial_result_dialog()
Example #41
0
# *                    Please do not change anything below!                  *
# *                                                                          *
# *                                                                          *
# ****************************************************************************

#  default pcb color
#       PCB_COLOR = (R/255., G/255., B/255.)
#            (84./255., 170./255., 0./255.) => (0.33, 0.67, 0.0)
#            PCB_COLOR = (0.33, 0.67, 0.0)
PCB_COLOR = getFromSettings_Color('boardColor', 1437204735)

#  partPaths = [path_1, path_2, etc]
#       for example: /home/mariusz/.FreeCAD/Mod/EaglePCB_2_FreeCAD/parts/
#       used in: PCBpartManaging.partExist()
partPaths = [
    os.path.join(FreeCAD.getHomePath(), "Mod/PCB/parts"),
    os.path.join(__currentPath__, "parts")
]

#  default software list
# defSoftware = ['Eagle', 'KiCad', 'FidoCadJ', 'FreePCB', 'Razen', 'gEDA', 'IDF', 'HyperLynx']  # do not change order!
defSoftware = [
    'Eagle', 'KiCad', 'FreePCB', 'gEDA', 'IDF', 'HyperLynx', 'LibrePCB'
]  # do not change order!

#########################
exportData = {
    "eagle": {
        'name': 'Eagle',
        'exportLayers': ['dim', 'hol', 'anno', 'glue'],
        'exportClass': 'eagle()',
Example #42
0
def get_fem_test_home_dir():
    return join(FreeCAD.getHomePath(), "Mod", "Fem", "femtest", "data")
    def __init__(self, obj):
        FreeCADGui.Selection.clearSelection()
        self.sel_server = None
        self.obj = obj
        self.material = self.obj.Material
        self.references = []
        if self.obj.References:
            self.tuplereferences = self.obj.References
            self.get_references()
        self.references_shape_type = None

        self.form = FreeCADGui.PySideUic.loadUi(
            FreeCAD.getHomePath() + "Mod/Fem/TaskPanelMechanicalMaterial.ui")
        QtCore.QObject.connect(self.form.pushButton_MatWeb,
                               QtCore.SIGNAL("clicked()"), self.goMatWeb)
        QtCore.QObject.connect(self.form.cb_materials,
                               QtCore.SIGNAL("activated(int)"),
                               self.choose_material)
        QtCore.QObject.connect(self.form.input_fd_young_modulus,
                               QtCore.SIGNAL("valueChanged(double)"),
                               self.ym_changed)
        QtCore.QObject.connect(self.form.spinBox_poisson_ratio,
                               QtCore.SIGNAL("valueChanged(double)"),
                               self.pr_changed)
        QtCore.QObject.connect(self.form.input_fd_density,
                               QtCore.SIGNAL("valueChanged(double)"),
                               self.density_changed)
        QtCore.QObject.connect(self.form.pushButton_Reference,
                               QtCore.SIGNAL("clicked()"), self.add_references)
        QtCore.QObject.connect(self.form.input_fd_thermal_conductivity,
                               QtCore.SIGNAL("valueChanged(double)"),
                               self.tc_changed)
        QtCore.QObject.connect(self.form.input_fd_expansion_coefficient,
                               QtCore.SIGNAL("valueChanged(double)"),
                               self.tec_changed)
        QtCore.QObject.connect(self.form.input_fd_specific_heat,
                               QtCore.SIGNAL("valueChanged(double)"),
                               self.sh_changed)

        self.form.list_References.setContextMenuPolicy(
            QtCore.Qt.CustomContextMenu)
        self.form.list_References.connect(
            self.form.list_References,
            QtCore.SIGNAL("customContextMenuRequested(QPoint)"),
            self.references_list_right_clicked)

        self.import_materials()
        previous_mat_path = self.get_material_path(self.material)
        if not previous_mat_path:
            material_name = self.get_material_name(self.material)
            if material_name != 'None':
                FreeCAD.Console.PrintMessage(
                    "Previously used material cannot be found in material directories. Using transient material.\n"
                )
                self.add_transient_material(self.material)
                index = self.form.cb_materials.findData(material_name)
            else:
                if not self.material:
                    index = self.form.cb_materials.findText(material_name)
                else:
                    FreeCAD.Console.PrintMessage(
                        "None material was previously used. Reload values.\n")
                    self.add_transient_material(self.material)
                    index = self.form.cb_materials.findData(material_name)
            self.choose_material(index)
        else:
            index = self.form.cb_materials.findData(previous_mat_path)
            self.choose_material(index)
        self.has_equal_references_shape_types()
        self.rebuild_list_References()
Example #44
0
def pathScriptsSourcePath():
    return os.path.join(FreeCAD.getHomePath(), "Mod/Path/PathScripts/")
Example #45
0
def searchPathsTool(sub):
    paths = []
    paths.append(
        os.path.join(FreeCAD.getHomePath(), 'Mod', 'Path', 'Tools', sub))
    return paths
Example #46
0
#The classes in this module provide funcionality for
#a `DocumentObjectGroupPython` CollisionDetector instance and creates a command
#to be used in a workbench.
#

import FreeCAD
import FreeCADGui
import json

from CollisionObject import CollisionProxy, ViewProviderCollisionProxy
from PySide2.QtWidgets import QMessageBox
from PySide2.QtCore import QTimer
from os import path

## Path to a folder with the necessary icons.
PATH_TO_ICONS = path.join(FreeCAD.getHomePath(), "Mod", "Animate", "Resources",
                          "Icons")

## @brief Proxy class for a `DocumentObjectGroupPython` CollisionDetector instance.
#
#A CollisionDetectorProxy instance adds properties to
#a `DocumentObjectGroupPython` CollisionDetector instance and responds to theirs
#changes. It detects collisions among `ObservedObjects`.
#
#
#
#To connect this `Proxy` object to a `DocumentObjectGroupPython`
#CollisionDetector do:
#
# @code
#        a = FreeCAD.ActiveDocument.addObject("App::DocumentObjectGroupPython",
Example #47
0
    def writeMeshCase(self):
        """ Collect case settings, and finally build a runnable case. """
        CfdTools.cfdMessage(
            "Populating mesh dictionaries in folder {}\n".format(
                self.meshCaseDir))

        if self.mesh_obj.MeshUtility == "cfMesh":
            self.cf_settings['ClMax'] = self.clmax * self.scale

            if len(self.cf_settings['BoundaryLayers']) > 0:
                self.cf_settings['BoundaryLayerPresent'] = True
            else:
                self.cf_settings['BoundaryLayerPresent'] = False
            if len(self.cf_settings["InternalRegions"]) > 0:
                self.cf_settings['InternalRefinementRegionsPresent'] = True
            else:
                self.cf_settings['InternalRefinementRegionsPresent'] = False

        elif self.mesh_obj.MeshUtility == "snappyHexMesh":
            bound_box = self.part_obj.Shape.BoundBox
            bC = 5  # Number of background mesh buffer cells
            x_min = (bound_box.XMin - bC * self.clmax) * self.scale
            x_max = (bound_box.XMax + bC * self.clmax) * self.scale
            y_min = (bound_box.YMin - bC * self.clmax) * self.scale
            y_max = (bound_box.YMax + bC * self.clmax) * self.scale
            z_min = (bound_box.ZMin - bC * self.clmax) * self.scale
            z_max = (bound_box.ZMax + bC * self.clmax) * self.scale
            cells_x = int(math.ceil(bound_box.XLength / self.clmax) + 2 * bC)
            cells_y = int(math.ceil(bound_box.YLength / self.clmax) + 2 * bC)
            cells_z = int(math.ceil(bound_box.ZLength / self.clmax) + 2 * bC)

            snappy_settings = self.snappy_settings
            snappy_settings['BlockMesh'] = {
                "xMin": x_min,
                "xMax": x_max,
                "yMin": y_min,
                "yMax": y_max,
                "zMin": z_min,
                "zMax": z_max,
                "cellsX": cells_x,
                "cellsY": cells_y,
                "cellsZ": cells_z
            }

            inside_x = Units.Quantity(
                self.mesh_obj.PointInMesh.get('x')).Value * self.scale
            inside_y = Units.Quantity(
                self.mesh_obj.PointInMesh.get('y')).Value * self.scale
            inside_z = Units.Quantity(
                self.mesh_obj.PointInMesh.get('z')).Value * self.scale

            shape_face_names_list = []
            for i in self.mesh_obj.ShapeFaceNames:
                shape_face_names_list.append(i)
            snappy_settings['ShapeFaceNames'] = tuple(shape_face_names_list)
            snappy_settings[
                'EdgeRefinementLevel'] = CfdTools.relLenToRefinementLevel(
                    self.mesh_obj.EdgeRefinement)
            snappy_settings['PointInMesh'] = {
                "x": inside_x,
                "y": inside_y,
                "z": inside_z
            }
            snappy_settings[
                'CellsBetweenLevels'] = self.mesh_obj.CellsBetweenLevels
            if self.mesh_obj.NumberCores <= 1:
                self.mesh_obj.NumberCores = 1
                snappy_settings['ParallelMesh'] = False
            else:
                snappy_settings['ParallelMesh'] = True
            snappy_settings['NumberCores'] = self.mesh_obj.NumberCores

            if len(self.snappy_settings["InternalRegions"]) > 0:
                self.snappy_settings['InternalRefinementRegionsPresent'] = True
            else:
                self.snappy_settings[
                    'InternalRefinementRegionsPresent'] = False
        elif self.mesh_obj.MeshUtility == "gmsh":
            if platform.system() == "Windows":
                exe = os.path.join(FreeCAD.getHomePath(), 'bin', 'gmsh.exe')
            else:
                exe = subprocess.check_output(
                    ["which", "gmsh"], universal_newlines=True).rstrip('\n')
            self.gmsh_settings['Executable'] = CfdTools.translatePath(exe)
            self.gmsh_settings['ShapeFile'] = self.temp_file_shape
            self.gmsh_settings['HasLengthMap'] = False
            if self.ele_length_map:
                self.gmsh_settings['HasLengthMap'] = True
                self.gmsh_settings['LengthMap'] = self.ele_length_map
                self.gmsh_settings['NodeMap'] = {}
                for e in self.ele_length_map:
                    ele_nodes = (''.join(
                        (str(n + 1) + ', ')
                        for n in self.ele_node_map[e])).rstrip(', ')
                    self.gmsh_settings['NodeMap'][e] = ele_nodes
            self.gmsh_settings['ClMax'] = self.clmax
            self.gmsh_settings['ClMin'] = self.clmin
            sols = (''.join(
                (str(n + 1) + ', ')
                for n in range(len(self.mesh_obj.Part.Shape.Solids)))
                    ).rstrip(', ')
            self.gmsh_settings['Solids'] = sols
            self.gmsh_settings['BoundaryFaceMap'] = {}
            # Write one boundary per face
            for i in range(len(self.mesh_obj.Part.Shape.Faces)):
                self.gmsh_settings['BoundaryFaceMap']['face' + str(i)] = i + 1
            self.gmsh_settings['MeshFile'] = self.temp_file_mesh

        # Perform initialisation here rather than __init__ in case of path changes
        self.template_path = os.path.join(CfdTools.get_module_path(), "data",
                                          "defaultsMesh")

        mesh_region_present = False
        if self.mesh_obj.MeshUtility == "cfMesh" and len(self.cf_settings['MeshRegions']) > 0 or \
           self.mesh_obj.MeshUtility == "snappyHexMesh" and len(self.snappy_settings['MeshRegions']) > 0:
            mesh_region_present = True

        self.settings = {
            'Name': self.part_obj.Name,
            'MeshPath': self.meshCaseDir,
            'FoamRuntime': CfdTools.getFoamRuntime(),
            'TranslatedFoamPath':
            CfdTools.translatePath(CfdTools.getFoamDir()),
            'MeshUtility': self.mesh_obj.MeshUtility,
            'MeshRegionPresent': mesh_region_present,
            'CfSettings': self.cf_settings,
            'SnappySettings': self.snappy_settings,
            'GmshSettings': self.gmsh_settings,
            'TwoDSettings': self.two_d_settings
        }

        TemplateBuilder.TemplateBuilder(self.meshCaseDir, self.template_path,
                                        self.settings)

        # Update Allmesh permission - will fail silently on Windows
        fname = os.path.join(self.meshCaseDir, "Allmesh")
        import stat
        s = os.stat(fname)
        os.chmod(fname, s.st_mode | stat.S_IEXEC)

        CfdTools.cfdMessage(
            "Successfully wrote meshCase to folder {}\n".format(
                self.meshCaseDir))
Example #48
0
def InitApplications():
    try:
        import sys, os
    except:
        FreeCAD.PrintError(
            "\n\nSeems the python standard libs are not installed, bailing out!\n\n"
        )
        raise
    # Checking on FreeCAD module path ++++++++++++++++++++++++++++++++++++++++++
    ModDir = FreeCAD.getHomePath() + 'Mod'
    ModDir = os.path.realpath(ModDir)
    BinDir = FreeCAD.getHomePath() + 'bin'
    BinDir = os.path.realpath(BinDir)
    LibDir = FreeCAD.getHomePath() + 'lib'
    LibDir = os.path.realpath(LibDir)
    AddPath = FreeCAD.ConfigGet("AdditionalModulePaths").split(";")
    HomeMod = FreeCAD.ConfigGet("UserAppData") + "Mod"
    HomeMod = os.path.realpath(HomeMod)
    MacroDir = FreeCAD.ParamGet(
        "User parameter:BaseApp/Preferences/Macro").GetString("MacroPath")
    MacroMod = os.path.realpath(MacroDir + "/Mod")
    ModPar = FreeCAD.ParamGet("System parameter:Modules")

    #print FreeCAD.getHomePath()
    if os.path.isdir(FreeCAD.getHomePath() + 'src\\Tools'):
        sys.path.append(FreeCAD.getHomePath() + 'src\\Tools')
    # Searching for module dirs +++++++++++++++++++++++++++++++++++++++++++++++++++
    # Use dict to handle duplicated module names
    ModDict = {}
    if os.path.isdir(ModDir):
        ModDirs = os.listdir(ModDir)
        for i in ModDirs:
            ModDict[i.lower()] = os.path.join(ModDir, i)
    else:
        Wrn("No modules found in " + ModDir + "\n")
    # Search for additional modules in the home directory
    if os.path.isdir(HomeMod):
        HomeMods = os.listdir(HomeMod)
        for i in HomeMods:
            ModDict[i.lower()] = os.path.join(HomeMod, i)
    # Search for additional modules in the macro directory
    if os.path.isdir(MacroMod):
        MacroMods = os.listdir(MacroMod)
        for i in MacroMods:
            key = i.lower()
            if key not in ModDict: ModDict[key] = os.path.join(MacroMod, i)
    # Search for additional modules in command line
    for i in AddPath:
        if os.path.isdir(i): ModDict[i] = i
    #AddModPaths = App.ParamGet("System parameter:AdditionalModulePaths")
    #Err( AddModPaths)
    # add also this path so that all modules search for libraries
    # they depend on first here
    PathExtension = BinDir + os.pathsep
    # prepend all module paths to Python search path
    Log('Init:   Searching for modules...\n')
    FreeCAD.__path__ = ModDict.values()
    for Dir in ModDict.values():
        if ((Dir != '') & (Dir != 'CVS') & (Dir != '__init__.py')):
            ModGrp = ModPar.GetGroup(Dir)
            sys.path.insert(0, Dir)
            PathExtension += Dir + os.pathsep
            InstallFile = os.path.join(Dir, "Init.py")
            if (os.path.exists(InstallFile)):
                try:
                    execfile(InstallFile)
                except Exception, inst:
                    Log('Init:      Initializing ' + Dir + '... failed\n')
                    Err('During initialization the error ' + str(inst) +
                        ' occurred in ' + InstallFile + '\n')
                else:
                    Log('Init:      Initializing ' + Dir + '... done\n')
            else:
                Log('Init:      Initializing ' + Dir +
                    '(Init.py not found)... ignore\n')
Example #49
0
    def __init__(self, obj):

        FreeCAD.Console.PrintMessage('\n')  # empty line on start task panel
        self.obj = obj
        self.material = self.obj.Material  # FreeCAD material dictionary of current material
        self.card_path = ''
        self.materials = {}  # { card_path : FreeCAD material dict, ... }
        self.cards = {}  # { card_path : card_names, ... }
        self.icons = {}  # { card_path : icon_path, ... }
        # mat_card is the FCMat file
        # card_name is the file name of the mat_card
        # card_path is the whole file path of the mat_card
        # material_name is the value of the key name in FreeCAD material dictionary
        # they might not match because of special letters in the material_name
        # which are changed in the card_name to english standard characters
        self.has_transient_mat = False

        # parameter widget
        self.parameterWidget = FreeCADGui.PySideUic.loadUi(
            FreeCAD.getHomePath() + "Mod/Fem/Resources/ui/Material.ui")
        # globals
        QtCore.QObject.connect(self.parameterWidget.cb_materials,
                               QtCore.SIGNAL("activated(int)"),
                               self.choose_material)
        QtCore.QObject.connect(self.parameterWidget.chbu_allow_edit,
                               QtCore.SIGNAL("clicked()"),
                               self.toggleInputFieldsReadOnly)
        QtCore.QObject.connect(self.parameterWidget.pushButton_editMat,
                               QtCore.SIGNAL("clicked()"), self.edit_material)
        # basic properties must be provided
        QtCore.QObject.connect(self.parameterWidget.input_fd_density,
                               QtCore.SIGNAL("editingFinished()"),
                               self.density_changed)
        # mechanical properties
        QtCore.QObject.connect(self.parameterWidget.input_fd_young_modulus,
                               QtCore.SIGNAL("editingFinished()"),
                               self.ym_changed)
        QtCore.QObject.connect(self.parameterWidget.spinBox_poisson_ratio,
                               QtCore.SIGNAL("editingFinished()"),
                               self.pr_changed)
        # thermal properties
        QtCore.QObject.connect(
            self.parameterWidget.input_fd_thermal_conductivity,
            QtCore.SIGNAL("editingFinished()"), self.tc_changed)
        QtCore.QObject.connect(
            self.parameterWidget.input_fd_expansion_coefficient,
            QtCore.SIGNAL("editingFinished()"), self.tec_changed)
        QtCore.QObject.connect(self.parameterWidget.input_fd_specific_heat,
                               QtCore.SIGNAL("editingFinished()"),
                               self.sh_changed)
        # fluidic properties, only volumetric thermal expansion coeff makes sense
        QtCore.QObject.connect(
            self.parameterWidget.input_fd_kinematic_viscosity,
            QtCore.SIGNAL("editingFinished()"),
            self.kinematic_viscosity_changed)
        QtCore.QObject.connect(
            self.parameterWidget.input_fd_vol_expansion_coefficient,
            QtCore.SIGNAL("editingFinished()"), self.vtec_changed)

        # init all parameter input files with read only
        self.parameterWidget.chbu_allow_edit.setCheckState(
            QtCore.Qt.CheckState.Unchecked)
        self.toggleInputFieldsReadOnly()

        # hide some groupBox according to material category
        self.parameterWidget.label_category.setText(self.obj.Category)
        if self.obj.Category == 'Fluid':
            self.parameterWidget.groupBox_mechanical.setVisible(0)
            self.parameterWidget.label_expansion_coefficient.setVisible(0)
            self.parameterWidget.input_fd_expansion_coefficient.setVisible(0)
        else:
            self.parameterWidget.groupBox_fluidic.setVisible(0)
            self.parameterWidget.label_vol_expansion_coefficient.setVisible(0)
            self.parameterWidget.input_fd_vol_expansion_coefficient.setVisible(
                0)

        # get all available materials (fill self.materials, self.cards and self.icons)
        from materialtools.cardutils import import_materials as getmats
        self.materials, self.cards, self.icons = getmats()
        # fill the material comboboxes with material cards
        self.add_cards_to_combo_box()

        # search for exact this mat_card in all known cards, choose the current material
        self.card_path = self.get_material_card(self.material)
        FreeCAD.Console.PrintLog('card_path: {}'.format(self.card_path))
        if not self.card_path:
            # we have not found our material in self.materials dict :-(
            # we're going to add a user-defined temporary material: a document material
            FreeCAD.Console.PrintMessage(
                "Previously used material card can not be found in material directories. "
                "Add document material.\n")
            self.card_path = '_document_material'
            self.materials[self.card_path] = self.material
            self.parameterWidget.cb_materials.addItem(
                QtGui.QIcon(":/icons/help-browser.svg"), self.card_path,
                self.card_path)
            index = self.parameterWidget.cb_materials.findData(self.card_path)
            # print(index)
            # fill input fields and set the current material in the cb widget
            self.choose_material(index)
        else:
            # we found our exact material in self.materials dict :-)
            FreeCAD.Console.PrintLog(
                "Previously used material card was found in material directories. "
                "We will use this material.\n")
            index = self.parameterWidget.cb_materials.findData(self.card_path)
            # print(index)
            # fill input fields and set the current material in the cb widget
            self.choose_material(index)

        # geometry selection widget
        self.selectionWidget = FemSelectionWidgets.GeometryElementsSelection(
            obj.References, ['Solid', 'Face', 'Edge'],
            False)  # start with Solid in list!

        # form made from param and selection widget
        self.form = [self.parameterWidget, self.selectionWidget]

        # check references, has to be after initialisation of selectionWidget
        self.selectionWidget.has_equal_references_shape_types()
Example #50
0
def get_fem_test_defs():

    test_path = join(FreeCAD.getHomePath(), "Mod", "Fem", "femtest", "app")
    print("Modules, classes, methods taken from: {}".format(test_path))

    collected_test_module_paths = []
    for tfile in sorted(os.listdir(test_path)):
        if tfile.startswith("test") and tfile.endswith(".py"):
            collected_test_module_paths.append(join(test_path, tfile))

    collected_test_modules = []
    collected_test_classes = []
    collected_test_methods = []
    for f in collected_test_module_paths:
        module_name = os.path.splitext(os.path.basename(f))[0]
        module_path = "femtest.app.{}".format(module_name)
        if module_path not in collected_test_modules:
            collected_test_modules.append(module_path)
        class_name = ""
        tfile = open(f, "r")
        for ln in tfile:
            ln = ln.lstrip()
            ln = ln.rstrip()
            if ln.startswith("class "):
                ln = ln.lstrip("class ")
                ln = ln.split("(")[0]
                class_name = ln
                class_path = "femtest.app.{}.{}".format(
                    module_name, class_name)
                if class_path not in collected_test_classes:
                    collected_test_classes.append(class_path)
            if ln.startswith("def test"):
                ln = ln.lstrip("def ")
                ln = ln.split("(")[0]
                if ln == "test_00print":
                    continue
                method_path = "femtest.app.{}.{}.{}".format(
                    module_name, class_name, ln)
                collected_test_methods.append(method_path)
        tfile.close()

    # write to file
    file_path = join(tempfile.gettempdir(), "test_commands.sh")
    cf = open(file_path, "w")
    cf.write("# created by Python\n")
    cf.write("'''\n")
    cf.write("from femtest.app.support_utils import get_fem_test_defs\n")
    cf.write("get_fem_test_defs()\n")
    cf.write("\n")
    cf.write("\n")
    cf.write("'''\n")
    cf.write("\n")
    cf.write("# modules\n")
    for m in collected_test_modules:
        cf.write("make -j 4 && ./bin/FreeCADCmd -t {}\n".format(m))
    cf.write("\n")
    cf.write("\n")
    cf.write("# classes\n")
    for m in collected_test_classes:
        cf.write("make -j 4 && ./bin/FreeCADCmd -t {}\n".format(m))
    cf.write("\n")
    cf.write("\n")
    cf.write("# methods\n")
    for m in collected_test_methods:
        cf.write("make -j 4 && ./bin/FreeCADCmd -t {}\n".format(m))
    cf.write("\n")
    cf.write("\n")
    cf.write("# methods in FreeCAD\n")
    for m in collected_test_methods:
        cf.write(
            "\nimport unittest\n"
            "unittest.TextTestRunner().run(unittest.TestLoader().loadTestsFromName(\n"
            "    '{}'\n"
            "))\n".format(m))
    cf.close()
    print("The file was saved in:{}".format(file_path))
Example #51
0
    def test005(self):
        """test005()... verify `_identifygcodeByToolNumberList()` produces correct output"""

        from PathScripts.post import gcode_pre as gcode_pre

        importFile = FreeCAD.getHomePath(
        ) + "Mod/Path/PathTests/test_centroid_00.ngc"
        gcodeByToolNumberList = gcode_pre._identifygcodeByToolNumberList(
            importFile)

        self.assertTrue(gcodeByToolNumberList[0][0] == ["G90 G80 G40 G49"])
        self.assertTrue(gcodeByToolNumberList[0][1] == 0)

        self.assertTrue(gcodeByToolNumberList[1][0] == [
            "G0 Z15.00",
            "G90",
            "G0 Z15.00",
            "G0 X10.00 Y10.00",
            "G0 Z10.00",
            "G1 X10.00 Y10.00 Z9.00",
            "G1 X10.00 Y0.00 Z9.00",
            "G1 X0.00 Y0.00 Z9.00",
            "G1 X0.00 Y10.00 Z9.00",
            "G1 X10.00 Y10.00 Z9.00",
            "G1 X10.00 Y10.00 Z8.00",
            "G1 X10.00 Y0.00 Z8.00",
            "G1 X0.00 Y0.00 Z8.00",
            "G1 X0.00 Y10.00 Z8.00",
            "G1 X10.00 Y10.00 Z8.00",
            "G1 X10.00 Y10.00 Z7.00",
            "G1 X10.00 Y0.00 Z7.00",
            "G1 X0.00 Y0.00 Z7.00",
            "G1 X0.00 Y10.00 Z7.00",
            "G1 X10.00 Y10.00 Z7.00",
            "G1 X10.00 Y10.00 Z6.00",
            "G1 X10.00 Y0.00 Z6.00",
            "G1 X0.00 Y0.00 Z6.00",
            "G1 X0.00 Y10.00 Z6.00",
            "G1 X10.00 Y10.00 Z6.00",
            "G1 X10.00 Y10.00 Z5.00",
            "G1 X10.00 Y0.00 Z5.00",
            "G1 X0.00 Y0.00 Z5.00",
            "G1 X0.00 Y10.00 Z5.00",
            "G1 X10.00 Y10.00 Z5.00",
            "G1 X10.00 Y10.00 Z4.00",
            "G1 X10.00 Y0.00 Z4.00",
            "G1 X0.00 Y0.00 Z4.00",
            "G1 X0.00 Y10.00 Z4.00",
            "G1 X10.00 Y10.00 Z4.00",
            "G1 X10.00 Y10.00 Z3.00",
            "G1 X10.00 Y0.00 Z3.00",
            "G1 X0.00 Y0.00 Z3.00",
            "G1 X0.00 Y10.00 Z3.00",
            "G1 X10.00 Y10.00 Z3.00",
            "G1 X10.00 Y10.00 Z2.00",
            "G1 X10.00 Y0.00 Z2.00",
            "G1 X0.00 Y0.00 Z2.00",
            "G1 X0.00 Y10.00 Z2.00",
            "G1 X10.00 Y10.00 Z2.00",
            "G1 X10.00 Y10.00 Z1.00",
            "G1 X10.00 Y0.00 Z1.00",
            "G1 X0.00 Y0.00 Z1.00",
            "G1 X0.00 Y10.00 Z1.00",
            "G1 X10.00 Y10.00 Z1.00",
            "G1 X10.00 Y10.00 Z0.00",
            "G1 X10.00 Y0.00 Z0.00",
            "G1 X0.00 Y0.00 Z0.00",
            "G1 X0.00 Y10.00 Z0.00",
            "G1 X10.00 Y10.00 Z0.00",
            "G0 Z15.00",
            "G90 G80 G40 G49",
        ])
        self.assertTrue(gcodeByToolNumberList[1][1] == 2)
Example #52
0
def InitApplications():
	# Checking on FreeCAD module path ++++++++++++++++++++++++++++++++++++++++++
	ModDir = FreeCAD.getHomePath()+'Mod'
	ModDir = os.path.realpath(ModDir)
	ExtDir = FreeCAD.getHomePath()+'Ext'
	ExtDir = os.path.realpath(ExtDir)
	BinDir = FreeCAD.getHomePath()+'bin'
	BinDir = os.path.realpath(BinDir)
	libpaths = []
	LibDir = FreeCAD.getHomePath()+'lib'
	LibDir = os.path.realpath(LibDir)
	if os.path.exists(LibDir):
		libpaths.append(LibDir)
	Lib64Dir = FreeCAD.getHomePath()+'lib64'
	Lib64Dir = os.path.realpath(Lib64Dir)
	if os.path.exists(Lib64Dir):
		libpaths.append(Lib64Dir)
	LibPyDir = FreeCAD.getHomePath()+'lib-py3'
	LibPyDir = os.path.realpath(LibPyDir)
	if (os.path.exists(LibPyDir)):
		libpaths.append(LibPyDir)
	AddPath = FreeCAD.ConfigGet("AdditionalModulePaths").split(";")
	HomeMod = FreeCAD.getUserAppDataDir()+"Mod"
	HomeMod = os.path.realpath(HomeMod)
	MacroDir = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Macro").GetString("MacroPath")
	MacroMod = os.path.realpath(MacroDir+"/Mod")
	SystemWideMacroDir = FreeCAD.getHomePath()+'Macro'
	SystemWideMacroDir = os.path.realpath(SystemWideMacroDir)

	#print FreeCAD.getHomePath()
	if os.path.isdir(FreeCAD.getHomePath()+'src\\Tools'):
		sys.path.append(FreeCAD.getHomePath()+'src\\Tools')



	# Searching for module dirs +++++++++++++++++++++++++++++++++++++++++++++++++++
	# Use dict to handle duplicated module names
	ModDict = {}
	if os.path.isdir(ModDir):
		ModDirs = os.listdir(ModDir)
		for i in ModDirs: ModDict[i.lower()] = os.path.join(ModDir,i)
	else:
		Wrn ("No modules found in " + ModDir + "\n")
	# Search for additional modules in the home directory
	if os.path.isdir(HomeMod):
		HomeMods = os.listdir(HomeMod)
		for i in HomeMods: ModDict[i.lower()] = os.path.join(HomeMod,i)
	elif os.path.isdir(os.path.join(os.path.expanduser("~"),".FreeCAD","Mod")):
		# Check if old location exists
		Wrn ("User path has changed to " + FreeCAD.getUserAppDataDir() + ". Please move user modules and macros\n")
	# Search for additional modules in the macro directory
	if os.path.isdir(MacroMod):
		MacroMods = os.listdir(MacroMod)
		for i in MacroMods:
			key = i.lower()
			if key not in ModDict: ModDict[key] = os.path.join(MacroMod,i)
	# Search for additional modules in command line
	for i in AddPath:
		if os.path.isdir(i): ModDict[i] = i
	#AddModPaths = App.ParamGet("System parameter:AdditionalModulePaths")
	#Err( AddModPaths)
	# add also this path so that all modules search for libraries
	# they depend on first here
	PathExtension = []
	PathExtension.append(BinDir)

	# prepend all module paths to Python search path
	Log('Init:   Searching for modules...\n')


	# to have all the module-paths available in FreeCADGuiInit.py:
	FreeCAD.__ModDirs__ = list(ModDict.values())

	# this allows importing with:
	# from FreeCAD.Module import package
	FreeCAD.__path__ = [ModDir] + libpaths + [HomeMod]

	# also add these directories to the sys.path to
	# not change the old behaviour. once we have moved to
	# proper python modules this can eventuelly be removed.
	sys.path = [ModDir] + libpaths + [ExtDir] + sys.path

	def RunInitPy(Dir):
		InstallFile = os.path.join(Dir,"Init.py")
		if (os.path.exists(InstallFile)):
			try:
				with open(file=InstallFile, encoding="utf-8") as f:
					exec(f.read())
			except Exception as inst:
				Log('Init:      Initializing ' + Dir + '... failed\n')
				Log('-'*100+'\n')
				Log(traceback.format_exc())
				Log('-'*100+'\n')
				Err('During initialization the error "' + str(inst) + '" occurred in ' + InstallFile + '\n')
				Err('Please look into the log file for further information\n')
			else:
				Log('Init:      Initializing ' + Dir + '... done\n')
		else:
			Log('Init:      Initializing ' + Dir + '(Init.py not found)... ignore\n')

	for Dir in ModDict.values():
		if ((Dir != '') & (Dir != 'CVS') & (Dir != '__init__.py')):
			sys.path.insert(0,Dir)
			PathExtension.append(Dir)
			MetadataFile = os.path.join(Dir, "package.xml")
			if os.path.exists(MetadataFile):
				meta = FreeCAD.Metadata(MetadataFile)
				content = meta.Content
				if "workbench" in content:
					workbenches = content["workbench"]
					for workbench in workbenches:
						subdirectory = workbench.Name if not workbench.Subdirectory else workbench.Subdirectory
						subdirectory = subdirectory.replace("/",os.path.sep)
						subdirectory = os.path.join(Dir, subdirectory)
						classname = workbench.Classname
						sys.path.insert(0,subdirectory)
						PathExtension.append(subdirectory)
						RunInitPy(subdirectory)
				else:
					continue # The package content says there are no workbenches here, so just skip
			else:
				RunInitPy(Dir)

	extension_modules = []

	try:
		import pkgutil
		import importlib
		import freecad
		for _, freecad_module_name, freecad_module_ispkg in pkgutil.iter_modules(freecad.__path__, "freecad."):
			if freecad_module_ispkg:
				Log('Init: Initializing ' + freecad_module_name + '\n')
				try:
					freecad_module = importlib.import_module(freecad_module_name)
					extension_modules += [freecad_module_name]
					if any (module_name == 'init' for _, module_name, ispkg in pkgutil.iter_modules(freecad_module.__path__)):
						importlib.import_module(freecad_module_name + '.init')
						Log('Init: Initializing ' + freecad_module_name + '... done\n')
					else:
						Log('Init: No init module found in ' + freecad_module_name + ', skipping\n')
				except Exception as inst:
					Err('During initialization the error "' + str(inst) + '" occurred in ' + freecad_module_name + '\n')
					Err('-'*80+'\n')
					Err(traceback.format_exc())
					Err('-'*80+'\n')
					Log('Init:      Initializing ' + freecad_module_name + '... failed\n')
					Log('-'*80+'\n')
					Log(traceback.format_exc())
					Log('-'*80+'\n')
	except ImportError as inst:
		Err('During initialization the error "' + str(inst) + '" occurred\n')

	Log("Using "+ModDir+" as module path!\n")
	# In certain cases the PathExtension list can contain invalid strings. We concatenate them to a single string
	# but check that the output is a valid string
	setupSearchPaths(PathExtension)
	path = os.environ["PATH"].split(os.pathsep)
	Log("System path after init:\n")
	for i in path:
		Log("   " + i + "\n")
	# add MacroDir to path (RFE #0000504)
	sys.path.append(MacroDir)
	# add SystemWideMacroDir to path
	sys.path.append(SystemWideMacroDir)
	# add special path for MacOSX (bug #0000307)
	import platform
	if len(platform.mac_ver()[0]) > 0:
		sys.path.append(os.path.expanduser('~/Library/Application Support/FreeCAD/Mod'))
Example #53
0
    def __init__(self, obj):

        FreeCAD.Console.PrintMessage("\n")  # empty line on start task panel
        self.obj = obj

        # init matrix and reinforcement material
        self.material_m = self.obj.Material
        self.card_path_m = ""
        self.has_transient_mat_m = False
        self.material_r = self.obj.Reinforcement
        self.card_path_r = ""
        self.has_transient_mat_r = False
        # mat_card is the FCMat file
        # card_name is the file name of the mat_card
        # card_path is the whole file path of the mat_card
        # material_name is the value of the key name in FreeCAD material dictionary
        # they might not match because of special letters in the material_name which are
        # changed in the card_name to english standard characters

        # init for collecting all mat data and icons
        self.materials = {}  # { card_path : FreeCAD material dict }
        self.cards = {}  # { card_path : card_names, ... }
        self.icons = {}  # { card_path : icon_path }

        # parameter widget
        self.parameterWidget = FreeCADGui.PySideUic.loadUi(
            FreeCAD.getHomePath() +
            "Mod/Fem/Resources/ui/MaterialReinforcement.ui")

        # globals
        QtCore.QObject.connect(self.parameterWidget.cb_materials_m,
                               QtCore.SIGNAL("activated(int)"),
                               self.choose_material_m)
        QtCore.QObject.connect(self.parameterWidget.pb_edit_m,
                               QtCore.SIGNAL("clicked()"),
                               self.edit_material_m)
        QtCore.QObject.connect(self.parameterWidget.cb_materials_r,
                               QtCore.SIGNAL("activated(int)"),
                               self.choose_material_r)
        QtCore.QObject.connect(self.parameterWidget.pb_edit_r,
                               QtCore.SIGNAL("clicked()"),
                               self.edit_material_r)

        # get all available materials (fill self.materials, self.cards and self.icons)
        from materialtools.cardutils import import_materials as getmats
        self.materials, self.cards, self.icons = getmats()
        # fill the material comboboxes with material cards
        self.add_cards_to_combo_boxes()

        # search for exact the mat_card_m and mat_card_r in all known cards
        # choose the current matrix material
        self.card_path_m = self.get_material_card(self.material_m)
        FreeCAD.Console.PrintLog("card_path: {}\n".format(self.card_path_m))
        if not self.card_path_m:
            # we have not found our material in self.materials dict :-(
            # we're going to add a user-defined temporary material: a document material
            FreeCAD.Console.PrintMessage(
                "Previously used material card cannot be found in material directories. "
                "Add document material.\n")
            self.card_path_m = "_Document_Matrix_Material"
            self.materials[self.card_path_m] = self.material_m
            self.parameterWidget.cb_materials_m.addItem(
                QtGui.QIcon(":/icons/help-browser.svg"), self.card_path_m,
                self.card_path_m)
            index = self.parameterWidget.cb_materials_m.findData(
                self.card_path_m)
            # print(index)
            # fill input fields and set the current material in the cb widget
            self.choose_material_m(index)
        else:
            # we found our exact material in self.materials dict :-)
            FreeCAD.Console.PrintLog(
                "Previously used material card was found in material directories. "
                "We will use this material.\n")
            index = self.parameterWidget.cb_materials_m.findData(
                self.card_path_m)
            # set the current material in the cb widget
            self.choose_material_m(index)

        # choose the current reinforcement material
        self.card_path_r = self.get_material_card(self.material_r)
        FreeCAD.Console.PrintLog("card_path: {}\n".format(self.card_path_r))
        if not self.card_path_r:
            # we have not found our material in self.materials dict :-(
            # we're going to add a user-defined temporary material: a document material
            FreeCAD.Console.PrintMessage(
                "Previously used material card cannot be found in material directories. "
                "Add document material.\n")
            self.card_path_r = "_Document_Reinforcement_Material"
            self.materials[self.card_path_r] = self.material_r
            self.parameterWidget.cb_materials_r.addItem(
                QtGui.QIcon(":/icons/help-browser.svg"), self.card_path_r,
                self.card_path_r)
            index = self.parameterWidget.cb_materials_r.findData(
                self.card_path_r)
            # set the current material in the cb widget
            self.choose_material_r(index)
        else:
            # we found our exact material in self.materials dict :-)
            FreeCAD.Console.PrintLog(
                "Previously used material card was found in material directories. "
                "We will use this material.\n")
            index = self.parameterWidget.cb_materials_r.findData(
                self.card_path_r)
            # print(index)
            # fill input fields and set the current material in the cb widget
            self.choose_material_r(index)

        # set up the form
        self.form = self.parameterWidget
    def __init__(self, obj):
        self.result_obj = obj
        self.mesh_obj = self.result_obj.Mesh
        # task panel should be started by use of setEdit of view provider
        # in view provider checks: Mesh, active analysis and
        # if Mesh and result are in active analysis

        ui_path = FreeCAD.getHomePath() + "Mod/Fem/Resources/ui/"
        self.result_widget = FreeCADGui.PySideUic.loadUi(ui_path +
                                                         "ResultShow.ui")
        self.info_widget = FreeCADGui.PySideUic.loadUi(ui_path +
                                                       "ResultHints.ui")
        self.form = [self.result_widget, self.info_widget]

        self.fem_prefs = FreeCAD.ParamGet(
            "User parameter:BaseApp/Preferences/Mod/Fem/General")
        self.restore_result_settings_in_dialog = self.fem_prefs.GetBool(
            "RestoreResultDialog", True)

        # Connect Signals and Slots
        # result type radio buttons
        # TODO: move to combo box, to be independent from result types and result types count
        QtCore.QObject.connect(self.result_widget.rb_none,
                               QtCore.SIGNAL("toggled(bool)"),
                               self.none_selected)
        QtCore.QObject.connect(self.result_widget.rb_abs_displacement,
                               QtCore.SIGNAL("toggled(bool)"),
                               self.abs_displacement_selected)
        QtCore.QObject.connect(self.result_widget.rb_x_displacement,
                               QtCore.SIGNAL("toggled(bool)"),
                               self.x_displacement_selected)
        QtCore.QObject.connect(self.result_widget.rb_y_displacement,
                               QtCore.SIGNAL("toggled(bool)"),
                               self.y_displacement_selected)
        QtCore.QObject.connect(self.result_widget.rb_z_displacement,
                               QtCore.SIGNAL("toggled(bool)"),
                               self.z_displacement_selected)
        QtCore.QObject.connect(self.result_widget.rb_temperature,
                               QtCore.SIGNAL("toggled(bool)"),
                               self.temperature_selected)
        QtCore.QObject.connect(self.result_widget.rb_vm_stress,
                               QtCore.SIGNAL("toggled(bool)"),
                               self.vm_stress_selected)
        QtCore.QObject.connect(self.result_widget.rb_maxprin,
                               QtCore.SIGNAL("toggled(bool)"),
                               self.max_prin_selected)
        QtCore.QObject.connect(self.result_widget.rb_minprin,
                               QtCore.SIGNAL("toggled(bool)"),
                               self.min_prin_selected)
        QtCore.QObject.connect(self.result_widget.rb_max_shear_stress,
                               QtCore.SIGNAL("toggled(bool)"),
                               self.max_shear_selected)
        QtCore.QObject.connect(self.result_widget.rb_massflowrate,
                               QtCore.SIGNAL("toggled(bool)"),
                               self.massflowrate_selected)
        QtCore.QObject.connect(self.result_widget.rb_networkpressure,
                               QtCore.SIGNAL("toggled(bool)"),
                               self.networkpressure_selected)
        QtCore.QObject.connect(self.result_widget.rb_peeq,
                               QtCore.SIGNAL("toggled(bool)"),
                               self.peeq_selected)

        # stats
        self.result_widget.show_histogram.clicked.connect(
            self.show_histogram_clicked)

        # displacement
        QtCore.QObject.connect(self.result_widget.cb_show_displacement,
                               QtCore.SIGNAL("clicked(bool)"),
                               self.show_displacement)
        QtCore.QObject.connect(self.result_widget.hsb_displacement_factor,
                               QtCore.SIGNAL("valueChanged(int)"),
                               self.hsb_disp_factor_changed)

        self.result_widget.sb_displacement_factor.valueChanged.connect(
            self.sb_disp_factor_changed)
        self.result_widget.sb_displacement_factor_max.valueChanged.connect(
            self.sb_disp_factor_max_changed)

        # user defined equation
        self.result_widget.user_def_eq.textChanged.connect(
            self.user_defined_text)
        QtCore.QObject.connect(self.result_widget.calculate,
                               QtCore.SIGNAL("clicked()"), self.calculate)

        self.update()
        if self.restore_result_settings_in_dialog:
            self.restore_result_dialog()
        else:
            self.restore_initial_result_dialog()
            # initialize scale factor for show displacement
            scale_factor = get_displacement_scale_factor(self.result_obj)
            self.result_widget.sb_displacement_factor_max.setValue(
                10. * scale_factor)
            self.result_widget.sb_displacement_factor.setValue(scale_factor)
Example #55
0
    def setup_ccx(self, ccx_binary=None, ccx_binary_sig="CalculiX"):
        error_title = "No CalculiX binary ccx"
        error_message = ""
        from platform import system
        ccx_std_location = FreeCAD.ParamGet(
            "User parameter:BaseApp/Preferences/Mod/Fem/Ccx").GetBool(
                "UseStandardCcxLocation", True)
        if ccx_std_location:
            if system() == "Windows":
                ccx_path = FreeCAD.getHomePath() + "bin/ccx.exe"
                FreeCAD.ParamGet(
                    "User parameter:BaseApp/Preferences/Mod/Fem/Ccx"
                ).SetString("ccxBinaryPath", ccx_path)
                self.ccx_binary = ccx_path
            elif system() == "Linux":
                p1 = subprocess.Popen(['which', 'ccx'], stdout=subprocess.PIPE)
                if p1.wait() == 0:
                    if sys.version_info.major >= 3:
                        ccx_path = str(p1.stdout.read()).split('\n')[0]
                    else:
                        ccx_path = p1.stdout.read().split('\n')[0]
                elif p1.wait() == 1:
                    error_message = (
                        "FEM: CalculiX binary ccx not found in standard system binary path. "
                        "Please install ccx or set path to binary in FEM preferences tab CalculiX.\n"
                    )
                    if FreeCAD.GuiUp:
                        QtGui.QMessageBox.critical(None, error_title,
                                                   error_message)
                    raise Exception(error_message)
                self.ccx_binary = ccx_path
        else:
            if not ccx_binary:
                self.ccx_prefs = FreeCAD.ParamGet(
                    "User parameter:BaseApp/Preferences/Mod/Fem/Ccx")
                ccx_binary = self.ccx_prefs.GetString("ccxBinaryPath", "")
                if not ccx_binary:
                    FreeCAD.ParamGet(
                        "User parameter:BaseApp/Preferences/Mod/Fem/Ccx"
                    ).SetBool("UseStandardCcxLocation", True)
                    error_message = (
                        "FEM: CalculiX binary ccx path not set at all. "
                        "The use of standard path was activated in FEM preferences tab CalculiX. Please try again!\n"
                    )
                    if FreeCAD.GuiUp:
                        QtGui.QMessageBox.critical(None, error_title,
                                                   error_message)
                    raise Exception(error_message)
            self.ccx_binary = ccx_binary

        startup_info = None
        if system() == "Windows":
            # Windows workaround to avoid blinking terminal window
            startup_info = subprocess.STARTUPINFO()
            startup_info.dwFlags = subprocess.STARTF_USESHOWWINDOW
        ccx_stdout = None
        ccx_stderr = None
        try:
            p = subprocess.Popen([self.ccx_binary],
                                 stdout=subprocess.PIPE,
                                 stderr=subprocess.PIPE,
                                 shell=False,
                                 startupinfo=startup_info)
            ccx_stdout, ccx_stderr = p.communicate()
            if ccx_binary_sig in str(ccx_stdout):
                self.ccx_binary_present = True
            else:
                raise Exception("FEM: wrong ccx binary")
                # since we raise an exception the try will fail and the exception later with the error popup will be raised
                # TODO: I'm still able to break it. If user doesn't give a file but a path without a file or
                # a file which is not a binary no exception at all is raised.
        except OSError as e:
            FreeCAD.Console.PrintError(str(e))
            if e.errno == 2:
                error_message = (
                    "FEM: CalculiX binary ccx \'{}\' not found. "
                    "Please set the CalculiX binary ccx path in FEM preferences tab CalculiX.\n"
                    .format(ccx_binary))
                if FreeCAD.GuiUp:
                    QtGui.QMessageBox.critical(None, error_title,
                                               error_message)
                raise Exception(error_message)
        except Exception as e:
            FreeCAD.Console.PrintError(str(e))
            error_message = (
                "FEM: CalculiX ccx \'{}\' output \'{}\' doesn't contain expected phrase \'{}\'. "
                'There are some problems when running the ccx binary. '
                'Check if ccx runs standalone without FreeCAD.\n'.format(
                    ccx_binary, ccx_stdout, ccx_binary_sig))
            if FreeCAD.GuiUp:
                QtGui.QMessageBox.critical(None, error_title, error_message)
            raise Exception(error_message)
Example #56
0
# *                                                                         *
# ***************************************************************************/

import Fem
import FemToolsCcx
import FreeCAD
import FemAnalysis
import FemSolverCalculix
import FemMaterial
import csv
import tempfile
import unittest

mesh_name = 'Mesh'

home_path = FreeCAD.getHomePath()
temp_dir = tempfile.gettempdir()
test_file_dir = home_path + 'Mod/Fem/test_files/ccx'

static_base_name = 'cube_static'
frequency_base_name = 'cube_frequency'
thermomech_base_name = 'spine_thermomech'
static_analysis_dir = temp_dir + '/FEM_static'
frequency_analysis_dir = temp_dir + '/FEM_frequency'
thermomech_analysis_dir = temp_dir + '/FEM_thermomech'
static_analysis_inp_file = test_file_dir + '/' + static_base_name + '.inp'
static_expected_values = test_file_dir + "/cube_static_expected_values"
frequency_analysis_inp_file = test_file_dir + '/' + frequency_base_name + '.inp'
frequency_expected_values = test_file_dir + "/cube_frequency_expected_values"
thermomech_analysis_inp_file = test_file_dir + '/' + thermomech_base_name + '.inp'
thermomech_expected_values = test_file_dir + "/spine_thermomech_expected_values"
    def __init__(self, solver_object):
        self.form = FreeCADGui.PySideUic.loadUi(
            FreeCAD.getHomePath() +
            "Mod/Fem/PyGui/TaskPanelFemSolverCalculix.ui")
        self.ccx_prefs = FreeCAD.ParamGet(
            "User parameter:BaseApp/Preferences/Mod/Fem/Ccx")
        ccx_binary = self.ccx_prefs.GetString("ccxBinaryPath", "")
        if ccx_binary:
            self.CalculixBinary = ccx_binary
            print("Using CalculiX 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.solver_object = solver_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.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.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()
Example #58
0
    def __init__(self, obj):
        FreeCADGui.Selection.clearSelection()
        self.sel_server = None
        self.obj = obj
        self.selection_mode_solid = False
        self.selection_mode_std_print_message = "Select Faces and Edges by single click on them to add them to the list."
        self.selection_mode_solid_print_message = "Select Solids by single click on a Face or Edge which belongs to the Solid, to add the Solid to the list."
        self.material = self.obj.Material
        self.references = []
        if self.obj.References:
            self.tuplereferences = self.obj.References
            self.get_references()

        self.form = FreeCADGui.PySideUic.loadUi(
            FreeCAD.getHomePath() + "Mod/Fem/PyGui/TaskPanelFemMaterial.ui")
        QtCore.QObject.connect(self.form.pushButton_MatWeb,
                               QtCore.SIGNAL("clicked()"), self.goto_MatWeb)
        QtCore.QObject.connect(self.form.pushButton_saveas,
                               QtCore.SIGNAL("clicked()"),
                               self.export_material)
        QtCore.QObject.connect(self.form.cb_materials,
                               QtCore.SIGNAL("activated(int)"),
                               self.choose_material)
        QtCore.QObject.connect(self.form.pushButton_Reference,
                               QtCore.SIGNAL("clicked()"), self.add_references)
        QtCore.QObject.connect(self.form.rb_standard,
                               QtCore.SIGNAL("toggled(bool)"),
                               self.choose_selection_mode_standard)
        QtCore.QObject.connect(self.form.rb_solid,
                               QtCore.SIGNAL("toggled(bool)"),
                               self.choose_selection_mode_solid)
        # basic properties must be provided
        QtCore.QObject.connect(self.form.input_fd_density,
                               QtCore.SIGNAL("valueChanged(double)"),
                               self.density_changed)
        # mechanical properties
        QtCore.QObject.connect(self.form.input_fd_young_modulus,
                               QtCore.SIGNAL("valueChanged(double)"),
                               self.ym_changed)
        QtCore.QObject.connect(self.form.spinBox_poisson_ratio,
                               QtCore.SIGNAL("valueChanged(double)"),
                               self.pr_changed)
        # thermal properties
        QtCore.QObject.connect(self.form.input_fd_thermal_conductivity,
                               QtCore.SIGNAL("valueChanged(double)"),
                               self.tc_changed)
        QtCore.QObject.connect(self.form.input_fd_expansion_coefficient,
                               QtCore.SIGNAL("valueChanged(double)"),
                               self.tec_changed)
        QtCore.QObject.connect(self.form.input_fd_specific_heat,
                               QtCore.SIGNAL("valueChanged(double)"),
                               self.sh_changed)
        # fluidic properties, only volumetric thermal expansion coeff makes sense
        QtCore.QObject.connect(self.form.input_fd_kinematic_viscosity,
                               QtCore.SIGNAL("valueChanged(double)"),
                               self.kinematic_viscosity_changed)
        QtCore.QObject.connect(self.form.input_fd_vol_expansion_coefficient,
                               QtCore.SIGNAL("valueChanged(double)"),
                               self.vtec_changed)

        # hide some groupBox according to material category
        self.form.label_category.setText(self.obj.Category)
        if self.obj.Category == 'Fluid':
            self.form.groupBox_mechanical.setVisible(0)
            self.form.label_expansion_coefficient.setVisible(0)
            self.form.input_fd_expansion_coefficient.setVisible(0)
        else:
            self.form.groupBox_fluidic.setVisible(0)
            self.form.label_vol_expansion_coefficient.setVisible(0)
            self.form.input_fd_vol_expansion_coefficient.setVisible(0)

        self.form.list_References.setContextMenuPolicy(
            QtCore.Qt.CustomContextMenu)
        self.form.list_References.connect(
            self.form.list_References,
            QtCore.SIGNAL("customContextMenuRequested(QPoint)"),
            self.references_list_right_clicked)

        self.import_materials()
        previous_mat_path = self.get_material_path(self.material)
        if not previous_mat_path:
            material_name = self.get_material_name(self.material)
            if material_name != 'None':
                FreeCAD.Console.PrintMessage(
                    "Previously used material cannot be found in material directories. Using transient material.\n"
                )
                self.add_transient_material(self.material)
                index = self.form.cb_materials.findData(material_name)
            else:
                if not self.material:
                    index = self.form.cb_materials.findText(material_name)
                else:
                    FreeCAD.Console.PrintMessage(
                        "None material was previously used. Reload values.\n")
                    self.add_transient_material(self.material)
                    index = self.form.cb_materials.findData(material_name)
            self.choose_material(index)
        else:
            index = self.form.cb_materials.findData(previous_mat_path)
            self.choose_material(index)
        self.has_equal_references_shape_types()
        self.rebuild_list_References()
Example #59
0
 def setUp(self):
     self.test_dir = join(FreeCAD.getHomePath(), "Mod", "Mesh", "App",
                          "TestData")
Example #60
0
 def testAll(self):
     mod_dir = os.path.join(App.getHomePath(), "Mod")
     test_python_syntax(mod_dir, self.whitelist)