From 359c1ae2bbd3fdb15b654043e75005e5742eb20f Mon Sep 17 00:00:00 2001 From: lyphrowny Date: Wed, 19 Jun 2024 14:29:15 +0300 Subject: [PATCH] FEM: reformat codebase --- src/Mod/Fem/FemGlobal.h | 10 +- src/Mod/Fem/Init.py | 26 +- src/Mod/Fem/InitGui.py | 1 + src/Mod/Fem/ObjectsFem.py | 424 ++-- src/Mod/Fem/coding_conventions.md | 14 +- src/Mod/Fem/femcommands/commands.py | 827 +++---- src/Mod/Fem/femcommands/manager.py | 113 +- src/Mod/Fem/femexamples/boxanalysis_base.py | 1 + .../Fem/femexamples/boxanalysis_frequency.py | 9 +- src/Mod/Fem/femexamples/boxanalysis_static.py | 9 +- .../buckling_lateraltorsionalbuckling.py | 14 +- .../Fem/femexamples/buckling_platebuckling.py | 12 +- .../ccx_buckling_flexuralbuckling.py | 10 +- .../femexamples/ccx_cantilever_base_edge.py | 7 +- .../femexamples/ccx_cantilever_base_face.py | 5 +- .../femexamples/ccx_cantilever_base_solid.py | 3 +- .../femexamples/ccx_cantilever_beam_circle.py | 7 +- .../femexamples/ccx_cantilever_beam_pipe.py | 7 +- .../femexamples/ccx_cantilever_beam_rect.py | 7 +- .../femexamples/ccx_cantilever_ele_hexa20.py | 8 +- .../femexamples/ccx_cantilever_ele_quad4.py | 8 +- .../femexamples/ccx_cantilever_ele_quad8.py | 8 +- .../femexamples/ccx_cantilever_ele_seg2.py | 8 +- .../femexamples/ccx_cantilever_ele_seg3.py | 7 +- .../femexamples/ccx_cantilever_ele_tetra4.py | 7 +- .../femexamples/ccx_cantilever_ele_tria3.py | 8 +- .../femexamples/ccx_cantilever_ele_tria6.py | 7 +- .../femexamples/ccx_cantilever_faceload.py | 7 +- .../femexamples/ccx_cantilever_nodeload.py | 9 +- .../ccx_cantilever_prescribeddisplacement.py | 7 +- src/Mod/Fem/femexamples/constraint_centrif.py | 10 +- .../constraint_contact_shell_shell.py | 14 +- .../constraint_contact_solid_solid.py | 17 +- .../femexamples/constraint_section_print.py | 31 +- .../constraint_selfweight_cantilever.py | 10 +- src/Mod/Fem/femexamples/constraint_tie.py | 10 +- .../constraint_transform_beam_hinged.py | 20 +- .../constraint_transform_torque.py | 10 +- ...uitutorial01_eigenvalue_of_elastic_beam.py | 15 +- .../equation_deformation_spring_elmer.py | 52 +- ...on_electrostatics_capacitance_two_balls.py | 20 +- ...ctrostatics_electricforce_elmer_nongui6.py | 38 +- .../Fem/femexamples/equation_flow_elmer_2D.py | 33 +- .../equation_flow_initial_elmer_2D.py | 32 +- .../equation_flow_turbulent_elmer_2D.py | 33 +- .../Fem/femexamples/equation_flux_elmer.py | 14 +- .../equation_magnetodynamics_2D_elmer.py | 23 +- .../equation_magnetodynamics_elmer.py | 23 +- .../equation_magnetostatics_2D_elmer.py | 72 +- src/Mod/Fem/femexamples/examplesgui.py | 17 +- .../Fem/femexamples/frequency_beamsimple.py | 14 +- src/Mod/Fem/femexamples/manager.py | 18 +- ...material_multiple_bendingbeam_fiveboxes.py | 12 +- ...material_multiple_bendingbeam_fivefaces.py | 22 +- .../material_multiple_tensionrod_twoboxes.py | 10 +- .../femexamples/material_nl_platewithhole.py | 16 +- .../meshes/mesh_canticcx_hexa20.py | 925 ++++++-- src/Mod/Fem/femexamples/mystran_plate.py | 14 +- src/Mod/Fem/femexamples/rc_wall_2d.py | 10 +- .../square_pipe_end_twisted_edgeforces.py | 13 +- .../square_pipe_end_twisted_nodeforces.py | 37 +- .../Fem/femexamples/thermomech_bimetall.py | 22 +- .../truss_3d_cs_circle_ele_seg2.py | 3 +- .../truss_3d_cs_circle_ele_seg3.py | 15 +- src/Mod/Fem/femguiutils/migrate_gui.py | 184 +- src/Mod/Fem/femguiutils/selection_widgets.py | 125 +- src/Mod/Fem/feminout/convert2TetGen.py | 77 +- src/Mod/Fem/feminout/exportNastranMesh.py | 50 +- src/Mod/Fem/feminout/importCcxDatResults.py | 21 +- src/Mod/Fem/feminout/importCcxFrdResults.py | 129 +- src/Mod/Fem/feminout/importFenicsMesh.py | 61 +- src/Mod/Fem/feminout/importInpMesh.py | 71 +- src/Mod/Fem/feminout/importPyMesh.py | 33 +- src/Mod/Fem/feminout/importToolsFem.py | 170 +- src/Mod/Fem/feminout/importVTKResults.py | 61 +- src/Mod/Fem/feminout/importYamlJsonMesh.py | 70 +- src/Mod/Fem/feminout/importZ88Mesh.py | 242 +- src/Mod/Fem/feminout/importZ88O2Results.py | 27 +- src/Mod/Fem/feminout/readFenicsXDMF.py | 2 +- src/Mod/Fem/feminout/readFenicsXML.py | 93 +- src/Mod/Fem/feminout/writeFenicsXDMF.py | 122 +- src/Mod/Fem/feminout/writeFenicsXML.py | 36 +- src/Mod/Fem/femmesh/femmesh2mesh.py | 111 +- src/Mod/Fem/femmesh/gmshtools.py | 191 +- src/Mod/Fem/femmesh/meshsetsgetter.py | 243 +-- src/Mod/Fem/femmesh/meshtools.py | 746 ++----- src/Mod/Fem/femobjects/base_femelement.py | 17 +- src/Mod/Fem/femobjects/base_femmeshelement.py | 17 +- .../Fem/femobjects/base_fempythonobject.py | 3 +- .../femobjects/constant_vacuumpermittivity.py | 4 +- .../femobjects/constraint_bodyheatsource.py | 43 +- src/Mod/Fem/femobjects/constraint_centrif.py | 6 +- .../femobjects/constraint_currentdensity.py | 44 +- .../constraint_electrostaticpotential.py | 94 +- .../Fem/femobjects/constraint_flowvelocity.py | 49 +- .../constraint_initialflowvelocity.py | 44 +- .../femobjects/constraint_initialpressure.py | 9 +- .../femobjects/constraint_magnetization.py | 44 +- .../Fem/femobjects/constraint_sectionprint.py | 18 +- .../Fem/femobjects/constraint_selfweight.py | 16 +- src/Mod/Fem/femobjects/constraint_tie.py | 81 +- src/Mod/Fem/femobjects/element_fluid1D.py | 89 +- src/Mod/Fem/femobjects/element_geometry1D.py | 25 +- src/Mod/Fem/femobjects/element_geometry2D.py | 16 +- src/Mod/Fem/femobjects/element_rotation1D.py | 16 +- src/Mod/Fem/femobjects/material_common.py | 12 +- .../material_mechanicalnonlinear.py | 20 +- src/Mod/Fem/femobjects/material_reinforced.py | 17 +- src/Mod/Fem/femobjects/mesh_boundarylayer.py | 20 +- src/Mod/Fem/femobjects/mesh_gmsh.py | 67 +- src/Mod/Fem/femobjects/mesh_group.py | 16 +- src/Mod/Fem/femobjects/mesh_region.py | 16 +- src/Mod/Fem/femobjects/mesh_result.py | 2 +- src/Mod/Fem/femobjects/result_mechanical.py | 194 +- src/Mod/Fem/femobjects/solver_ccxtools.py | 7 +- src/Mod/Fem/femresult/resulttools.py | 199 +- src/Mod/Fem/femsolver/calculix/solver.py | 136 +- src/Mod/Fem/femsolver/calculix/tasks.py | 35 +- .../write_constraint_bodyheatsource.py | 16 +- .../calculix/write_constraint_centrif.py | 15 +- .../calculix/write_constraint_contact.py | 26 +- .../calculix/write_constraint_displacement.py | 18 +- .../calculix/write_constraint_fixed.py | 28 +- .../calculix/write_constraint_fluidsection.py | 87 +- .../calculix/write_constraint_force.py | 14 +- .../calculix/write_constraint_heatflux.py | 19 +- .../write_constraint_initialtemperature.py | 9 +- .../write_constraint_planerotation.py | 22 +- .../calculix/write_constraint_pressure.py | 7 +- .../calculix/write_constraint_rigidbody.py | 19 +- .../write_constraint_rigidbody_step.py | 14 +- .../calculix/write_constraint_sectionprint.py | 11 +- .../calculix/write_constraint_selfweight.py | 9 +- .../calculix/write_constraint_temperature.py | 6 +- .../calculix/write_constraint_tie.py | 31 +- .../calculix/write_constraint_transform.py | 38 +- .../calculix/write_femelement_geometry.py | 75 +- .../calculix/write_femelement_material.py | 22 +- .../Fem/femsolver/calculix/write_footer.py | 22 +- src/Mod/Fem/femsolver/calculix/write_mesh.py | 8 +- .../femsolver/calculix/write_step_equation.py | 29 +- .../femsolver/calculix/write_step_output.py | 10 +- src/Mod/Fem/femsolver/calculix/writer.py | 42 +- .../femsolver/elmer/equations/deformation.py | 35 +- .../elmer/equations/deformation_writer.py | 31 +- .../femsolver/elmer/equations/elasticity.py | 86 +- .../elmer/equations/elasticity_writer.py | 83 +- .../elmer/equations/electricforce.py | 8 +- .../elmer/equations/electricforce_writer.py | 3 +- .../elmer/equations/electrostatic.py | 47 +- .../elmer/equations/electrostatic_writer.py | 25 +- .../Fem/femsolver/elmer/equations/equation.py | 9 +- src/Mod/Fem/femsolver/elmer/equations/flow.py | 29 +- .../femsolver/elmer/equations/flow_writer.py | 25 +- src/Mod/Fem/femsolver/elmer/equations/flux.py | 45 +- .../femsolver/elmer/equations/flux_writer.py | 22 +- src/Mod/Fem/femsolver/elmer/equations/heat.py | 23 +- .../femsolver/elmer/equations/heat_writer.py | 47 +- .../Fem/femsolver/elmer/equations/linear.py | 82 +- .../elmer/equations/magnetodynamic.py | 111 +- .../elmer/equations/magnetodynamic2D.py | 78 +- .../equations/magnetodynamic2D_writer.py | 30 +- .../elmer/equations/magnetodynamic_writer.py | 37 +- .../femsolver/elmer/equations/nonlinear.py | 21 +- src/Mod/Fem/femsolver/elmer/sifio.py | 35 +- src/Mod/Fem/femsolver/elmer/solver.py | 82 +- src/Mod/Fem/femsolver/elmer/tasks.py | 67 +- src/Mod/Fem/femsolver/elmer/writer.py | 152 +- src/Mod/Fem/femsolver/equationbase.py | 8 +- src/Mod/Fem/femsolver/fenics/fenics_tools.py | 91 +- .../Fem/femsolver/mystran/add_con_fixed.py | 13 +- .../Fem/femsolver/mystran/add_con_force.py | 16 +- .../mystran/add_femelement_geometry.py | 15 +- .../mystran/add_femelement_material.py | 5 +- src/Mod/Fem/femsolver/mystran/add_mesh.py | 11 +- src/Mod/Fem/femsolver/mystran/solver.py | 17 +- src/Mod/Fem/femsolver/mystran/tasks.py | 12 +- src/Mod/Fem/femsolver/mystran/writer.py | 41 +- src/Mod/Fem/femsolver/report.py | 7 +- src/Mod/Fem/femsolver/reportdialog.py | 7 +- src/Mod/Fem/femsolver/run.py | 82 +- src/Mod/Fem/femsolver/settings.py | 54 +- src/Mod/Fem/femsolver/signal.py | 1 + src/Mod/Fem/femsolver/solver_taskpanel.py | 25 +- src/Mod/Fem/femsolver/solverbase.py | 22 +- src/Mod/Fem/femsolver/task.py | 17 +- src/Mod/Fem/femsolver/writerbase.py | 38 +- src/Mod/Fem/femsolver/z88/solver.py | 27 +- src/Mod/Fem/femsolver/z88/tasks.py | 27 +- src/Mod/Fem/femsolver/z88/writer.py | 109 +- .../task_constraint_bodyheatsource.py | 28 +- .../femtaskpanels/task_constraint_centrif.py | 25 +- .../task_constraint_currentdensity.py | 116 +- .../task_constraint_electrostaticpotential.py | 179 +- .../task_constraint_flowvelocity.py | 104 +- .../task_constraint_initialflowvelocity.py | 104 +- .../task_constraint_initialpressure.py | 21 +- .../task_constraint_magnetization.py | 116 +- .../task_constraint_sectionprint.py | 12 +- .../Fem/femtaskpanels/task_constraint_tie.py | 20 +- .../Fem/femtaskpanels/task_element_fluid1D.py | 81 +- .../femtaskpanels/task_element_geometry1D.py | 21 +- .../femtaskpanels/task_element_geometry2D.py | 7 +- .../femtaskpanels/task_element_rotation1D.py | 7 +- .../Fem/femtaskpanels/task_material_common.py | 130 +- .../femtaskpanels/task_material_reinforced.py | 52 +- .../femtaskpanels/task_mesh_boundarylayer.py | 11 +- src/Mod/Fem/femtaskpanels/task_mesh_gmsh.py | 71 +- src/Mod/Fem/femtaskpanels/task_mesh_group.py | 9 +- src/Mod/Fem/femtaskpanels/task_mesh_region.py | 7 +- .../femtaskpanels/task_result_mechanical.py | 242 +- .../Fem/femtaskpanels/task_solver_ccxtools.py | 109 +- src/Mod/Fem/femtest/app/support_utils.py | 219 +- src/Mod/Fem/femtest/app/test_ccxtools.py | 72 +- src/Mod/Fem/femtest/app/test_common.py | 41 +- src/Mod/Fem/femtest/app/test_femimport.py | 68 +- src/Mod/Fem/femtest/app/test_material.py | 54 +- src/Mod/Fem/femtest/app/test_mesh.py | 292 +-- src/Mod/Fem/femtest/app/test_object.py | 1938 +++++------------ src/Mod/Fem/femtest/app/test_open.py | 232 +- src/Mod/Fem/femtest/app/test_result.py | 120 +- src/Mod/Fem/femtest/app/test_solver_elmer.py | 103 +- .../Fem/femtest/app/test_solver_mystran.py | 86 +- src/Mod/Fem/femtest/app/test_solver_z88.py | 90 +- .../femtest/data/calculix/box_frequency.dat | 2 +- .../femtest/data/calculix/box_frequency.frd | 56 +- .../femtest/data/calculix/box_frequency.inp | 2 +- .../Fem/femtest/data/calculix/box_static.frd | 26 +- .../Fem/femtest/data/calculix/box_static.inp | 4 +- .../ccx_buckling_flexuralbuckling.inp | 2 +- .../calculix/ccx_cantilever_beam_circle.inp | 4 +- .../calculix/ccx_cantilever_beam_pipe.inp | 4 +- .../calculix/ccx_cantilever_beam_rect.inp | 4 +- .../calculix/ccx_cantilever_ele_hexa20.inp | 66 +- .../calculix/ccx_cantilever_ele_quad4.inp | 2 +- .../calculix/ccx_cantilever_ele_quad8.inp | 2 +- .../data/calculix/ccx_cantilever_ele_seg2.inp | 2 +- .../data/calculix/ccx_cantilever_ele_seg3.inp | 2 +- .../calculix/ccx_cantilever_ele_tria3.inp | 2 +- .../calculix/ccx_cantilever_ele_tria6.inp | 2 +- .../data/calculix/ccx_cantilever_faceload.inp | 2 +- .../data/calculix/ccx_cantilever_nodeload.inp | 2 +- .../ccx_cantilever_prescribeddisplacement.inp | 2 +- .../data/calculix/constraint_centrif.inp | 2 +- .../constraint_contact_shell_shell.inp | 2 +- .../constraint_contact_solid_solid.inp | 4 +- .../data/calculix/constraint_sectionprint.inp | 4 +- .../constraint_selfweight_cantilever.inp | 4 +- .../femtest/data/calculix/constraint_tie.inp | 4 +- .../constraint_transform_beam_hinged.inp | 2 +- .../calculix/constraint_transform_torque.inp | 2 +- .../data/calculix/frequency_beamsimple.inp | 2 +- ...aterial_multiple_bendingbeam_fiveboxes.inp | 4 +- ...aterial_multiple_bendingbeam_fivefaces.inp | 4 +- .../material_multiple_tensionrod_twoboxes.inp | 4 +- .../data/calculix/material_nonlinear.inp | 4 +- .../square_pipe_end_twisted_edgeforces.inp | 4 +- .../square_pipe_end_twisted_nodeforces.inp | 4 +- .../data/calculix/thermomech_bimetall.inp | 4 +- .../femtest/data/elmer/ELMERSOLVER_STARTINFO | 2 +- .../femtest/data/elmer/box_static_0_mm.sif | 5 +- .../elmer/ccxcantilever_faceload_0_mm.sif | 5 +- .../elmer/ccxcantilever_faceload_1_si.sif | 5 +- .../elmer/ccxcantilever_nodeload_0_mm.sif | 5 +- ...cantilever_prescribeddisplacement_0_mm.sif | 5 +- .../Fem/femtest/data/mesh/tetra10_mesh.vtk | 9 +- .../z88/ccx_cantilever_ele_tria6/z88elp.txt | 2 +- .../function_tests/test_support_utils.py | 26 +- src/Mod/Fem/femtest/gui/test_open.py | 222 +- src/Mod/Fem/femtest/test_information.md | 1 - src/Mod/Fem/femtools/ccxtools.py | 230 +- src/Mod/Fem/femtools/checksanalysis.py | 76 +- src/Mod/Fem/femtools/femutils.py | 84 +- src/Mod/Fem/femtools/geomtools.py | 20 +- src/Mod/Fem/femtools/membertools.py | 117 +- src/Mod/Fem/femtools/migrate_app.py | 94 +- src/Mod/Fem/femtools/tokrules.py | 97 +- .../femviewprovider/view_base_femelement.py | 2 +- .../femviewprovider/view_base_femmaterial.py | 2 +- .../view_base_femmeshelement.py | 2 +- .../femviewprovider/view_base_femobject.py | 21 +- .../view_constraint_bodyheatsource.py | 5 +- .../view_constraint_centrif.py | 5 +- .../view_constraint_currentdensity.py | 5 +- .../view_constraint_electrostaticpotential.py | 5 +- .../view_constraint_flowvelocity.py | 5 +- .../view_constraint_initialflowvelocity.py | 5 +- .../view_constraint_initialpressure.py | 5 +- .../view_constraint_magnetization.py | 5 +- .../view_constraint_sectionprint.py | 5 +- .../femviewprovider/view_constraint_tie.py | 5 +- .../femviewprovider/view_element_fluid1D.py | 10 +- .../view_element_geometry1D.py | 10 +- .../view_element_geometry2D.py | 10 +- .../femviewprovider/view_material_common.py | 10 +- .../view_material_reinforced.py | 10 +- .../view_mesh_boundarylayer.py | 10 +- src/Mod/Fem/femviewprovider/view_mesh_gmsh.py | 13 +- .../Fem/femviewprovider/view_mesh_group.py | 10 +- .../Fem/femviewprovider/view_mesh_region.py | 10 +- .../femviewprovider/view_result_mechanical.py | 2 +- .../femviewprovider/view_solver_ccxtools.py | 6 +- 302 files changed, 6702 insertions(+), 9421 deletions(-) diff --git a/src/Mod/Fem/FemGlobal.h b/src/Mod/Fem/FemGlobal.h index b2703d8c38..a9e707885f 100644 --- a/src/Mod/Fem/FemGlobal.h +++ b/src/Mod/Fem/FemGlobal.h @@ -29,19 +29,19 @@ // Fem #ifndef FemExport #ifdef Fem_EXPORTS -# define FemExport FREECAD_DECL_EXPORT +#define FemExport FREECAD_DECL_EXPORT #else -# define FemExport FREECAD_DECL_IMPORT +#define FemExport FREECAD_DECL_IMPORT #endif #endif // FemGui #ifndef FemGuiExport #ifdef FemGui_EXPORTS -# define FemGuiExport FREECAD_DECL_EXPORT +#define FemGuiExport FREECAD_DECL_EXPORT #else -# define FemGuiExport FREECAD_DECL_IMPORT +#define FemGuiExport FREECAD_DECL_IMPORT #endif #endif -#endif //FEM_GLOBAL_H +#endif // FEM_GLOBAL_H diff --git a/src/Mod/Fem/Init.py b/src/Mod/Fem/Init.py index e2d422c2ca..a24adad59c 100644 --- a/src/Mod/Fem/Init.py +++ b/src/Mod/Fem/Init.py @@ -63,11 +63,10 @@ FreeCAD.addExportType("FEM mesh TetGen (*.poly)", "feminout.convert2TetGen") # see FemMesh::read() and FemMesh::write() methods in src/Mod/Fem/App/FemMesh.cpp FreeCAD.addImportType( - "FEM mesh formats (*.bdf *.BDF *.dat *.DAT *.inp *.INP *.med *.MED *.unv *.UNV *.vtk *.VTK *.vtu *.VTU *.pvtu *.PVTU *.z88 *.Z88)", "Fem" -) -FreeCAD.addExportType( - "FEM mesh formats (*.dat *.inp *.med *.stl *.unv *.vtk *.vtu *.z88)", "Fem" + "FEM mesh formats (*.bdf *.BDF *.dat *.DAT *.inp *.INP *.med *.MED *.unv *.UNV *.vtk *.VTK *.vtu *.VTU *.pvtu *.PVTU *.z88 *.Z88)", + "Fem", ) +FreeCAD.addExportType("FEM mesh formats (*.dat *.inp *.med *.stl *.unv *.vtk *.vtu *.z88)", "Fem") FreeCAD.addExportType("FEM mesh Nastran (*.bdf)", "feminout.exportNastranMesh") @@ -77,17 +76,26 @@ FreeCAD.addImportType("FEM mesh Fenics (*.xml *.XML *.xdmf *.XDMF)", "feminout.i FreeCAD.addExportType("FEM mesh Fenics (*.xml *.xdmf)", "feminout.importFenicsMesh") FreeCAD.addImportType( - "FEM mesh YAML/JSON (*.meshyaml *.MESHYAML *.meshjson *.MESHJSON *.yaml *.YAML *.json *.JSON)", "feminout.importYamlJsonMesh" + "FEM mesh YAML/JSON (*.meshyaml *.MESHYAML *.meshjson *.MESHJSON *.yaml *.YAML *.json *.JSON)", + "feminout.importYamlJsonMesh", ) FreeCAD.addExportType( - "FEM mesh YAML/JSON (*.meshyaml *.meshjson *.yaml *.json)", "feminout.importYamlJsonMesh" + "FEM mesh YAML/JSON (*.meshyaml *.meshjson *.yaml *.json)", + "feminout.importYamlJsonMesh", ) FreeCAD.addImportType("FEM mesh Z88 (*i1.txt *I1.TXT)", "feminout.importZ88Mesh") FreeCAD.addExportType("FEM mesh Z88 (*i1.txt)", "feminout.importZ88Mesh") -FreeCAD.addImportType("FEM result Z88 displacements (*o2.txt *O2.TXT)", "feminout.importZ88O2Results") +FreeCAD.addImportType( + "FEM result Z88 displacements (*o2.txt *O2.TXT)", "feminout.importZ88O2Results" +) if "BUILD_FEM_VTK" in FreeCAD.__cmake__: - FreeCAD.addImportType("FEM result VTK (*.vtk *.VTK *.vtu *.VTU *.pvtu *.PVTU)", "feminout.importVTKResults") - FreeCAD.addExportType("FEM result VTK (*.vtu *.vtp *.vts *.vtr *.vti)", "feminout.importVTKResults") + FreeCAD.addImportType( + "FEM result VTK (*.vtk *.VTK *.vtu *.VTU *.pvtu *.PVTU)", + "feminout.importVTKResults", + ) + FreeCAD.addExportType( + "FEM result VTK (*.vtu *.vtp *.vts *.vtr *.vti)", "feminout.importVTKResults" + ) diff --git a/src/Mod/Fem/InitGui.py b/src/Mod/Fem/InitGui.py index f6086a0734..f32ec68677 100644 --- a/src/Mod/Fem/InitGui.py +++ b/src/Mod/Fem/InitGui.py @@ -71,6 +71,7 @@ class FemWorkbench(Workbench): import Fem import FemGui import femcommands.commands + # dummy usage to get flake8 and lgtm quiet False if Fem.__name__ else True False if FemGui.__name__ else True diff --git a/src/Mod/Fem/ObjectsFem.py b/src/Mod/Fem/ObjectsFem.py index 40f73d3945..a35b866892 100644 --- a/src/Mod/Fem/ObjectsFem.py +++ b/src/Mod/Fem/ObjectsFem.py @@ -46,10 +46,7 @@ import FreeCAD # ********* analysis objects ********************************************************************* -def makeAnalysis( - doc, - name="Analysis" -): +def makeAnalysis(doc, name="Analysis"): """makeAnalysis(document, [name]): makes a Fem Analysis object""" obj = doc.addObject("Fem::FemAnalysis", name) @@ -57,343 +54,281 @@ def makeAnalysis( # ********* constant objects ********************************************************************* -def makeConstantVacuumPermittivity( - doc, - name="ConstantVacuumPermittivity" -): +def makeConstantVacuumPermittivity(doc, name="ConstantVacuumPermittivity"): """makeConstantVacuumPermittivity(document, [name]): makes a Fem ConstantVacuumPermittivity object""" obj = doc.addObject("Fem::ConstraintPython", name) from femobjects import constant_vacuumpermittivity + constant_vacuumpermittivity.ConstantVacuumPermittivity(obj) if FreeCAD.GuiUp: from femviewprovider import view_constant_vacuumpermittivity + view_constant_vacuumpermittivity.VPConstantVacuumPermittivity(obj.ViewObject) return obj # ********* constraint objects ******************************************************************* -def makeConstraintBearing( - doc, - name="ConstraintBearing" -): +def makeConstraintBearing(doc, name="ConstraintBearing"): """makeConstraintBearing(document, [name]): makes a Fem ConstraintBearing object""" obj = doc.addObject("Fem::ConstraintBearing", name) return obj -def makeConstraintBodyHeatSource( - doc, - name="ConstraintBodyHeatSource" -): +def makeConstraintBodyHeatSource(doc, name="ConstraintBodyHeatSource"): """makeConstraintBodyHeatSource(document, [name]): makes a Fem ConstraintBodyHeatSource object""" obj = doc.addObject("Fem::ConstraintPython", name) from femobjects import constraint_bodyheatsource + constraint_bodyheatsource.ConstraintBodyHeatSource(obj) if FreeCAD.GuiUp: from femviewprovider import view_constraint_bodyheatsource as viewprov + viewprov.VPConstraintBodyHeatSource(obj.ViewObject) return obj -def makeConstraintCentrif( - doc, - name="ConstraintCentrif" -): +def makeConstraintCentrif(doc, name="ConstraintCentrif"): """makeConstraintCentrif(document, [name]): creates a centrif object to define centrifugal body load constraint""" obj = doc.addObject("Fem::ConstraintPython", name) from femobjects import constraint_centrif + constraint_centrif.ConstraintCentrif(obj) if FreeCAD.GuiUp: from femviewprovider import view_constraint_centrif + view_constraint_centrif.VPConstraintCentrif(obj.ViewObject) return obj -def makeConstraintCurrentDensity( - doc, - name="ConstraintCurrentDensity" -): +def makeConstraintCurrentDensity(doc, name="ConstraintCurrentDensity"): """makeConstraintCurrentDensity(document, [name]): makes a Fem CurrentDensity object""" obj = doc.addObject("Fem::ConstraintPython", name) from femobjects import constraint_currentdensity + constraint_currentdensity.ConstraintCurrentDensity(obj) if FreeCAD.GuiUp: from femviewprovider import view_constraint_currentdensity + view_constraint_currentdensity.VPConstraintCurrentDensity(obj.ViewObject) return obj -def makeConstraintContact( - doc, - name="ConstraintContact" -): +def makeConstraintContact(doc, name="ConstraintContact"): """makeConstraintContact(document, [name]): makes a Fem ConstraintContact object""" obj = doc.addObject("Fem::ConstraintContact", name) return obj -def makeConstraintDisplacement( - doc, - name="ConstraintDisplacement" -): +def makeConstraintDisplacement(doc, name="ConstraintDisplacement"): """makeConstraintDisplacement(document, [name]): makes a Fem ConstraintDisplacement object""" obj = doc.addObject("Fem::ConstraintDisplacement", name) return obj -def makeConstraintElectrostaticPotential( - doc, - name="ConstraintElectrostaticPotential" -): +def makeConstraintElectrostaticPotential(doc, name="ConstraintElectrostaticPotential"): """makeConstraintElectrostaticPotential(document, [name]): makes a Fem ElectrostaticPotential object""" obj = doc.addObject("Fem::ConstraintPython", name) from femobjects import constraint_electrostaticpotential + constraint_electrostaticpotential.ConstraintElectrostaticPotential(obj) if FreeCAD.GuiUp: from femviewprovider import view_constraint_electrostaticpotential + view_constraint_electrostaticpotential.VPConstraintElectroStaticPotential(obj.ViewObject) return obj -def makeConstraintFixed( - doc, - name="ConstraintFixed" -): +def makeConstraintFixed(doc, name="ConstraintFixed"): """makeConstraintFixed(document, [name]): makes a Fem ConstraintFixed object""" obj = doc.addObject("Fem::ConstraintFixed", name) return obj -def makeConstraintRigidBody( - doc, - name="ConstraintRigidBody" -): +def makeConstraintRigidBody(doc, name="ConstraintRigidBody"): """makeConstraintRigidBody(document, [name]): makes a Fem ConstraintRigidBody object""" obj = doc.addObject("Fem::ConstraintRigidBody", name) return obj -def makeConstraintFlowVelocity( - doc, - name="ConstraintFlowVelocity" -): +def makeConstraintFlowVelocity(doc, name="ConstraintFlowVelocity"): """makeConstraintFlowVelocity(document, [name]): makes a Fem ConstraintFlowVelocity object""" obj = doc.addObject("Fem::ConstraintPython", name) from femobjects import constraint_flowvelocity + constraint_flowvelocity.ConstraintFlowVelocity(obj) if FreeCAD.GuiUp: from femviewprovider import view_constraint_flowvelocity + view_constraint_flowvelocity.VPConstraintFlowVelocity(obj.ViewObject) return obj -def makeConstraintFluidBoundary( - doc, - name="ConstraintFluidBoundary" -): +def makeConstraintFluidBoundary(doc, name="ConstraintFluidBoundary"): """makeConstraintFluidBoundary(document, name): makes a Fem ConstraintFluidBoundary object""" obj = doc.addObject("Fem::ConstraintFluidBoundary", name) return obj -def makeConstraintForce( - doc, - name="ConstraintForce" -): +def makeConstraintForce(doc, name="ConstraintForce"): """makeConstraintForce(document, [name]): makes a Fem ConstraintForce object""" obj = doc.addObject("Fem::ConstraintForce", name) return obj -def makeConstraintGear( - doc, - name="ConstraintGear" -): +def makeConstraintGear(doc, name="ConstraintGear"): """makeConstraintGear(document, [name]): makes a Fem ConstraintGear object""" obj = doc.addObject("Fem::ConstraintGear", name) return obj -def makeConstraintHeatflux( - doc, - name="ConstraintHeatflux" -): +def makeConstraintHeatflux(doc, name="ConstraintHeatflux"): """makeConstraintHeatflux(document, [name]): makes a Fem ConstraintHeatflux object""" obj = doc.addObject("Fem::ConstraintHeatflux", name) return obj -def makeConstraintInitialFlowVelocity( - doc, - name="ConstraintInitialFlowVelocity" -): +def makeConstraintInitialFlowVelocity(doc, name="ConstraintInitialFlowVelocity"): """makeConstraintInitialFlowVelocity(document, [name]): makes a Fem ConstraintInitialFlowVelocity object""" obj = doc.addObject("Fem::ConstraintPython", name) from femobjects import constraint_initialflowvelocity + constraint_initialflowvelocity.ConstraintInitialFlowVelocity(obj) if FreeCAD.GuiUp: from femviewprovider import view_constraint_initialflowvelocity + view_constraint_initialflowvelocity.VPConstraintInitialFlowVelocity(obj.ViewObject) return obj -def makeConstraintInitialPressure( - doc, - name="ConstraintInitialPressure" -): +def makeConstraintInitialPressure(doc, name="ConstraintInitialPressure"): """makeConstraintInitialPressure(document, [name]): makes a Fem ConstraintInitialPressure object""" obj = doc.addObject("Fem::ConstraintPython", name) from femobjects import constraint_initialpressure + constraint_initialpressure.ConstraintInitialPressure(obj) if FreeCAD.GuiUp: from femviewprovider import view_constraint_initialpressure + view_constraint_initialpressure.VPConstraintInitialPressure(obj.ViewObject) return obj -def makeConstraintInitialTemperature( - doc, - name="ConstraintInitialTemperature" -): +def makeConstraintInitialTemperature(doc, name="ConstraintInitialTemperature"): """makeConstraintInitialTemperature(document, name): makes a Fem ConstraintInitialTemperature object""" obj = doc.addObject("Fem::ConstraintInitialTemperature", name) return obj -def makeConstraintMagnetization( - doc, - name="ConstraintMagnetization" -): +def makeConstraintMagnetization(doc, name="ConstraintMagnetization"): """makeConstraintMagnetization(document, [name]): makes a Fem Magnetization object""" obj = doc.addObject("Fem::ConstraintPython", name) from femobjects import constraint_magnetization + constraint_magnetization.ConstraintMagnetization(obj) if FreeCAD.GuiUp: from femviewprovider import view_constraint_magnetization + view_constraint_magnetization.VPConstraintMagnetization(obj.ViewObject) return obj -def makeConstraintPlaneRotation( - doc, - name="ConstraintPlaneRotation" -): +def makeConstraintPlaneRotation(doc, name="ConstraintPlaneRotation"): """makeConstraintPlaneRotation(document, [name]): makes a Fem ConstraintPlaneRotation object""" obj = doc.addObject("Fem::ConstraintPlaneRotation", name) return obj -def makeConstraintPressure( - doc, - name="ConstraintPressure" -): +def makeConstraintPressure(doc, name="ConstraintPressure"): """makeConstraintPressure(document, [name]): makes a Fem ConstraintPressure object""" obj = doc.addObject("Fem::ConstraintPressure", name) return obj -def makeConstraintPulley( - doc, - name="ConstraintPulley" -): +def makeConstraintPulley(doc, name="ConstraintPulley"): """makeConstraintPulley(document, [name]): makes a Fem ConstraintPulley object""" obj = doc.addObject("Fem::ConstraintPulley", name) return obj -def makeConstraintSelfWeight( - doc, - name="ConstraintSelfWeight" -): +def makeConstraintSelfWeight(doc, name="ConstraintSelfWeight"): """makeConstraintSelfWeight(document, [name]): creates a self weight object to define a gravity load""" obj = doc.addObject("Fem::ConstraintPython", name) from femobjects import constraint_selfweight + constraint_selfweight.ConstraintSelfWeight(obj) if FreeCAD.GuiUp: from femviewprovider import view_constraint_selfweight - view_constraint_selfweight.VPConstraintSelfWeight( - obj.ViewObject - ) + + view_constraint_selfweight.VPConstraintSelfWeight(obj.ViewObject) return obj -def makeConstraintTemperature( - doc, - name="ConstraintTemperature" -): +def makeConstraintTemperature(doc, name="ConstraintTemperature"): """makeConstraintTemperature(document, [name]): makes a Fem ConstraintTemperature object""" obj = doc.addObject("Fem::ConstraintTemperature", name) return obj -def makeConstraintTie( - doc, - name="ConstraintTie" -): +def makeConstraintTie(doc, name="ConstraintTie"): """makeConstraintTie(document, [name]): creates a tie object to define bonded faces constraint""" obj = doc.addObject("Fem::ConstraintPython", name) from femobjects import constraint_tie + constraint_tie.ConstraintTie(obj) if FreeCAD.GuiUp: from femviewprovider import view_constraint_tie + view_constraint_tie.VPConstraintTie(obj.ViewObject) return obj -def makeConstraintTransform( - doc, - name="ConstraintTransform" -): +def makeConstraintTransform(doc, name="ConstraintTransform"): """makeConstraintTransform(document, [name]): makes a Fem ConstraintTransform object""" obj = doc.addObject("Fem::ConstraintTransform", name) return obj -def makeConstraintSectionPrint( - doc, - name="ConstraintSectionPrint" -): +def makeConstraintSectionPrint(doc, name="ConstraintSectionPrint"): """makeConstraintSectionPrint(document, [name]): creates a section print object to evaluate forces and moments of defined face""" obj = doc.addObject("Fem::ConstraintPython", name) from femobjects import constraint_sectionprint + constraint_sectionprint.ConstraintSectionPrint(obj) if FreeCAD.GuiUp: from femviewprovider import view_constraint_sectionprint + view_constraint_sectionprint.VPConstraintSectionPrint(obj.ViewObject) return obj -def makeConstraintSpring( - doc, - name="ConstraintSpring" -): +def makeConstraintSpring(doc, name="ConstraintSpring"): """makeConstraintSpring(document, [name]): makes a Fem ConstraintSpring object""" obj = doc.addObject("Fem::ConstraintSpring", name) @@ -401,32 +336,28 @@ def makeConstraintSpring( # ********* element definition objects *********************************************************** -def makeElementFluid1D( - doc, - name="ElementFluid1D" -): +def makeElementFluid1D(doc, name="ElementFluid1D"): """makeElementFluid1D(document, [name]): creates a 1D fluid element object to define 1D flow""" obj = doc.addObject("Fem::FeaturePython", name) from femobjects import element_fluid1D + element_fluid1D.ElementFluid1D(obj) if FreeCAD.GuiUp: from femviewprovider import view_element_fluid1D + view_element_fluid1D.VPElementFluid1D(obj.ViewObject) return obj def makeElementGeometry1D( - doc, - sectiontype="Rectangular", - width=10.0, - height=25.0, - name="ElementGeometry1D" + doc, sectiontype="Rectangular", width=10.0, height=25.0, name="ElementGeometry1D" ): """makeElementGeometry1D(document, [width], [height], [name]): creates a 1D geometry element object to define a cross section""" obj = doc.addObject("Fem::FeaturePython", name) from femobjects import element_geometry1D + element_geometry1D.ElementGeometry1D(obj) sec_types = element_geometry1D.ElementGeometry1D.known_beam_types if sectiontype not in sec_types: @@ -441,119 +372,107 @@ def makeElementGeometry1D( obj.PipeThickness = width if FreeCAD.GuiUp: from femviewprovider import view_element_geometry1D + view_element_geometry1D.VPElementGeometry1D(obj.ViewObject) return obj -def makeElementGeometry2D( - doc, - thickness=1.0, - name="ElementGeometry2D" -): +def makeElementGeometry2D(doc, thickness=1.0, name="ElementGeometry2D"): """makeElementGeometry2D(document, [thickness], [name]): creates a 2D geometry element object to define a plate thickness""" obj = doc.addObject("Fem::FeaturePython", name) from femobjects import element_geometry2D + element_geometry2D.ElementGeometry2D(obj) obj.Thickness = thickness if FreeCAD.GuiUp: from femviewprovider import view_element_geometry2D + view_element_geometry2D.VPElementGeometry2D(obj.ViewObject) return obj -def makeElementRotation1D( - doc, - name="ElementRotation1D" -): +def makeElementRotation1D(doc, name="ElementRotation1D"): """makeElementRotation1D(document, [name]): creates a 1D geometry rotation element object to rotate a 1D cross section""" obj = doc.addObject("Fem::FeaturePython", name) from femobjects import element_rotation1D + element_rotation1D.ElementRotation1D(obj) if FreeCAD.GuiUp: from femviewprovider import view_element_rotation1D + view_element_rotation1D.VPElementRotation1D(obj.ViewObject) return obj # ********* material objects ********************************************************************* -def makeMaterialFluid( - doc, - name="MaterialFluid" -): +def makeMaterialFluid(doc, name="MaterialFluid"): """makeMaterialFluid(document, [name]): makes a FEM Material for fluid""" obj = doc.addObject("App::MaterialObjectPython", name) from femobjects import material_common + material_common.MaterialCommon(obj) obj.Category = "Fluid" if FreeCAD.GuiUp: from femviewprovider import view_material_common + view_material_common.VPMaterialCommon(obj.ViewObject) return obj -def makeMaterialMechanicalNonlinear( - doc, - base_material, - name="MaterialMechanicalNonlinear" -): +def makeMaterialMechanicalNonlinear(doc, base_material, name="MaterialMechanicalNonlinear"): """makeMaterialMechanicalNonlinear(document, base_material, [name]): creates a nonlinear material object""" obj = doc.addObject("Fem::FeaturePython", name) from femobjects import material_mechanicalnonlinear + material_mechanicalnonlinear.MaterialMechanicalNonlinear(obj) obj.LinearBaseMaterial = base_material if FreeCAD.GuiUp: from femviewprovider import view_material_mechanicalnonlinear - view_material_mechanicalnonlinear.VPMaterialMechanicalNonlinear( - obj.ViewObject - ) + + view_material_mechanicalnonlinear.VPMaterialMechanicalNonlinear(obj.ViewObject) return obj -def makeMaterialReinforced( - doc, - name="MaterialReinforced" -): +def makeMaterialReinforced(doc, name="MaterialReinforced"): """makeMaterialReinforced(document, [matrix_material], [reinforcement_material], [name]): creates a reinforced material object""" obj = doc.addObject("App::MaterialObjectPython", name) from femobjects import material_reinforced + material_reinforced.MaterialReinforced(obj) if FreeCAD.GuiUp: from femviewprovider import view_material_reinforced + view_material_reinforced.VPMaterialReinforced(obj.ViewObject) return obj -def makeMaterialSolid( - doc, - name="MaterialSolid" -): +def makeMaterialSolid(doc, name="MaterialSolid"): """makeMaterialSolid(document, [name]): makes a FEM Material for solid""" obj = doc.addObject("App::MaterialObjectPython", name) from femobjects import material_common + material_common.MaterialCommon(obj) obj.Category = "Solid" if FreeCAD.GuiUp: from femviewprovider import view_material_common + view_material_common.VPMaterialCommon(obj.ViewObject) return obj # ********* mesh objects ************************************************************************* -def makeMeshBoundaryLayer( - doc, - base_mesh, - name="MeshBoundaryLayer" -): +def makeMeshBoundaryLayer(doc, base_mesh, name="MeshBoundaryLayer"): """makeMeshBoundaryLayer(document, base_mesh, [name]): creates a FEM mesh BoundaryLayer object to define boundary layer properties""" obj = doc.addObject("Fem::FeaturePython", name) from femobjects import mesh_boundarylayer + mesh_boundarylayer.MeshBoundaryLayer(obj) # obj.BaseMesh = base_mesh # App::PropertyLinkList does not support append @@ -563,35 +482,32 @@ def makeMeshBoundaryLayer( base_mesh.MeshBoundaryLayerList = tmplist if FreeCAD.GuiUp: from femviewprovider import view_mesh_boundarylayer + view_mesh_boundarylayer.VPMeshBoundaryLayer(obj.ViewObject) return obj -def makeMeshGmsh( - doc, - name="MeshGmsh" -): +def makeMeshGmsh(doc, name="MeshGmsh"): """makeMeshGmsh(document, [name]): makes a Gmsh FEM mesh object""" obj = doc.addObject("Fem::FemMeshObjectPython", name) from femobjects import mesh_gmsh + mesh_gmsh.MeshGmsh(obj) if FreeCAD.GuiUp: from femviewprovider import view_mesh_gmsh + view_mesh_gmsh.VPMeshGmsh(obj.ViewObject) return obj -def makeMeshGroup( - doc, - base_mesh, - use_label=False, - name="MeshGroup" -): +def makeMeshGroup(doc, base_mesh, use_label=False, name="MeshGroup"): """makeMeshGroup(document, base_mesh, [use_label], [name]): - creates a FEM mesh refinement object to define properties for a region of a FEM mesh""" + creates a FEM mesh refinement object to define properties for a region of a FEM mesh + """ obj = doc.addObject("Fem::FeaturePython", name) from femobjects import mesh_group + mesh_group.MeshGroup(obj) obj.UseLabel = use_label # obj.BaseMesh = base_mesh @@ -602,30 +518,25 @@ def makeMeshGroup( base_mesh.MeshGroupList = tmplist if FreeCAD.GuiUp: from femviewprovider import view_mesh_group + view_mesh_group.VPMeshGroup(obj.ViewObject) return obj -def makeMeshNetgen( - doc, - name="MeshNetgen" -): +def makeMeshNetgen(doc, name="MeshNetgen"): """makeMeshNetgen(document, [name]): makes a Fem MeshShapeNetgenObject object""" obj = doc.addObject("Fem::FemMeshShapeNetgenObject", name) return obj -def makeMeshRegion( - doc, - base_mesh, - element_length=0.0, - name="MeshRegion" -): +def makeMeshRegion(doc, base_mesh, element_length=0.0, name="MeshRegion"): """makeMeshRegion(document, base_mesh, [element_length], [name]): - creates a FEM mesh refinement object to define properties for a refinement of a FEM mesh""" + creates a FEM mesh refinement object to define properties for a refinement of a FEM mesh + """ obj = doc.addObject("Fem::FeaturePython", name) from femobjects import mesh_region + mesh_region.MeshRegion(obj) obj.CharacteristicLength = element_length # obj.BaseMesh = base_mesh @@ -636,45 +547,40 @@ def makeMeshRegion( base_mesh.MeshRegionList = tmplist if FreeCAD.GuiUp: from femviewprovider import view_mesh_region + view_mesh_region.VPMeshRegion(obj.ViewObject) return obj -def makeMeshResult( - doc, - name="MeshResult" -): +def makeMeshResult(doc, name="MeshResult"): """makeMeshResult(document, name): makes a Fem MeshResult object""" obj = doc.addObject("Fem::FemMeshObjectPython", name) from femobjects import mesh_result + mesh_result.MeshResult(obj) if FreeCAD.GuiUp: from femviewprovider import view_mesh_result + view_mesh_result.VPFemMeshResult(obj.ViewObject) return obj # ********* post processing objects ************************************************************** -def makeResultMechanical( - doc, - name="ResultMechanical" -): +def makeResultMechanical(doc, name="ResultMechanical"): """makeResultMechanical(document, [name]): creates a mechanical result object to hold FEM results""" obj = doc.addObject("Fem::FemResultObjectPython", name) from femobjects import result_mechanical + result_mechanical.ResultMechanical(obj) if FreeCAD.GuiUp: from femviewprovider import view_result_mechanical + view_result_mechanical.VPResultMechanical(obj.ViewObject) return obj -def makePostVtkFilterClipRegion( - doc, - base_vtk_result, - name="VtkFilterClipRegion" -): +def makePostVtkFilterClipRegion(doc, base_vtk_result, name="VtkFilterClipRegion"): """makePostVtkFilterClipRegion(document, base_vtk_result, [name]): creates a FEM post processing region clip filter object (vtk based)""" obj = doc.addObject("Fem::FemPostClipFilter", name) @@ -685,11 +591,7 @@ def makePostVtkFilterClipRegion( return obj -def makePostVtkFilterClipScalar( - doc, - base_vtk_result, - name="VtkFilterClipScalar" -): +def makePostVtkFilterClipScalar(doc, base_vtk_result, name="VtkFilterClipScalar"): """makePostVtkFilterClipScalar(document, base_vtk_result, [name]): creates a FEM post processing scalar clip filter object (vtk based)""" obj = doc.addObject("Fem::FemPostScalarClipFilter", name) @@ -700,11 +602,7 @@ def makePostVtkFilterClipScalar( return obj -def makePostVtkFilterCutFunction( - doc, - base_vtk_result, - name="VtkFilterCutFunction" -): +def makePostVtkFilterCutFunction(doc, base_vtk_result, name="VtkFilterCutFunction"): """makePostVtkFilterCutFunction(document, base_vtk_result, [name]): creates a FEM post processing cut function filter object (vtk based)""" obj = doc.addObject("Fem::FemPostClipFilter", name) @@ -715,11 +613,7 @@ def makePostVtkFilterCutFunction( return obj -def makePostVtkFilterWarp( - doc, - base_vtk_result, - name="VtkFilterWarp" -): +def makePostVtkFilterWarp(doc, base_vtk_result, name="VtkFilterWarp"): """makePostVtkFilterWarp(document, base_vtk_result, [name]): creates a FEM post processing warp filter object (vtk based)""" obj = doc.addObject("Fem::FemPostWarpVectorFilter", name) @@ -730,11 +624,7 @@ def makePostVtkFilterWarp( return obj -def makePostVtkFilterContours( - doc, - base_vtk_result, - name="VtkFilterContours" -): +def makePostVtkFilterContours(doc, base_vtk_result, name="VtkFilterContours"): """makePostVtkFilterContours(document, base_vtk_result, [name]): creates a FEM post processing contours filter object (vtk based)""" obj = doc.addObject("Fem::FemPostContoursFilter", name) @@ -745,11 +635,7 @@ def makePostVtkFilterContours( return obj -def makePostVtkResult( - doc, - base_result, - name="VtkResult" -): +def makePostVtkResult(doc, base_result, name="VtkResult"): """makePostVtkResult(document, base_result, [name]): creates a FEM post processing result object (vtk based) to hold FEM results""" Pipeline_Name = "Pipeline_" + name @@ -763,187 +649,151 @@ def makePostVtkResult( # ********* solver objects *********************************************************************** -def makeEquationDeformation( - doc, - base_solver=None, - name="Deformation" -): +def makeEquationDeformation(doc, base_solver=None, name="Deformation"): """makeEquationDeformation(document, [base_solver], [name]): creates a FEM deformation (nonlinear elasticity) equation for a solver""" from femsolver.elmer.equations import deformation + obj = deformation.create(doc, name) if base_solver: base_solver.addObject(obj) return obj -def makeEquationElasticity( - doc, - base_solver=None, - name="Elasticity" -): +def makeEquationElasticity(doc, base_solver=None, name="Elasticity"): """makeEquationElasticity(document, [base_solver], [name]): creates a FEM elasticity equation for a solver""" from femsolver.elmer.equations import elasticity + obj = elasticity.create(doc, name) if base_solver: base_solver.addObject(obj) return obj -def makeEquationElectricforce( - doc, - base_solver=None, - name="Electricforce" -): +def makeEquationElectricforce(doc, base_solver=None, name="Electricforce"): """makeEquationElectricforce(document, [base_solver], [name]): creates a FEM Electricforce equation for a solver""" from femsolver.elmer.equations import electricforce + obj = electricforce.create(doc, name) if base_solver: base_solver.addObject(obj) return obj -def makeEquationElectrostatic( - doc, - base_solver=None, - name="Electrostatic" -): +def makeEquationElectrostatic(doc, base_solver=None, name="Electrostatic"): """makeEquationElectrostatic(document, [base_solver], [name]): creates a FEM electrostatic equation for a solver""" from femsolver.elmer.equations import electrostatic + obj = electrostatic.create(doc, name) if base_solver: base_solver.addObject(obj) return obj -def makeEquationFlow( - doc, - base_solver=None, - name="Flow" -): +def makeEquationFlow(doc, base_solver=None, name="Flow"): """makeEquationFlow(document, [base_solver], [name]): creates a FEM flow equation for a solver""" from femsolver.elmer.equations import flow + obj = flow.create(doc, name) if base_solver: base_solver.addObject(obj) return obj -def makeEquationFlux( - doc, - base_solver=None, - name="Flux" -): +def makeEquationFlux(doc, base_solver=None, name="Flux"): """makeEquationFlux(document, [base_solver], [name]): creates a FEM flux equation for a solver""" from femsolver.elmer.equations import flux + obj = flux.create(doc, name) if base_solver: base_solver.addObject(obj) return obj -def makeEquationHeat( - doc, - base_solver=None, - name="Heat" -): +def makeEquationHeat(doc, base_solver=None, name="Heat"): """makeEquationHeat(document, [base_solver], [name]): creates a FEM heat equation for a solver""" from femsolver.elmer.equations import heat + obj = heat.create(doc, name) if base_solver: base_solver.addObject(obj) return obj -def makeEquationMagnetodynamic( - doc, - base_solver=None, - name="Magnetodynamic" -): +def makeEquationMagnetodynamic(doc, base_solver=None, name="Magnetodynamic"): """makeEquationMagnetodynamic(document, [base_solver], [name]): creates a FEM magnetodynamic equation for a solver""" from femsolver.elmer.equations import magnetodynamic + obj = magnetodynamic.create(doc, name) if base_solver: base_solver.addObject(obj) return obj -def makeEquationMagnetodynamic2D( - doc, - base_solver=None, - name="Magnetodynamic2D" -): +def makeEquationMagnetodynamic2D(doc, base_solver=None, name="Magnetodynamic2D"): """makeEquationMagnetodynamic2D(document, [base_solver], [name]): creates a FEM magnetodynamic2D equation for a solver""" from femsolver.elmer.equations import magnetodynamic2D + obj = magnetodynamic2D.create(doc, name) if base_solver: base_solver.addObject(obj) return obj -def makeSolverCalculiXCcxTools( - doc, - name="SolverCcxTools" -): +def makeSolverCalculiXCcxTools(doc, name="SolverCcxTools"): """makeSolverCalculiXCcxTools(document, [name]): makes a Calculix solver object for the ccx tools module""" obj = doc.addObject("Fem::FemSolverObjectPython", name) from femobjects import solver_ccxtools + solver_ccxtools.SolverCcxTools(obj) if FreeCAD.GuiUp: from femviewprovider import view_solver_ccxtools + view_solver_ccxtools.VPSolverCcxTools(obj.ViewObject) return obj -def makeSolverCalculix( - doc, - name="SolverCalculix" -): +def makeSolverCalculix(doc, name="SolverCalculix"): """makeSolverCalculix(document, [name]): makes a Calculix solver object""" import femsolver.calculix.solver + obj = femsolver.calculix.solver.create(doc, name) return obj -def makeSolverElmer( - doc, - name="SolverElmer" -): +def makeSolverElmer(doc, name="SolverElmer"): """makeSolverElmer(document, [name]): makes a Elmer solver object""" import femsolver.elmer.solver + obj = femsolver.elmer.solver.create(doc, name) return obj -def makeSolverMystran( - doc, - name="SolverMystran" -): +def makeSolverMystran(doc, name="SolverMystran"): """makeSolverMystran(document, [name]): makes a Mystran solver object""" import femsolver.mystran.solver + obj = femsolver.mystran.solver.create(doc, name) return obj -def makeSolverZ88( - doc, - name="SolverZ88" -): +def makeSolverZ88(doc, name="SolverZ88"): """makeSolverZ88(document, [name]): makes a Z88 solver object""" import femsolver.z88.solver + obj = femsolver.z88.solver.create(doc, name) return obj diff --git a/src/Mod/Fem/coding_conventions.md b/src/Mod/Fem/coding_conventions.md index c5d01bcdf7..b706b25aea 100644 --- a/src/Mod/Fem/coding_conventions.md +++ b/src/Mod/Fem/coding_conventions.md @@ -4,7 +4,7 @@ These coding rules apply to FEM module code only. Other modules or the base syst ## Spelling - Be mindful of spelling. Spell checks are quite often neglected. -- Utilize [codespell](https://github.com/codespell-project/codespell) to discover and quickly correct spelling errors. +- Utilize [codespell](https://github.com/codespell-project/codespell) to discover and quickly correct spelling errors. ```bash # Find typos @@ -14,9 +14,9 @@ These coding rules apply to FEM module code only. Other modules or the base syst codespell -i 3 -w -S *.ts -S *.dyn -S *.svg -L childs,dof,dum,freez,methode,nd,normaly,programm,som,uint,vertexes,inout src/Mod/Fem/ ``` - **Notes:** - 1) We recommend running the dev version as it uses the most up to date typo dictionaries. - 2) To find the most amount of typos we recommend running a quick `pip install --upgrade` + **Notes:** + 1) We recommend running the dev version as it uses the most up to date typo dictionaries. + 2) To find the most amount of typos we recommend running a quick `pip install --upgrade` See the [codespell docs](https://github.com/codespell-project/codespell#updating) for more info. @@ -68,7 +68,7 @@ These coding rules apply to FEM module code only. Other modules or the base syst - One empty line - relative imports - One empty line - - FreeCAD Gui imports: + - FreeCAD Gui imports: - The import of Gui modules should be guarded by a 'if FreeCAD.GuiUp:' - On Gui only modules the guard is not needed - Same as above but without a empty line @@ -99,7 +99,7 @@ find src/Mod/Fem/ -name "*\.py" | xargs -I [] flake8 --ignore=E266,W503 --max-li - print() vs. FreeCAD.Console.PrintMessage() - `FreeCAD.Console.PrintMessage()` or Log or Error should be used - `print()` should be used for debugging only - - [forum topic](https://forum.freecad.org/viewtopic.php?f=10&t=39110) + - [forum topic](https://forum.freecad.org/viewtopic.php?f=10&t=39110) - BTW: Console prints need a new line where as print does not need one - type checking: - do not use hasattr(obj, "Proxy") and obj.Proxy.Type @@ -114,7 +114,7 @@ find src/Mod/Fem/ -name "*\.py" | xargs -I [] flake8 --ignore=E266,W503 --max-li - FreeCAD Python console - in code examples which will be copied in FreeCAD Python console - it is common to use App.ActiveDocument.some_obj or method - + ### Documenting Python style is preferred over Doxygen style - see `ccx` tools module in fem tools package diff --git a/src/Mod/Fem/femcommands/commands.py b/src/Mod/Fem/femcommands/commands.py index b047e1b480..b84339155c 100644 --- a/src/Mod/Fem/femcommands/commands.py +++ b/src/Mod/Fem/femcommands/commands.py @@ -53,12 +53,11 @@ class _Analysis(CommandManager): "The FEM_Analysis command definition" def __init__(self): - super(_Analysis, self).__init__() + super().__init__() self.menutext = Qt.QT_TRANSLATE_NOOP("FEM_Analysis", "Analysis container") self.accel = "S, A" self.tooltip = Qt.QT_TRANSLATE_NOOP( - "FEM_Analysis", - "Creates an analysis container with default solver" + "FEM_Analysis", "Creates an analysis container with default solver" ) self.is_active = "with_document" @@ -72,8 +71,7 @@ class _Analysis(CommandManager): if get_default_solver() != "None": FreeCAD.ActiveDocument.openTransaction("Create default solver") FreeCADGui.doCommand( - "ObjectsFem.makeSolver{}(FreeCAD.ActiveDocument)" - .format(get_default_solver()) + f"ObjectsFem.makeSolver{get_default_solver()}(FreeCAD.ActiveDocument)" ) FreeCADGui.doCommand( "FemGui.getActiveAnalysis().addObject(FreeCAD.ActiveDocument.ActiveObject)" @@ -90,14 +88,10 @@ class _ClippingPlaneAdd(CommandManager): "The FEM_ClippingPlaneAdd command definition" def __init__(self): - super(_ClippingPlaneAdd, self).__init__() - self.menutext = Qt.QT_TRANSLATE_NOOP( - "FEM_ClippingPlaneAdd", - "Clipping plane on face" - ) + super().__init__() + self.menutext = Qt.QT_TRANSLATE_NOOP("FEM_ClippingPlaneAdd", "Clipping plane on face") self.tooltip = Qt.QT_TRANSLATE_NOOP( - "FEM_ClippingPlaneAdd", - "Add a clipping plane on a selected face" + "FEM_ClippingPlaneAdd", "Add a clipping plane on a selected face" ) self.is_active = "with_document" @@ -109,13 +103,15 @@ class _ClippingPlaneAdd(CommandManager): overallboundbox = getBoundBoxOfAllDocumentShapes(FreeCAD.ActiveDocument) # print(overallboundbox) if overallboundbox: - min_bb_length = (min(set([ - overallboundbox.XLength, - overallboundbox.YLength, - overallboundbox.ZLength - ]))) + min_bb_length = min( + { + overallboundbox.XLength, + overallboundbox.YLength, + overallboundbox.ZLength, + } + ) else: - min_bb_length = 10. # default + min_bb_length = 10.0 # default dbox = min_bb_length * 0.2 @@ -130,11 +126,12 @@ class _ClippingPlaneAdd(CommandManager): coin_normal_vector = coin.SbVec3f(-f_normal.x, -f_normal.y, -f_normal.z) coin_bound_box = coin.SbBox3f( - f_CoM.x - dbox, f_CoM.y - dbox, + f_CoM.x - dbox, + f_CoM.y - dbox, f_CoM.z - dbox * 0.15, f_CoM.x + dbox, f_CoM.y + dbox, - f_CoM.z + dbox * 0.15 + f_CoM.z + dbox * 0.15, ) clip_plane = coin.SoClipPlaneManip() clip_plane.setValue(coin_bound_box, coin_normal_vector, 1) @@ -145,14 +142,12 @@ class _ClippingPlaneRemoveAll(CommandManager): "The FEM_ClippingPlaneRemoveAll command definition" def __init__(self): - super(_ClippingPlaneRemoveAll, self).__init__() + super().__init__() self.menutext = Qt.QT_TRANSLATE_NOOP( - "FEM_ClippingPlaneRemoveAll", - "Remove all clipping planes" + "FEM_ClippingPlaneRemoveAll", "Remove all clipping planes" ) self.tooltip = Qt.QT_TRANSLATE_NOOP( - "FEM_ClippingPlaneRemoveAll", - "Removes all clipping planes" + "FEM_ClippingPlaneRemoveAll", "Removes all clipping planes" ) self.is_active = "with_document" @@ -170,15 +165,14 @@ class _ConstantVacuumPermittivity(CommandManager): "The FEM_ConstantVacuumPermittivity command definition" def __init__(self): - super(_ConstantVacuumPermittivity, self).__init__() + super().__init__() self.pixmap = "fem-solver-analysis-thermomechanical.svg" self.menutext = Qt.QT_TRANSLATE_NOOP( - "FEM_ConstantVacuumPermittivity", - "Constant vacuum permittivity" + "FEM_ConstantVacuumPermittivity", "Constant vacuum permittivity" ) self.tooltip = Qt.QT_TRANSLATE_NOOP( "FEM_ConstantVacuumPermittivity", - "Creates a FEM constant vacuum permittivity to overwrite standard value" + "Creates a FEM constant vacuum permittivity to overwrite standard value", ) self.is_active = "with_document" self.is_active = "with_analysis" @@ -189,15 +183,11 @@ class _ConstraintBodyHeatSource(CommandManager): "The FEM_ConstraintBodyHeatSource command definition" def __init__(self): - super(_ConstraintBodyHeatSource, self).__init__() + super().__init__() self.pixmap = "FEM_ConstraintBodyHeatSource" - self.menutext = Qt.QT_TRANSLATE_NOOP( - "FEM_ConstraintBodyHeatSource", - "Body heat source" - ) + self.menutext = Qt.QT_TRANSLATE_NOOP("FEM_ConstraintBodyHeatSource", "Body heat source") self.tooltip = Qt.QT_TRANSLATE_NOOP( - "FEM_ConstraintBodyHeatSource", - "Creates a body heat source" + "FEM_ConstraintBodyHeatSource", "Creates a body heat source" ) self.is_active = "with_analysis" self.do_activated = "add_obj_on_gui_set_edit" @@ -207,15 +197,9 @@ class _ConstraintCentrif(CommandManager): "The FEM_ConstraintCentrif command definition" def __init__(self): - super(_ConstraintCentrif, self).__init__() - self.menutext = Qt.QT_TRANSLATE_NOOP( - "FEM_ConstraintCentrif", - "Centrifugal load" - ) - self.tooltip = Qt.QT_TRANSLATE_NOOP( - "FEM_ConstraintCentrif", - "Creates a centrifugal load" - ) + super().__init__() + self.menutext = Qt.QT_TRANSLATE_NOOP("FEM_ConstraintCentrif", "Centrifugal load") + self.tooltip = Qt.QT_TRANSLATE_NOOP("FEM_ConstraintCentrif", "Creates a centrifugal load") self.is_active = "with_analysis" self.do_activated = "add_obj_on_gui_set_edit" @@ -224,15 +208,14 @@ class _ConstraintCurrentDensity(CommandManager): "The FEM_ConstraintCurrentDensity command definition" def __init__(self): - super(_ConstraintCurrentDensity, self).__init__() + super().__init__() self.pixmap = "FEM_ConstraintCurrentDensity" self.menutext = Qt.QT_TRANSLATE_NOOP( - "FEM_ConstraintCurrentDensity", - "Current density boundary condition" + "FEM_ConstraintCurrentDensity", "Current density boundary condition" ) self.tooltip = Qt.QT_TRANSLATE_NOOP( "FEM_ConstraintCurrentDensity", - "Creates a current density boundary condition" + "Creates a current density boundary condition", ) self.is_active = "with_analysis" self.do_activated = "add_obj_on_gui_set_edit" @@ -242,14 +225,14 @@ class _ConstraintElectrostaticPotential(CommandManager): "The FEM_ConstraintElectrostaticPotential command definition" def __init__(self): - super(_ConstraintElectrostaticPotential, self).__init__() + super().__init__() self.menutext = Qt.QT_TRANSLATE_NOOP( "FEM_ConstraintElectrostaticPotential", - "Electrostatic potential boundary condition" + "Electrostatic potential boundary condition", ) self.tooltip = Qt.QT_TRANSLATE_NOOP( "FEM_ConstraintElectrostaticPotential", - "Creates an electrostatic potential boundary condition" + "Creates an electrostatic potential boundary condition", ) self.is_active = "with_analysis" self.do_activated = "add_obj_on_gui_set_edit" @@ -259,14 +242,12 @@ class _ConstraintFlowVelocity(CommandManager): "The FEM_ConstraintFlowVelocity command definition" def __init__(self): - super(_ConstraintFlowVelocity, self).__init__() + super().__init__() self.menutext = Qt.QT_TRANSLATE_NOOP( - "FEM_ConstraintFlowVelocity", - "Flow velocity boundary condition" + "FEM_ConstraintFlowVelocity", "Flow velocity boundary condition" ) self.tooltip = Qt.QT_TRANSLATE_NOOP( - "FEM_ConstraintFlowVelocity", - "Creates a flow velocity boundary condition" + "FEM_ConstraintFlowVelocity", "Creates a flow velocity boundary condition" ) self.is_active = "with_analysis" self.do_activated = "add_obj_on_gui_set_edit" @@ -276,14 +257,13 @@ class _ConstraintInitialFlowVelocity(CommandManager): "The FEM_ConstraintInitialFlowVelocity command definition" def __init__(self): - super(_ConstraintInitialFlowVelocity, self).__init__() + super().__init__() self.menutext = Qt.QT_TRANSLATE_NOOP( - "FEM_ConstraintInitialFlowVelocity", - "Initial flow velocity condition" + "FEM_ConstraintInitialFlowVelocity", "Initial flow velocity condition" ) self.tooltip = Qt.QT_TRANSLATE_NOOP( "FEM_ConstraintInitialFlowVelocity", - "Creates initial flow velocity condition" + "Creates initial flow velocity condition", ) self.is_active = "with_analysis" self.do_activated = "add_obj_on_gui_set_edit" @@ -293,14 +273,12 @@ class _ConstraintInitialPressure(CommandManager): "The FEM_ConstraintInitialPressure command definition" def __init__(self): - super(_ConstraintInitialPressure, self).__init__() + super().__init__() self.menutext = Qt.QT_TRANSLATE_NOOP( - "FEM_ConstraintInitialPressure", - "Initial pressure condition" + "FEM_ConstraintInitialPressure", "Initial pressure condition" ) self.tooltip = Qt.QT_TRANSLATE_NOOP( - "FEM_ConstraintInitialPressure", - "Creates an initial pressure condition" + "FEM_ConstraintInitialPressure", "Creates an initial pressure condition" ) self.is_active = "with_analysis" self.do_activated = "add_obj_on_gui_set_edit" @@ -310,14 +288,12 @@ class _ConstraintMagnetization(CommandManager): "The FEM_ConstraintMagnetization command definition" def __init__(self): - super(_ConstraintMagnetization, self).__init__() + super().__init__() self.menutext = Qt.QT_TRANSLATE_NOOP( - "FEM_ConstraintMagnetization", - "Magnetization boundary condition" + "FEM_ConstraintMagnetization", "Magnetization boundary condition" ) self.tooltip = Qt.QT_TRANSLATE_NOOP( - "FEM_ConstraintMagnetization", - "Creates a magnetization boundary condition" + "FEM_ConstraintMagnetization", "Creates a magnetization boundary condition" ) self.is_active = "with_analysis" self.do_activated = "add_obj_on_gui_set_edit" @@ -327,14 +303,10 @@ class _ConstraintSectionPrint(CommandManager): "The FEM_ConstraintSectionPrint command definition" def __init__(self): - super(_ConstraintSectionPrint, self).__init__() - self.menutext = Qt.QT_TRANSLATE_NOOP( - "FEM_ConstraintSectionPrint", - "Section print feature" - ) + super().__init__() + self.menutext = Qt.QT_TRANSLATE_NOOP("FEM_ConstraintSectionPrint", "Section print feature") self.tooltip = Qt.QT_TRANSLATE_NOOP( - "FEM_ConstraintSectionPrint", - "Creates a section print feature" + "FEM_ConstraintSectionPrint", "Creates a section print feature" ) self.is_active = "with_analysis" self.do_activated = "add_obj_on_gui_set_edit" @@ -344,15 +316,9 @@ class _ConstraintSelfWeight(CommandManager): "The FEM_ConstraintSelfWeight command definition" def __init__(self): - super(_ConstraintSelfWeight, self).__init__() - self.menutext = Qt.QT_TRANSLATE_NOOP( - "FEM_ConstraintSelfWeight", - "Gravity load" - ) - self.tooltip = Qt.QT_TRANSLATE_NOOP( - "FEM_ConstraintSelfWeight", - "Creates a gravity load" - ) + super().__init__() + self.menutext = Qt.QT_TRANSLATE_NOOP("FEM_ConstraintSelfWeight", "Gravity load") + self.tooltip = Qt.QT_TRANSLATE_NOOP("FEM_ConstraintSelfWeight", "Creates a gravity load") self.is_active = "with_analysis" self.do_activated = "add_obj_on_gui_noset_edit" @@ -361,15 +327,9 @@ class _ConstraintTie(CommandManager): "The FEM_ConstraintTie command definition" def __init__(self): - super(_ConstraintTie, self).__init__() - self.menutext = Qt.QT_TRANSLATE_NOOP( - "FEM_ConstraintTie", - "Tie constraint" - ) - self.tooltip = Qt.QT_TRANSLATE_NOOP( - "FEM_ConstraintTie", - "Creates a tie constraint" - ) + super().__init__() + self.menutext = Qt.QT_TRANSLATE_NOOP("FEM_ConstraintTie", "Tie constraint") + self.tooltip = Qt.QT_TRANSLATE_NOOP("FEM_ConstraintTie", "Creates a tie constraint") self.is_active = "with_analysis" self.do_activated = "add_obj_on_gui_set_edit" @@ -378,14 +338,10 @@ class _ElementFluid1D(CommandManager): "The FEM_ElementFluid1D command definition" def __init__(self): - super(_ElementFluid1D, self).__init__() - self.menutext = Qt.QT_TRANSLATE_NOOP( - "FEM_ElementFluid1D", - "Fluid section for 1D flow" - ) + super().__init__() + self.menutext = Qt.QT_TRANSLATE_NOOP("FEM_ElementFluid1D", "Fluid section for 1D flow") self.tooltip = Qt.QT_TRANSLATE_NOOP( - "FEM_ElementFluid1D", - "Creates a FEM fluid section for 1D flow" + "FEM_ElementFluid1D", "Creates a FEM fluid section for 1D flow" ) self.is_active = "with_analysis" self.do_activated = "add_obj_on_gui_set_edit" @@ -395,14 +351,10 @@ class _ElementGeometry1D(CommandManager): "The Fem_ElementGeometry1D command definition" def __init__(self): - super(_ElementGeometry1D, self).__init__() - self.menutext = Qt.QT_TRANSLATE_NOOP( - "FEM_ElementGeometry1D", - "Beam cross section" - ) + super().__init__() + self.menutext = Qt.QT_TRANSLATE_NOOP("FEM_ElementGeometry1D", "Beam cross section") self.tooltip = Qt.QT_TRANSLATE_NOOP( - "FEM_ElementGeometry1D", - "Creates a FEM beam cross section" + "FEM_ElementGeometry1D", "Creates a FEM beam cross section" ) self.is_active = "with_analysis" self.do_activated = "add_obj_on_gui_set_edit" @@ -412,14 +364,10 @@ class _ElementGeometry2D(CommandManager): "The FEM_ElementGeometry2D command definition" def __init__(self): - super(_ElementGeometry2D, self).__init__() - self.menutext = Qt.QT_TRANSLATE_NOOP( - "FEM_ElementGeometry2D", - "Shell plate thickness" - ) + super().__init__() + self.menutext = Qt.QT_TRANSLATE_NOOP("FEM_ElementGeometry2D", "Shell plate thickness") self.tooltip = Qt.QT_TRANSLATE_NOOP( - "FEM_ElementGeometry2D", - "Creates a FEM shell plate thickness" + "FEM_ElementGeometry2D", "Creates a FEM shell plate thickness" ) self.is_active = "with_analysis" self.do_activated = "add_obj_on_gui_set_edit" @@ -429,15 +377,9 @@ class _ElementRotation1D(CommandManager): "The Fem_ElementRotation1D command definition" def __init__(self): - super(_ElementRotation1D, self).__init__() - self.menutext = Qt.QT_TRANSLATE_NOOP( - "FEM_ElementRotation1D", - "Beam rotation" - ) - self.tooltip = Qt.QT_TRANSLATE_NOOP( - "FEM_ElementRotation1D", - "Creates a FEM beam rotation" - ) + super().__init__() + self.menutext = Qt.QT_TRANSLATE_NOOP("FEM_ElementRotation1D", "Beam rotation") + self.tooltip = Qt.QT_TRANSLATE_NOOP("FEM_ElementRotation1D", "Creates a FEM beam rotation") self.is_active = "with_analysis" self.do_activated = "add_obj_on_gui_noset_edit" @@ -446,14 +388,11 @@ class _EquationDeformation(CommandManager): "The FEM_EquationDeformation command definition" def __init__(self): - super(_EquationDeformation, self).__init__() - self.menutext = Qt.QT_TRANSLATE_NOOP( - "FEM_EquationDeformation", - "Deformation equation" - ) + super().__init__() + self.menutext = Qt.QT_TRANSLATE_NOOP("FEM_EquationDeformation", "Deformation equation") self.tooltip = Qt.QT_TRANSLATE_NOOP( "FEM_EquationDeformation", - "Creates a FEM equation for\n deformation (nonlinear elasticity)" + "Creates a FEM equation for\n deformation (nonlinear elasticity)", ) self.is_active = "with_solver_elmer" self.do_activated = "add_obj_on_gui_selobj_expand_noset_edit" @@ -463,14 +402,10 @@ class _EquationElasticity(CommandManager): "The FEM_EquationElasticity command definition" def __init__(self): - super(_EquationElasticity, self).__init__() - self.menutext = Qt.QT_TRANSLATE_NOOP( - "FEM_EquationElasticity", - "Elasticity equation" - ) + super().__init__() + self.menutext = Qt.QT_TRANSLATE_NOOP("FEM_EquationElasticity", "Elasticity equation") self.tooltip = Qt.QT_TRANSLATE_NOOP( - "FEM_EquationElasticity", - "Creates a FEM equation for\n elasticity (stress)" + "FEM_EquationElasticity", "Creates a FEM equation for\n elasticity (stress)" ) self.is_active = "with_solver_elmer" self.do_activated = "add_obj_on_gui_selobj_expand_noset_edit" @@ -480,14 +415,10 @@ class _EquationElectricforce(CommandManager): "The FEM_EquationElectricforce command definition" def __init__(self): - super(_EquationElectricforce, self).__init__() - self.menutext = Qt.QT_TRANSLATE_NOOP( - "FEM_EquationElectricforce", - "Electricforce equation" - ) + super().__init__() + self.menutext = Qt.QT_TRANSLATE_NOOP("FEM_EquationElectricforce", "Electricforce equation") self.tooltip = Qt.QT_TRANSLATE_NOOP( - "FEM_EquationElectricforce", - "Creates a FEM equation for electric forces" + "FEM_EquationElectricforce", "Creates a FEM equation for electric forces" ) self.is_active = "with_solver_elmer" self.do_activated = "add_obj_on_gui_selobj_expand_noset_edit" @@ -497,14 +428,10 @@ class _EquationElectrostatic(CommandManager): "The FEM_EquationElectrostatic command definition" def __init__(self): - super(_EquationElectrostatic, self).__init__() - self.menutext = Qt.QT_TRANSLATE_NOOP( - "FEM_EquationElectrostatic", - "Electrostatic equation" - ) + super().__init__() + self.menutext = Qt.QT_TRANSLATE_NOOP("FEM_EquationElectrostatic", "Electrostatic equation") self.tooltip = Qt.QT_TRANSLATE_NOOP( - "FEM_EquationElectrostatic", - "Creates a FEM equation for electrostatic" + "FEM_EquationElectrostatic", "Creates a FEM equation for electrostatic" ) self.is_active = "with_solver_elmer" self.do_activated = "add_obj_on_gui_selobj_expand_noset_edit" @@ -514,15 +441,9 @@ class _EquationFlow(CommandManager): "The FEM_EquationFlow command definition" def __init__(self): - super(_EquationFlow, self).__init__() - self.menutext = Qt.QT_TRANSLATE_NOOP( - "FEM_EquationFlow", - "Flow equation" - ) - self.tooltip = Qt.QT_TRANSLATE_NOOP( - "FEM_EquationFlow", - "Creates a FEM equation for flow" - ) + super().__init__() + self.menutext = Qt.QT_TRANSLATE_NOOP("FEM_EquationFlow", "Flow equation") + self.tooltip = Qt.QT_TRANSLATE_NOOP("FEM_EquationFlow", "Creates a FEM equation for flow") self.is_active = "with_solver_elmer" self.do_activated = "add_obj_on_gui_selobj_expand_noset_edit" @@ -531,15 +452,9 @@ class _EquationFlux(CommandManager): "The FEM_EquationFlux command definition" def __init__(self): - super(_EquationFlux, self).__init__() - self.menutext = Qt.QT_TRANSLATE_NOOP( - "FEM_EquationFlux", - "Flux equation" - ) - self.tooltip = Qt.QT_TRANSLATE_NOOP( - "FEM_EquationFlux", - "Creates a FEM equation for flux" - ) + super().__init__() + self.menutext = Qt.QT_TRANSLATE_NOOP("FEM_EquationFlux", "Flux equation") + self.tooltip = Qt.QT_TRANSLATE_NOOP("FEM_EquationFlux", "Creates a FEM equation for flux") self.is_active = "with_solver_elmer" self.do_activated = "add_obj_on_gui_selobj_expand_noset_edit" @@ -548,15 +463,9 @@ class _EquationHeat(CommandManager): "The FEM_EquationHeat command definition" def __init__(self): - super(_EquationHeat, self).__init__() - self.menutext = Qt.QT_TRANSLATE_NOOP( - "FEM_EquationHeat", - "Heat equation" - ) - self.tooltip = Qt.QT_TRANSLATE_NOOP( - "FEM_EquationHeat", - "Creates a FEM equation for heat" - ) + super().__init__() + self.menutext = Qt.QT_TRANSLATE_NOOP("FEM_EquationHeat", "Heat equation") + self.tooltip = Qt.QT_TRANSLATE_NOOP("FEM_EquationHeat", "Creates a FEM equation for heat") self.is_active = "with_solver_elmer" self.do_activated = "add_obj_on_gui_selobj_expand_noset_edit" @@ -565,14 +474,13 @@ class _EquationMagnetodynamic(CommandManager): "The FEM_EquationMagnetodynamic command definition" def __init__(self): - super(_EquationMagnetodynamic, self).__init__() + super().__init__() self.menutext = Qt.QT_TRANSLATE_NOOP( - "FEM_EquationMagnetodynamic", - "Magnetodynamic equation" + "FEM_EquationMagnetodynamic", "Magnetodynamic equation" ) self.tooltip = Qt.QT_TRANSLATE_NOOP( "FEM_EquationMagnetodynamic", - "Creates a FEM equation for\n magnetodynamic forces" + "Creates a FEM equation for\n magnetodynamic forces", ) self.is_active = "with_solver_elmer" self.do_activated = "add_obj_on_gui_selobj_expand_noset_edit" @@ -582,14 +490,13 @@ class _EquationMagnetodynamic2D(CommandManager): "The FEM_EquationMagnetodynamic2D command definition" def __init__(self): - super(_EquationMagnetodynamic2D, self).__init__() + super().__init__() self.menutext = Qt.QT_TRANSLATE_NOOP( - "FEM_EquationMagnetodynamic2D", - "Magnetodynamic2D equation" + "FEM_EquationMagnetodynamic2D", "Magnetodynamic2D equation" ) self.tooltip = Qt.QT_TRANSLATE_NOOP( "FEM_EquationMagnetodynamic2D", - "Creates a FEM equation for\n 2D magnetodynamic forces" + "Creates a FEM equation for\n 2D magnetodynamic forces", ) self.is_active = "with_solver_elmer" self.do_activated = "add_obj_on_gui_selobj_expand_noset_edit" @@ -599,16 +506,10 @@ class _Examples(CommandManager): "The FEM_Examples command definition" def __init__(self): - super(_Examples, self).__init__() + super().__init__() self.pixmap = "FemWorkbench" - self.menutext = Qt.QT_TRANSLATE_NOOP( - "FEM_Examples", - "Open FEM examples" - ) - self.tooltip = Qt.QT_TRANSLATE_NOOP( - "FEM_Examples", - "Opens the FEM examples" - ) + self.menutext = Qt.QT_TRANSLATE_NOOP("FEM_Examples", "Open FEM examples") + self.tooltip = Qt.QT_TRANSLATE_NOOP("FEM_Examples", "Opens the FEM examples") self.is_active = "always" def Activated(self): @@ -620,15 +521,11 @@ class _MaterialEditor(CommandManager): "The FEM_MaterialEditor command definition" def __init__(self): - super(_MaterialEditor, self).__init__() + super().__init__() self.pixmap = "Arch_Material_Group" - self.menutext = Qt.QT_TRANSLATE_NOOP( - "FEM_MaterialEditor", - "Material editor" - ) + self.menutext = Qt.QT_TRANSLATE_NOOP("FEM_MaterialEditor", "Material editor") self.tooltip = Qt.QT_TRANSLATE_NOOP( - "FEM_MaterialEditor", - "Opens the FreeCAD material editor" + "FEM_MaterialEditor", "Opens the FreeCAD material editor" ) self.is_active = "always" @@ -641,15 +538,9 @@ class _MaterialFluid(CommandManager): "The FEM_MaterialFluid command definition" def __init__(self): - super(_MaterialFluid, self).__init__() - self.menutext = Qt.QT_TRANSLATE_NOOP( - "FEM_MaterialFluid", - "Material for fluid" - ) - self.tooltip = Qt.QT_TRANSLATE_NOOP( - "FEM_MaterialFluid", - "Creates a FEM material for fluid" - ) + super().__init__() + self.menutext = Qt.QT_TRANSLATE_NOOP("FEM_MaterialFluid", "Material for fluid") + self.tooltip = Qt.QT_TRANSLATE_NOOP("FEM_MaterialFluid", "Creates a FEM material for fluid") self.is_active = "with_analysis" self.do_activated = "add_obj_on_gui_set_edit" @@ -658,14 +549,12 @@ class _MaterialMechanicalNonlinear(CommandManager): "The FEM_MaterialMechanicalNonlinear command definition" def __init__(self): - super(_MaterialMechanicalNonlinear, self).__init__() + super().__init__() self.menutext = Qt.QT_TRANSLATE_NOOP( - "FEM_MaterialMechanicalNonlinear", - "Nonlinear mechanical material" + "FEM_MaterialMechanicalNonlinear", "Nonlinear mechanical material" ) self.tooltip = Qt.QT_TRANSLATE_NOOP( - "FEM_MaterialMechanicalNonlinear", - "Creates a nonlinear mechanical material" + "FEM_MaterialMechanicalNonlinear", "Creates a nonlinear mechanical material" ) self.is_active = "with_material_solid" @@ -678,8 +567,9 @@ class _MaterialMechanicalNonlinear(CommandManager): ): FreeCAD.Console.PrintError( "Nonlinear material {} is based on the selected material {}. " - "Only one nonlinear object allowed for each material.\n" - .format(o.Name, self.selobj.Name) + "Only one nonlinear object allowed for each material.\n".format( + o.Name, self.selobj.Name + ) ) return @@ -687,8 +577,9 @@ class _MaterialMechanicalNonlinear(CommandManager): string_lin_mat_obj = "FreeCAD.ActiveDocument.getObject('" + self.selobj.Name + "')" command_to_run = ( "FemGui.getActiveAnalysis().addObject(ObjectsFem." - "makeMaterialMechanicalNonlinear(FreeCAD.ActiveDocument, {}))" - .format(string_lin_mat_obj) + "makeMaterialMechanicalNonlinear(FreeCAD.ActiveDocument, {}))".format( + string_lin_mat_obj + ) ) FreeCAD.ActiveDocument.openTransaction("Create FemMaterialMechanicalNonlinear") FreeCADGui.addModule("ObjectsFem") @@ -713,8 +604,7 @@ class _MaterialMechanicalNonlinear(CommandManager): or is_of_type(solver_object, "Fem::SolverCalculix") ): FreeCAD.Console.PrintMessage( - "Set MaterialNonlinearity to nonlinear for {}\n" - .format(solver_object.Label) + f"Set MaterialNonlinearity to nonlinear for {solver_object.Label}\n" ) solver_object.MaterialNonlinearity = "nonlinear" FreeCAD.ActiveDocument.commitTransaction() @@ -726,14 +616,13 @@ class _MaterialReinforced(CommandManager): "The FEM_MaterialReinforced command definition" def __init__(self): - super(_MaterialReinforced, self).__init__() + super().__init__() self.menutext = Qt.QT_TRANSLATE_NOOP( - "FEM_MaterialReinforced", - "Reinforced material (concrete)" + "FEM_MaterialReinforced", "Reinforced material (concrete)" ) self.tooltip = Qt.QT_TRANSLATE_NOOP( "FEM_MaterialReinforced", - "Creates a material for reinforced matrix material such as concrete" + "Creates a material for reinforced matrix material such as concrete", ) self.is_active = "with_analysis" self.do_activated = "add_obj_on_gui_set_edit" @@ -743,16 +632,10 @@ class _MaterialSolid(CommandManager): "The FEM_MaterialSolid command definition" def __init__(self): - super(_MaterialSolid, self).__init__() - self.menutext = Qt.QT_TRANSLATE_NOOP( - "FEM_MaterialSolid", - "Material for solid" - ) + super().__init__() + self.menutext = Qt.QT_TRANSLATE_NOOP("FEM_MaterialSolid", "Material for solid") self.accel = "M, S" - self.tooltip = Qt.QT_TRANSLATE_NOOP( - "FEM_MaterialSolid", - "Creates a FEM material for solid" - ) + self.tooltip = Qt.QT_TRANSLATE_NOOP("FEM_MaterialSolid", "Creates a FEM material for solid") self.is_active = "with_analysis" self.do_activated = "add_obj_on_gui_set_edit" @@ -761,14 +644,10 @@ class _FEMMesh2Mesh(CommandManager): "The FEM_FEMMesh2Mesh command definition" def __init__(self): - super(_FEMMesh2Mesh, self).__init__() - self.menutext = Qt.QT_TRANSLATE_NOOP( - "FEM_FEMMesh2Mesh", - "FEM mesh to mesh" - ) + super().__init__() + self.menutext = Qt.QT_TRANSLATE_NOOP("FEM_FEMMesh2Mesh", "FEM mesh to mesh") self.tooltip = Qt.QT_TRANSLATE_NOOP( - "FEM_FEMMesh2Mesh", - "Converts the surface of a FEM mesh to a mesh" + "FEM_FEMMesh2Mesh", "Converts the surface of a FEM mesh to a mesh" ) self.is_active = "with_femmesh_andor_res" @@ -778,8 +657,7 @@ class _FEMMesh2Mesh(CommandManager): FreeCADGui.addModule("femmesh.femmesh2mesh") FreeCADGui.doCommand( "out_mesh = femmesh.femmesh2mesh.femmesh_2_mesh(" - "FreeCAD.ActiveDocument.{}.FemMesh)" - .format(self.selobj.Name) + "FreeCAD.ActiveDocument.{}.FemMesh)".format(self.selobj.Name) ) FreeCADGui.addModule("Mesh") FreeCADGui.doCommand("Mesh.show(Mesh.Mesh(out_mesh))") @@ -792,14 +670,13 @@ class _FEMMesh2Mesh(CommandManager): FreeCADGui.addModule("femmesh.femmesh2mesh") FreeCADGui.doCommand( "out_mesh = femmesh.femmesh2mesh.femmesh_2_mesh(" - "FreeCAD.ActiveDocument.{}.FemMesh, FreeCAD.ActiveDocument.{})" - .format(femmesh.Name, res.Name) + "FreeCAD.ActiveDocument.{}.FemMesh, FreeCAD.ActiveDocument.{})".format( + femmesh.Name, res.Name + ) ) FreeCADGui.addModule("Mesh") FreeCADGui.doCommand("Mesh.show(Mesh.Mesh(out_mesh))") - FreeCADGui.doCommand( - "FreeCAD.ActiveDocument." + femmesh.Name + ".ViewObject.hide()" - ) + FreeCADGui.doCommand("FreeCAD.ActiveDocument." + femmesh.Name + ".ViewObject.hide()") FreeCAD.ActiveDocument.commitTransaction() FreeCADGui.Selection.clearSelection() FreeCAD.ActiveDocument.recompute() @@ -809,14 +686,10 @@ class _MeshBoundaryLayer(CommandManager): "The FEM_MeshBoundaryLayer command definition" def __init__(self): - super(_MeshBoundaryLayer, self).__init__() - self.menutext = Qt.QT_TRANSLATE_NOOP( - "FEM_MeshBoundaryLayer", - "FEM mesh boundary layer" - ) + super().__init__() + self.menutext = Qt.QT_TRANSLATE_NOOP("FEM_MeshBoundaryLayer", "FEM mesh boundary layer") self.tooltip = Qt.QT_TRANSLATE_NOOP( - "FEM_MeshBoundaryLayer", - "Creates a FEM mesh boundary layer" + "FEM_MeshBoundaryLayer", "Creates a FEM mesh boundary layer" ) self.is_active = "with_gmsh_femmesh" self.do_activated = "add_obj_on_gui_selobj_set_edit" @@ -826,15 +699,9 @@ class _MeshClear(CommandManager): "The FEM_MeshClear command definition" def __init__(self): - super(_MeshClear, self).__init__() - self.menutext = Qt.QT_TRANSLATE_NOOP( - "FEM_MeshClear", - "Clear FEM mesh" - ) - self.tooltip = Qt.QT_TRANSLATE_NOOP( - "FEM_MeshClear", - "Clears the Mesh of a FEM mesh object" - ) + super().__init__() + self.menutext = Qt.QT_TRANSLATE_NOOP("FEM_MeshClear", "Clear FEM mesh") + self.tooltip = Qt.QT_TRANSLATE_NOOP("FEM_MeshClear", "Clears the Mesh of a FEM mesh object") self.is_active = "with_femmesh" def Activated(self): @@ -852,15 +719,9 @@ class _MeshDisplayInfo(CommandManager): "The FEM_MeshDisplayInfo command definition" def __init__(self): - super(_MeshDisplayInfo, self).__init__() - self.menutext = Qt.QT_TRANSLATE_NOOP( - "FEM_MeshDisplayInfo", - "Display FEM mesh info" - ) - self.tooltip = Qt.QT_TRANSLATE_NOOP( - "FEM_MeshDisplayInfo", - "Displays FEM mesh information" - ) + super().__init__() + self.menutext = Qt.QT_TRANSLATE_NOOP("FEM_MeshDisplayInfo", "Display FEM mesh info") + self.tooltip = Qt.QT_TRANSLATE_NOOP("FEM_MeshDisplayInfo", "Displays FEM mesh information") self.is_active = "with_femmesh" def Activated(self): @@ -882,14 +743,10 @@ class _MeshGmshFromShape(CommandManager): "The FEM_MeshGmshFromShape command definition" def __init__(self): - super(_MeshGmshFromShape, self).__init__() - self.menutext = Qt.QT_TRANSLATE_NOOP( - "FEM_MeshGmshFromShape", - "FEM mesh from shape by Gmsh" - ) + super().__init__() + self.menutext = Qt.QT_TRANSLATE_NOOP("FEM_MeshGmshFromShape", "FEM mesh from shape by Gmsh") self.tooltip = Qt.QT_TRANSLATE_NOOP( - "FEM_MeshGmshFromShape", - "Creates a FEM mesh from a shape by Gmsh mesher" + "FEM_MeshGmshFromShape", "Creates a FEM mesh from a shape by Gmsh mesher" ) self.is_active = "with_part_feature" @@ -905,12 +762,14 @@ class _MeshGmshFromShape(CommandManager): "ObjectsFem.makeMeshGmsh(FreeCAD.ActiveDocument, '" + mesh_obj_name + "')" ) FreeCADGui.doCommand( - "FreeCAD.ActiveDocument.ActiveObject.Part = FreeCAD.ActiveDocument.{}" - .format(self.selobj.Name) + "FreeCAD.ActiveDocument.ActiveObject.Part = FreeCAD.ActiveDocument.{}".format( + self.selobj.Name + ) ) # Gmsh mesh object could be added without an active analysis # but if there is an active analysis move it in there import FemGui + if FemGui.getActiveAnalysis(): FreeCADGui.addModule("FemGui") FreeCADGui.doCommand( @@ -928,15 +787,9 @@ class _MeshGroup(CommandManager): "The FEM_MeshGroup command definition" def __init__(self): - super(_MeshGroup, self).__init__() - self.menutext = Qt.QT_TRANSLATE_NOOP( - "FEM_MeshGroup", - "FEM mesh group" - ) - self.tooltip = Qt.QT_TRANSLATE_NOOP( - "FEM_MeshGroup", - "Creates a FEM mesh group" - ) + super().__init__() + self.menutext = Qt.QT_TRANSLATE_NOOP("FEM_MeshGroup", "FEM mesh group") + self.tooltip = Qt.QT_TRANSLATE_NOOP("FEM_MeshGroup", "Creates a FEM mesh group") self.is_active = "with_gmsh_femmesh" self.do_activated = "add_obj_on_gui_selobj_set_edit" @@ -945,14 +798,13 @@ class _MeshNetgenFromShape(CommandManager): "The FEM_MeshNetgenFromShape command definition" def __init__(self): - super(_MeshNetgenFromShape, self).__init__() + super().__init__() self.menutext = Qt.QT_TRANSLATE_NOOP( - "FEM_MeshNetgenFromShape", - "FEM mesh from shape by Netgen" + "FEM_MeshNetgenFromShape", "FEM mesh from shape by Netgen" ) self.tooltip = Qt.QT_TRANSLATE_NOOP( "FEM_MeshNetgenFromShape", - "Creates a FEM mesh from a solid or face shape by Netgen internal mesher" + "Creates a FEM mesh from a solid or face shape by Netgen internal mesher", ) self.is_active = "with_part_feature" @@ -968,12 +820,14 @@ class _MeshNetgenFromShape(CommandManager): "ObjectsFem.makeMeshNetgen(FreeCAD.ActiveDocument, '" + mesh_obj_name + "')" ) FreeCADGui.doCommand( - "FreeCAD.ActiveDocument.ActiveObject.Shape = FreeCAD.ActiveDocument.{}" - .format(self.selobj.Name) + "FreeCAD.ActiveDocument.ActiveObject.Shape = FreeCAD.ActiveDocument.{}".format( + self.selobj.Name + ) ) # Netgen mesh object could be added without an active analysis # but if there is an active analysis move it in there import FemGui + if FemGui.getActiveAnalysis(): FreeCADGui.addModule("FemGui") FreeCADGui.doCommand( @@ -991,15 +845,9 @@ class _MeshRegion(CommandManager): "The FEM_MeshRefinement command definition" def __init__(self): - super(_MeshRegion, self).__init__() - self.menutext = Qt.QT_TRANSLATE_NOOP( - "FEM_MeshRegion", - "FEM mesh refinement" - ) - self.tooltip = Qt.QT_TRANSLATE_NOOP( - "FEM_MeshRegion", - "Creates a FEM mesh refinement" - ) + super().__init__() + self.menutext = Qt.QT_TRANSLATE_NOOP("FEM_MeshRegion", "FEM mesh refinement") + self.tooltip = Qt.QT_TRANSLATE_NOOP("FEM_MeshRegion", "Creates a FEM mesh refinement") self.is_active = "with_gmsh_femmesh" self.do_activated = "add_obj_on_gui_selobj_set_edit" @@ -1008,15 +856,11 @@ class _ResultShow(CommandManager): "The FEM_ResultShow command definition" def __init__(self): - super(_ResultShow, self).__init__() - self.menutext = Qt.QT_TRANSLATE_NOOP( - "FEM_ResultShow", - "Show result" - ) + super().__init__() + self.menutext = Qt.QT_TRANSLATE_NOOP("FEM_ResultShow", "Show result") self.accel = "R, S" self.tooltip = Qt.QT_TRANSLATE_NOOP( - "FEM_ResultShow", - "Shows and visualizes selected result data" + "FEM_ResultShow", "Shows and visualizes selected result data" ) self.is_active = "with_selresult" @@ -1028,22 +872,20 @@ class _ResultsPurge(CommandManager): "The FEM_ResultsPurge command definition" def __init__(self): - super(_ResultsPurge, self).__init__() - self.menutext = Qt.QT_TRANSLATE_NOOP( - "FEM_ResultsPurge", - "Purge results" - ) + super().__init__() + self.menutext = Qt.QT_TRANSLATE_NOOP("FEM_ResultsPurge", "Purge results") self.accel = "R, P" self.tooltip = Qt.QT_TRANSLATE_NOOP( - "FEM_ResultsPurge", - "Purges all results from active analysis" + "FEM_ResultsPurge", "Purges all results from active analysis" ) self.is_active = "with_results" def Activated(self): import femresult.resulttools as resulttools + resulttools.purge_results(self.active_analysis) + class _SolverCalculixContextManager: def __init__(self, make_name, cli_obj_ref_name): @@ -1056,19 +898,13 @@ class _SolverCalculixContextManager: FreeCADGui.addModule("ObjectsFem") FreeCADGui.addModule("FemGui") FreeCADGui.doCommand( - "{} = ObjectsFem.{}(FreeCAD.ActiveDocument)".format( - self.cli_name, self.make_name - ) + f"{self.cli_name} = ObjectsFem.{self.make_name}(FreeCAD.ActiveDocument)" ) FreeCADGui.doCommand( - "{}.AnalysisType = {}".format( - self.cli_name, ccx_prefs.GetInt("AnalysisType", 0) - ) + "{}.AnalysisType = {}".format(self.cli_name, ccx_prefs.GetInt("AnalysisType", 0)) ) FreeCADGui.doCommand( - "{}.EigenmodesCount = {}".format( - self.cli_name, ccx_prefs.GetInt("EigenmodesCount", 10) - ) + "{}.EigenmodesCount = {}".format(self.cli_name, ccx_prefs.GetInt("EigenmodesCount", 10)) ) FreeCADGui.doCommand( "{}.EigenmodeLowLimit = {}".format( @@ -1091,9 +927,7 @@ class _SolverCalculixContextManager: ) ) FreeCADGui.doCommand( - "{}.TimeEnd = {}".format( - self.cli_name, ccx_prefs.GetFloat("AnalysisTime", 1.0) - ) + "{}.TimeEnd = {}".format(self.cli_name, ccx_prefs.GetFloat("AnalysisTime", 1.0)) ) FreeCADGui.doCommand( "{}.TimeMinimumStep = {}".format( @@ -1121,9 +955,7 @@ class _SolverCalculixContextManager: ) ) FreeCADGui.doCommand( - "{}.MatrixSolverType = {}".format( - self.cli_name, ccx_prefs.GetInt("Solver", 0) - ) + "{}.MatrixSolverType = {}".format(self.cli_name, ccx_prefs.GetInt("Solver", 0)) ) FreeCADGui.doCommand( "{}.BeamShellResultOutput3D = {}".format( @@ -1131,18 +963,16 @@ class _SolverCalculixContextManager: ) ) FreeCADGui.doCommand( - "{}.GeometricalNonlinearity = \"{}\"".format( + '{}.GeometricalNonlinearity = "{}"'.format( self.cli_name, - "nonlinear" if ccx_prefs.GetBool("NonlinearGeometry", False) else "linear" + ("nonlinear" if ccx_prefs.GetBool("NonlinearGeometry", False) else "linear"), ) ) return self def __exit__(self, exc_type, exc_value, trace): - FreeCADGui.doCommand( - "FemGui.getActiveAnalysis().addObject({})".format(self.cli_name) - ) + FreeCADGui.doCommand(f"FemGui.getActiveAnalysis().addObject({self.cli_name})") FreeCAD.ActiveDocument.commitTransaction() # expand analysis object in tree view expandParentObject() @@ -1153,16 +983,15 @@ class _SolverCcxTools(CommandManager): "The FEM_SolverCalculix ccx tools command definition" def __init__(self): - super(_SolverCcxTools, self).__init__() + super().__init__() self.pixmap = "FEM_SolverStandard" self.menutext = Qt.QT_TRANSLATE_NOOP( - "FEM_SolverCalculiXCcxTools", - "Solver CalculiX Standard" + "FEM_SolverCalculiXCcxTools", "Solver CalculiX Standard" ) self.accel = "S, X" self.tooltip = Qt.QT_TRANSLATE_NOOP( "FEM_SolverCalculiXCcxTools", - "Creates a standard FEM solver CalculiX with ccx tools" + "Creates a standard FEM solver CalculiX with ccx tools", ) self.is_active = "with_analysis" @@ -1174,28 +1003,23 @@ class _SolverCcxTools(CommandManager): has_nonlinear_material_obj = True if has_nonlinear_material_obj: - FreeCADGui.doCommand( - "{}.GeometricalNonlinearity = 'nonlinear'".format(cm.cli_name) - ) - FreeCADGui.doCommand( - "{}.MaterialNonlinearity = 'nonlinear'".format(cm.cli_name) - ) + FreeCADGui.doCommand(f"{cm.cli_name}.GeometricalNonlinearity = 'nonlinear'") + FreeCADGui.doCommand(f"{cm.cli_name}.MaterialNonlinearity = 'nonlinear'") class _SolverCalculix(CommandManager): "The FEM_SolverCalculix command definition" def __init__(self): - super(_SolverCalculix, self).__init__() + super().__init__() self.pixmap = "FEM_SolverStandard" self.menutext = Qt.QT_TRANSLATE_NOOP( - "FEM_SolverCalculiX", - "Solver CalculiX (new framework)" + "FEM_SolverCalculiX", "Solver CalculiX (new framework)" ) self.accel = "S, C" self.tooltip = Qt.QT_TRANSLATE_NOOP( "FEM_SolverCalculiX", - "Creates a FEM solver CalculiX new framework (less result error handling)" + "Creates a FEM solver CalculiX new framework (less result error handling)", ) self.is_active = "with_analysis" @@ -1207,27 +1031,20 @@ class _SolverCalculix(CommandManager): has_nonlinear_material_obj = True if has_nonlinear_material_obj: - FreeCADGui.doCommand( - "{}.GeometricalNonlinearity = 'nonlinear'".format(cm.cli_name) - ) - FreeCADGui.doCommand( - "{}.MaterialNonlinearity = 'nonlinear'".format(cm.cli_name) - ) + FreeCADGui.doCommand(f"{cm.cli_name}.GeometricalNonlinearity = 'nonlinear'") + FreeCADGui.doCommand(f"{cm.cli_name}.MaterialNonlinearity = 'nonlinear'") class _SolverControl(CommandManager): "The FEM_SolverControl command definition" def __init__(self): - super(_SolverControl, self).__init__() - self.menutext = Qt.QT_TRANSLATE_NOOP( - "FEM_SolverControl", - "Solver job control" - ) + super().__init__() + self.menutext = Qt.QT_TRANSLATE_NOOP("FEM_SolverControl", "Solver job control") self.accel = "S, T" self.tooltip = Qt.QT_TRANSLATE_NOOP( "FEM_SolverControl", - "Changes solver attributes and runs the calculations for the selected solver" + "Changes solver attributes and runs the calculations for the selected solver", ) self.is_active = "with_solver" @@ -1239,13 +1056,10 @@ class _SolverElmer(CommandManager): "The FEM_SolverElmer command definition" def __init__(self): - super(_SolverElmer, self).__init__() + super().__init__() self.menutext = Qt.QT_TRANSLATE_NOOP("FEM_SolverElmer", "Solver Elmer") self.accel = "S, E" - self.tooltip = Qt.QT_TRANSLATE_NOOP( - "FEM_SolverElmer", - "Creates a FEM solver Elmer" - ) + self.tooltip = Qt.QT_TRANSLATE_NOOP("FEM_SolverElmer", "Creates a FEM solver Elmer") self.is_active = "with_analysis" self.do_activated = "add_obj_on_gui_expand_noset_edit" @@ -1254,7 +1068,7 @@ class _SolverMystran(CommandManager): "The FEM_SolverMystran command definition" def __init__(self): - super(_SolverMystran, self).__init__() + super().__init__() self.pixmap = "FEM_SolverMystran" self.menutext = Qt.QT_TRANSLATE_NOOP("FEM_SolverMystran", "Solver Mystran") self.accel = "S, M" @@ -1267,17 +1081,17 @@ class _SolverRun(CommandManager): "The FEM_SolverRun command definition" def __init__(self): - super(_SolverRun, self).__init__() + super().__init__() self.menutext = Qt.QT_TRANSLATE_NOOP("FEM_SolverRun", "Run solver calculations") self.accel = "S, R" self.tooltip = Qt.QT_TRANSLATE_NOOP( - "FEM_SolverRun", - "Runs the calculations for the selected solver" + "FEM_SolverRun", "Runs the calculations for the selected solver" ) self.is_active = "with_solver" def Activated(self): from femsolver.run import run_fem_solver + run_fem_solver(self.selobj) FreeCADGui.Selection.clearSelection() FreeCAD.ActiveDocument.recompute() @@ -1287,7 +1101,7 @@ class _SolverZ88(CommandManager): "The FEM_SolverZ88 command definition" def __init__(self): - super(_SolverZ88, self).__init__() + super().__init__() self.menutext = Qt.QT_TRANSLATE_NOOP("FEM_SolverZ88", "Solver Z88") self.accel = "S, Z" self.tooltip = Qt.QT_TRANSLATE_NOOP("FEM_SolverZ88", "Creates a FEM solver Z88") @@ -1296,207 +1110,54 @@ class _SolverZ88(CommandManager): # the string in add command will be the page name on FreeCAD wiki -FreeCADGui.addCommand( - "FEM_Analysis", - _Analysis() -) -FreeCADGui.addCommand( - "FEM_ClippingPlaneAdd", - _ClippingPlaneAdd() -) -FreeCADGui.addCommand( - "FEM_ClippingPlaneRemoveAll", - _ClippingPlaneRemoveAll() -) -FreeCADGui.addCommand( - "FEM_ConstantVacuumPermittivity", - _ConstantVacuumPermittivity() -) -FreeCADGui.addCommand( - "FEM_ConstraintBodyHeatSource", - _ConstraintBodyHeatSource() -) -FreeCADGui.addCommand( - "FEM_ConstraintCentrif", - _ConstraintCentrif() -) -FreeCADGui.addCommand( - "FEM_ConstraintCurrentDensity", - _ConstraintCurrentDensity() -) -FreeCADGui.addCommand( - "FEM_ConstraintElectrostaticPotential", - _ConstraintElectrostaticPotential() -) -FreeCADGui.addCommand( - "FEM_ConstraintFlowVelocity", - _ConstraintFlowVelocity() -) -FreeCADGui.addCommand( - "FEM_ConstraintInitialFlowVelocity", - _ConstraintInitialFlowVelocity() -) -FreeCADGui.addCommand( - "FEM_ConstraintInitialPressure", - _ConstraintInitialPressure() -) -FreeCADGui.addCommand( - "FEM_ConstraintMagnetization", - _ConstraintMagnetization() -) -FreeCADGui.addCommand( - "FEM_ConstraintSectionPrint", - _ConstraintSectionPrint() -) -FreeCADGui.addCommand( - "FEM_ConstraintSelfWeight", - _ConstraintSelfWeight() -) -FreeCADGui.addCommand( - "FEM_ConstraintTie", - _ConstraintTie() -) -FreeCADGui.addCommand( - "FEM_ElementFluid1D", - _ElementFluid1D() -) -FreeCADGui.addCommand( - "FEM_ElementGeometry1D", - _ElementGeometry1D() -) -FreeCADGui.addCommand( - "FEM_ElementGeometry2D", - _ElementGeometry2D() -) -FreeCADGui.addCommand( - "FEM_ElementRotation1D", - _ElementRotation1D() -) -FreeCADGui.addCommand( - "FEM_EquationDeformation", - _EquationDeformation() -) -FreeCADGui.addCommand( - "FEM_EquationElasticity", - _EquationElasticity() -) -FreeCADGui.addCommand( - "FEM_EquationElectricforce", - _EquationElectricforce() -) -FreeCADGui.addCommand( - "FEM_EquationElectrostatic", - _EquationElectrostatic() -) -FreeCADGui.addCommand( - "FEM_EquationFlow", - _EquationFlow() -) -FreeCADGui.addCommand( - "FEM_EquationFlux", - _EquationFlux() -) -FreeCADGui.addCommand( - "FEM_EquationHeat", - _EquationHeat() -) -FreeCADGui.addCommand( - "FEM_EquationMagnetodynamic", - _EquationMagnetodynamic() -) -FreeCADGui.addCommand( - "FEM_EquationMagnetodynamic2D", - _EquationMagnetodynamic2D() -) -FreeCADGui.addCommand( - "FEM_Examples", - _Examples() -) -FreeCADGui.addCommand( - "FEM_MaterialEditor", - _MaterialEditor() -) -FreeCADGui.addCommand( - "FEM_MaterialFluid", - _MaterialFluid() -) -FreeCADGui.addCommand( - "FEM_MaterialMechanicalNonlinear", - _MaterialMechanicalNonlinear() -) -FreeCADGui.addCommand( - "FEM_MaterialReinforced", - _MaterialReinforced() -) -FreeCADGui.addCommand( - "FEM_MaterialSolid", - _MaterialSolid() -) -FreeCADGui.addCommand( - "FEM_FEMMesh2Mesh", - _FEMMesh2Mesh() -) -FreeCADGui.addCommand( - "FEM_MeshBoundaryLayer", - _MeshBoundaryLayer() -) -FreeCADGui.addCommand( - "FEM_MeshClear", - _MeshClear() -) -FreeCADGui.addCommand( - "FEM_MeshDisplayInfo", - _MeshDisplayInfo() -) -FreeCADGui.addCommand( - "FEM_MeshGmshFromShape", - _MeshGmshFromShape() -) -FreeCADGui.addCommand( - "FEM_MeshGroup", - _MeshGroup() -) -FreeCADGui.addCommand( - "FEM_MeshNetgenFromShape", - _MeshNetgenFromShape() -) -FreeCADGui.addCommand( - "FEM_MeshRegion", - _MeshRegion() -) -FreeCADGui.addCommand( - "FEM_ResultShow", - _ResultShow() -) -FreeCADGui.addCommand( - "FEM_ResultsPurge", - _ResultsPurge() -) -FreeCADGui.addCommand( - "FEM_SolverCalculiXCcxTools", - _SolverCcxTools() -) -FreeCADGui.addCommand( - "FEM_SolverCalculiX", - _SolverCalculix() -) -FreeCADGui.addCommand( - "FEM_SolverControl", - _SolverControl() -) -FreeCADGui.addCommand( - "FEM_SolverElmer", - _SolverElmer() -) -FreeCADGui.addCommand( - "FEM_SolverMystran", - _SolverMystran() -) -FreeCADGui.addCommand( - "FEM_SolverRun", - _SolverRun() -) -FreeCADGui.addCommand( - "FEM_SolverZ88", - _SolverZ88() -) +FreeCADGui.addCommand("FEM_Analysis", _Analysis()) +FreeCADGui.addCommand("FEM_ClippingPlaneAdd", _ClippingPlaneAdd()) +FreeCADGui.addCommand("FEM_ClippingPlaneRemoveAll", _ClippingPlaneRemoveAll()) +FreeCADGui.addCommand("FEM_ConstantVacuumPermittivity", _ConstantVacuumPermittivity()) +FreeCADGui.addCommand("FEM_ConstraintBodyHeatSource", _ConstraintBodyHeatSource()) +FreeCADGui.addCommand("FEM_ConstraintCentrif", _ConstraintCentrif()) +FreeCADGui.addCommand("FEM_ConstraintCurrentDensity", _ConstraintCurrentDensity()) +FreeCADGui.addCommand("FEM_ConstraintElectrostaticPotential", _ConstraintElectrostaticPotential()) +FreeCADGui.addCommand("FEM_ConstraintFlowVelocity", _ConstraintFlowVelocity()) +FreeCADGui.addCommand("FEM_ConstraintInitialFlowVelocity", _ConstraintInitialFlowVelocity()) +FreeCADGui.addCommand("FEM_ConstraintInitialPressure", _ConstraintInitialPressure()) +FreeCADGui.addCommand("FEM_ConstraintMagnetization", _ConstraintMagnetization()) +FreeCADGui.addCommand("FEM_ConstraintSectionPrint", _ConstraintSectionPrint()) +FreeCADGui.addCommand("FEM_ConstraintSelfWeight", _ConstraintSelfWeight()) +FreeCADGui.addCommand("FEM_ConstraintTie", _ConstraintTie()) +FreeCADGui.addCommand("FEM_ElementFluid1D", _ElementFluid1D()) +FreeCADGui.addCommand("FEM_ElementGeometry1D", _ElementGeometry1D()) +FreeCADGui.addCommand("FEM_ElementGeometry2D", _ElementGeometry2D()) +FreeCADGui.addCommand("FEM_ElementRotation1D", _ElementRotation1D()) +FreeCADGui.addCommand("FEM_EquationDeformation", _EquationDeformation()) +FreeCADGui.addCommand("FEM_EquationElasticity", _EquationElasticity()) +FreeCADGui.addCommand("FEM_EquationElectricforce", _EquationElectricforce()) +FreeCADGui.addCommand("FEM_EquationElectrostatic", _EquationElectrostatic()) +FreeCADGui.addCommand("FEM_EquationFlow", _EquationFlow()) +FreeCADGui.addCommand("FEM_EquationFlux", _EquationFlux()) +FreeCADGui.addCommand("FEM_EquationHeat", _EquationHeat()) +FreeCADGui.addCommand("FEM_EquationMagnetodynamic", _EquationMagnetodynamic()) +FreeCADGui.addCommand("FEM_EquationMagnetodynamic2D", _EquationMagnetodynamic2D()) +FreeCADGui.addCommand("FEM_Examples", _Examples()) +FreeCADGui.addCommand("FEM_MaterialEditor", _MaterialEditor()) +FreeCADGui.addCommand("FEM_MaterialFluid", _MaterialFluid()) +FreeCADGui.addCommand("FEM_MaterialMechanicalNonlinear", _MaterialMechanicalNonlinear()) +FreeCADGui.addCommand("FEM_MaterialReinforced", _MaterialReinforced()) +FreeCADGui.addCommand("FEM_MaterialSolid", _MaterialSolid()) +FreeCADGui.addCommand("FEM_FEMMesh2Mesh", _FEMMesh2Mesh()) +FreeCADGui.addCommand("FEM_MeshBoundaryLayer", _MeshBoundaryLayer()) +FreeCADGui.addCommand("FEM_MeshClear", _MeshClear()) +FreeCADGui.addCommand("FEM_MeshDisplayInfo", _MeshDisplayInfo()) +FreeCADGui.addCommand("FEM_MeshGmshFromShape", _MeshGmshFromShape()) +FreeCADGui.addCommand("FEM_MeshGroup", _MeshGroup()) +FreeCADGui.addCommand("FEM_MeshNetgenFromShape", _MeshNetgenFromShape()) +FreeCADGui.addCommand("FEM_MeshRegion", _MeshRegion()) +FreeCADGui.addCommand("FEM_ResultShow", _ResultShow()) +FreeCADGui.addCommand("FEM_ResultsPurge", _ResultsPurge()) +FreeCADGui.addCommand("FEM_SolverCalculiXCcxTools", _SolverCcxTools()) +FreeCADGui.addCommand("FEM_SolverCalculiX", _SolverCalculix()) +FreeCADGui.addCommand("FEM_SolverControl", _SolverControl()) +FreeCADGui.addCommand("FEM_SolverElmer", _SolverElmer()) +FreeCADGui.addCommand("FEM_SolverMystran", _SolverMystran()) +FreeCADGui.addCommand("FEM_SolverRun", _SolverRun()) +FreeCADGui.addCommand("FEM_SolverZ88", _SolverZ88()) diff --git a/src/Mod/Fem/femcommands/manager.py b/src/Mod/Fem/femcommands/manager.py index eb01cabfe8..789e19481e 100644 --- a/src/Mod/Fem/femcommands/manager.py +++ b/src/Mod/Fem/femcommands/manager.py @@ -41,7 +41,7 @@ if FreeCAD.GuiUp: import FemGui -class CommandManager(object): +class CommandManager: def __init__(self): @@ -49,7 +49,7 @@ class CommandManager(object): self.pixmap = self.command self.menutext = self.__class__.__name__.lstrip("_") self.accel = "" - self.tooltip = "Creates a {}".format(self.menutext) + self.tooltip = f"Creates a {self.menutext}" self.resources = None self.is_active = None @@ -64,7 +64,7 @@ class CommandManager(object): "Pixmap": self.pixmap, "MenuText": QtCore.QT_TRANSLATE_NOOP(self.command, self.menutext), "Accel": self.accel, - "ToolTip": QtCore.QT_TRANSLATE_NOOP(self.command, self.tooltip) + "ToolTip": QtCore.QT_TRANSLATE_NOOP(self.command, self.tooltip), } return self.resources @@ -76,10 +76,7 @@ class CommandManager(object): elif self.is_active == "with_document": active = FreeCADGui.ActiveDocument is not None elif self.is_active == "with_analysis": - active = ( - FemGui.getActiveAnalysis() is not None - and self.active_analysis_in_active_doc() - ) + active = FemGui.getActiveAnalysis() is not None and self.active_analysis_in_active_doc() elif self.is_active == "with_results": active = ( FemGui.getActiveAnalysis() is not None @@ -93,24 +90,14 @@ class CommandManager(object): and self.result_selected() ) elif self.is_active == "with_part_feature": - active = ( - FreeCADGui.ActiveDocument is not None - and self.part_feature_selected() - ) + active = FreeCADGui.ActiveDocument is not None and self.part_feature_selected() elif self.is_active == "with_femmesh": - active = ( - FreeCADGui.ActiveDocument is not None - and self.femmesh_selected() - ) + active = FreeCADGui.ActiveDocument is not None and self.femmesh_selected() elif self.is_active == "with_gmsh_femmesh": - active = ( - FreeCADGui.ActiveDocument is not None - and self.gmsh_femmesh_selected() - ) + active = FreeCADGui.ActiveDocument is not None and self.gmsh_femmesh_selected() elif self.is_active == "with_femmesh_andor_res": active = ( - FreeCADGui.ActiveDocument is not None - and self.with_femmesh_andor_res_selected() + FreeCADGui.ActiveDocument is not None and self.with_femmesh_andor_res_selected() ) elif self.is_active == "with_material": active = ( @@ -301,20 +288,12 @@ class CommandManager(object): # methods to add the objects to the document in FreeCADGui mode def add_obj_on_gui_set_edit(self, objtype): - FreeCAD.ActiveDocument.openTransaction( - "Create Fem{}" - .format(objtype) - ) - FreeCADGui.addModule( - "ObjectsFem" - ) - FreeCADGui.addModule( - "FemGui" - ) + FreeCAD.ActiveDocument.openTransaction(f"Create Fem{objtype}") + FreeCADGui.addModule("ObjectsFem") + FreeCADGui.addModule("FemGui") FreeCADGui.doCommand( "FemGui.getActiveAnalysis().addObject(ObjectsFem." - "make{}(FreeCAD.ActiveDocument))" - .format(objtype) + "make{}(FreeCAD.ActiveDocument))".format(objtype) ) # no other obj should be selected if we go in task panel FreeCADGui.Selection.clearSelection() @@ -324,20 +303,12 @@ class CommandManager(object): FreeCAD.ActiveDocument.recompute() def add_obj_on_gui_noset_edit(self, objtype): - FreeCAD.ActiveDocument.openTransaction( - "Create Fem{}" - .format(objtype) - ) - FreeCADGui.addModule( - "ObjectsFem" - ) - FreeCADGui.addModule( - "FemGui" - ) + FreeCAD.ActiveDocument.openTransaction(f"Create Fem{objtype}") + FreeCADGui.addModule("ObjectsFem") + FreeCADGui.addModule("FemGui") FreeCADGui.doCommand( "FemGui.getActiveAnalysis().addObject(ObjectsFem." - "make{}(FreeCAD.ActiveDocument))" - .format(objtype) + "make{}(FreeCAD.ActiveDocument))".format(objtype) ) # FreeCAD.ActiveDocument.commitTransaction() # solver command class had this line # no clear selection is done @@ -347,23 +318,15 @@ class CommandManager(object): # like add_obj_on_gui_noset_edit but the parent object # is expanded in the tree to see the added obj # the added obj is also selected to enable direct additions to it - FreeCAD.ActiveDocument.openTransaction( - "Create Fem{}" - .format(objtype) - ) - FreeCADGui.addModule( - "ObjectsFem" - ) - FreeCADGui.addModule( - "FemGui" - ) + FreeCAD.ActiveDocument.openTransaction(f"Create Fem{objtype}") + FreeCADGui.addModule("ObjectsFem") + FreeCADGui.addModule("FemGui") # expand parent obj in tree view if selected expandParentObject() # add the object FreeCADGui.doCommand( "addedObj = FemGui.getActiveAnalysis().addObject(ObjectsFem." - "make{}(FreeCAD.ActiveDocument))[0]" - .format(objtype) + "make{}(FreeCAD.ActiveDocument))[0]".format(objtype) ) # select only added object FreeCADGui.Selection.clearSelection() @@ -372,17 +335,11 @@ class CommandManager(object): FreeCAD.ActiveDocument.recompute() def add_obj_on_gui_selobj_set_edit(self, objtype): - FreeCAD.ActiveDocument.openTransaction( - "Create Fem{}" - .format(objtype) - ) - FreeCADGui.addModule( - "ObjectsFem" - ) + FreeCAD.ActiveDocument.openTransaction(f"Create Fem{objtype}") + FreeCADGui.addModule("ObjectsFem") FreeCADGui.doCommand( "ObjectsFem.make{}(" - "FreeCAD.ActiveDocument, FreeCAD.ActiveDocument.{})" - .format(objtype, self.selobj.Name) + "FreeCAD.ActiveDocument, FreeCAD.ActiveDocument.{})".format(objtype, self.selobj.Name) ) FreeCADGui.Selection.clearSelection() FreeCADGui.doCommand( @@ -391,17 +348,11 @@ class CommandManager(object): FreeCAD.ActiveDocument.recompute() def add_obj_on_gui_selobj_noset_edit(self, objtype): - FreeCAD.ActiveDocument.openTransaction( - "Create Fem{}" - .format(objtype) - ) - FreeCADGui.addModule( - "ObjectsFem" - ) + FreeCAD.ActiveDocument.openTransaction(f"Create Fem{objtype}") + FreeCADGui.addModule("ObjectsFem") FreeCADGui.doCommand( "ObjectsFem.make{}(" - "FreeCAD.ActiveDocument, FreeCAD.ActiveDocument.{})" - .format(objtype, self.selobj.Name) + "FreeCAD.ActiveDocument, FreeCAD.ActiveDocument.{})".format(objtype, self.selobj.Name) ) FreeCADGui.Selection.clearSelection() FreeCAD.ActiveDocument.recompute() @@ -409,17 +360,11 @@ class CommandManager(object): def add_obj_on_gui_selobj_expand_noset_edit(self, objtype): # like add_obj_on_gui_selobj_noset_edit but the selection is kept # and the selobj is expanded in the tree to see the added obj - FreeCAD.ActiveDocument.openTransaction( - "Create Fem{}" - .format(objtype) - ) - FreeCADGui.addModule( - "ObjectsFem" - ) + FreeCAD.ActiveDocument.openTransaction(f"Create Fem{objtype}") + FreeCADGui.addModule("ObjectsFem") FreeCADGui.doCommand( "ObjectsFem.make{}(" - "FreeCAD.ActiveDocument, FreeCAD.ActiveDocument.{})" - .format(objtype, self.selobj.Name) + "FreeCAD.ActiveDocument, FreeCAD.ActiveDocument.{})".format(objtype, self.selobj.Name) ) # expand selobj in tree view expandParentObject() diff --git a/src/Mod/Fem/femexamples/boxanalysis_base.py b/src/Mod/Fem/femexamples/boxanalysis_base.py index 71d9e5d333..fdf0484023 100644 --- a/src/Mod/Fem/femexamples/boxanalysis_base.py +++ b/src/Mod/Fem/femexamples/boxanalysis_base.py @@ -63,6 +63,7 @@ def setup_boxanalysisbase(doc=None, solvertype="ccxtools"): # mesh from .meshes.mesh_boxanalysis_tetra10 import create_nodes, create_elements + fem_mesh = Fem.FemMesh() control = create_nodes(fem_mesh) if not control: diff --git a/src/Mod/Fem/femexamples/boxanalysis_frequency.py b/src/Mod/Fem/femexamples/boxanalysis_frequency.py index 2c6918a15c..67628832ac 100644 --- a/src/Mod/Fem/femexamples/boxanalysis_frequency.py +++ b/src/Mod/Fem/femexamples/boxanalysis_frequency.py @@ -37,12 +37,14 @@ def get_information(): "constraints": [], "solvers": ["ccxtools"], "material": "solid", - "equations": ["frequency"] + "equations": ["frequency"], } def get_explanation(header=""): - return header + """ + return ( + header + + """ To run the example from Python console use: from femexamples.boxanalysis_frequency import setup @@ -53,6 +55,7 @@ See forum topic post: ... """ + ) def setup(doc=None, solvertype="ccxtools"): @@ -72,7 +75,7 @@ def setup(doc=None, solvertype="ccxtools"): # solver if solvertype == "ccxtools": solver_obj = ObjectsFem.makeSolverCalculiXCcxTools(doc, "CalculiXCcxTools") - solver_obj.WorkingDir = u"" + solver_obj.WorkingDir = "" if solvertype == "ccxtools": solver_obj.AnalysisType = "frequency" solver_obj.GeometricalNonlinearity = "linear" diff --git a/src/Mod/Fem/femexamples/boxanalysis_static.py b/src/Mod/Fem/femexamples/boxanalysis_static.py index 8e44bac59e..3b4eee2c2c 100644 --- a/src/Mod/Fem/femexamples/boxanalysis_static.py +++ b/src/Mod/Fem/femexamples/boxanalysis_static.py @@ -39,12 +39,14 @@ def get_information(): "constraints": ["fixed", "force", "pressure"], "solvers": ["ccxtools", "elmer"], "material": "solid", - "equations": ["mechanical"] + "equations": ["mechanical"], } def get_explanation(header=""): - return header + """ + return ( + header + + """ To run the example from Python console use: from femexamples.boxanalysis_static import setup @@ -55,6 +57,7 @@ See forum topic post: ... """ + ) def setup(doc=None, solvertype="ccxtools"): @@ -75,7 +78,7 @@ def setup(doc=None, solvertype="ccxtools"): # solver if solvertype == "ccxtools": solver_obj = ObjectsFem.makeSolverCalculiXCcxTools(doc, "CalculiXCcxTools") - solver_obj.WorkingDir = u"" + solver_obj.WorkingDir = "" elif solvertype == "elmer": solver_obj = ObjectsFem.makeSolverElmer(doc, "SolverElmer") ObjectsFem.makeEquationElasticity(doc, solver_obj) diff --git a/src/Mod/Fem/femexamples/buckling_lateraltorsionalbuckling.py b/src/Mod/Fem/femexamples/buckling_lateraltorsionalbuckling.py index b4886c3141..74018d2ac5 100644 --- a/src/Mod/Fem/femexamples/buckling_lateraltorsionalbuckling.py +++ b/src/Mod/Fem/femexamples/buckling_lateraltorsionalbuckling.py @@ -39,12 +39,14 @@ def get_information(): "constraints": ["displacement", "force"], "solvers": ["ccxtools"], "material": "solid", - "equations": ["buckling"] + "equations": ["buckling"], } def get_explanation(header=""): - return header + """ + return ( + header + + """ To run the example from Python console use: from femexamples.buckling_lateraltorsionalbuckling import setup @@ -65,6 +67,7 @@ flange load for a buckling factor of 1.00: 43280000 Nmm / 278.6 mm = 155348 N """ + ) def setup(doc=None, solvertype="ccxtools"): @@ -108,7 +111,7 @@ def setup(doc=None, solvertype="ccxtools"): # solver if solvertype == "ccxtools": solver_obj = ObjectsFem.makeSolverCalculiXCcxTools(doc, "CalculiXCcxTools") - solver_obj.WorkingDir = u"" + solver_obj.WorkingDir = "" else: FreeCAD.Console.PrintWarning( "Unknown or unsupported solver type: {}. " @@ -125,10 +128,10 @@ def setup(doc=None, solvertype="ccxtools"): analysis.addObject(solver_obj) # shell thicknesses - thickness_flanges = ObjectsFem.makeElementGeometry2D(doc, 10.7, 'Thickness_Flanges') + thickness_flanges = ObjectsFem.makeElementGeometry2D(doc, 10.7, "Thickness_Flanges") thickness_flanges.References = [(geom_obj, ("Face1", "Face2", "Face3", "Face4"))] analysis.addObject(thickness_flanges) - thickness_web = ObjectsFem.makeElementGeometry2D(doc, 7.1, 'Thickness_Web') + thickness_web = ObjectsFem.makeElementGeometry2D(doc, 7.1, "Thickness_Web") thickness_web.References = [(geom_obj, "Face5")] analysis.addObject(thickness_web) @@ -173,6 +176,7 @@ def setup(doc=None, solvertype="ccxtools"): # mesh from .meshes.mesh_buckling_ibeam_tria6 import create_nodes, create_elements + fem_mesh = Fem.FemMesh() control = create_nodes(fem_mesh) if not control: diff --git a/src/Mod/Fem/femexamples/buckling_platebuckling.py b/src/Mod/Fem/femexamples/buckling_platebuckling.py index bee21be01a..65b8f1ea9f 100644 --- a/src/Mod/Fem/femexamples/buckling_platebuckling.py +++ b/src/Mod/Fem/femexamples/buckling_platebuckling.py @@ -39,12 +39,14 @@ def get_information(): "constraints": ["displacement", "force"], "solvers": ["ccxtools"], "material": "solid", - "equations": ["buckling"] + "equations": ["buckling"], } def get_explanation(header=""): - return header + """ + return ( + header + + """ To run the example from Python console use: from femexamples.buckling_platebuckling import setup @@ -55,6 +57,7 @@ See forum topic post: https://forum.freecad.org/viewtopic.php?f=18&t=20217&start=110#p509935 """ + ) def setup(doc=None, solvertype="ccxtools"): @@ -82,7 +85,7 @@ def setup(doc=None, solvertype="ccxtools"): # solver if solvertype == "ccxtools": solver_obj = ObjectsFem.makeSolverCalculiXCcxTools(doc, "CalculiXCcxTools") - solver_obj.WorkingDir = u"" + solver_obj.WorkingDir = "" else: FreeCAD.Console.PrintWarning( "Unknown or unsupported solver type: {}. " @@ -100,7 +103,7 @@ def setup(doc=None, solvertype="ccxtools"): analysis.addObject(solver_obj) # shell thickness - thickness_obj = ObjectsFem.makeElementGeometry2D(doc, 50, 'Thickness') + thickness_obj = ObjectsFem.makeElementGeometry2D(doc, 50, "Thickness") analysis.addObject(thickness_obj) # material @@ -146,6 +149,7 @@ def setup(doc=None, solvertype="ccxtools"): # mesh from .meshes.mesh_buckling_plate_tria6 import create_nodes, create_elements + fem_mesh = Fem.FemMesh() control = create_nodes(fem_mesh) if not control: diff --git a/src/Mod/Fem/femexamples/ccx_buckling_flexuralbuckling.py b/src/Mod/Fem/femexamples/ccx_buckling_flexuralbuckling.py index 40ec0b7038..264696e7d3 100644 --- a/src/Mod/Fem/femexamples/ccx_buckling_flexuralbuckling.py +++ b/src/Mod/Fem/femexamples/ccx_buckling_flexuralbuckling.py @@ -40,12 +40,14 @@ def get_information(): "constraints": ["fixed", "force"], "solvers": ["ccxtools"], "material": "solid", - "equations": ["buckling"] + "equations": ["buckling"], } def get_explanation(header=""): - return header + """ + return ( + header + + """ To run the example from Python console use: from femexamples.ccx_buckling_flexuralbuckling import setup @@ -59,6 +61,7 @@ This example is based on a CalculiX verification example. http://www.feacluster.com/CalculiX/ccx_2.13/doc/ccx/input_deck_viewer.php?input_deck=beam8b.inp """ + ) def setup(doc=None, solvertype="ccxtools"): @@ -87,7 +90,7 @@ def setup(doc=None, solvertype="ccxtools"): # solver, if solvertype == "ccxtools": solver_obj = ObjectsFem.makeSolverCalculiXCcxTools(doc, "CalculiXCcxTools") - solver_obj.WorkingDir = u"" + solver_obj.WorkingDir = "" else: FreeCAD.Console.PrintWarning( "Unknown or unsupported solver type: {}. " @@ -126,6 +129,7 @@ def setup(doc=None, solvertype="ccxtools"): # mesh from .meshes.mesh_flexural_buckling import create_nodes, create_elements + fem_mesh = Fem.FemMesh() control = create_nodes(fem_mesh) if not control: diff --git a/src/Mod/Fem/femexamples/ccx_cantilever_base_edge.py b/src/Mod/Fem/femexamples/ccx_cantilever_base_edge.py index 8633ad959d..8528a59bd3 100644 --- a/src/Mod/Fem/femexamples/ccx_cantilever_base_edge.py +++ b/src/Mod/Fem/femexamples/ccx_cantilever_base_edge.py @@ -69,7 +69,7 @@ def setup_cantilever_base_edge(doc=None, solvertype="ccxtools"): # solver if solvertype == "ccxtools": solver_obj = ObjectsFem.makeSolverCalculiXCcxTools(doc, "CalculiXCcxTools") - solver_obj.WorkingDir = u"" + solver_obj.WorkingDir = "" elif solvertype == "mystran": solver_obj = ObjectsFem.makeSolverMystran(doc, "SolverMystran") else: @@ -92,7 +92,7 @@ def setup_cantilever_base_edge(doc=None, solvertype="ccxtools"): sectiontype="Rectangular", width=1000.0, height=1000.0, - name="BeamCrossSection" + name="BeamCrossSection", ) analysis.addObject(beamsection_obj) @@ -113,13 +113,14 @@ def setup_cantilever_base_edge(doc=None, solvertype="ccxtools"): # constraint force con_force = ObjectsFem.makeConstraintForce(doc, "ConstraintForce") con_force.References = [(geom_obj, "Vertex2")] - con_force.Force = "9000000.0 N" # 9 MN + con_force.Force = "9000000.0 N" # 9 MN con_force.Direction = (load_line, ["Edge1"]) con_force.Reversed = False analysis.addObject(con_force) # mesh from .meshes.mesh_canticcx_seg3 import create_nodes, create_elements + fem_mesh = Fem.FemMesh() control = create_nodes(fem_mesh) if not control: diff --git a/src/Mod/Fem/femexamples/ccx_cantilever_base_face.py b/src/Mod/Fem/femexamples/ccx_cantilever_base_face.py index 4eaca443f2..e241fa6dc8 100644 --- a/src/Mod/Fem/femexamples/ccx_cantilever_base_face.py +++ b/src/Mod/Fem/femexamples/ccx_cantilever_base_face.py @@ -58,7 +58,7 @@ def setup_cantilever_base_face(doc=None, solvertype="ccxtools"): # solver if solvertype == "ccxtools": solver_obj = ObjectsFem.makeSolverCalculiXCcxTools(doc, "CalculiXCcxTools") - solver_obj.WorkingDir = u"" + solver_obj.WorkingDir = "" elif solvertype == "mystran": solver_obj = ObjectsFem.makeSolverMystran(doc, "SolverMystran") elif solvertype == "z88": @@ -78,7 +78,7 @@ def setup_cantilever_base_face(doc=None, solvertype="ccxtools"): analysis.addObject(solver_obj) # shell thickness - thickness_obj = ObjectsFem.makeElementGeometry2D(doc, 1000, 'Thickness') + thickness_obj = ObjectsFem.makeElementGeometry2D(doc, 1000, "Thickness") analysis.addObject(thickness_obj) # material @@ -105,6 +105,7 @@ def setup_cantilever_base_face(doc=None, solvertype="ccxtools"): # mesh from .meshes.mesh_canticcx_tria6 import create_nodes, create_elements + fem_mesh = Fem.FemMesh() control = create_nodes(fem_mesh) if not control: diff --git a/src/Mod/Fem/femexamples/ccx_cantilever_base_solid.py b/src/Mod/Fem/femexamples/ccx_cantilever_base_solid.py index 160d6dbf2f..9edc993cf1 100644 --- a/src/Mod/Fem/femexamples/ccx_cantilever_base_solid.py +++ b/src/Mod/Fem/femexamples/ccx_cantilever_base_solid.py @@ -54,7 +54,7 @@ def setup_cantilever_base_solid(doc=None, solvertype="ccxtools"): # solver if solvertype == "ccxtools": solver_obj = ObjectsFem.makeSolverCalculiXCcxTools(doc, "CalculiXCcxTools") - solver_obj.WorkingDir = u"" + solver_obj.WorkingDir = "" elif solvertype == "elmer": solver_obj = ObjectsFem.makeSolverElmer(doc, "SolverElmer") ObjectsFem.makeEquationElasticity(doc, solver_obj) @@ -92,6 +92,7 @@ def setup_cantilever_base_solid(doc=None, solvertype="ccxtools"): # mesh from .meshes.mesh_canticcx_tetra10 import create_nodes, create_elements + fem_mesh = Fem.FemMesh() control = create_nodes(fem_mesh) if not control: diff --git a/src/Mod/Fem/femexamples/ccx_cantilever_beam_circle.py b/src/Mod/Fem/femexamples/ccx_cantilever_beam_circle.py index fc1c4e50cd..fe2fad0400 100644 --- a/src/Mod/Fem/femexamples/ccx_cantilever_beam_circle.py +++ b/src/Mod/Fem/femexamples/ccx_cantilever_beam_circle.py @@ -36,12 +36,14 @@ def get_information(): "constraints": ["fixed", "force"], "solvers": ["ccxtools"], "material": "solid", - "equations": ["mechanical"] + "equations": ["mechanical"], } def get_explanation(header=""): - return header + """ + return ( + header + + """ To run the example from Python console use: from femexamples.ccx_cantilever_beam_circle import setup @@ -73,6 +75,7 @@ CalculiX FEM max deflection: - Delta ca. 1.5 % """ + ) def setup(doc=None, solvertype="ccxtools"): diff --git a/src/Mod/Fem/femexamples/ccx_cantilever_beam_pipe.py b/src/Mod/Fem/femexamples/ccx_cantilever_beam_pipe.py index 7855db288f..e4d38e872b 100644 --- a/src/Mod/Fem/femexamples/ccx_cantilever_beam_pipe.py +++ b/src/Mod/Fem/femexamples/ccx_cantilever_beam_pipe.py @@ -36,12 +36,14 @@ def get_information(): "constraints": ["fixed", "force"], "solvers": ["ccxtools"], "material": "solid", - "equations": ["mechanical"] + "equations": ["mechanical"], } def get_explanation(header=""): - return header + """ + return ( + header + + """ To run the example from Python console use: from femexamples.ccx_cantilever_beam_pipe import setup @@ -77,6 +79,7 @@ CalculiX FEM max deflection: - Delta ca. 1.0 % """ + ) def setup(doc=None, solvertype="ccxtools"): diff --git a/src/Mod/Fem/femexamples/ccx_cantilever_beam_rect.py b/src/Mod/Fem/femexamples/ccx_cantilever_beam_rect.py index ef6a164404..218291e421 100644 --- a/src/Mod/Fem/femexamples/ccx_cantilever_beam_rect.py +++ b/src/Mod/Fem/femexamples/ccx_cantilever_beam_rect.py @@ -36,12 +36,14 @@ def get_information(): "constraints": ["fixed", "force"], "solvers": ["ccxtools"], "material": "solid", - "equations": ["mechanical"] + "equations": ["mechanical"], } def get_explanation(header=""): - return header + """ + return ( + header + + """ To run the example from Python console use: from femexamples.ccx_cantilever_beam_rect import setup @@ -74,6 +76,7 @@ CalculiX FEM max deflection: - but the rotation seems 90 degree rotated (FIXME) """ + ) def setup(doc=None, solvertype="ccxtools"): diff --git a/src/Mod/Fem/femexamples/ccx_cantilever_ele_hexa20.py b/src/Mod/Fem/femexamples/ccx_cantilever_ele_hexa20.py index 88a08009c7..3ff22f19af 100644 --- a/src/Mod/Fem/femexamples/ccx_cantilever_ele_hexa20.py +++ b/src/Mod/Fem/femexamples/ccx_cantilever_ele_hexa20.py @@ -40,12 +40,14 @@ def get_information(): "constraints": ["fixed", "force"], "solvers": ["ccxtools", "elmer", "z88"], "material": "solid", - "equations": ["mechanical"] + "equations": ["mechanical"], } def get_explanation(header=""): - return header + """ + return ( + header + + """ To run the example from Python console use: from femexamples.ccx_cantilever_ele_hexa20 import setup @@ -57,6 +59,7 @@ hexa20 elements and face load ... """ + ) def setup(doc=None, solvertype="ccxtools"): @@ -80,6 +83,7 @@ def setup(doc=None, solvertype="ccxtools"): # load the hexa20 mesh from .meshes.mesh_canticcx_hexa20 import create_nodes, create_elements + new_fem_mesh = Fem.FemMesh() control = create_nodes(new_fem_mesh) if not control: diff --git a/src/Mod/Fem/femexamples/ccx_cantilever_ele_quad4.py b/src/Mod/Fem/femexamples/ccx_cantilever_ele_quad4.py index 984aba1db1..732bf67b9b 100644 --- a/src/Mod/Fem/femexamples/ccx_cantilever_ele_quad4.py +++ b/src/Mod/Fem/femexamples/ccx_cantilever_ele_quad4.py @@ -39,12 +39,14 @@ def get_information(): "constraints": ["fixed", "force"], "solvers": ["ccxtools", "mystran"], "material": "solid", - "equations": ["mechanical"] + "equations": ["mechanical"], } def get_explanation(header=""): - return header + """ + return ( + header + + """ To run the example from Python console use: from femexamples.ccx_cantilever_ele_quad4 import setup @@ -57,6 +59,7 @@ See forum topic post: CalculiX cantilever modeled with quad4 face elements """ + ) def setup(doc=None, solvertype="ccxtools"): @@ -76,6 +79,7 @@ def setup(doc=None, solvertype="ccxtools"): # load the quad4 mesh from .meshes.mesh_canticcx_quad4 import create_nodes, create_elements + new_fem_mesh = Fem.FemMesh() control = create_nodes(new_fem_mesh) if not control: diff --git a/src/Mod/Fem/femexamples/ccx_cantilever_ele_quad8.py b/src/Mod/Fem/femexamples/ccx_cantilever_ele_quad8.py index b7497246eb..81aba770d7 100644 --- a/src/Mod/Fem/femexamples/ccx_cantilever_ele_quad8.py +++ b/src/Mod/Fem/femexamples/ccx_cantilever_ele_quad8.py @@ -39,12 +39,14 @@ def get_information(): "constraints": ["fixed", "force"], "solvers": ["ccxtools"], "material": "solid", - "equations": ["mechanical"] + "equations": ["mechanical"], } def get_explanation(header=""): - return header + """ + return ( + header + + """ To run the example from Python console use: from femexamples.ccx_cantilever_ele_quad8 import setup @@ -57,6 +59,7 @@ See forum topic post: CalculiX cantilever modeled with quad8 face elements """ + ) def setup(doc=None, solvertype="ccxtools"): @@ -76,6 +79,7 @@ def setup(doc=None, solvertype="ccxtools"): # load the quad8 mesh from .meshes.mesh_canticcx_quad8 import create_nodes, create_elements + new_fem_mesh = Fem.FemMesh() control = create_nodes(new_fem_mesh) if not control: diff --git a/src/Mod/Fem/femexamples/ccx_cantilever_ele_seg2.py b/src/Mod/Fem/femexamples/ccx_cantilever_ele_seg2.py index 4b59d49954..6a3b39e430 100644 --- a/src/Mod/Fem/femexamples/ccx_cantilever_ele_seg2.py +++ b/src/Mod/Fem/femexamples/ccx_cantilever_ele_seg2.py @@ -39,12 +39,14 @@ def get_information(): "constraints": ["fixed", "force"], "solvers": ["ccxtools", "mystran"], "material": "solid", - "equations": ["mechanical"] + "equations": ["mechanical"], } def get_explanation(header=""): - return header + """ + return ( + header + + """ To run the example from Python console use: from femexamples.ccx_cantilever_ele_seg2 import setup @@ -57,6 +59,7 @@ https://forum.freecad.org/viewtopic.php?f=18&t=16044 CalculiX cantilever modeled with seg2 beam elements """ + ) def setup(doc=None, solvertype="ccxtools"): @@ -76,6 +79,7 @@ def setup(doc=None, solvertype="ccxtools"): # load the seg2 mesh from .meshes.mesh_canticcx_seg2 import create_nodes, create_elements + new_fem_mesh = Fem.FemMesh() control = create_nodes(new_fem_mesh) if not control: diff --git a/src/Mod/Fem/femexamples/ccx_cantilever_ele_seg3.py b/src/Mod/Fem/femexamples/ccx_cantilever_ele_seg3.py index 1736e1fc59..a172529b05 100644 --- a/src/Mod/Fem/femexamples/ccx_cantilever_ele_seg3.py +++ b/src/Mod/Fem/femexamples/ccx_cantilever_ele_seg3.py @@ -34,12 +34,14 @@ def get_information(): "constraints": ["fixed", "force"], "solvers": ["ccxtools"], "material": "solid", - "equations": ["mechanical"] + "equations": ["mechanical"], } def get_explanation(header=""): - return header + """ + return ( + header + + """ To run the example from Python console use: from femexamples.ccx_cantilever_ele_seg3 import setup @@ -52,6 +54,7 @@ https://forum.freecad.org/viewtopic.php?f=18&t=16044 CalculiX cantilever modeled with seg3 beam elements """ + ) def setup(doc=None, solvertype="ccxtools"): diff --git a/src/Mod/Fem/femexamples/ccx_cantilever_ele_tetra4.py b/src/Mod/Fem/femexamples/ccx_cantilever_ele_tetra4.py index e6bbc8016b..aaee791155 100644 --- a/src/Mod/Fem/femexamples/ccx_cantilever_ele_tetra4.py +++ b/src/Mod/Fem/femexamples/ccx_cantilever_ele_tetra4.py @@ -38,12 +38,14 @@ def get_information(): "constraints": ["fixed", "force"], "solvers": ["ccxtools", "elmer", "mystran", "z88"], "material": "solid", - "equations": ["mechanical"] + "equations": ["mechanical"], } def get_explanation(header=""): - return header + """ + return ( + header + + """ To run the example from Python console use: from femexamples.ccx_cantilever_ele_tetra4 import setup @@ -55,6 +57,7 @@ Mesh before run the example. ... """ + ) def setup(doc=None, solvertype="ccxtools"): diff --git a/src/Mod/Fem/femexamples/ccx_cantilever_ele_tria3.py b/src/Mod/Fem/femexamples/ccx_cantilever_ele_tria3.py index f5f406ce28..2ce9f607ef 100644 --- a/src/Mod/Fem/femexamples/ccx_cantilever_ele_tria3.py +++ b/src/Mod/Fem/femexamples/ccx_cantilever_ele_tria3.py @@ -39,12 +39,14 @@ def get_information(): "constraints": ["fixed", "force"], "solvers": ["ccxtools", "mystran"], "material": "solid", - "equations": ["mechanical"] + "equations": ["mechanical"], } def get_explanation(header=""): - return header + """ + return ( + header + + """ To run the example from Python console use: from femexamples.ccx_cantilever_ele_tria3 import setup @@ -57,6 +59,7 @@ See forum topic post: CalculiX cantilever modeled with tria3 face elements """ + ) def setup(doc=None, solvertype="ccxtools"): @@ -76,6 +79,7 @@ def setup(doc=None, solvertype="ccxtools"): # load the tria3 mesh from .meshes.mesh_canticcx_tria3 import create_nodes, create_elements + new_fem_mesh = Fem.FemMesh() control = create_nodes(new_fem_mesh) if not control: diff --git a/src/Mod/Fem/femexamples/ccx_cantilever_ele_tria6.py b/src/Mod/Fem/femexamples/ccx_cantilever_ele_tria6.py index aad7e19531..56383b7b5e 100644 --- a/src/Mod/Fem/femexamples/ccx_cantilever_ele_tria6.py +++ b/src/Mod/Fem/femexamples/ccx_cantilever_ele_tria6.py @@ -34,12 +34,14 @@ def get_information(): "constraints": ["fixed", "force"], "solvers": ["ccxtools", "z88"], "material": "solid", - "equations": ["mechanical"] + "equations": ["mechanical"], } def get_explanation(header=""): - return header + """ + return ( + header + + """ To run the example from Python console use: from femexamples.ccx_cantilever_ele_tria6 import setup @@ -51,6 +53,7 @@ See forum topic post: CalculiX cantilever modeled with face elements """ + ) def setup(doc=None, solvertype="ccxtools"): diff --git a/src/Mod/Fem/femexamples/ccx_cantilever_faceload.py b/src/Mod/Fem/femexamples/ccx_cantilever_faceload.py index b84a83c34b..46658dcd9a 100644 --- a/src/Mod/Fem/femexamples/ccx_cantilever_faceload.py +++ b/src/Mod/Fem/femexamples/ccx_cantilever_faceload.py @@ -37,12 +37,14 @@ def get_information(): "constraints": ["fixed", "force"], "solvers": ["ccxtools", "elmer", "mystran", "z88"], "material": "solid", - "equations": ["mechanical"] + "equations": ["mechanical"], } def get_explanation(header=""): - return header + """ + return ( + header + + """ To run the example from Python console use: from femexamples.ccx_cantilever_faceload import setup @@ -53,6 +55,7 @@ See forum topic post: ... """ + ) def setup(doc=None, solvertype="ccxtools"): diff --git a/src/Mod/Fem/femexamples/ccx_cantilever_nodeload.py b/src/Mod/Fem/femexamples/ccx_cantilever_nodeload.py index 1e73a7495e..b2e2a30e8a 100644 --- a/src/Mod/Fem/femexamples/ccx_cantilever_nodeload.py +++ b/src/Mod/Fem/femexamples/ccx_cantilever_nodeload.py @@ -37,12 +37,14 @@ def get_information(): "constraints": ["fixed", "force"], "solvers": ["ccxtools", "elmer", "mystran", "z88"], "material": "solid", - "equations": ["mechanical"] + "equations": ["mechanical"], } def get_explanation(header=""): - return header + """ + return ( + header + + """ To run the example from Python console use: from femexamples.ccx_cantilever_nodeload import setup @@ -53,6 +55,7 @@ See forum topic post: ... """ + ) def setup(doc=None, solvertype="ccxtools"): @@ -76,7 +79,7 @@ def setup(doc=None, solvertype="ccxtools"): (geom_obj, "Vertex5"), (geom_obj, "Vertex6"), (geom_obj, "Vertex7"), - (geom_obj, "Vertex8") + (geom_obj, "Vertex8"), ] con_force.Force = "9000000.0 N" con_force.Direction = (doc.Box, ["Edge5"]) diff --git a/src/Mod/Fem/femexamples/ccx_cantilever_prescribeddisplacement.py b/src/Mod/Fem/femexamples/ccx_cantilever_prescribeddisplacement.py index 91b4b441a7..5ca90a9fae 100644 --- a/src/Mod/Fem/femexamples/ccx_cantilever_prescribeddisplacement.py +++ b/src/Mod/Fem/femexamples/ccx_cantilever_prescribeddisplacement.py @@ -37,12 +37,14 @@ def get_information(): "constraints": ["fixed", "displacement"], "solvers": ["ccxtools", "elmer"], "material": "solid", - "equations": ["mechanical"] + "equations": ["mechanical"], } def get_explanation(header=""): - return header + """ + return ( + header + + """ To run the example from Python console use: from femexamples.ccx_cantilever_prescribeddisplacement import setup @@ -53,6 +55,7 @@ See forum topic post: ... """ + ) def setup(doc=None, solvertype="ccxtools"): diff --git a/src/Mod/Fem/femexamples/constraint_centrif.py b/src/Mod/Fem/femexamples/constraint_centrif.py index c48107789c..caa95808fc 100644 --- a/src/Mod/Fem/femexamples/constraint_centrif.py +++ b/src/Mod/Fem/femexamples/constraint_centrif.py @@ -44,12 +44,14 @@ def get_information(): "constraints": ["centrif", "fixed"], "solvers": ["ccxtools"], "material": "multimaterial", - "equations": ["mechanical"] + "equations": ["mechanical"], } def get_explanation(header=""): - return header + """ + return ( + header + + """ To run the example from Python console use: from femexamples.constraint_centrif import setup @@ -62,6 +64,7 @@ https://forum.freecad.org/viewtopic.php?f=18&t=57770 constraint centrif, concerning CENTRIF label from ccx's *DLOAD card """ + ) def setup(doc=None, solvertype="ccxtools"): @@ -129,7 +132,7 @@ def setup(doc=None, solvertype="ccxtools"): # solver if solvertype == "ccxtools": solver_obj = ObjectsFem.makeSolverCalculiXCcxTools(doc, "CalculiXCcxTools") - solver_obj.WorkingDir = u"" + solver_obj.WorkingDir = "" else: FreeCAD.Console.PrintWarning( "Unknown or unsupported solver type: {}. " @@ -178,6 +181,7 @@ def setup(doc=None, solvertype="ccxtools"): # mesh from .meshes.mesh_constraint_centrif_tetra10 import create_nodes, create_elements + fem_mesh = Fem.FemMesh() control = create_nodes(fem_mesh) if not control: diff --git a/src/Mod/Fem/femexamples/constraint_contact_shell_shell.py b/src/Mod/Fem/femexamples/constraint_contact_shell_shell.py index 69df808077..c179c107e3 100644 --- a/src/Mod/Fem/femexamples/constraint_contact_shell_shell.py +++ b/src/Mod/Fem/femexamples/constraint_contact_shell_shell.py @@ -43,12 +43,14 @@ def get_information(): "constraints": ["fixed", "force", "contact"], "solvers": ["ccxtools"], "material": "solid", - "equations": ["mechanical"] + "equations": ["mechanical"], } def get_explanation(header=""): - return header + """ + return ( + header + + """ To run the example from Python console use: from femexamples.constraint_contact_shell_shell import setup @@ -62,6 +64,7 @@ based on https://forum.freecad.org/viewtopic.php?f=18&t=42228#p359488 contact example shell to shell elements """ + ) def setup(doc=None, solvertype="ccxtools"): @@ -109,7 +112,7 @@ def setup(doc=None, solvertype="ccxtools"): force_point.ViewObject.PointColor = (1.0, 0.0, 0.0) # boolean fragment of upper tubo and force point - boolfrag = SplitFeatures.makeBooleanFragments(name='BooleanFragments') + boolfrag = SplitFeatures.makeBooleanFragments(name="BooleanFragments") boolfrag.Objects = [upper_tube, force_point] if FreeCAD.GuiUp: upper_tube.ViewObject.hide() @@ -138,7 +141,7 @@ def setup(doc=None, solvertype="ccxtools"): # solver if solvertype == "ccxtools": solver_obj = ObjectsFem.makeSolverCalculiXCcxTools(doc, "CalculiXCcxTools") - solver_obj.WorkingDir = u"" + solver_obj.WorkingDir = "" else: FreeCAD.Console.PrintWarning( "Unknown or unsupported solver type: {}. " @@ -156,7 +159,7 @@ def setup(doc=None, solvertype="ccxtools"): analysis.addObject(solver_obj) # shell thickness - shell_thick = ObjectsFem.makeElementGeometry2D(doc, 0.5, 'ShellThickness') + shell_thick = ObjectsFem.makeElementGeometry2D(doc, 0.5, "ShellThickness") analysis.addObject(shell_thick) # material @@ -197,6 +200,7 @@ def setup(doc=None, solvertype="ccxtools"): # mesh from .meshes.mesh_contact_tube_tube_tria3 import create_nodes, create_elements + fem_mesh = Fem.FemMesh() control = create_nodes(fem_mesh) if not control: diff --git a/src/Mod/Fem/femexamples/constraint_contact_solid_solid.py b/src/Mod/Fem/femexamples/constraint_contact_solid_solid.py index fc3af04a12..a5ed032b5f 100644 --- a/src/Mod/Fem/femexamples/constraint_contact_solid_solid.py +++ b/src/Mod/Fem/femexamples/constraint_contact_solid_solid.py @@ -44,12 +44,14 @@ def get_information(): "constraints": ["fixed", "pressure", "contact"], "solvers": ["ccxtools"], "material": "solid", - "equations": ["mechanical"] + "equations": ["mechanical"], } def get_explanation(header=""): - return header + """ + return ( + header + + """ To run the example from Python console use: from femexamples.constraint_contact_solid_solid import setup @@ -61,6 +63,7 @@ https://forum.freecad.org/viewtopic.php?f=18&t=20276 constraint contact for solid to solid mesh """ + ) def setup(doc=None, solvertype="ccxtools"): @@ -91,7 +94,7 @@ def setup(doc=None, solvertype="ccxtools"): top_halfcyl_obj.Radius = 30 top_halfcyl_obj.Height = 500 top_halfcyl_obj.Angle = 180 - top_halfcyl_sh = Part.getShape(top_halfcyl_obj, '', needSubElement=False, refine=True) + top_halfcyl_sh = Part.getShape(top_halfcyl_obj, "", needSubElement=False, refine=True) top_halfcyl_obj.Shape = top_halfcyl_sh top_halfcyl_obj.Placement = FreeCAD.Placement( Vector(0, -42, 0), @@ -118,7 +121,7 @@ def setup(doc=None, solvertype="ccxtools"): # solver if solvertype == "ccxtools": solver_obj = ObjectsFem.makeSolverCalculiXCcxTools(doc, "CalculiXCcxTools") - solver_obj.WorkingDir = u"" + solver_obj.WorkingDir = "" else: FreeCAD.Console.PrintWarning( "Unknown or unsupported solver type: {}. " @@ -180,7 +183,11 @@ def setup(doc=None, solvertype="ccxtools"): analysis.addObject(con_contact) # mesh - from .meshes.mesh_contact_box_halfcylinder_tetra10 import create_nodes, create_elements + from .meshes.mesh_contact_box_halfcylinder_tetra10 import ( + create_nodes, + create_elements, + ) + fem_mesh = Fem.FemMesh() control = create_nodes(fem_mesh) if not control: diff --git a/src/Mod/Fem/femexamples/constraint_section_print.py b/src/Mod/Fem/femexamples/constraint_section_print.py index 5eacb9555a..ce3352e532 100644 --- a/src/Mod/Fem/femexamples/constraint_section_print.py +++ b/src/Mod/Fem/femexamples/constraint_section_print.py @@ -50,12 +50,14 @@ def get_information(): "constraints": ["section_print", "fixed", "pressure"], "solvers": ["ccxtools"], "material": "solid", - "equations": ["mechanical"] + "equations": ["mechanical"], } def get_explanation(header=""): - return header + """ + return ( + header + + """ To run the example from Python console use: from femexamples.constraint_section_print import setup @@ -68,6 +70,7 @@ https://forum.freecad.org/viewtopic.php?t=43044 constraint section print with volume elements """ + ) def setup(doc=None, solvertype="ccxtools"): @@ -83,27 +86,20 @@ def setup(doc=None, solvertype="ccxtools"): # geometric objects # the part sketch arc_sketch = doc.addObject("Sketcher::SketchObject", "Arc_Sketch") - arc_sketch.Placement = FreeCAD.Placement( - Vector(0, 0, 0), - Rotation(0, 0, 0, 1) - ) + arc_sketch.Placement = FreeCAD.Placement(Vector(0, 0, 0), Rotation(0, 0, 0, 1)) arc_sketch.MapMode = "Deactivated" # not the exact geometry which makes a closed wire # exact geometry will be made by the constraints # the order is important for the constraints definition geoList = [ - Part.ArcOfCircle( - Part.Circle(Vector(0, 0, 0), Vector(0, 0, 1), 47), - 0, - math.pi - ), + Part.ArcOfCircle(Part.Circle(Vector(0, 0, 0), Vector(0, 0, 1), 47), 0, math.pi), Part.ArcOfCircle( Part.Circle(Vector(-19, -22, 0), Vector(0, 0, 1), 89), math.pi / 12, - math.pi / 1.1 + math.pi / 1.1, ), Part.LineSegment(Vector(-105, 0, 0), Vector(-47, 0, 0)), - Part.LineSegment(Vector(47, 0, 0), Vector(67, 0, 0)) + Part.LineSegment(Vector(47, 0, 0), Vector(67, 0, 0)), ] arc_sketch.addGeometry(geoList, False) # https://wiki.freecad.org/Sketcher_ConstrainCoincident @@ -122,7 +118,7 @@ def setup(doc=None, solvertype="ccxtools"): Sketcher.Constraint("DistanceX", 2, 2, 2, 1, 58), Sketcher.Constraint("DistanceX", 3, 2, 3, 1, 20), Sketcher.Constraint("Radius", 0, 47), - Sketcher.Constraint("Radius", 1, 89) + Sketcher.Constraint("Radius", 1, 89), ] arc_sketch.addConstraint(conList) @@ -144,12 +140,12 @@ def setup(doc=None, solvertype="ccxtools"): section_sketch = doc.addObject("Sketcher::SketchObject", "Section_Sketch") section_sketch.Placement = FreeCAD.Placement( Vector(0.000000, 0.000000, 0.000000), - Rotation(0.000000, 0.000000, 0.000000, 1.000000) + Rotation(0.000000, 0.000000, 0.000000, 1.000000), ) section_sketch.MapMode = "Deactivated" section_sketch.addGeometry( Part.LineSegment(Vector(-6.691961, -16.840161, 0), Vector(75.156087, 79.421394, 0)), - False + False, ) # section_sketch.ExternalGeometry = extrude_part @@ -223,7 +219,7 @@ def setup(doc=None, solvertype="ccxtools"): # solver if solvertype == "ccxtools": solver_obj = ObjectsFem.makeSolverCalculiXCcxTools(doc, "CalculiXCcxTools") - solver_obj.WorkingDir = u"" + solver_obj.WorkingDir = "" else: FreeCAD.Console.PrintWarning( "Unknown or unsupported solver type: {}. " @@ -266,6 +262,7 @@ def setup(doc=None, solvertype="ccxtools"): # mesh from .meshes.mesh_section_print_tetra10 import create_nodes, create_elements + fem_mesh = Fem.FemMesh() control = create_nodes(fem_mesh) if not control: diff --git a/src/Mod/Fem/femexamples/constraint_selfweight_cantilever.py b/src/Mod/Fem/femexamples/constraint_selfweight_cantilever.py index 68e5a6c0b0..fbfe5afafb 100644 --- a/src/Mod/Fem/femexamples/constraint_selfweight_cantilever.py +++ b/src/Mod/Fem/femexamples/constraint_selfweight_cantilever.py @@ -39,12 +39,14 @@ def get_information(): "constraints": ["fixed", "self weight"], "solvers": ["ccxtools", "elmer"], "material": "solid", - "equations": ["mechanical"] + "equations": ["mechanical"], } def get_explanation(header=""): - return header + """ + return ( + header + + """ To run the example from Python console use: from femexamples.constraint_selfweight_cantilever import setup @@ -59,6 +61,7 @@ l = 32 m, yields just from self weight, means max sigma around 235 n/mm2 max deformation = 576.8 mm """ + ) def setup(doc=None, solvertype="ccxtools"): @@ -86,7 +89,7 @@ def setup(doc=None, solvertype="ccxtools"): # solver if solvertype == "ccxtools": solver_obj = ObjectsFem.makeSolverCalculiXCcxTools(doc, "CalculiXCcxTools") - solver_obj.WorkingDir = u"" + solver_obj.WorkingDir = "" elif solvertype == "elmer": solver_obj = ObjectsFem.makeSolverElmer(doc, "SolverElmer") eq_obj = ObjectsFem.makeEquationElasticity(doc, solver_obj) @@ -127,6 +130,7 @@ def setup(doc=None, solvertype="ccxtools"): # mesh from .meshes.mesh_selfweight_cantilever_tetra10 import create_nodes, create_elements + fem_mesh = Fem.FemMesh() control = create_nodes(fem_mesh) if not control: diff --git a/src/Mod/Fem/femexamples/constraint_tie.py b/src/Mod/Fem/femexamples/constraint_tie.py index 0abc42c927..c95428f017 100644 --- a/src/Mod/Fem/femexamples/constraint_tie.py +++ b/src/Mod/Fem/femexamples/constraint_tie.py @@ -44,12 +44,14 @@ def get_information(): "constraints": ["fixed", "force", "tie"], "solvers": ["ccxtools"], "material": "solid", - "equations": ["mechanical"] + "equations": ["mechanical"], } def get_explanation(header=""): - return header + """ + return ( + header + + """ To run the example from Python console use: from femexamples.constraint_tie import setup @@ -62,6 +64,7 @@ https://forum.freecad.org/viewtopic.php?f=18&t=42783 constraint tie, bond two surfaces together (solid mesh only) """ + ) def setup(doc=None, solvertype="ccxtools"): @@ -108,7 +111,7 @@ def setup(doc=None, solvertype="ccxtools"): # solver if solvertype == "ccxtools": solver_obj = ObjectsFem.makeSolverCalculiXCcxTools(doc, "CalculiXCcxTools") - solver_obj.WorkingDir = u"" + solver_obj.WorkingDir = "" else: FreeCAD.Console.PrintWarning( "Unknown or unsupported solver type: {}. " @@ -156,6 +159,7 @@ def setup(doc=None, solvertype="ccxtools"): # mesh from .meshes.mesh_constraint_tie_tetra10 import create_nodes, create_elements + fem_mesh = Fem.FemMesh() control = create_nodes(fem_mesh) if not control: diff --git a/src/Mod/Fem/femexamples/constraint_transform_beam_hinged.py b/src/Mod/Fem/femexamples/constraint_transform_beam_hinged.py index ab1bc43824..3bf63f79c2 100644 --- a/src/Mod/Fem/femexamples/constraint_transform_beam_hinged.py +++ b/src/Mod/Fem/femexamples/constraint_transform_beam_hinged.py @@ -44,12 +44,14 @@ def get_information(): "constraints": ["pressure", "displacement", "transform"], "solvers": ["ccxtools"], "material": "solid", - "equations": ["mechanical"] + "equations": ["mechanical"], } def get_explanation(header=""): - return header + """ + return ( + header + + """ To run the example from Python console use: from femexamples.constraint_transform_beam_hinged import setup @@ -62,6 +64,7 @@ https://forum.freecad.org/viewtopic.php?f=18&t=20238#p157643 Constraint transform on a beam """ + ) def setup(doc=None, solvertype="ccxtools"): @@ -83,7 +86,9 @@ def setup(doc=None, solvertype="ccxtools"): cylinder.Height = "20 mm" cylinder.Radius = "6 mm" cylinder.Placement = FreeCAD.Placement( - Vector(10, 12, 10), Rotation(0, 0, 90), Vector(0, 0, 0), + Vector(10, 12, 10), + Rotation(0, 0, 90), + Vector(0, 0, 0), ) cut = doc.addObject("Part::Cut", "Cut") cut.Base = cube @@ -102,9 +107,9 @@ def setup(doc=None, solvertype="ccxtools"): fusion.Refine = True # compound filter - geom_obj = CompoundFilter.makeCompoundFilter(name='CompoundFilter') + geom_obj = CompoundFilter.makeCompoundFilter(name="CompoundFilter") geom_obj.Base = fusion - geom_obj.FilterType = 'window-volume' + geom_obj.FilterType = "window-volume" doc.recompute() if FreeCAD.GuiUp: @@ -118,7 +123,7 @@ def setup(doc=None, solvertype="ccxtools"): # solver if solvertype == "ccxtools": solver_obj = ObjectsFem.makeSolverCalculiXCcxTools(doc, "CalculiXCcxTools") - solver_obj.WorkingDir = u"" + solver_obj.WorkingDir = "" else: FreeCAD.Console.PrintWarning( "Unknown or unsupported solver type: {}. " @@ -169,6 +174,7 @@ def setup(doc=None, solvertype="ccxtools"): # mesh from .meshes.mesh_transform_beam_hinged_tetra10 import create_nodes, create_elements + fem_mesh = Fem.FemMesh() control = create_nodes(fem_mesh) if not control: @@ -180,7 +186,7 @@ def setup(doc=None, solvertype="ccxtools"): femmesh_obj.FemMesh = fem_mesh femmesh_obj.Part = geom_obj femmesh_obj.SecondOrderLinear = False - femmesh_obj.CharacteristicLengthMax = '7 mm' + femmesh_obj.CharacteristicLengthMax = "7 mm" doc.recompute() return doc diff --git a/src/Mod/Fem/femexamples/constraint_transform_torque.py b/src/Mod/Fem/femexamples/constraint_transform_torque.py index 312cdbeb46..bd94609898 100644 --- a/src/Mod/Fem/femexamples/constraint_transform_torque.py +++ b/src/Mod/Fem/femexamples/constraint_transform_torque.py @@ -52,12 +52,14 @@ def get_information(): "constraints": ["fixed", "force", "transform"], "solvers": ["ccxtools"], "material": "solid", - "equations": ["mechanical"] + "equations": ["mechanical"], } def get_explanation(header=""): - return header + """ + return ( + header + + """ To run the example from Python console use: from femexamples.constraint_transform_torque import setup @@ -72,6 +74,7 @@ https://forum.freecad.org/viewtopic.php?t=18970 constraint transform with a constraint force """ + ) def setup(doc=None, solvertype="ccxtools"): @@ -115,7 +118,7 @@ def setup(doc=None, solvertype="ccxtools"): # solver if solvertype == "ccxtools": solver_obj = ObjectsFem.makeSolverCalculiXCcxTools(doc, "CalculiXCcxTools") - solver_obj.WorkingDir = u"" + solver_obj.WorkingDir = "" else: FreeCAD.Console.PrintWarning( "Unknown or unsupported solver type: {}. " @@ -160,6 +163,7 @@ def setup(doc=None, solvertype="ccxtools"): # mesh from .meshes.mesh_transform_torque_tetra10 import create_nodes, create_elements + fem_mesh = Fem.FemMesh() control = create_nodes(fem_mesh) if not control: diff --git a/src/Mod/Fem/femexamples/elmer_nonguitutorial01_eigenvalue_of_elastic_beam.py b/src/Mod/Fem/femexamples/elmer_nonguitutorial01_eigenvalue_of_elastic_beam.py index 71b2fe7faf..dc5a1ce143 100644 --- a/src/Mod/Fem/femexamples/elmer_nonguitutorial01_eigenvalue_of_elastic_beam.py +++ b/src/Mod/Fem/femexamples/elmer_nonguitutorial01_eigenvalue_of_elastic_beam.py @@ -39,12 +39,14 @@ def get_information(): "constraints": [], "solvers": ["ccxtools", "elmer"], "material": "solid", - "equations": ["elasticity"] # "frequency", but list not allowed here + "equations": ["elasticity"], # "frequency", but list not allowed here } def get_explanation(header=""): - return header + """ + return ( + header + + """ To run the example from Python console use: from femexamples.elmer_nonguitutorial01_eigenvalue_of_elastic_beam import setup @@ -55,6 +57,7 @@ See forum topic post: https://forum.freecad.org/viewtopic.php?t=56590 """ + ) def setup(doc=None, solvertype="elmer"): @@ -83,7 +86,7 @@ def setup(doc=None, solvertype="elmer"): # solver if solvertype == "ccxtools": solver_obj = ObjectsFem.makeSolverCalculiXCcxTools(doc, "CalculiXCcxTools") - solver_obj.WorkingDir = u"" + solver_obj.WorkingDir = "" elif solvertype == "elmer": solver_obj = ObjectsFem.makeSolverElmer(doc, "SolverElmer") eq_obj = ObjectsFem.makeEquationElasticity(doc, solver_obj) @@ -118,15 +121,13 @@ def setup(doc=None, solvertype="elmer"): # constraint fixed con_fixed = ObjectsFem.makeConstraintFixed(doc, "ConstraintFixed") - con_fixed.References = [ - (geom_obj, "Face1"), - (geom_obj, "Face2") - ] + con_fixed.References = [(geom_obj, "Face1"), (geom_obj, "Face2")] analysis.addObject(con_fixed) # mesh from .meshes.mesh_eigenvalue_of_elastic_beam_tetra10 import create_nodes from .meshes.mesh_eigenvalue_of_elastic_beam_tetra10 import create_elements + fem_mesh = Fem.FemMesh() control = create_nodes(fem_mesh) if not control: diff --git a/src/Mod/Fem/femexamples/equation_deformation_spring_elmer.py b/src/Mod/Fem/femexamples/equation_deformation_spring_elmer.py index a049126d6f..136d894777 100644 --- a/src/Mod/Fem/femexamples/equation_deformation_spring_elmer.py +++ b/src/Mod/Fem/femexamples/equation_deformation_spring_elmer.py @@ -42,12 +42,14 @@ def get_information(): "constraints": ["displacement", "spring"], "solvers": ["elmer"], "material": "solid", - "equations": ["deformation"] + "equations": ["deformation"], } def get_explanation(header=""): - return header + """ + return ( + header + + """ To run the example from Python console use: from femexamples.equation_deformation_spring_elmer import setup @@ -56,6 +58,7 @@ setup() Deformation equation - Elmer solver """ + ) def setup(doc=None, solvertype="elmer"): @@ -75,18 +78,24 @@ def setup(doc=None, solvertype="elmer"): SketchPath = body.newObject("Sketcher::SketchObject", "Spring_Path") SketchPath.AttachmentSupport = (doc.getObject("XY_Plane"), [""]) SketchPath.MapMode = "FlatFace" - SketchPath.addGeometry(Part.LineSegment(Vector( - -20.0, 30.0, 0.0), Vector(-20.0, 0.0, 0.0)), False) - SketchPath.addConstraint(Sketcher.Constraint('PointOnObject', 0, 2, -1)) - SketchPath.addConstraint(Sketcher.Constraint('Vertical', 0)) - SketchPath.addGeometry(Part.ArcOfCircle(Part.Circle( - Vector(0.0, 0.0, 0.0), Vector(0, 0, 1), 20.0), 3.141593, 6.283185), False) - SketchPath.addConstraint(Sketcher.Constraint('Tangent', 0, 2, 1, 1)) - SketchPath.addConstraint(Sketcher.Constraint('PointOnObject', 1, 2, -1)) - SketchPath.addGeometry(Part.LineSegment( - Vector(20.0, 0.0, 0.0), Vector(20.0, 30.0, 0.0)), False) - SketchPath.addConstraint(Sketcher.Constraint('Tangent', 1, 2, 2, 1)) - SketchPath.addConstraint(Sketcher.Constraint('Equal', 2, 0)) + SketchPath.addGeometry( + Part.LineSegment(Vector(-20.0, 30.0, 0.0), Vector(-20.0, 0.0, 0.0)), False + ) + SketchPath.addConstraint(Sketcher.Constraint("PointOnObject", 0, 2, -1)) + SketchPath.addConstraint(Sketcher.Constraint("Vertical", 0)) + SketchPath.addGeometry( + Part.ArcOfCircle( + Part.Circle(Vector(0.0, 0.0, 0.0), Vector(0, 0, 1), 20.0), + 3.141593, + 6.283185, + ), + False, + ) + SketchPath.addConstraint(Sketcher.Constraint("Tangent", 0, 2, 1, 1)) + SketchPath.addConstraint(Sketcher.Constraint("PointOnObject", 1, 2, -1)) + SketchPath.addGeometry(Part.LineSegment(Vector(20.0, 0.0, 0.0), Vector(20.0, 30.0, 0.0)), False) + SketchPath.addConstraint(Sketcher.Constraint("Tangent", 1, 2, 2, 1)) + SketchPath.addConstraint(Sketcher.Constraint("Equal", 2, 0)) SketchPath.ViewObject.Visibility = False # sketch defining the spring cross section @@ -94,11 +103,11 @@ def setup(doc=None, solvertype="elmer"): SketchCircle.AttachmentSupport = (doc.getObject("XZ_Plane"), [""]) SketchCircle.MapMode = "FlatFace" SketchCircle.addGeometry(Part.Circle(Vector(-20.0, 0.0, 0.0), Vector(0, 0, 1), 7.5), False) - SketchCircle.addConstraint(Sketcher.Constraint('PointOnObject', 0, 3, -1)) + SketchCircle.addConstraint(Sketcher.Constraint("PointOnObject", 0, 3, -1)) SketchCircle.ViewObject.Visibility = False # the spring object - SpringObject = body.newObject('PartDesign::AdditivePipe', 'Spring') + SpringObject = body.newObject("PartDesign::AdditivePipe", "Spring") SpringObject.Profile = SketchCircle SpringObject.Spine = SketchPath @@ -112,6 +121,7 @@ def setup(doc=None, solvertype="elmer"): analysis = ObjectsFem.makeAnalysis(doc, "Analysis") if FreeCAD.GuiUp: import FemGui + FemGui.setActiveAnalysis(analysis) # solver @@ -148,7 +158,7 @@ def setup(doc=None, solvertype="elmer"): DisplaceLeft = doc.addObject("Fem::ConstraintDisplacement", "DisplacementLeft") DisplaceLeft.xFree = False DisplaceLeft.hasXFormula = True - DisplaceLeft.xDisplacementFormula = "Variable \"time\"; Real MATC \"0.006*tx\"" + DisplaceLeft.xDisplacementFormula = 'Variable "time"; Real MATC "0.006*tx"' DisplaceLeft.yFree = False DisplaceLeft.yFix = True DisplaceLeft.zFree = False @@ -159,7 +169,7 @@ def setup(doc=None, solvertype="elmer"): DisplaceRight = doc.addObject("Fem::ConstraintDisplacement", "DisplacementRight") DisplaceRight.xFree = False DisplaceRight.hasXFormula = True - DisplaceRight.xDisplacementFormula = "Variable \"time\"; Real MATC \"-0.006*tx\"" + DisplaceRight.xDisplacementFormula = 'Variable "time"; Real MATC "-0.006*tx"' DisplaceRight.yFree = False DisplaceRight.yFix = True DisplaceRight.zFree = False @@ -189,15 +199,13 @@ def setup(doc=None, solvertype="elmer"): # generate the mesh from femmesh import gmshtools + gmsh_mesh = gmshtools.GmshTools(femmesh_obj, analysis) try: error = gmsh_mesh.create_mesh() except Exception: error = sys.exc_info()[1] - FreeCAD.Console.PrintError( - "Unexpected error when creating mesh: {}\n" - .format(error) - ) + FreeCAD.Console.PrintError(f"Unexpected error when creating mesh: {error}\n") doc.recompute() return doc diff --git a/src/Mod/Fem/femexamples/equation_electrostatics_capacitance_two_balls.py b/src/Mod/Fem/femexamples/equation_electrostatics_capacitance_two_balls.py index ed4624da90..1141e4c82f 100644 --- a/src/Mod/Fem/femexamples/equation_electrostatics_capacitance_two_balls.py +++ b/src/Mod/Fem/femexamples/equation_electrostatics_capacitance_two_balls.py @@ -43,12 +43,14 @@ def get_information(): "constraints": ["electrostatic potential"], "solvers": ["elmer"], "material": "fluid", - "equations": ["electrostatic"] + "equations": ["electrostatic"], } def get_explanation(header=""): - return header + """ + return ( + header + + """ To run the example from Python console use: from femexamples.equation_electrostatics_capacitance_two_balls import setup @@ -61,6 +63,7 @@ https://forum.freecad.org/viewtopic.php?f=18&t=41488&start=90#p412047 Electrostatics equation in FreeCAD FEM-Elmer """ + ) def setup(doc=None, solvertype="elmer"): @@ -102,6 +105,7 @@ def setup(doc=None, solvertype="elmer"): analysis = ObjectsFem.makeAnalysis(doc, "Analysis") if FreeCAD.GuiUp: import FemGui + FemGui.setActiveAnalysis(analysis) # solver @@ -174,18 +178,20 @@ def setup(doc=None, solvertype="elmer"): # generate the mesh from femmesh import gmshtools + gmsh_mesh = gmshtools.GmshTools(femmesh_obj, analysis) try: error = gmsh_mesh.create_mesh() except Exception: error = sys.exc_info()[1] - FreeCAD.Console.PrintError( - "Unexpected error when creating mesh: {}\n" - .format(error) - ) + FreeCAD.Console.PrintError(f"Unexpected error when creating mesh: {error}\n") if error: # try to create from existing rough mesh - from .meshes.mesh_capacitance_two_balls_tetra10 import create_nodes, create_elements + from .meshes.mesh_capacitance_two_balls_tetra10 import ( + create_nodes, + create_elements, + ) + fem_mesh = Fem.FemMesh() control = create_nodes(fem_mesh) if not control: diff --git a/src/Mod/Fem/femexamples/equation_electrostatics_electricforce_elmer_nongui6.py b/src/Mod/Fem/femexamples/equation_electrostatics_electricforce_elmer_nongui6.py index a59ab04d96..8ca92caab6 100644 --- a/src/Mod/Fem/femexamples/equation_electrostatics_electricforce_elmer_nongui6.py +++ b/src/Mod/Fem/femexamples/equation_electrostatics_electricforce_elmer_nongui6.py @@ -46,12 +46,14 @@ def get_information(): "constraints": ["electrostatic potential"], "solvers": ["elmer"], "material": "fluid", - "equations": ["electrostatic"] + "equations": ["electrostatic"], } def get_explanation(header=""): - return header + """ + return ( + header + + """ To run the example from Python console use: from femexamples.equation_electrostatics_electricforce_elmer_nongui6 import setup @@ -64,6 +66,7 @@ https://forum.freecad.org/viewtopic.php?f=18&t=41488&start=40#p373292 Electrostatics equation in FreeCAD FEM-Elmer """ + ) def setup(doc=None, solvertype="elmer"): @@ -86,7 +89,8 @@ def setup(doc=None, solvertype="elmer"): Part.LineSegment(Vector(0.000000, 0.000000, 0), Vector(57.407921, 0.000000, 0)), Part.LineSegment(Vector(57.407921, 0.000000, 0), Vector(57.407921, 35.205284, 0)), Part.LineSegment(Vector(57.407921, 35.205284, 0), Vector(0.000000, 35.205284, 0)), - Part.LineSegment(Vector(0.000000, 35.205284, 0), Vector(0.000000, 0.000000, 0))] + Part.LineSegment(Vector(0.000000, 35.205284, 0), Vector(0.000000, 0.000000, 0)), + ] base_sketch.addGeometry(base_geoList, False) base_conList = [ Sketcher.Constraint("Coincident", 0, 2, 1, 1), @@ -99,7 +103,8 @@ def setup(doc=None, solvertype="elmer"): Sketcher.Constraint("Vertical", 3), Sketcher.Constraint("Coincident", 0, 1, -1, 1), Sketcher.Constraint("DistanceY", 1, 1, 1, 2, 35.205284), - Sketcher.Constraint("DistanceX", 0, 1, 0, 2, 57.407921)] + Sketcher.Constraint("DistanceX", 0, 1, 0, 2, 57.407921), + ] base_sketch.addConstraint(base_conList) base_sketch.setDatum(9, Units.Quantity("5000.000000 mm")) base_sketch.setDatum(10, Units.Quantity("5000.000000 mm")) @@ -120,7 +125,8 @@ def setup(doc=None, solvertype="elmer"): Part.LineSegment(Vector(5037.082520, 0.000000, 0), Vector(1309.763672, -21.422216, 0)), Part.LineSegment(Vector(1309.763672, 0.000000, 0), Vector(1372.406982, 1544.678467, 0)), Part.LineSegment(Vector(1372.406982, 1544.678467, 0), Vector(-37.083382, 1544.678467, 0)), - Part.LineSegment(Vector(0.000000, 1544.678467, 0), Vector(25.560951, 4958.778320, 0))] + Part.LineSegment(Vector(0.000000, 1544.678467, 0), Vector(25.560951, 4958.778320, 0)), + ] upper_sketch.addGeometry(upper_geoList, False) upper_conList = [ Sketcher.Constraint("Horizontal", 0), @@ -140,7 +146,8 @@ def setup(doc=None, solvertype="elmer"): Sketcher.Constraint("DistanceX", 0, 1, 0, 2, 5037.082520), Sketcher.Constraint("DistanceY", 1, 2, 1, 1, 4958.778320), Sketcher.Constraint("DistanceY", 3, 1, 3, 2, 1544.678467), - Sketcher.Constraint("DistanceX", 4, 2, 4, 1, 1309.763672)] + Sketcher.Constraint("DistanceX", 4, 2, 4, 1, 1309.763672), + ] upper_sketch.addConstraint(upper_conList) upper_sketch.setDatum(14, Units.Quantity("5000.000000 mm")) upper_sketch.setDatum(15, Units.Quantity("5000.000000 mm")) @@ -163,6 +170,7 @@ def setup(doc=None, solvertype="elmer"): analysis = ObjectsFem.makeAnalysis(doc, "Analysis") if FreeCAD.GuiUp: import FemGui + FemGui.setActiveAnalysis(analysis) # solver @@ -209,7 +217,8 @@ def setup(doc=None, solvertype="elmer"): (geom_obj, "Face4"), (geom_obj, "Face5"), (geom_obj, "Face6"), - (geom_obj, "Face11")] + (geom_obj, "Face11"), + ] con_elect_pot2.Potential = "1 V" con_elect_pot2.CapacitanceBody = 2 con_elect_pot2.CapacitanceBodyEnabled = True @@ -231,23 +240,26 @@ def setup(doc=None, solvertype="elmer"): (geom_obj, "Face4"), (geom_obj, "Face5"), (geom_obj, "Face6"), - (geom_obj, "Face11")] + (geom_obj, "Face11"), + ] mesh_region.ViewObject.Visibility = False # generate the mesh from femmesh import gmshtools + gmsh_mesh = gmshtools.GmshTools(femmesh_obj, analysis) try: error = gmsh_mesh.create_mesh() except Exception: error = sys.exc_info()[1] - FreeCAD.Console.PrintError( - "Unexpected error when creating mesh: {}\n" - .format(error) - ) + FreeCAD.Console.PrintError(f"Unexpected error when creating mesh: {error}\n") if error: # try to create from existing rough mesh - from .meshes.mesh_electricforce_elmer_nongui6_tetra10 import create_nodes, create_elements + from .meshes.mesh_electricforce_elmer_nongui6_tetra10 import ( + create_nodes, + create_elements, + ) + fem_mesh = Fem.FemMesh() control = create_nodes(fem_mesh) if not control: diff --git a/src/Mod/Fem/femexamples/equation_flow_elmer_2D.py b/src/Mod/Fem/femexamples/equation_flow_elmer_2D.py index 561878799b..c083da38da 100644 --- a/src/Mod/Fem/femexamples/equation_flow_elmer_2D.py +++ b/src/Mod/Fem/femexamples/equation_flow_elmer_2D.py @@ -41,16 +41,22 @@ def get_information(): "name": "Flow - Elmer 2D", "meshtype": "solid", "meshelement": "Tet10", - "constraints": ["initial pressure", "initial temperature", - "temperature", "velocity"], + "constraints": [ + "initial pressure", + "initial temperature", + "temperature", + "velocity", + ], "solvers": ["elmer"], "material": "fluid", - "equations": ["flow", "heat"] + "equations": ["flow", "heat"], } def get_explanation(header=""): - return header + """ + return ( + header + + """ To run the example from Python console use: from femexamples.equation_flow_elmer_2D import setup @@ -59,6 +65,7 @@ setup() Flow and Heat equation - Elmer solver """ + ) def setup(doc=None, solvertype="elmer"): @@ -118,6 +125,7 @@ def setup(doc=None, solvertype="elmer"): analysis = ObjectsFem.makeAnalysis(doc, "Analysis") if FreeCAD.GuiUp: import FemGui + FemGui.setActiveAnalysis(analysis) # solver @@ -185,7 +193,7 @@ def setup(doc=None, solvertype="elmer"): FlowVelocity_Inlet = ObjectsFem.makeConstraintFlowVelocity(doc, "FlowVelocity_Inlet") FlowVelocity_Inlet.References = [(BooleanFragments, "Edge5")] FlowVelocity_Inlet.VelocityXFormula = ( - "Variable Coordinate 2; Real MATC \"10*(tx+50e-3)*(50e-3-tx)\"" + 'Variable Coordinate 2; Real MATC "10*(tx+50e-3)*(50e-3-tx)"' ) FlowVelocity_Inlet.VelocityXUnspecified = False FlowVelocity_Inlet.VelocityXHasFormula = True @@ -198,7 +206,8 @@ def setup(doc=None, solvertype="elmer"): (BooleanFragments, "Edge2"), (BooleanFragments, "Edge3"), (BooleanFragments, "Edge4"), - (BooleanFragments, "Edge7")] + (BooleanFragments, "Edge7"), + ] FlowVelocity_Wall.VelocityXUnspecified = False FlowVelocity_Wall.VelocityYUnspecified = False analysis.addObject(FlowVelocity_Wall) @@ -216,7 +225,8 @@ def setup(doc=None, solvertype="elmer"): (BooleanFragments, "Edge2"), (BooleanFragments, "Edge3"), (BooleanFragments, "Edge4"), - (BooleanFragments, "Edge7")] + (BooleanFragments, "Edge7"), + ] analysis.addObject(Temperature_Wall) # constraint inlet temperature @@ -254,20 +264,19 @@ def setup(doc=None, solvertype="elmer"): (BooleanFragments, "Edge1"), (BooleanFragments, "Vertex2"), (BooleanFragments, "Vertex4"), - (BooleanFragments, "Vertex6")] + (BooleanFragments, "Vertex6"), + ] mesh_region.ViewObject.Visibility = False # generate the mesh from femmesh import gmshtools + gmsh_mesh = gmshtools.GmshTools(femmesh_obj, analysis) try: error = gmsh_mesh.create_mesh() except Exception: error = sys.exc_info()[1] - FreeCAD.Console.PrintError( - "Unexpected error when creating mesh: {}\n" - .format(error) - ) + FreeCAD.Console.PrintError(f"Unexpected error when creating mesh: {error}\n") doc.recompute() return doc diff --git a/src/Mod/Fem/femexamples/equation_flow_initial_elmer_2D.py b/src/Mod/Fem/femexamples/equation_flow_initial_elmer_2D.py index 42f2b95ab9..0098726fdb 100644 --- a/src/Mod/Fem/femexamples/equation_flow_initial_elmer_2D.py +++ b/src/Mod/Fem/femexamples/equation_flow_initial_elmer_2D.py @@ -41,16 +41,23 @@ def get_information(): "name": "Initial Flow - Elmer 2D", "meshtype": "solid", "meshelement": "Tet10", - "constraints": ["initial pressure", "initial temperature", "initial velocity", - "temperature", "velocity"], + "constraints": [ + "initial pressure", + "initial temperature", + "initial velocity", + "temperature", + "velocity", + ], "solvers": ["elmer"], "material": "fluid", - "equations": ["flow", "heat"] + "equations": ["flow", "heat"], } def get_explanation(header=""): - return header + """ + return ( + header + + """ To run the example from Python console use: from femexamples.equation_flow_initial_elmer_2D import setup @@ -59,6 +66,7 @@ setup() Flow and Heat equation with initial velocity - Elmer solver """ + ) def setup(doc=None, solvertype="elmer"): @@ -118,6 +126,7 @@ def setup(doc=None, solvertype="elmer"): analysis = ObjectsFem.makeAnalysis(doc, "Analysis") if FreeCAD.GuiUp: import FemGui + FemGui.setActiveAnalysis(analysis) # solver @@ -196,7 +205,8 @@ def setup(doc=None, solvertype="elmer"): (BooleanFragments, "Edge2"), (BooleanFragments, "Edge3"), (BooleanFragments, "Edge4"), - (BooleanFragments, "Edge7")] + (BooleanFragments, "Edge7"), + ] FlowVelocity_Wall.VelocityXUnspecified = False FlowVelocity_Wall.VelocityYUnspecified = False analysis.addObject(FlowVelocity_Wall) @@ -223,7 +233,8 @@ def setup(doc=None, solvertype="elmer"): (BooleanFragments, "Edge2"), (BooleanFragments, "Edge3"), (BooleanFragments, "Edge4"), - (BooleanFragments, "Edge7")] + (BooleanFragments, "Edge7"), + ] analysis.addObject(Temperature_Wall) # constraint inlet temperature @@ -261,20 +272,19 @@ def setup(doc=None, solvertype="elmer"): (BooleanFragments, "Edge1"), (BooleanFragments, "Vertex2"), (BooleanFragments, "Vertex4"), - (BooleanFragments, "Vertex6")] + (BooleanFragments, "Vertex6"), + ] mesh_region.ViewObject.Visibility = False # generate the mesh from femmesh import gmshtools + gmsh_mesh = gmshtools.GmshTools(femmesh_obj, analysis) try: error = gmsh_mesh.create_mesh() except Exception: error = sys.exc_info()[1] - FreeCAD.Console.PrintError( - "Unexpected error when creating mesh: {}\n" - .format(error) - ) + FreeCAD.Console.PrintError(f"Unexpected error when creating mesh: {error}\n") doc.recompute() return doc diff --git a/src/Mod/Fem/femexamples/equation_flow_turbulent_elmer_2D.py b/src/Mod/Fem/femexamples/equation_flow_turbulent_elmer_2D.py index 53905004e7..2b2e088df8 100644 --- a/src/Mod/Fem/femexamples/equation_flow_turbulent_elmer_2D.py +++ b/src/Mod/Fem/femexamples/equation_flow_turbulent_elmer_2D.py @@ -41,16 +41,22 @@ def get_information(): "name": "Turbulent Flow - Elmer 2D", "meshtype": "solid", "meshelement": "Tet10", - "constraints": ["initial pressure", "initial temperature", - "temperature", "velocity"], + "constraints": [ + "initial pressure", + "initial temperature", + "temperature", + "velocity", + ], "solvers": ["elmer"], "material": "fluid", - "equations": ["flow", "heat"] + "equations": ["flow", "heat"], } def get_explanation(header=""): - return header + """ + return ( + header + + """ To run the example from Python console use: from femexamples.equation_flow_turbulent_elmer_2D import setup @@ -59,6 +65,7 @@ setup() Flow and Heat equation in turbulent flow - Elmer solver """ + ) def setup(doc=None, solvertype="elmer"): @@ -118,6 +125,7 @@ def setup(doc=None, solvertype="elmer"): analysis = ObjectsFem.makeAnalysis(doc, "Analysis") if FreeCAD.GuiUp: import FemGui + FemGui.setActiveAnalysis(analysis) # solver @@ -191,7 +199,7 @@ def setup(doc=None, solvertype="elmer"): FlowVelocity_Inlet = ObjectsFem.makeConstraintFlowVelocity(doc, "FlowVelocity_Inlet") FlowVelocity_Inlet.References = [(BooleanFragments, "Edge5")] FlowVelocity_Inlet.VelocityXFormula = ( - "Variable Coordinate 2; Real MATC \"10*(tx+50e-3)*(50e-3-tx)\"" + 'Variable Coordinate 2; Real MATC "10*(tx+50e-3)*(50e-3-tx)"' ) FlowVelocity_Inlet.VelocityXUnspecified = False FlowVelocity_Inlet.VelocityXHasFormula = True @@ -204,7 +212,8 @@ def setup(doc=None, solvertype="elmer"): (BooleanFragments, "Edge2"), (BooleanFragments, "Edge3"), (BooleanFragments, "Edge4"), - (BooleanFragments, "Edge7")] + (BooleanFragments, "Edge7"), + ] FlowVelocity_Wall.VelocityXUnspecified = False FlowVelocity_Wall.VelocityYUnspecified = False analysis.addObject(FlowVelocity_Wall) @@ -222,7 +231,8 @@ def setup(doc=None, solvertype="elmer"): (BooleanFragments, "Edge2"), (BooleanFragments, "Edge3"), (BooleanFragments, "Edge4"), - (BooleanFragments, "Edge7")] + (BooleanFragments, "Edge7"), + ] analysis.addObject(Temperature_Wall) # constraint inlet temperature @@ -260,20 +270,19 @@ def setup(doc=None, solvertype="elmer"): (BooleanFragments, "Edge1"), (BooleanFragments, "Vertex2"), (BooleanFragments, "Vertex4"), - (BooleanFragments, "Vertex6")] + (BooleanFragments, "Vertex6"), + ] mesh_region.ViewObject.Visibility = False # generate the mesh from femmesh import gmshtools + gmsh_mesh = gmshtools.GmshTools(femmesh_obj, analysis) try: error = gmsh_mesh.create_mesh() except Exception: error = sys.exc_info()[1] - FreeCAD.Console.PrintError( - "Unexpected error when creating mesh: {}\n" - .format(error) - ) + FreeCAD.Console.PrintError(f"Unexpected error when creating mesh: {error}\n") doc.recompute() return doc diff --git a/src/Mod/Fem/femexamples/equation_flux_elmer.py b/src/Mod/Fem/femexamples/equation_flux_elmer.py index aa25d7e9e1..0e90a34ce9 100644 --- a/src/Mod/Fem/femexamples/equation_flux_elmer.py +++ b/src/Mod/Fem/femexamples/equation_flux_elmer.py @@ -40,12 +40,14 @@ def get_information(): "constraints": ["electrostatic potential", "temperature"], "solvers": ["elmer"], "material": "solid", - "equations": ["electrostatic", "flux", "heat"] + "equations": ["electrostatic", "flux", "heat"], } def get_explanation(header=""): - return header + """ + return ( + header + + """ To run the example from Python console use: from femexamples.equation_flux_elmer import setup @@ -54,6 +56,7 @@ setup() Potential flux and heat flux - Elmer solver """ + ) def setup(doc=None, solvertype="elmer"): @@ -80,6 +83,7 @@ def setup(doc=None, solvertype="elmer"): analysis = ObjectsFem.makeAnalysis(doc, "Analysis") if FreeCAD.GuiUp: import FemGui + FemGui.setActiveAnalysis(analysis) # solver @@ -155,15 +159,13 @@ def setup(doc=None, solvertype="elmer"): # generate the mesh from femmesh import gmshtools + gmsh_mesh = gmshtools.GmshTools(femmesh_obj, analysis) try: error = gmsh_mesh.create_mesh() except Exception: error = sys.exc_info()[1] - FreeCAD.Console.PrintError( - "Unexpected error when creating mesh: {}\n" - .format(error) - ) + FreeCAD.Console.PrintError(f"Unexpected error when creating mesh: {error}\n") doc.recompute() return doc diff --git a/src/Mod/Fem/femexamples/equation_magnetodynamics_2D_elmer.py b/src/Mod/Fem/femexamples/equation_magnetodynamics_2D_elmer.py index 3a8fcc84da..540dec6471 100644 --- a/src/Mod/Fem/femexamples/equation_magnetodynamics_2D_elmer.py +++ b/src/Mod/Fem/femexamples/equation_magnetodynamics_2D_elmer.py @@ -43,12 +43,14 @@ def get_information(): "constraints": ["current density"], "solvers": ["elmer"], "material": "solid", - "equations": ["electromagnetic"] + "equations": ["electromagnetic"], } def get_explanation(header=""): - return header + """ + return ( + header + + """ To run the example from Python console use: from femexamples.equation_magnetodynamics_2D_elmer import setup @@ -57,6 +59,7 @@ setup() Magnetodynamic2D equation - Elmer solver """ + ) def setup(doc=None, solvertype="elmer"): @@ -120,8 +123,7 @@ def setup(doc=None, solvertype="elmer"): Powder.ViewObject.Visibility = False # a half circle defining later the air volume - Air_Circle = Part.makeCircle( - 140.0, Vector(0.0, 60.0, 0.0), Vector(0.0, 0.0, 1.0), -90.0, 90.0) + Air_Circle = Part.makeCircle(140.0, Vector(0.0, 60.0, 0.0), Vector(0.0, 0.0, 1.0), -90.0, 90.0) Air_Line = Part.makeLine((0.0, -80.0, 0.0), (0.0, 200.0, 0.0)) Air_Area = doc.addObject("Part::Feature", "Air_Area") Air_Area.Shape = Part.Face([Part.Wire([Air_Circle, Air_Line])]) @@ -175,6 +177,7 @@ def setup(doc=None, solvertype="elmer"): analysis = ObjectsFem.makeAnalysis(doc, "Analysis") if FreeCAD.GuiUp: import FemGui + FemGui.setActiveAnalysis(analysis) # solver @@ -212,7 +215,8 @@ def setup(doc=None, solvertype="elmer"): material_obj.References = [ (BooleanFragments, "Face2"), (BooleanFragments, "Face5"), - (BooleanFragments, "Face6")] + (BooleanFragments, "Face6"), + ] analysis.addObject(material_obj) # graphite of the crucible @@ -265,20 +269,19 @@ def setup(doc=None, solvertype="elmer"): (BooleanFragments, "Face1"), (BooleanFragments, "Face2"), (BooleanFragments, "Face3"), - (BooleanFragments, "Face4")] + (BooleanFragments, "Face4"), + ] mesh_region.ViewObject.Visibility = False # generate the mesh from femmesh import gmshtools + gmsh_mesh = gmshtools.GmshTools(femmesh_obj, analysis) try: error = gmsh_mesh.create_mesh() except Exception: error = sys.exc_info()[1] - FreeCAD.Console.PrintError( - "Unexpected error when creating mesh: {}\n" - .format(error) - ) + FreeCAD.Console.PrintError(f"Unexpected error when creating mesh: {error}\n") doc.recompute() return doc diff --git a/src/Mod/Fem/femexamples/equation_magnetodynamics_elmer.py b/src/Mod/Fem/femexamples/equation_magnetodynamics_elmer.py index 142fff0b19..e639de873d 100644 --- a/src/Mod/Fem/femexamples/equation_magnetodynamics_elmer.py +++ b/src/Mod/Fem/femexamples/equation_magnetodynamics_elmer.py @@ -42,12 +42,14 @@ def get_information(): "constraints": ["electrostatic potential", "magnetization"], "solvers": ["elmer"], "material": "solid", - "equations": ["electromagnetic"] + "equations": ["electromagnetic"], } def get_explanation(header=""): - return header + """ + return ( + header + + """ To run the example from Python console use: from femexamples.equation_magnetodynamics_elmer import setup @@ -56,6 +58,7 @@ setup() Magnetodynamic equation - Elmer solver """ + ) def setup(doc=None, solvertype="elmer"): @@ -99,6 +102,7 @@ def setup(doc=None, solvertype="elmer"): analysis = ObjectsFem.makeAnalysis(doc, "Analysis") if FreeCAD.GuiUp: import FemGui + FemGui.setActiveAnalysis(analysis) # solver @@ -157,7 +161,8 @@ def setup(doc=None, solvertype="elmer"): AxialField.References = [ (BooleanFragments, "Face4"), (BooleanFragments, "Face5"), - (BooleanFragments, "Face6")] + (BooleanFragments, "Face6"), + ] AxialField.PotentialEnabled = False AxialField.AV_im_1_Disabled = False AxialField.AV_im_2_Disabled = False @@ -209,18 +214,20 @@ def setup(doc=None, solvertype="elmer"): # generate the mesh from femmesh import gmshtools + gmsh_mesh = gmshtools.GmshTools(femmesh_obj, analysis) try: error = gmsh_mesh.create_mesh() except Exception: error = sys.exc_info()[1] - FreeCAD.Console.PrintError( - "Unexpected error when creating mesh: {}\n" - .format(error) - ) + FreeCAD.Console.PrintError(f"Unexpected error when creating mesh: {error}\n") if error: # try to create from existing rough mesh - from .meshes.mesh_capacitance_two_balls_tetra10 import create_nodes, create_elements + from .meshes.mesh_capacitance_two_balls_tetra10 import ( + create_nodes, + create_elements, + ) + fem_mesh = Fem.FemMesh() control = create_nodes(fem_mesh) if not control: diff --git a/src/Mod/Fem/femexamples/equation_magnetostatics_2D_elmer.py b/src/Mod/Fem/femexamples/equation_magnetostatics_2D_elmer.py index 73497db68d..d4000cb0d4 100644 --- a/src/Mod/Fem/femexamples/equation_magnetostatics_2D_elmer.py +++ b/src/Mod/Fem/femexamples/equation_magnetostatics_2D_elmer.py @@ -43,12 +43,14 @@ def get_information(): "constraints": ["magnetization"], "solvers": ["elmer"], "material": "solid", - "equations": ["magnetostatic"] + "equations": ["magnetostatic"], } def get_explanation(header=""): - return header + """ + return ( + header + + """ To run the example from Python console use: from femexamples.equation_magnetostatics_2D_elmer import setup @@ -57,6 +59,7 @@ setup() Magnetodynamic2D equation - Elmer solver """ + ) def setup(doc=None, solvertype="elmer"): @@ -93,25 +96,43 @@ def setup(doc=None, solvertype="elmer"): # the U-part of the horse shoe # credits: https://forum.freecad.org/viewtopic.php?p=663051#p663051 - vpairs = [[Vector(340.0, 200.0, 0.0), Vector(200.0, 200.0, 0.0)], - [Vector(200.0, 200.0, 0.0), Vector(200.0, 100.0, 0.0)], - [Vector(200.0, 100.0, 0.0), Vector(325.0, 100.0, 0.0)], - [Vector(325.0, 100.0, 0.0), Vector(325.0, -100.0, 0.0)], - [Vector(325.0, -100.0, 0.0), Vector(200.0, -100.0, 0.0)], - [Vector(200.0, -100.0, 0.0), Vector(200.0, -200.0, 0.0)], - [Vector(200.0, -200.0, 0.0), Vector(340.0, -200.0, 0.0)], - [Vector(340.0, 200.0, 0.0), Vector(340.0, -200.0, 0.0)]] - typeId = ['Part::GeomLine', 'Part::GeomLine', 'Part::GeomLine', 'Part::GeomBSplineCurve', - 'Part::GeomLine', 'Part::GeomLine', 'Part::GeomLine', 'Part::GeomBSplineCurve'] - e3Poles = [Vector(325.0, 100.0, 0.0), Vector(400.0, 100.0, 0.0), - Vector(400.0, 0.0, 0.0), Vector(400.0, -100.0, 0.0), - Vector(325.0, -100.0, 0.0)] + vpairs = [ + [Vector(340.0, 200.0, 0.0), Vector(200.0, 200.0, 0.0)], + [Vector(200.0, 200.0, 0.0), Vector(200.0, 100.0, 0.0)], + [Vector(200.0, 100.0, 0.0), Vector(325.0, 100.0, 0.0)], + [Vector(325.0, 100.0, 0.0), Vector(325.0, -100.0, 0.0)], + [Vector(325.0, -100.0, 0.0), Vector(200.0, -100.0, 0.0)], + [Vector(200.0, -100.0, 0.0), Vector(200.0, -200.0, 0.0)], + [Vector(200.0, -200.0, 0.0), Vector(340.0, -200.0, 0.0)], + [Vector(340.0, 200.0, 0.0), Vector(340.0, -200.0, 0.0)], + ] + typeId = [ + "Part::GeomLine", + "Part::GeomLine", + "Part::GeomLine", + "Part::GeomBSplineCurve", + "Part::GeomLine", + "Part::GeomLine", + "Part::GeomLine", + "Part::GeomBSplineCurve", + ] + e3Poles = [ + Vector(325.0, 100.0, 0.0), + Vector(400.0, 100.0, 0.0), + Vector(400.0, 0.0, 0.0), + Vector(400.0, -100.0, 0.0), + Vector(325.0, -100.0, 0.0), + ] e3Knots = [0.0, 0.5, 1.0] e3Mults = [4, 1, 4] e3Degree = 3 - e7Poles = [Vector(340.0, 200.0, 0.0), Vector(500.0, 200.0, 0.0), - Vector(500.0, 0.0, 0.0), Vector(500.0, -200.0, 0.0), - Vector(340.0, -200.0, 0.0)] + e7Poles = [ + Vector(340.0, 200.0, 0.0), + Vector(500.0, 200.0, 0.0), + Vector(500.0, 0.0, 0.0), + Vector(500.0, -200.0, 0.0), + Vector(340.0, -200.0, 0.0), + ] e7Knots = [0.0, 0.5, 1.0] e7Mults = [4, 1, 4] e7Degree = 3 @@ -121,7 +142,7 @@ def setup(doc=None, solvertype="elmer"): c7.buildFromPolesMultsKnots(e7Poles, e7Mults, e7Knots, False, e7Degree) edges = [c3.toShape(), c7.toShape()] for i in range(len(typeId)): - if typeId[i] == 'Part::GeomLine': + if typeId[i] == "Part::GeomLine": edges.append(Part.makeLine(*vpairs[i])) sedges = Part.__sortEdges__(edges) @@ -175,6 +196,7 @@ def setup(doc=None, solvertype="elmer"): analysis = ObjectsFem.makeAnalysis(doc, "Analysis") if FreeCAD.GuiUp: import FemGui + FemGui.setActiveAnalysis(analysis) # solver @@ -218,7 +240,8 @@ def setup(doc=None, solvertype="elmer"): material_obj.References = [ (BooleanFragments, "Face1"), (BooleanFragments, "Face2"), - (BooleanFragments, "Face3")] + (BooleanFragments, "Face3"), + ] analysis.addObject(material_obj) # magnetization lower @@ -247,20 +270,19 @@ def setup(doc=None, solvertype="elmer"): mesh_region.References = [ (BooleanFragments, "Face1"), (BooleanFragments, "Face2"), - (BooleanFragments, "Face3")] + (BooleanFragments, "Face3"), + ] mesh_region.ViewObject.Visibility = False # generate the mesh from femmesh import gmshtools + gmsh_mesh = gmshtools.GmshTools(femmesh_obj, analysis) try: error = gmsh_mesh.create_mesh() except Exception: error = sys.exc_info()[1] - FreeCAD.Console.PrintError( - "Unexpected error when creating mesh: {}\n" - .format(error) - ) + FreeCAD.Console.PrintError(f"Unexpected error when creating mesh: {error}\n") doc.recompute() return doc diff --git a/src/Mod/Fem/femexamples/examplesgui.py b/src/Mod/Fem/femexamples/examplesgui.py index 2461c0f957..5f24bac2b3 100644 --- a/src/Mod/Fem/femexamples/examplesgui.py +++ b/src/Mod/Fem/femexamples/examplesgui.py @@ -38,10 +38,12 @@ import FreeCADGui class FemExamples(QtGui.QWidget): def __init__(self): - super(FemExamples, self).__init__() + super().__init__() self.init_ui() - def __del__(self,): + def __del__( + self, + ): # need as fix for qt event error # --> see https://forum.freecad.org/viewtopic.php?f=18&t=10732&start=10#p86493 return @@ -205,9 +207,9 @@ class FemExamples(QtGui.QWidget): if grand_parent_name == "Solvers": solver = parent.text(0) # if done this way the Python commands are printed in Python console - FreeCADGui.doCommand("from femexamples.{} import setup".format(str(example))) + FreeCADGui.doCommand(f"from femexamples.{str(example)} import setup") if solver is not None: - FreeCADGui.doCommand("setup(solvertype=\"{}\")".format(str(solver))) + FreeCADGui.doCommand(f'setup(solvertype="{str(solver)}")') else: FreeCADGui.doCommand("setup()") QtGui.QApplication.restoreOverrideCursor() @@ -236,10 +238,11 @@ class FemExamples(QtGui.QWidget): # if done this way the Python commands are printed in Python console FreeCADGui.doCommand("from femexamples.manager import run_example") if solver is not None: - FreeCADGui.doCommand("run_example(\"{}\", solver=\"{}\", run_solver=True)" - .format(str(example), str(solver))) + FreeCADGui.doCommand( + f'run_example("{str(example)}", solver="{str(solver)}", run_solver=True)' + ) else: - FreeCADGui.doCommand("run_example(\"{}\", run_solver=True)".format(str(example))) + FreeCADGui.doCommand(f'run_example("{str(example)}", run_solver=True)') QtGui.QApplication.restoreOverrideCursor() def enable_buttons(self): diff --git a/src/Mod/Fem/femexamples/frequency_beamsimple.py b/src/Mod/Fem/femexamples/frequency_beamsimple.py index 1e55b0e06d..3b6d7d2787 100644 --- a/src/Mod/Fem/femexamples/frequency_beamsimple.py +++ b/src/Mod/Fem/femexamples/frequency_beamsimple.py @@ -39,12 +39,14 @@ def get_information(): "constraints": ["fixed"], "solvers": ["ccxtools"], "material": "solid", - "equations": ["frequency"] + "equations": ["frequency"], } def get_explanation(header=""): - return header + """ + return ( + header + + """ To run the example from Python console use: from femexamples.frequency_beamsimple import setup @@ -57,6 +59,7 @@ https://forum.freecad.org/viewtopic.php?f=18&t=58959#p506565 simple frequency analysis """ + ) def setup(doc=None, solvertype="ccxtools"): @@ -85,7 +88,7 @@ def setup(doc=None, solvertype="ccxtools"): # solver if solvertype == "ccxtools": solver_obj = ObjectsFem.makeSolverCalculiXCcxTools(doc, "CalculiXCcxTools") - solver_obj.WorkingDir = u"" + solver_obj.WorkingDir = "" else: FreeCAD.Console.PrintWarning( "Unknown or unsupported solver type: {}. " @@ -104,9 +107,7 @@ def setup(doc=None, solvertype="ccxtools"): analysis.addObject(solver_obj) # material - material_obj = analysis.addObject( - ObjectsFem.makeMaterialSolid(doc, "MechanicalMaterial") - )[0] + material_obj = analysis.addObject(ObjectsFem.makeMaterialSolid(doc, "MechanicalMaterial"))[0] mat = material_obj.Material mat["Name"] = "Steel-Generic" mat["YoungsModulus"] = "200000 MPa" @@ -145,6 +146,7 @@ def setup(doc=None, solvertype="ccxtools"): # mesh from .meshes.mesh_beamsimple_tetra10 import create_nodes, create_elements + fem_mesh = Fem.FemMesh() control = create_nodes(fem_mesh) if not control: diff --git a/src/Mod/Fem/femexamples/manager.py b/src/Mod/Fem/femexamples/manager.py index 4f9e121c59..c607d61fd6 100644 --- a/src/Mod/Fem/femexamples/manager.py +++ b/src/Mod/Fem/femexamples/manager.py @@ -148,6 +148,7 @@ def run_analysis(doc, base_name, filepath="", run_solver=False): # find the first solver # thus ATM only one solver per analysis is supported from femtools.femutils import is_derived_from + for m in doc.Analysis.Group: if is_derived_from(m, "Fem::FemSolverObjectPython"): solver = m @@ -155,17 +156,17 @@ def run_analysis(doc, base_name, filepath="", run_solver=False): # a file name is needed for the besides dir to work save_fc_file = join(filepath, (base_name + ".FCStd")) - FreeCAD.Console.PrintMessage( - "Save FreeCAD file for {} analysis to {}\n.".format(base_name, save_fc_file) - ) + FreeCAD.Console.PrintMessage(f"Save FreeCAD file for {base_name} analysis to {save_fc_file}\n.") doc.saveAs(save_fc_file) # get analysis workig dir from femtools.femutils import get_beside_dir + working_dir = get_beside_dir(solver) # run analysis from femsolver.run import run_fem_solver + if run_solver is True: run_fem_solver(solver, working_dir) @@ -176,9 +177,10 @@ def run_analysis(doc, base_name, filepath="", run_solver=False): def run_example(example, solver=None, base_name=None, run_solver=False): from importlib import import_module + module = import_module("femexamples." + example) if not hasattr(module, "setup"): - FreeCAD.Console.PrintError("Setup method not found in {}\n".format(example)) + FreeCAD.Console.PrintError(f"Setup method not found in {example}\n") return None if solver is None: @@ -215,7 +217,9 @@ def get_meshname(): def get_header(information): return """{name} -{information}""".format(name=information["name"], information=print_info_dict(information)) +{information}""".format( + name=information["name"], information=print_info_dict(information) + ) def print_info_dict(information): @@ -224,11 +228,11 @@ def print_info_dict(information): value_text = "" if isinstance(v, list): for j in v: - value_text += "{}, ".format(j) + value_text += f"{j}, " value_text = value_text.rstrip(", ") else: value_text = v - the_text += "{} --> {}\n".format(k, value_text) + the_text += f"{k} --> {value_text}\n" # print(the_text) return the_text diff --git a/src/Mod/Fem/femexamples/material_multiple_bendingbeam_fiveboxes.py b/src/Mod/Fem/femexamples/material_multiple_bendingbeam_fiveboxes.py index aac5eff947..1d091eeeca 100644 --- a/src/Mod/Fem/femexamples/material_multiple_bendingbeam_fiveboxes.py +++ b/src/Mod/Fem/femexamples/material_multiple_bendingbeam_fiveboxes.py @@ -42,12 +42,14 @@ def get_information(): "constraints": ["fixed", "force"], "solvers": ["ccxtools"], "material": "multimaterial", - "equations": ["mechanical"] + "equations": ["mechanical"], } def get_explanation(header=""): - return header + """ + return ( + header + + """ To run the example from Python console use: from femexamples.material_multiple_bendingbeam_fiveboxes import setup @@ -58,6 +60,7 @@ See forum topic post: ... """ + ) def setup(doc=None, solvertype="ccxtools"): @@ -124,7 +127,7 @@ def setup(doc=None, solvertype="ccxtools"): # solver if solvertype == "ccxtools": solver_obj = ObjectsFem.makeSolverCalculiXCcxTools(doc, "CalculiXCcxTools") - solver_obj.WorkingDir = u"" + solver_obj.WorkingDir = "" else: FreeCAD.Console.PrintWarning( "Unknown or unsupported solver type: {}. " @@ -179,7 +182,7 @@ def setup(doc=None, solvertype="ccxtools"): (doc.Box2, "Face6"), (doc.Box3, "Face6"), (doc.Box4, "Face6"), - (doc.Box5, "Face6") + (doc.Box5, "Face6"), ] con_force.Force = "10000.00 N" con_force.Direction = (doc.Box1, ["Edge1"]) @@ -188,6 +191,7 @@ def setup(doc=None, solvertype="ccxtools"): # mesh from .meshes.mesh_multibodybeam_tetra10 import create_nodes, create_elements + fem_mesh = Fem.FemMesh() control = create_nodes(fem_mesh) if not control: diff --git a/src/Mod/Fem/femexamples/material_multiple_bendingbeam_fivefaces.py b/src/Mod/Fem/femexamples/material_multiple_bendingbeam_fivefaces.py index f054e2256b..6a402c949b 100644 --- a/src/Mod/Fem/femexamples/material_multiple_bendingbeam_fivefaces.py +++ b/src/Mod/Fem/femexamples/material_multiple_bendingbeam_fivefaces.py @@ -40,12 +40,14 @@ def get_information(): "constraints": ["fixed", "force"], "solvers": ["ccxtools"], "material": "multimaterial", - "equations": ["mechanical"] + "equations": ["mechanical"], } def get_explanation(header=""): - return header + """ + return ( + header + + """ To run the example from Python console use: from femexamples.material_multiple_bendingbeam_fivefaces import setup @@ -56,6 +58,7 @@ See forum topic post: ... """ + ) def setup(doc=None, solvertype="ccxtools"): @@ -113,7 +116,7 @@ def setup(doc=None, solvertype="ccxtools"): # solver if solvertype == "ccxtools": solver_obj = ObjectsFem.makeSolverCalculiXCcxTools(doc, "CalculiXCcxTools") - solver_obj.WorkingDir = u"" + solver_obj.WorkingDir = "" else: FreeCAD.Console.PrintWarning( "Unknown or unsupported solver type: {}. " @@ -143,10 +146,7 @@ def setup(doc=None, solvertype="ccxtools"): analysis.addObject(material_obj1) material_obj2 = ObjectsFem.makeMaterialSolid(doc, "FemMaterial2") - material_obj2.References = [ - (doc.Face2, "Face1"), - (doc.Face4, "Face1") - ] + material_obj2.References = [(doc.Face2, "Face1"), (doc.Face4, "Face1")] mat = material_obj2.Material mat["Name"] = "PLA" mat["YoungsModulus"] = "3640 MPa" @@ -165,10 +165,7 @@ def setup(doc=None, solvertype="ccxtools"): # constraint fixed con_fixed = ObjectsFem.makeConstraintFixed(doc, "ConstraintFixed") - con_fixed.References = [ - (doc.Face1, "Edge1"), - (doc.Face5, "Edge3") - ] + con_fixed.References = [(doc.Face1, "Edge1"), (doc.Face5, "Edge3")] analysis.addObject(con_fixed) # constraint force @@ -178,7 +175,7 @@ def setup(doc=None, solvertype="ccxtools"): (doc.Face2, "Edge4"), (doc.Face3, "Edge4"), (doc.Face4, "Edge4"), - (doc.Face5, "Edge4") + (doc.Face5, "Edge4"), ] con_force.Force = "10000.00 N" con_force.Direction = (doc.Face1, ["Edge1"]) @@ -187,6 +184,7 @@ def setup(doc=None, solvertype="ccxtools"): # mesh from .meshes.mesh_multibodybeam_tria6 import create_nodes, create_elements + fem_mesh = Fem.FemMesh() control = create_nodes(fem_mesh) if not control: diff --git a/src/Mod/Fem/femexamples/material_multiple_tensionrod_twoboxes.py b/src/Mod/Fem/femexamples/material_multiple_tensionrod_twoboxes.py index 15bd83f6a4..46d2f052e7 100644 --- a/src/Mod/Fem/femexamples/material_multiple_tensionrod_twoboxes.py +++ b/src/Mod/Fem/femexamples/material_multiple_tensionrod_twoboxes.py @@ -43,12 +43,14 @@ def get_information(): "constraints": ["fixed", "pressure"], "solvers": ["ccxtools"], "material": "multimaterial", - "equations": ["mechanical"] + "equations": ["mechanical"], } def get_explanation(header=""): - return header + """ + return ( + header + + """ To run the example from Python console use: from femexamples.material_multiple_tensionrod_twoboxes import setup @@ -59,6 +61,7 @@ See forum topic post: ... """ + ) def setup(doc=None, solvertype="ccxtools"): @@ -109,7 +112,7 @@ def setup(doc=None, solvertype="ccxtools"): # solver if solvertype == "ccxtools": solver_obj = ObjectsFem.makeSolverCalculiXCcxTools(doc, "CalculiXCcxTools") - solver_obj.WorkingDir = u"" + solver_obj.WorkingDir = "" else: FreeCAD.Console.PrintWarning( "Unknown or unsupported solver type: {}. " @@ -157,6 +160,7 @@ def setup(doc=None, solvertype="ccxtools"): # mesh from .meshes.mesh_boxes_2_vertikal_tetra10 import create_nodes, create_elements + fem_mesh = Fem.FemMesh() control = create_nodes(fem_mesh) if not control: diff --git a/src/Mod/Fem/femexamples/material_nl_platewithhole.py b/src/Mod/Fem/femexamples/material_nl_platewithhole.py index b03340773c..acd7897799 100644 --- a/src/Mod/Fem/femexamples/material_nl_platewithhole.py +++ b/src/Mod/Fem/femexamples/material_nl_platewithhole.py @@ -51,12 +51,14 @@ def get_information(): "constraints": ["fixed", "force"], "solvers": ["ccxtools"], "material": "nonlinear", - "equations": ["mechanical"] + "equations": ["mechanical"], } def get_explanation(header=""): - return header + """ + return ( + header + + """ To run the example from Python console use: from femexamples.material_nl_platewithhole import setup @@ -80,6 +82,7 @@ TODO nonlinear material: give more information, use values from harry TODO compare results with example from HarryvL """ + ) def setup(doc=None, solvertype="ccxtools"): @@ -118,7 +121,7 @@ def setup(doc=None, solvertype="ccxtools"): # solver if solvertype == "ccxtools": solver_obj = ObjectsFem.makeSolverCalculiXCcxTools(doc, "CalculiXCcxTools") - solver_obj.WorkingDir = u"" + solver_obj.WorkingDir = "" else: FreeCAD.Console.PrintWarning( "Unknown or unsupported solver type: {}. " @@ -131,8 +134,8 @@ def setup(doc=None, solvertype="ccxtools"): solver_obj.ThermoMechSteadyState = False solver_obj.MatrixSolverType = "default" solver_obj.IterationsControlParameterTimeUse = False - solver_obj.GeometricalNonlinearity = 'nonlinear' - solver_obj.MaterialNonlinearity = 'nonlinear' + solver_obj.GeometricalNonlinearity = "nonlinear" + solver_obj.MaterialNonlinearity = "nonlinear" analysis.addObject(solver_obj) # linear material @@ -147,7 +150,7 @@ def setup(doc=None, solvertype="ccxtools"): # nonlinear material name_nlm = "Material_nonlin" nonlinear_mat = ObjectsFem.makeMaterialMechanicalNonlinear(doc, material_obj, name_nlm) - nonlinear_mat.YieldPoints = ['240.0, 0.0', '270.0, 0.025'] + nonlinear_mat.YieldPoints = ["240.0, 0.0", "270.0, 0.025"] analysis.addObject(nonlinear_mat) # check solver attributes, Nonlinearity needs to be set to nonlinear @@ -165,6 +168,7 @@ def setup(doc=None, solvertype="ccxtools"): # mesh from .meshes.mesh_platewithhole_tetra10 import create_nodes, create_elements + fem_mesh = Fem.FemMesh() control = create_nodes(fem_mesh) if not control: diff --git a/src/Mod/Fem/femexamples/meshes/mesh_canticcx_hexa20.py b/src/Mod/Fem/femexamples/meshes/mesh_canticcx_hexa20.py index 63e11c0b49..032e5433d9 100644 --- a/src/Mod/Fem/femexamples/meshes/mesh_canticcx_hexa20.py +++ b/src/Mod/Fem/femexamples/meshes/mesh_canticcx_hexa20.py @@ -266,129 +266,804 @@ def create_nodes(femmesh): def create_elements(femmesh): # elements - femmesh.addVolume([ - 192, 61, 105, 222, 19, 1, 10, 95, 193, 104, 220, 221, 20, 9, 93, 94, 190, 62, 103, 219 - ], 1) - femmesh.addVolume([ - 222, 105, 34, 134, 95, 10, 2, 13, 220, 106, 133, 223, 93, 11, 12, 96, 219, 103, 33, 132 - ], 2) - femmesh.addVolume([ - 79, 192, 222, 163, 4, 19, 95, 16, 191, 221, 224, 164, 18, 94, 97, 17, 78, 190, 219, 161 - ], 3) - femmesh.addVolume([ - 163, 222, 134, 64, 16, 95, 13, 3, 224, 223, - 135, 162, 97, 96, 14, 15, 161, 219, 132, 63 - ], 4) - femmesh.addVolume([ - 196, 59, 109, 228, 192, 61, 105, 222, 197, - 108, 226, 227, 193, 104, 220, 221, 194, 60, 107, 225 - ], 5) - femmesh.addVolume([ - 228, 109, 36, 138, 222, 105, 34, 134, 226, - 110, 137, 229, 220, 106, 133, 223, 225, 107, 35, 136 - ], 6) - femmesh.addVolume([ - 81, 196, 228, 167, 79, 192, 222, 163, 195, 227, - 230, 168, 191, 221, 224, 164, 80, 194, 225, 165 - ], 7) - femmesh.addVolume([ - 167, 228, 138, 66, 163, 222, 134, 64, 230, 229, - 139, 166, 224, 223, 135, 162, 165, 225, 136, 65 - ], 8) - femmesh.addVolume([ - 200, 57, 113, 234, 196, 59, 109, 228, 201, 112, - 232, 233, 197, 108, 226, 227, 198, 58, 111, 231 - ], 9) - femmesh.addVolume([ - 234, 113, 38, 142, 228, 109, 36, 138, 232, 114, - 141, 235, 226, 110, 137, 229, 231, 111, 37, 140 - ], 10) - femmesh.addVolume([ - 83, 200, 234, 171, 81, 196, 228, 167, 199, 233, - 236, 172, 195, 227, 230, 168, 82, 198, 231, 169 - ], 11) - femmesh.addVolume([ - 171, 234, 142, 68, 167, 228, 138, 66, 236, 235, - 143, 170, 230, 229, 139, 166, 169, 231, 140, 67 - ], 12) - femmesh.addVolume([ - 204, 55, 117, 240, 200, 57, 113, 234, 205, 116, - 238, 239, 201, 112, 232, 233, 202, 56, 115, 237 - ], 13) - femmesh.addVolume([ - 240, 117, 40, 146, 234, 113, 38, 142, 238, 118, - 145, 241, 232, 114, 141, 235, 237, 115, 39, 144 - ], 14) - femmesh.addVolume([ - 85, 204, 240, 175, 83, 200, 234, 171, 203, 239, - 242, 176, 199, 233, 236, 172, 84, 202, 237, 173 - ], 15) - femmesh.addVolume([ - 175, 240, 146, 70, 171, 234, 142, 68, 242, 241, - 147, 174, 236, 235, 143, 170, 173, 237, 144, 69 - ], 16) - femmesh.addVolume([ - 208, 53, 121, 246, 204, 55, 117, 240, 209, 120, - 244, 245, 205, 116, 238, 239, 206, 54, 119, 243 - ], 17) - femmesh.addVolume([ - 246, 121, 42, 150, 240, 117, 40, 146, 244, 122, - 149, 247, 238, 118, 145, 241, 243, 119, 41, 148 - ], 18) - femmesh.addVolume([ - 87, 208, 246, 179, 85, 204, 240, 175, 207, 245, - 248, 180, 203, 239, 242, 176, 86, 206, 243, 177 - ], 19) - femmesh.addVolume([ - 179, 246, 150, 72, 175, 240, 146, 70, 248, 247, - 151, 178, 242, 241, 147, 174, 177, 243, 148, 71 - ], 20) - femmesh.addVolume([ - 212, 51, 125, 252, 208, 53, 121, 246, 213, 124, - 250, 251, 209, 120, 244, 245, 210, 52, 123, 249 - ], 21) - femmesh.addVolume([ - 252, 125, 44, 154, 246, 121, 42, 150, 250, 126, - 153, 253, 244, 122, 149, 247, 249, 123, 43, 152 - ], 22) - femmesh.addVolume([ - 89, 212, 252, 183, 87, 208, 246, 179, 211, 251, - 254, 184, 207, 245, 248, 180, 88, 210, 249, 181 - ], 23) - femmesh.addVolume([ - 183, 252, 154, 74, 179, 246, 150, 72, 254, 253, - 155, 182, 248, 247, 151, 178, 181, 249, 152, 73 - ], 24) - femmesh.addVolume([ - 216, 49, 129, 258, 212, 51, 125, 252, 217, 128, - 256, 257, 213, 124, 250, 251, 214, 50, 127, 255 - ], 25) - femmesh.addVolume([ - 258, 129, 46, 158, 252, 125, 44, 154, 256, 130, - 157, 259, 250, 126, 153, 253, 255, 127, 45, 156 - ], 26) - femmesh.addVolume([ - 91, 216, 258, 187, 89, 212, 252, 183, 215, 257, - 260, 188, 211, 251, 254, 184, 90, 214, 255, 185 - ], 27) - femmesh.addVolume([ - 187, 258, 158, 76, 183, 252, 154, 74, 260, 259, - 159, 186, 254, 253, 155, 182, 185, 255, 156, 75 - ], 28) - femmesh.addVolume([ - 31, 5, 22, 100, 216, 49, 129, 258, 32, 21, - 98, 99, 217, 128, 256, 257, 218, 48, 131, 261 - ], 29) - femmesh.addVolume([ - 100, 22, 6, 25, 258, 129, 46, 158, 98, 23, - 24, 101, 256, 130, 157, 259, 261, 131, 47, 160 - ], 30) - femmesh.addVolume([ - 8, 31, 100, 28, 91, 216, 258, 187, 30, 99, - 102, 29, 215, 257, 260, 188, 92, 218, 261, 189 - ], 31) - femmesh.addVolume([ - 28, 100, 25, 7, 187, 258, 158, 76, 102, 101, - 26, 27, 260, 259, 159, 186, 189, 261, 160, 77 - ], 32) + femmesh.addVolume( + [ + 192, + 61, + 105, + 222, + 19, + 1, + 10, + 95, + 193, + 104, + 220, + 221, + 20, + 9, + 93, + 94, + 190, + 62, + 103, + 219, + ], + 1, + ) + femmesh.addVolume( + [ + 222, + 105, + 34, + 134, + 95, + 10, + 2, + 13, + 220, + 106, + 133, + 223, + 93, + 11, + 12, + 96, + 219, + 103, + 33, + 132, + ], + 2, + ) + femmesh.addVolume( + [ + 79, + 192, + 222, + 163, + 4, + 19, + 95, + 16, + 191, + 221, + 224, + 164, + 18, + 94, + 97, + 17, + 78, + 190, + 219, + 161, + ], + 3, + ) + femmesh.addVolume( + [ + 163, + 222, + 134, + 64, + 16, + 95, + 13, + 3, + 224, + 223, + 135, + 162, + 97, + 96, + 14, + 15, + 161, + 219, + 132, + 63, + ], + 4, + ) + femmesh.addVolume( + [ + 196, + 59, + 109, + 228, + 192, + 61, + 105, + 222, + 197, + 108, + 226, + 227, + 193, + 104, + 220, + 221, + 194, + 60, + 107, + 225, + ], + 5, + ) + femmesh.addVolume( + [ + 228, + 109, + 36, + 138, + 222, + 105, + 34, + 134, + 226, + 110, + 137, + 229, + 220, + 106, + 133, + 223, + 225, + 107, + 35, + 136, + ], + 6, + ) + femmesh.addVolume( + [ + 81, + 196, + 228, + 167, + 79, + 192, + 222, + 163, + 195, + 227, + 230, + 168, + 191, + 221, + 224, + 164, + 80, + 194, + 225, + 165, + ], + 7, + ) + femmesh.addVolume( + [ + 167, + 228, + 138, + 66, + 163, + 222, + 134, + 64, + 230, + 229, + 139, + 166, + 224, + 223, + 135, + 162, + 165, + 225, + 136, + 65, + ], + 8, + ) + femmesh.addVolume( + [ + 200, + 57, + 113, + 234, + 196, + 59, + 109, + 228, + 201, + 112, + 232, + 233, + 197, + 108, + 226, + 227, + 198, + 58, + 111, + 231, + ], + 9, + ) + femmesh.addVolume( + [ + 234, + 113, + 38, + 142, + 228, + 109, + 36, + 138, + 232, + 114, + 141, + 235, + 226, + 110, + 137, + 229, + 231, + 111, + 37, + 140, + ], + 10, + ) + femmesh.addVolume( + [ + 83, + 200, + 234, + 171, + 81, + 196, + 228, + 167, + 199, + 233, + 236, + 172, + 195, + 227, + 230, + 168, + 82, + 198, + 231, + 169, + ], + 11, + ) + femmesh.addVolume( + [ + 171, + 234, + 142, + 68, + 167, + 228, + 138, + 66, + 236, + 235, + 143, + 170, + 230, + 229, + 139, + 166, + 169, + 231, + 140, + 67, + ], + 12, + ) + femmesh.addVolume( + [ + 204, + 55, + 117, + 240, + 200, + 57, + 113, + 234, + 205, + 116, + 238, + 239, + 201, + 112, + 232, + 233, + 202, + 56, + 115, + 237, + ], + 13, + ) + femmesh.addVolume( + [ + 240, + 117, + 40, + 146, + 234, + 113, + 38, + 142, + 238, + 118, + 145, + 241, + 232, + 114, + 141, + 235, + 237, + 115, + 39, + 144, + ], + 14, + ) + femmesh.addVolume( + [ + 85, + 204, + 240, + 175, + 83, + 200, + 234, + 171, + 203, + 239, + 242, + 176, + 199, + 233, + 236, + 172, + 84, + 202, + 237, + 173, + ], + 15, + ) + femmesh.addVolume( + [ + 175, + 240, + 146, + 70, + 171, + 234, + 142, + 68, + 242, + 241, + 147, + 174, + 236, + 235, + 143, + 170, + 173, + 237, + 144, + 69, + ], + 16, + ) + femmesh.addVolume( + [ + 208, + 53, + 121, + 246, + 204, + 55, + 117, + 240, + 209, + 120, + 244, + 245, + 205, + 116, + 238, + 239, + 206, + 54, + 119, + 243, + ], + 17, + ) + femmesh.addVolume( + [ + 246, + 121, + 42, + 150, + 240, + 117, + 40, + 146, + 244, + 122, + 149, + 247, + 238, + 118, + 145, + 241, + 243, + 119, + 41, + 148, + ], + 18, + ) + femmesh.addVolume( + [ + 87, + 208, + 246, + 179, + 85, + 204, + 240, + 175, + 207, + 245, + 248, + 180, + 203, + 239, + 242, + 176, + 86, + 206, + 243, + 177, + ], + 19, + ) + femmesh.addVolume( + [ + 179, + 246, + 150, + 72, + 175, + 240, + 146, + 70, + 248, + 247, + 151, + 178, + 242, + 241, + 147, + 174, + 177, + 243, + 148, + 71, + ], + 20, + ) + femmesh.addVolume( + [ + 212, + 51, + 125, + 252, + 208, + 53, + 121, + 246, + 213, + 124, + 250, + 251, + 209, + 120, + 244, + 245, + 210, + 52, + 123, + 249, + ], + 21, + ) + femmesh.addVolume( + [ + 252, + 125, + 44, + 154, + 246, + 121, + 42, + 150, + 250, + 126, + 153, + 253, + 244, + 122, + 149, + 247, + 249, + 123, + 43, + 152, + ], + 22, + ) + femmesh.addVolume( + [ + 89, + 212, + 252, + 183, + 87, + 208, + 246, + 179, + 211, + 251, + 254, + 184, + 207, + 245, + 248, + 180, + 88, + 210, + 249, + 181, + ], + 23, + ) + femmesh.addVolume( + [ + 183, + 252, + 154, + 74, + 179, + 246, + 150, + 72, + 254, + 253, + 155, + 182, + 248, + 247, + 151, + 178, + 181, + 249, + 152, + 73, + ], + 24, + ) + femmesh.addVolume( + [ + 216, + 49, + 129, + 258, + 212, + 51, + 125, + 252, + 217, + 128, + 256, + 257, + 213, + 124, + 250, + 251, + 214, + 50, + 127, + 255, + ], + 25, + ) + femmesh.addVolume( + [ + 258, + 129, + 46, + 158, + 252, + 125, + 44, + 154, + 256, + 130, + 157, + 259, + 250, + 126, + 153, + 253, + 255, + 127, + 45, + 156, + ], + 26, + ) + femmesh.addVolume( + [ + 91, + 216, + 258, + 187, + 89, + 212, + 252, + 183, + 215, + 257, + 260, + 188, + 211, + 251, + 254, + 184, + 90, + 214, + 255, + 185, + ], + 27, + ) + femmesh.addVolume( + [ + 187, + 258, + 158, + 76, + 183, + 252, + 154, + 74, + 260, + 259, + 159, + 186, + 254, + 253, + 155, + 182, + 185, + 255, + 156, + 75, + ], + 28, + ) + femmesh.addVolume( + [ + 31, + 5, + 22, + 100, + 216, + 49, + 129, + 258, + 32, + 21, + 98, + 99, + 217, + 128, + 256, + 257, + 218, + 48, + 131, + 261, + ], + 29, + ) + femmesh.addVolume( + [ + 100, + 22, + 6, + 25, + 258, + 129, + 46, + 158, + 98, + 23, + 24, + 101, + 256, + 130, + 157, + 259, + 261, + 131, + 47, + 160, + ], + 30, + ) + femmesh.addVolume( + [ + 8, + 31, + 100, + 28, + 91, + 216, + 258, + 187, + 30, + 99, + 102, + 29, + 215, + 257, + 260, + 188, + 92, + 218, + 261, + 189, + ], + 31, + ) + femmesh.addVolume( + [ + 28, + 100, + 25, + 7, + 187, + 258, + 158, + 76, + 102, + 101, + 26, + 27, + 260, + 259, + 159, + 186, + 189, + 261, + 160, + 77, + ], + 32, + ) return True diff --git a/src/Mod/Fem/femexamples/mystran_plate.py b/src/Mod/Fem/femexamples/mystran_plate.py index 54abe7ee62..ca3d3eac37 100644 --- a/src/Mod/Fem/femexamples/mystran_plate.py +++ b/src/Mod/Fem/femexamples/mystran_plate.py @@ -41,12 +41,14 @@ def get_information(): "constraints": ["fixed", "force"], "solvers": ["ccxtools", "elmer", "mystran"], "material": "solid", - "equations": ["mechanical"] + "equations": ["mechanical"], } def get_explanation(header=""): - return header + """ + return ( + header + + """ To run the example from Python console use: from femexamples.buckling_platebuckling import setup @@ -64,6 +66,7 @@ one each mesh node on one edge 100 N tension force Does not work on Z88 because Z88 does not support quad4 elements """ + ) def setup(doc=None, solvertype="ccxtools"): @@ -95,7 +98,7 @@ def setup(doc=None, solvertype="ccxtools"): doc.recompute() # all geom boolean fragment - geom_obj = SplitFeatures.makeBooleanFragments(name='ThePointPlate') + geom_obj = SplitFeatures.makeBooleanFragments(name="ThePointPlate") geom_obj.Objects = [plate, force_pt1, force_pt2, force_pt3, force_pt4] doc.recompute() if FreeCAD.GuiUp: @@ -117,7 +120,7 @@ def setup(doc=None, solvertype="ccxtools"): # solver if solvertype == "ccxtools": solver_obj = ObjectsFem.makeSolverCalculiXCcxTools(doc, "CalculiXCcxTools") - solver_obj.WorkingDir = u"" + solver_obj.WorkingDir = "" elif solvertype == "elmer": solver_obj = ObjectsFem.makeSolverElmer(doc, "SolverElmer") ObjectsFem.makeEquationElasticity(doc, solver_obj) @@ -141,7 +144,7 @@ def setup(doc=None, solvertype="ccxtools"): analysis.addObject(solver_obj) # shell thickness - thickness_obj = ObjectsFem.makeElementGeometry2D(doc, 0.3, 'Thickness') + thickness_obj = ObjectsFem.makeElementGeometry2D(doc, 0.3, "Thickness") analysis.addObject(thickness_obj) # material @@ -175,6 +178,7 @@ def setup(doc=None, solvertype="ccxtools"): # mesh from .meshes.mesh_plate_mystran_quad4 import create_nodes, create_elements + fem_mesh = Fem.FemMesh() control = create_nodes(fem_mesh) if not control: diff --git a/src/Mod/Fem/femexamples/rc_wall_2d.py b/src/Mod/Fem/femexamples/rc_wall_2d.py index 6d263d7776..a1bf4c961e 100644 --- a/src/Mod/Fem/femexamples/rc_wall_2d.py +++ b/src/Mod/Fem/femexamples/rc_wall_2d.py @@ -44,12 +44,14 @@ def get_information(): "constraints": ["fixed", "force", "displacement"], "solvers": ["ccxtools"], "material": "reinforced", - "equations": ["mechanical"] + "equations": ["mechanical"], } def get_explanation(header=""): - return header + """ + return ( + header + + """ To run the example from Python console use: from femexamples.rc_wall_2d import setup @@ -62,6 +64,7 @@ https://forum.freecad.org/viewtopic.php?f=18&t=33106&start=80#p296469 example from Harry's epic topic: Concrete branch ready for testing """ + ) def setup(doc=None, solvertype="ccxtools"): @@ -104,7 +107,7 @@ def setup(doc=None, solvertype="ccxtools"): # solver if solvertype == "ccxtools": solver_obj = ObjectsFem.makeSolverCalculiXCcxTools(doc, "CalculiXCcxTools") - solver_obj.WorkingDir = u"" + solver_obj.WorkingDir = "" else: FreeCAD.Console.PrintWarning( "Unknown or unsupported solver type: {}. " @@ -163,6 +166,7 @@ def setup(doc=None, solvertype="ccxtools"): # mesh from .meshes.mesh_rc_wall_2d_tria6 import create_nodes, create_elements + fem_mesh = Fem.FemMesh() control = create_nodes(fem_mesh) if not control: diff --git a/src/Mod/Fem/femexamples/square_pipe_end_twisted_edgeforces.py b/src/Mod/Fem/femexamples/square_pipe_end_twisted_edgeforces.py index 2d42f47256..c6f01e2008 100644 --- a/src/Mod/Fem/femexamples/square_pipe_end_twisted_edgeforces.py +++ b/src/Mod/Fem/femexamples/square_pipe_end_twisted_edgeforces.py @@ -43,12 +43,14 @@ def get_information(): "constraints": ["force", "fixed"], "solvers": ["ccxtools"], "material": "solid", - "equations": ["mechanical"] + "equations": ["mechanical"], } def get_explanation(header=""): - return header + """ + return ( + header + + """ To run the example from Python console use: from femexamples.square_pipe_end_twisted_edgeforces import setup @@ -59,6 +61,7 @@ See forum topic post: ... """ + ) def setup(doc=None, solvertype="ccxtools"): @@ -93,7 +96,7 @@ def setup(doc=None, solvertype="ccxtools"): # solver if solvertype == "ccxtools": solver_obj = ObjectsFem.makeSolverCalculiXCcxTools(doc, "CalculiXCcxTools") - solver_obj.WorkingDir = u"" + solver_obj.WorkingDir = "" else: FreeCAD.Console.PrintWarning( "Unknown or unsupported solver type: {}. " @@ -127,7 +130,8 @@ def setup(doc=None, solvertype="ccxtools"): (doc.SquareTube, "Edge4"), (doc.SquareTube, "Edge7"), (doc.SquareTube, "Edge10"), - (doc.SquareTube, "Edge12")] + (doc.SquareTube, "Edge12"), + ] analysis.addObject(con_fixed) # con_force1 @@ -164,6 +168,7 @@ def setup(doc=None, solvertype="ccxtools"): # mesh from .meshes.mesh_square_pipe_end_twisted_tria6 import create_nodes, create_elements + fem_mesh = Fem.FemMesh() control = create_nodes(fem_mesh) if not control: diff --git a/src/Mod/Fem/femexamples/square_pipe_end_twisted_nodeforces.py b/src/Mod/Fem/femexamples/square_pipe_end_twisted_nodeforces.py index 2138ff095f..5386677255 100644 --- a/src/Mod/Fem/femexamples/square_pipe_end_twisted_nodeforces.py +++ b/src/Mod/Fem/femexamples/square_pipe_end_twisted_nodeforces.py @@ -43,12 +43,14 @@ def get_information(): "constraints": ["force", "fixed"], "solvers": ["ccxtools"], "material": "solid", - "equations": ["mechanical"] + "equations": ["mechanical"], } def get_explanation(header=""): - return header + """ + return ( + header + + """ To run the example from Python console use: from femexamples.square_pipe_end_twisted_nodeforces import setup @@ -59,6 +61,7 @@ See forum topic post: ... """ + ) def setup(doc=None, solvertype="ccxtools"): @@ -203,7 +206,7 @@ def setup(doc=None, solvertype="ccxtools"): # solver if solvertype == "ccxtools": solver_obj = ObjectsFem.makeSolverCalculiXCcxTools(doc, "CalculiXCcxTools") - solver_obj.WorkingDir = u"" + solver_obj.WorkingDir = "" else: FreeCAD.Console.PrintWarning( "Unknown or unsupported solver type: {}. " @@ -281,7 +284,8 @@ def setup(doc=None, solvertype="ccxtools"): (geofixes_obj, "Vertex45"), (geofixes_obj, "Vertex27"), (geofixes_obj, "Vertex2"), - (geofixes_obj, "Vertex25")] + (geofixes_obj, "Vertex25"), + ] analysis.addObject(con_fixed) # con_force1 @@ -307,7 +311,8 @@ def setup(doc=None, solvertype="ccxtools"): (geoforces_obj, "Vertex21"), (geoforces_obj, "Vertex22"), (geoforces_obj, "Vertex23"), - (geoforces_obj, "Vertex24"), ] + (geoforces_obj, "Vertex24"), + ] con_force3.Force = "27777.78 N" con_force3.Direction = (geom_obj, ["Edge9"]) con_force3.Reversed = False @@ -320,7 +325,8 @@ def setup(doc=None, solvertype="ccxtools"): (geoforces_obj, "Vertex10"), (geoforces_obj, "Vertex11"), (geoforces_obj, "Vertex12"), - (geoforces_obj, "Vertex13"), ] + (geoforces_obj, "Vertex13"), + ] con_force4.Force = "27777.78 N" con_force4.Direction = (geom_obj, ["Edge3"]) con_force4.Reversed = False @@ -334,7 +340,8 @@ def setup(doc=None, solvertype="ccxtools"): (geoforces_obj, "Vertex45"), (geoforces_obj, "Vertex46"), (geoforces_obj, "Vertex47"), - (geoforces_obj, "Vertex48"), ] + (geoforces_obj, "Vertex48"), + ] con_force5.Force = "66666.67 N" con_force5.Direction = (geom_obj, ["Edge9"]) con_force5.Reversed = False @@ -348,7 +355,8 @@ def setup(doc=None, solvertype="ccxtools"): (geoforces_obj, "Vertex33"), (geoforces_obj, "Vertex34"), (geoforces_obj, "Vertex35"), - (geoforces_obj, "Vertex36"), ] + (geoforces_obj, "Vertex36"), + ] con_force6.Force = "66666.67 N" con_force6.Direction = (geom_obj, ["Edge3"]) con_force6.Reversed = False @@ -377,7 +385,8 @@ def setup(doc=None, solvertype="ccxtools"): (geoforces_obj, "Vertex4"), (geoforces_obj, "Vertex5"), (geoforces_obj, "Vertex6"), - (geoforces_obj, "Vertex7"), ] + (geoforces_obj, "Vertex7"), + ] con_force9.Force = "27777.78 N" con_force9.Direction = (geom_obj, ["Edge11"]) con_force9.Reversed = False @@ -390,7 +399,8 @@ def setup(doc=None, solvertype="ccxtools"): (geoforces_obj, "Vertex16"), (geoforces_obj, "Vertex17"), (geoforces_obj, "Vertex18"), - (geoforces_obj, "Vertex19"), ] + (geoforces_obj, "Vertex19"), + ] con_force10.Force = "27777.78 N" con_force10.Direction = (geom_obj, ["Edge6"]) con_force10.Reversed = False @@ -404,7 +414,8 @@ def setup(doc=None, solvertype="ccxtools"): (geoforces_obj, "Vertex27"), (geoforces_obj, "Vertex28"), (geoforces_obj, "Vertex29"), - (geoforces_obj, "Vertex30"), ] + (geoforces_obj, "Vertex30"), + ] con_force11.Force = "66666.67 N" con_force11.Direction = (geom_obj, ["Edge11"]) con_force11.Reversed = False @@ -418,7 +429,8 @@ def setup(doc=None, solvertype="ccxtools"): (geoforces_obj, "Vertex39"), (geoforces_obj, "Vertex40"), (geoforces_obj, "Vertex41"), - (geoforces_obj, "Vertex42"), ] + (geoforces_obj, "Vertex42"), + ] con_force12.Force = "66666.67 N" con_force12.Direction = (geom_obj, ["Edge6"]) con_force12.Reversed = False @@ -426,6 +438,7 @@ def setup(doc=None, solvertype="ccxtools"): # mesh from .meshes.mesh_square_pipe_end_twisted_tria6 import create_nodes, create_elements + fem_mesh = Fem.FemMesh() control = create_nodes(fem_mesh) if not control: diff --git a/src/Mod/Fem/femexamples/thermomech_bimetall.py b/src/Mod/Fem/femexamples/thermomech_bimetall.py index 42f68c99ce..c66e711793 100644 --- a/src/Mod/Fem/femexamples/thermomech_bimetall.py +++ b/src/Mod/Fem/femexamples/thermomech_bimetall.py @@ -51,12 +51,14 @@ def get_information(): "constraints": ["fixed", "initial temperature", "temperature"], "solvers": ["ccxtools", "elmer"], "material": "multimaterial", - "equations": ["thermomechanical"] + "equations": ["thermomechanical"], } def get_explanation(header=""): - return header + """ + return ( + header + + """ To run the example from Python console use: from femexamples.thermomech_bimetall import setup @@ -73,6 +75,7 @@ this file has 7.15 mm max deflection """ + ) def setup(doc=None, solvertype="ccxtools"): @@ -105,7 +108,7 @@ def setup(doc=None, solvertype="ccxtools"): doc.recompute() # all geom boolean fragment - geom_obj = SplitFeatures.makeBooleanFragments(name='BooleanFragments') + geom_obj = SplitFeatures.makeBooleanFragments(name="BooleanFragments") geom_obj.Objects = [bottom_box_obj, top_box_obj] if FreeCAD.GuiUp: bottom_box_obj.ViewObject.hide() @@ -122,7 +125,7 @@ def setup(doc=None, solvertype="ccxtools"): # solver if solvertype == "ccxtools": solver_obj = ObjectsFem.makeSolverCalculiXCcxTools(doc, "CalculiXCcxTools") - solver_obj.WorkingDir = u"" + solver_obj.WorkingDir = "" elif solvertype == "elmer": solver_obj = analysis.addObject(ObjectsFem.makeSolverElmer(doc, "SolverElmer"))[0] solver_obj.SteadyStateMinIterations = 1 @@ -189,25 +192,20 @@ def setup(doc=None, solvertype="ccxtools"): # constraint temperature con_temp = ObjectsFem.makeConstraintTemperature(doc, "ConstraintTemperatureHot") - con_temp.References = [ - (geom_obj, "Face5"), - (geom_obj, "Face11") - ] + con_temp.References = [(geom_obj, "Face5"), (geom_obj, "Face11")] con_temp.Temperature = 373.0 con_temp.CFlux = 0.0 analysis.addObject(con_temp) con_temp = ObjectsFem.makeConstraintTemperature(doc, "ConstraintTemperatureNormal") - con_temp.References = [ - (geom_obj, "Face1"), - (geom_obj, "Face7") - ] + con_temp.References = [(geom_obj, "Face1"), (geom_obj, "Face7")] con_temp.Temperature = 273.0 con_temp.CFlux = 0.0 analysis.addObject(con_temp) # mesh from .meshes.mesh_thermomech_bimetall_tetra10 import create_nodes, create_elements + fem_mesh = Fem.FemMesh() control = create_nodes(fem_mesh) if not control: diff --git a/src/Mod/Fem/femexamples/truss_3d_cs_circle_ele_seg2.py b/src/Mod/Fem/femexamples/truss_3d_cs_circle_ele_seg2.py index 1d8a844cb3..3419cd0212 100644 --- a/src/Mod/Fem/femexamples/truss_3d_cs_circle_ele_seg2.py +++ b/src/Mod/Fem/femexamples/truss_3d_cs_circle_ele_seg2.py @@ -38,7 +38,7 @@ def get_information(): "constraints": ["fixed", "force"], "solvers": ["z88"], "material": "solid", - "equations": ["mechanical"] + "equations": ["mechanical"], } @@ -58,6 +58,7 @@ def setup(doc=None, solvertype="z88"): # mesh from .meshes.mesh_truss_crane_seg2 import create_nodes, create_elements + fem_mesh = Fem.FemMesh() control = create_nodes(fem_mesh) if not control: diff --git a/src/Mod/Fem/femexamples/truss_3d_cs_circle_ele_seg3.py b/src/Mod/Fem/femexamples/truss_3d_cs_circle_ele_seg3.py index 97af0dd82d..245527b089 100644 --- a/src/Mod/Fem/femexamples/truss_3d_cs_circle_ele_seg3.py +++ b/src/Mod/Fem/femexamples/truss_3d_cs_circle_ele_seg3.py @@ -43,12 +43,14 @@ def get_information(): "constraints": ["fixed", "force"], "solvers": ["ccxtools"], "material": "solid", - "equations": ["mechanical"] + "equations": ["mechanical"], } def get_explanation(header=""): - return header + """ + return ( + header + + """ # To run the example from Python console use, # (works even after an edit without restart of FreeCAD): @@ -69,6 +71,7 @@ Z88 official example 2, crane beam - max deflection Mystran : x.xx mm - max deflection Z88 : 8.19 mm # one seg2 truss element foreach bar """ + ) def setup(doc=None, solvertype="ccxtools"): @@ -401,7 +404,7 @@ def setup(doc=None, solvertype="ccxtools"): # solver if solvertype == "ccxtools": solver_obj = ObjectsFem.makeSolverCalculiXCcxTools(doc, "CalculiXCcxTools") - solver_obj.WorkingDir = u"" + solver_obj.WorkingDir = "" elif solvertype == "z88": solver_obj = ObjectsFem.makeSolverZ88(doc, "SolverZ88") else: @@ -420,10 +423,7 @@ def setup(doc=None, solvertype="ccxtools"): # beam section beamsection_obj = ObjectsFem.makeElementGeometry1D( - doc, - sectiontype="Circular", - height=25.0, - name="CrossSectionCircular" + doc, sectiontype="Circular", height=25.0, name="CrossSectionCircular" ) analysis.addObject(beamsection_obj) @@ -451,6 +451,7 @@ def setup(doc=None, solvertype="ccxtools"): # mesh from .meshes.mesh_truss_crane_seg3 import create_nodes, create_elements + fem_mesh = Fem.FemMesh() control = create_nodes(fem_mesh) if not control: diff --git a/src/Mod/Fem/femguiutils/migrate_gui.py b/src/Mod/Fem/femguiutils/migrate_gui.py index ce0c5fc941..b55f5b0033 100644 --- a/src/Mod/Fem/femguiutils/migrate_gui.py +++ b/src/Mod/Fem/femguiutils/migrate_gui.py @@ -31,7 +31,7 @@ __author__ = "Bernd Hahnebach" __url__ = "https://www.freecad.org" -class FemMigrateGui(object): +class FemMigrateGui: def find_module(self, fullname, path): @@ -168,220 +168,308 @@ class FemMigrateGui(object): module.__path__ = "femguiobjects" if module.__name__ == "femguiobjects._ViewProviderFemConstraintBodyHeatSource": import femviewprovider.view_constraint_bodyheatsource - module.ViewProxy = \ + + module.ViewProxy = ( femviewprovider.view_constraint_bodyheatsource.VPConstraintBodyHeatSource + ) if module.__name__ == "femguiobjects._ViewProviderFemConstraintElectrostaticPotential": import femviewprovider.view_constraint_electrostaticpotential - module.ViewProxy = \ + + module.ViewProxy = ( femviewprovider.view_constraint_electrostaticpotential.VPConstraintElectroStaticPotential + ) if module.__name__ == "femguiobjects._ViewProviderFemConstraintFlowVelocity": import femviewprovider.view_constraint_flowvelocity - module.ViewProxy = \ - femviewprovider.view_constraint_flowvelocity.VPConstraintFlowVelocity + + module.ViewProxy = femviewprovider.view_constraint_flowvelocity.VPConstraintFlowVelocity if module.__name__ == "femguiobjects._ViewProviderFemConstraintInitialFlowVelocity": import femviewprovider.view_constraint_initialflowvelocity - module.ViewProxy = \ + + module.ViewProxy = ( femviewprovider.view_constraint_initialflowvelocity.VPConstraintInitialFlowVelocity + ) if module.__name__ == "femguiobjects._ViewProviderFemConstraintSelfWeight": import femviewprovider.view_constraint_selfweight - module._ViewProviderFemConstraintSelfWeight = \ + + module._ViewProviderFemConstraintSelfWeight = ( femviewprovider.view_constraint_selfweight.VPConstraintSelfWeight + ) if module.__name__ == "femguiobjects._ViewProviderFemConstraintTie": import femviewprovider.view_constraint_tie - module._ViewProviderFemConstraintTie = \ + + module._ViewProviderFemConstraintTie = ( femviewprovider.view_constraint_tie.VPConstraintTie + ) if module.__name__ == "femguiobjects._ViewProviderFemElementFluid1D": import femviewprovider.view_element_fluid1D - module._ViewProviderFemElementFluid1D = \ + + module._ViewProviderFemElementFluid1D = ( femviewprovider.view_element_fluid1D.VPElementFluid1D + ) if module.__name__ == "femguiobjects._ViewProviderFemElementGeometry1D": import femviewprovider.view_element_geometry1D - module._ViewProviderFemElementGeometry1D = \ + + module._ViewProviderFemElementGeometry1D = ( femviewprovider.view_element_geometry1D.VPElementGeometry1D + ) if module.__name__ == "femguiobjects._ViewProviderFemElementGeometry2D": import femviewprovider.view_element_geometry2D - module._ViewProviderFemElementGeometry2D = \ + + module._ViewProviderFemElementGeometry2D = ( femviewprovider.view_element_geometry2D.VPElementGeometry2D + ) if module.__name__ == "femguiobjects._ViewProviderFemElementRotation1D": import femviewprovider.view_element_rotation1D - module._ViewProviderFemElementRotation1D = \ + + module._ViewProviderFemElementRotation1D = ( femviewprovider.view_element_rotation1D.VPElementRotation1D + ) if module.__name__ == "femguiobjects._ViewProviderFemMaterial": import femviewprovider.view_material_common + module._ViewProviderFemMaterial = femviewprovider.view_material_common.VPMaterialCommon if module.__name__ == "femguiobjects._ViewProviderFemMaterialMechanicalNonlinear": import femviewprovider.view_material_mechanicalnonlinear - module._ViewProviderFemMaterialMechanicalNonlinear = \ + + module._ViewProviderFemMaterialMechanicalNonlinear = ( femviewprovider.view_material_mechanicalnonlinear.VPMaterialMechanicalNonlinear + ) if module.__name__ == "femguiobjects._ViewProviderFemMaterialReinforced": import femviewprovider.view_material_reinforced - module._ViewProviderFemMaterialReinforced = \ + + module._ViewProviderFemMaterialReinforced = ( femviewprovider.view_material_reinforced.VPMaterialReinforced + ) if module.__name__ == "femguiobjects._ViewProviderFemMeshBoundaryLayer": import femviewprovider.view_mesh_boundarylayer - module._ViewProviderFemMeshBoundaryLayer = \ + + module._ViewProviderFemMeshBoundaryLayer = ( femviewprovider.view_mesh_boundarylayer.VPMeshBoundaryLayer + ) if module.__name__ == "femguiobjects._ViewProviderFemMeshGmsh": import femviewprovider.view_mesh_gmsh + module._ViewProviderFemMeshGmsh = femviewprovider.view_mesh_gmsh.VPMeshGmsh if module.__name__ == "femguiobjects._ViewProviderFemMeshGroup": import femviewprovider.view_mesh_group + module._ViewProviderFemMeshGroup = femviewprovider.view_mesh_group.VPMeshGroup if module.__name__ == "femguiobjects._ViewProviderFemMeshRegion": import femviewprovider.view_mesh_region + module._ViewProviderFemMeshRegion = femviewprovider.view_mesh_region.VPMeshRegion if module.__name__ == "femguiobjects._ViewProviderFemMeshResult": import femviewprovider.view_mesh_result + module._ViewProviderFemMeshResult = femviewprovider.view_mesh_result.VPFemMeshResult if module.__name__ == "femguiobjects._ViewProviderFemResultMechanical": import femviewprovider.view_result_mechanical - module._ViewProviderFemResultMechanical = \ + + module._ViewProviderFemResultMechanical = ( femviewprovider.view_result_mechanical.VPResultMechanical + ) if module.__name__ == "femguiobjects._ViewProviderFemSolverCalculix": import femviewprovider.view_solver_ccxtools - module._ViewProviderFemSolverCalculix = \ + + module._ViewProviderFemSolverCalculix = ( femviewprovider.view_solver_ccxtools.VPSolverCcxTools + ) if module.__name__ == "PyGui": module.__path__ = "PyGui" if module.__name__ == "PyGui._ViewProviderFemConstraintBodyHeatSource": import femviewprovider.view_constraint_bodyheatsource - module.ViewProxy = \ + + module.ViewProxy = ( femviewprovider.view_constraint_bodyheatsource.VPConstraintBodyHeatSource + ) if module.__name__ == "PyGui._ViewProviderFemConstraintElectrostaticPotential": import femviewprovider.view_constraint_electrostaticpotential - module.ViewProxy = \ + + module.ViewProxy = ( femviewprovider.view_constraint_electrostaticpotential.VPConstraintElectroStaticPotential + ) if module.__name__ == "PyGui._ViewProviderFemConstraintFlowVelocity": import femviewprovider.view_constraint_flowvelocity - module.ViewProxy = \ - femviewprovider.view_constraint_flowvelocity.VPConstraintFlowVelocity + + module.ViewProxy = femviewprovider.view_constraint_flowvelocity.VPConstraintFlowVelocity if module.__name__ == "PyGui._ViewProviderFemConstraintInitialFlowVelocity": import femviewprovider.view_constraint_initialflowvelocity - module.ViewProxy = \ + + module.ViewProxy = ( femviewprovider.view_constraint_initialflowvelocity.VPConstraintInitialFlowVelocity + ) if module.__name__ == "PyGui._ViewProviderFemConstraintSelfWeight": import femviewprovider.view_constraint_selfweight - module._ViewProviderFemConstraintSelfWeight = \ + + module._ViewProviderFemConstraintSelfWeight = ( femviewprovider.view_constraint_selfweight.VPConstraintSelfWeight + ) if module.__name__ == "PyGui._ViewProviderFemElementFluid1D": import femviewprovider.view_element_fluid1D - module._ViewProviderFemElementFluid1D = \ + + module._ViewProviderFemElementFluid1D = ( femviewprovider.view_element_fluid1D.VPElementFluid1D + ) if module.__name__ == "PyGui._ViewProviderFemElementGeometry1D": import femviewprovider.view_element_geometry1D - module._ViewProviderFemElementGeometry1D = \ + + module._ViewProviderFemElementGeometry1D = ( femviewprovider.view_element_geometry1D.VPElementGeometry1D + ) if module.__name__ == "PyGui._ViewProviderFemElementGeometry2D": import femviewprovider.view_element_geometry2D - module._ViewProviderFemElementGeometry2D = \ + + module._ViewProviderFemElementGeometry2D = ( femviewprovider.view_element_geometry2D.VPElementGeometry2D + ) if module.__name__ == "PyGui._ViewProviderFemElementRotation1D": import femviewprovider.view_element_rotation1D - module._ViewProviderFemElementRotation1D = \ + + module._ViewProviderFemElementRotation1D = ( femviewprovider.view_element_rotation1D.VPElementRotation1D + ) if module.__name__ == "PyGui._ViewProviderFemMaterial": import femviewprovider.view_material_common - module._ViewProviderFemMaterial = \ - femviewprovider.view_material_common.VPMaterialCommon + + module._ViewProviderFemMaterial = femviewprovider.view_material_common.VPMaterialCommon if module.__name__ == "PyGui._ViewProviderFemMaterialMechanicalNonlinear": import femviewprovider.view_material_mechanicalnonlinear - module._ViewProviderFemMaterialMechanicalNonlinear = \ + + module._ViewProviderFemMaterialMechanicalNonlinear = ( femviewprovider.view_material_mechanicalnonlinear.VPMaterialMechanicalNonlinear + ) if module.__name__ == "PyGui._ViewProviderFemMeshBoundaryLayer": import femviewprovider.view_mesh_boundarylayer - module._ViewProviderFemMeshBoundaryLayer = \ + + module._ViewProviderFemMeshBoundaryLayer = ( femviewprovider.view_mesh_boundarylayer.VPMeshBoundaryLayer + ) if module.__name__ == "PyGui._ViewProviderFemMeshGmsh": import femviewprovider.view_mesh_gmsh + module._ViewProviderFemMeshGmsh = femviewprovider.view_mesh_gmsh.VPMeshGmsh if module.__name__ == "PyGui._ViewProviderFemMeshGroup": import femviewprovider.view_mesh_group + module._ViewProviderFemMeshGroup = femviewprovider.view_mesh_group.VPMeshGroup if module.__name__ == "PyGui._ViewProviderFemMeshRegion": import femviewprovider.view_mesh_region + module._ViewProviderFemMeshRegion = femviewprovider.view_mesh_region.VPMeshRegion if module.__name__ == "PyGui._ViewProviderFemMeshResult": import femviewprovider.view_mesh_result + module._ViewProviderFemMeshResult = femviewprovider.view_mesh_result.VPFemMeshResult if module.__name__ == "PyGui._ViewProviderFemResultMechanical": import femviewprovider.view_result_mechanical - module._ViewProviderFemResultMechanical = \ + + module._ViewProviderFemResultMechanical = ( femviewprovider.view_result_mechanical.VPResultMechanical + ) if module.__name__ == "PyGui._ViewProviderFemSolverCalculix": import femviewprovider.view_solver_ccxtools - module._ViewProviderFemSolverCalculix = \ + + module._ViewProviderFemSolverCalculix = ( femviewprovider.view_solver_ccxtools.VPSolverCcxTools + ) if module.__name__ == "PyGui._ViewProviderFemSolverZ88": import femsolver.z88.solver + module._ViewProviderFemSolverZ88 = femsolver.z88.solver.ViewProxy if module.__name__ == "PyGui._ViewProviderFemBeamSection": import femviewprovider.view_element_geometry1D - module._ViewProviderFemBeamSection = \ + + module._ViewProviderFemBeamSection = ( femviewprovider.view_element_geometry1D.VPElementGeometry1D + ) if module.__name__ == "PyGui._ViewProviderFemFluidSection": import femviewprovider.view_element_fluid1D - module._ViewProviderFemFluidSection = \ + + module._ViewProviderFemFluidSection = ( femviewprovider.view_element_fluid1D.VPElementFluid1D + ) if module.__name__ == "PyGui._ViewProviderFemShellThickness": import femviewprovider.view_element_geometry2D - module._ViewProviderFemShellThickness = \ + + module._ViewProviderFemShellThickness = ( femviewprovider.view_element_geometry2D.VPElementGeometry2D + ) if module.__name__ == "_ViewProviderFemBeamSection": import femviewprovider.view_element_geometry1D - module._ViewProviderFemBeamSection = \ + + module._ViewProviderFemBeamSection = ( femviewprovider.view_element_geometry1D.VPElementGeometry1D + ) if module.__name__ == "_ViewProviderFemConstraintSelfWeight": import femviewprovider.view_constraint_selfweight - module._ViewProviderFemConstraintSelfWeight = \ + + module._ViewProviderFemConstraintSelfWeight = ( femviewprovider.view_constraint_selfweight.VPConstraintSelfWeight + ) if module.__name__ == "_ViewProviderFemMaterial": import femviewprovider.view_material_common - module._ViewProviderFemMaterial = \ - femviewprovider.view_material_common.VPMaterialCommon + + module._ViewProviderFemMaterial = femviewprovider.view_material_common.VPMaterialCommon if module.__name__ == "_ViewProviderFemMaterialMechanicalNonlinear": import femviewprovider.view_material_mechanicalnonlinear - module._ViewProviderFemMaterialMechanicalNonlinear = \ + + module._ViewProviderFemMaterialMechanicalNonlinear = ( femviewprovider.view_material_mechanicalnonlinear.VPMaterialMechanicalNonlinear + ) if module.__name__ == "_ViewProviderFemMeshGmsh": import femviewprovider.view_mesh_gmsh + module._ViewProviderFemMeshGmsh = femviewprovider.view_mesh_gmsh.VPMeshGmsh if module.__name__ == "_ViewProviderFemMeshGroup": import femviewprovider.view_mesh_group + module._ViewProviderFemMeshGroup = femviewprovider.view_mesh_group.VPMeshGroup if module.__name__ == "_ViewProviderFemMeshRegion": import femviewprovider.view_mesh_region + module._ViewProviderFemMeshRegion = femviewprovider.view_mesh_region.VPMeshRegion if module.__name__ == "_ViewProviderFemResultMechanical": import femviewprovider.view_result_mechanical - module._ViewProviderFemResultMechanical = \ + + module._ViewProviderFemResultMechanical = ( femviewprovider.view_result_mechanical.VPResultMechanical + ) if module.__name__ == "_ViewProviderFemShellThickness": import femviewprovider.view_element_geometry2D - module._ViewProviderFemShellThickness = \ + + module._ViewProviderFemShellThickness = ( femviewprovider.view_element_geometry2D.VPElementGeometry2D + ) if module.__name__ == "_ViewProviderFemSolverCalculix": import femviewprovider.view_solver_ccxtools - module._ViewProviderFemSolverCalculix = \ + + module._ViewProviderFemSolverCalculix = ( femviewprovider.view_solver_ccxtools.VPSolverCcxTools + ) if module.__name__ == "_ViewProviderFemSolverZ88": import femsolver.z88.solver + module._ViewProviderFemSolverZ88 = femsolver.z88.solver.ViewProxy if module.__name__ == "_ViewProviderFemMechanicalResult": import femviewprovider.view_result_mechanical - module._ViewProviderFemMechanicalResult = \ + + module._ViewProviderFemMechanicalResult = ( femviewprovider.view_result_mechanical.VPResultMechanical + ) if module.__name__ == "ViewProviderFemResult": import femviewprovider.view_result_mechanical - module.ViewProviderFemResult = \ - femviewprovider.view_result_mechanical.VPResultMechanical + + module.ViewProviderFemResult = femviewprovider.view_result_mechanical.VPResultMechanical if module.__name__ == "_ViewProviderMechanicalMaterial": import femviewprovider.view_material_common - module._ViewProviderMechanicalMaterial = \ + + module._ViewProviderMechanicalMaterial = ( femviewprovider.view_material_common.VPMaterialCommon + ) return None diff --git a/src/Mod/Fem/femguiutils/selection_widgets.py b/src/Mod/Fem/femguiutils/selection_widgets.py index 1a6a3cd341..c038ce390f 100644 --- a/src/Mod/Fem/femguiutils/selection_widgets.py +++ b/src/Mod/Fem/femguiutils/selection_widgets.py @@ -43,7 +43,7 @@ from femtools import geomtools class _Selector(QtGui.QWidget): def __init__(self): - super(_Selector, self).__init__() + super().__init__() self._references = [] self._register = dict() @@ -92,7 +92,7 @@ class _Selector(QtGui.QWidget): obj, sub = self._register[identifier] refIndex = self._getIndex(obj) entry = self._references[refIndex] - newSub = tuple((x for x in entry[1] if x != sub)) + newSub = tuple(x for x in entry[1] if x != sub) self._references[refIndex] = (obj, newSub) self._model.removeRow(index.row()) @@ -107,7 +107,7 @@ class _Selector(QtGui.QWidget): self._references[index] = newEntry def _addToWidget(self, obj, sub): - identifier = "%s::%s" % (obj.Name, sub) + identifier = f"{obj.Name}::{sub}" item = QtGui.QStandardItem(identifier) self._model.appendRow(item) self._register[identifier] = (obj, sub) @@ -126,12 +126,9 @@ class _Selector(QtGui.QWidget): class BoundarySelector(_Selector): def __init__(self): - super(BoundarySelector, self).__init__() + super().__init__() self.setWindowTitle(self.tr("Select Faces/Edges/Vertexes")) - self.setHelpText(self.tr( - "To add references: select them in the 3D view " - ' and click "Add".' - )) + self.setHelpText(self.tr('To add references: select them in the 3D view and click "Add".')) def getSelection(self): selection = [] @@ -145,12 +142,14 @@ class BoundarySelector(_Selector): class SolidSelector(_Selector): def __init__(self): - super(SolidSelector, self).__init__() + super().__init__() self.setWindowTitle(self.tr("Select Solids")) - self.setHelpText(self.tr( - "Select elements part of the solid that shall be added" - ' to the list. To add the solid click "Add".' - )) + self.setHelpText( + self.tr( + "Select elements part of the solid that shall be added" + ' to the list. To add the solid click "Add".' + ) + ) def getSelection(self): selection = [] @@ -172,9 +171,7 @@ class SolidSelector(_Selector): def _getObjects(self, obj, names): objects = [] if not hasattr(obj, "Shape"): - FreeCAD.Console.PrintMessage( - "Selected object has no Shape.\n" - ) + FreeCAD.Console.PrintMessage("Selected object has no Shape.\n") return objects shape = obj.Shape for n in names: @@ -227,7 +224,7 @@ class SmallListView(QtGui.QListView): class GeometryElementsSelection(QtGui.QWidget): def __init__(self, ref, eltypes, multigeom, showHintEmptyList): - super(GeometryElementsSelection, self).__init__() + super().__init__() # init ui stuff FreeCADGui.Selection.clearSelection() self.sel_server = None @@ -264,9 +261,9 @@ class GeometryElementsSelection(QtGui.QWidget): def initUI(self): # ArchPanel is coded without ui-file too # title - self.setWindowTitle(self.tr( - "Geometry reference selector for a {}" - ).format(self.sel_elem_text)) + self.setWindowTitle( + self.tr("Geometry reference selector for a {}").format(self.sel_elem_text) + ) # button self.pushButton_Add = QtGui.QPushButton(self.tr("Add")) # label @@ -280,13 +277,9 @@ class GeometryElementsSelection(QtGui.QWidget): "{}If no geometry is added to the list, all remaining ones are used." ).format("
") if self.showHintEmptyList is True: - self._helpTextLbl.setText( - helpTextPart1 + helpTextEmpty - ) + self._helpTextLbl.setText(helpTextPart1 + helpTextEmpty) else: - self._helpTextLbl.setText( - helpTextPart1 - ) + self._helpTextLbl.setText(helpTextPart1) # list self.list_References = QtGui.QListWidget() # radiobutton down the list @@ -324,22 +317,14 @@ class GeometryElementsSelection(QtGui.QWidget): self.list_References.connect( self.list_References, QtCore.SIGNAL("customContextMenuRequested(QPoint)"), - self.references_list_right_clicked + self.references_list_right_clicked, + ) + QtCore.QObject.connect(self.pushButton_Add, QtCore.SIGNAL("clicked()"), self.add_references) + QtCore.QObject.connect( + self.rb_standard, QtCore.SIGNAL("toggled(bool)"), self.choose_selection_mode_standard ) QtCore.QObject.connect( - self.pushButton_Add, - QtCore.SIGNAL("clicked()"), - self.add_references - ) - QtCore.QObject.connect( - self.rb_standard, - QtCore.SIGNAL("toggled(bool)"), - self.choose_selection_mode_standard - ) - QtCore.QObject.connect( - self.rb_solid, - QtCore.SIGNAL("toggled(bool)"), - self.choose_selection_mode_solid + self.rb_solid, QtCore.SIGNAL("toggled(bool)"), self.choose_selection_mode_solid ) def get_references(self): @@ -408,8 +393,7 @@ class GeometryElementsSelection(QtGui.QWidget): FreeCADGui.Selection.addSelection(ref[0], ref[1]) def setback_listobj_visibility(self): - """set back Visibility of the list objects - """ + """set back Visibility of the list objects""" FreeCADGui.Selection.clearSelection() for obj in self.obj_notvisible: obj.ViewObject.Visibility = False @@ -423,15 +407,9 @@ class GeometryElementsSelection(QtGui.QWidget): menu_item_remove_selected.setDisabled(True) menu_item_remove_all.setDisabled(True) self.connect( - menu_item_remove_selected, - QtCore.SIGNAL("triggered()"), - self.remove_selected_reference - ) - self.connect( - menu_item_remove_all, - QtCore.SIGNAL("triggered()"), - self.remove_all_references + menu_item_remove_selected, QtCore.SIGNAL("triggered()"), self.remove_selected_reference ) + self.connect(menu_item_remove_all, QtCore.SIGNAL("triggered()"), self.remove_all_references) parentPosition = self.list_References.mapToGlobal(QtCore.QPoint(0, 0)) self.contextMenu.move(parentPosition + QPos) self.contextMenu.show() @@ -479,11 +457,11 @@ class GeometryElementsSelection(QtGui.QWidget): def selectionParser(self, selection): if hasattr(selection[0], "Shape") and selection[1]: - FreeCAD.Console.PrintMessage("Selection: {} {} {}\n".format( - selection[0].Shape.ShapeType, - selection[0].Name, - selection[1] - )) + FreeCAD.Console.PrintMessage( + "Selection: {} {} {}\n".format( + selection[0].Shape.ShapeType, selection[0].Name, selection[1] + ) + ) sobj = selection[0] elt = sobj.Shape.getElement(selection[1]) ele_ShapeType = elt.ShapeType @@ -502,8 +480,7 @@ class GeometryElementsSelection(QtGui.QWidget): # could be more than two solids, think of polar pattern FreeCAD.Console.PrintMessage( " Edge belongs to at least two solids: " - " Solid{}, Solid{}\n" - .format(solid_to_add, str(i + 1)) + " Solid{}, Solid{}\n".format(solid_to_add, str(i + 1)) ) solid_to_add = None found_eltedge_in_other_solid = True @@ -517,8 +494,9 @@ class GeometryElementsSelection(QtGui.QWidget): else: # AFAIK (bernd) a face can only belong to two solids FreeCAD.Console.PrintMessage( - " Face belongs to two solids: Solid{}, Solid{}\n" - .format(solid_to_add, str(i + 1)) + " Face belongs to two solids: Solid{}, Solid{}\n".format( + solid_to_add, str(i + 1) + ) ) solid_to_add = None found_eltface_in_other_solid = True @@ -526,14 +504,16 @@ class GeometryElementsSelection(QtGui.QWidget): selection = (sobj, "Solid" + solid_to_add) ele_ShapeType = "Solid" FreeCAD.Console.PrintMessage( - " Selection variable adapted to hold the Solid: {} {} {}\n" - .format(sobj.Shape.ShapeType, sobj.Name, selection[1]) + " Selection variable adapted to hold the Solid: {} {} {}\n".format( + sobj.Shape.ShapeType, sobj.Name, selection[1] + ) ) else: return if ele_ShapeType in self.sel_elem_types: - if (self.selection_mode_solid and ele_ShapeType == "Solid") \ - or self.selection_mode_solid is False: + if ( + self.selection_mode_solid and ele_ShapeType == "Solid" + ) or self.selection_mode_solid is False: if selection not in self.references: # only equal shape types are allowed to add if self.allow_multiple_geom_types is False: @@ -553,15 +533,12 @@ class GeometryElementsSelection(QtGui.QWidget): else: # selected shape will not added to the list FreeCADGui.Selection.clearSelection() - message = ( - " Selection {} is in reference list already!\n" - .format(self.get_item_text(selection)) + message = " Selection {} is in reference list already!\n".format( + self.get_item_text(selection) ) FreeCAD.Console.PrintMessage(message) QtGui.QMessageBox.critical( - None, - "Geometry already in list", - message.lstrip(" ") + None, "Geometry already in list", message.lstrip(" ") ) else: # selected shape will not added to the list @@ -575,13 +552,12 @@ class GeometryElementsSelection(QtGui.QWidget): # the method getElement(element) does not return Solid elements r = geomtools.get_element(ref[0], ref[1]) if not r: - FreeCAD.Console.PrintError( - "Problem in retrieving element: {} \n".format(ref[1]) - ) + FreeCAD.Console.PrintError(f"Problem in retrieving element: {ref[1]} \n") continue FreeCAD.Console.PrintLog( - " ReferenceShape : {}, {}, {} --> {}\n" - .format(r.ShapeType, ref[0].Name, ref[0].Label, ref[1]) + " ReferenceShape : {}, {}, {} --> {}\n".format( + r.ShapeType, ref[0].Name, ref[0].Label, ref[1] + ) ) if not ref_shty: ref_shty = r.ShapeType @@ -600,6 +576,7 @@ class GeometryElementsSelection(QtGui.QWidget): class FemSelectionObserver: """selection observer especially for the needs of geometry reference selection of FEM""" + def __init__(self, parseSelectionFunction, print_message=""): self.parseSelectionFunction = parseSelectionFunction FreeCADGui.Selection.addObserver(self) diff --git a/src/Mod/Fem/feminout/convert2TetGen.py b/src/Mod/Fem/feminout/convert2TetGen.py index 5ddf785b13..ef7a001f1b 100644 --- a/src/Mod/Fem/feminout/convert2TetGen.py +++ b/src/Mod/Fem/feminout/convert2TetGen.py @@ -37,6 +37,7 @@ import Mesh App = FreeCAD # shortcut if FreeCAD.GuiUp: import FreeCADGui + Gui = FreeCADGui # shortcut ## \addtogroup FEM @@ -54,23 +55,25 @@ def exportMeshToTetGenPoly(meshToExport, filePath, beVerbose=1): f.write("# Part 1 - node list\n") f.write( "TotalNumOfPoints: {}, NumOfDimensions; {}, " - "NumOfProperties: {}, BoundaryMarkerExists: {}\n" - .format(len(allVertices), 3, 0, 0) + "NumOfProperties: {}, BoundaryMarkerExists: {}\n".format(len(allVertices), 3, 0, 0) ) for PointIndex in range(len(allVertices)): - f.write("%(PointIndex)5i %(x) e %(y) e %(z) e\n" % { - "PointIndex": PointIndex, - "x": allVertices[PointIndex].x, - "y": allVertices[PointIndex].y, - "z": allVertices[PointIndex].z - }) + f.write( + "%(PointIndex)5i %(x) e %(y) e %(z) e\n" + % { + "PointIndex": PointIndex, + "x": allVertices[PointIndex].x, + "y": allVertices[PointIndex].y, + "z": allVertices[PointIndex].z, + } + ) # Find out BoundaryMarker for each facet. If edge connects only two facets, # then this facets should have the same BoundaryMarker BoundaryMarkerExists = 1 PointList = [allFacets[0][1], allFacets[0][0]] PointList.sort() - EdgeFacets = {(PointList[0], PointList[1]): set([0])} + EdgeFacets = {(PointList[0], PointList[1]): {0}} Edge = [] # Find all facets for each edge @@ -85,7 +88,7 @@ def exportMeshToTetGenPoly(meshToExport, filePath, beVerbose=1): if EdgeIndex in EdgeFacets: EdgeFacets[EdgeIndex].add(FacetIndex) else: - EdgeFacets[EdgeIndex] = set([FacetIndex]) + EdgeFacets[EdgeIndex] = {FacetIndex} Edge = [] # Find BoundaryMarker for each facet @@ -120,7 +123,7 @@ def exportMeshToTetGenPoly(meshToExport, filePath, beVerbose=1): if (BoundaryMarker[FacetPair[0]] != 0) and (BoundaryMarker[FacetPair[1]] != 0): removeEdge = 1 break - if (BoundaryMarker[FacetPair[0]] != 0): + if BoundaryMarker[FacetPair[0]] != 0: BoundaryMarker[FacetPair[1]] = BoundaryMarker[FacetPair[0]] else: BoundaryMarker[FacetPair[0]] = BoundaryMarker[FacetPair[1]] @@ -156,10 +159,10 @@ def exportMeshToTetGenPoly(meshToExport, filePath, beVerbose=1): # ********** Part 2 - write all facets to *.poly file f.write("# Part 2 - facet list\n") - f.write("%(TotalNumOfFacets)i %(BoundaryMarkerExists)i\n" % { - "TotalNumOfFacets": len(allFacets), - "BoundaryMarkerExists": BoundaryMarkerExists - }) + f.write( + "%(TotalNumOfFacets)i %(BoundaryMarkerExists)i\n" + % {"TotalNumOfFacets": len(allFacets), "BoundaryMarkerExists": BoundaryMarkerExists} + ) for FacetIndex in range(len(allFacets)): f.write("# FacetIndex = %(Index)i\n" % {"Index": FacetIndex}) f.write("%(NumOfPolygons)3i " % {"NumOfPolygons": 1}) @@ -215,14 +218,7 @@ def createMesh(): AdsorbtionBox = AppPyDoc.addObject("Part::Box", AdsorbtionBoxName) pnMesh = AppPyDoc.addObject("Mesh::Feature", pnMeshName) - BoxList = [ - NSideBox, - DepletionBox, - PSideBox, - OxideBox, - AdsorbtionBox, - SurfDepletionBox - ] + BoxList = [NSideBox, DepletionBox, PSideBox, OxideBox, AdsorbtionBox, SurfDepletionBox] NSideBoxMesh = Mesh.Mesh() PSideBoxMesh = Mesh.Mesh() DepletionBoxMesh = Mesh.Mesh() @@ -235,7 +231,7 @@ def createMesh(): PSideBoxMesh, OxideBoxMesh, AdsorbtionBoxMesh, - SurfDepletionBoxMesh + SurfDepletionBoxMesh, ] if beVerbose == 1: if len(BoxList) != len(BoxMeshList): @@ -280,30 +276,14 @@ def createMesh(): # Object placement Rot = App.Rotation(0, 0, 0, 1) - NSideBox.Placement = App.Placement( - App.Vector(0, 0, -BulkHeight), - Rot - ) + NSideBox.Placement = App.Placement(App.Vector(0, 0, -BulkHeight), Rot) PSideBox.Placement = App.Placement( - App.Vector(DepletionSize * 2 + BulkLength, 0, -BulkHeight), - Rot - ) - DepletionBox.Placement = App.Placement( - App.Vector(BulkLength, 0, -BulkHeight), - Rot - ) - SurfDepletionBox.Placement = App.Placement( - App.Vector(0, 0, 0), - Rot - ) - OxideBox.Placement = App.Placement( - App.Vector(0, 0, DepletionSize), - Rot - ) - AdsorbtionBox.Placement = App.Placement( - App.Vector(0, 0, DepletionSize + OxideThickness), - Rot + App.Vector(DepletionSize * 2 + BulkLength, 0, -BulkHeight), Rot ) + DepletionBox.Placement = App.Placement(App.Vector(BulkLength, 0, -BulkHeight), Rot) + SurfDepletionBox.Placement = App.Placement(App.Vector(0, 0, 0), Rot) + OxideBox.Placement = App.Placement(App.Vector(0, 0, DepletionSize), Rot) + AdsorbtionBox.Placement = App.Placement(App.Vector(0, 0, DepletionSize + OxideThickness), Rot) # Unite if beVerbose == 1: @@ -316,9 +296,7 @@ def createMesh(): # for index in range(len(BoxList)): for index in range(len(BoxList) - 1): # Manual hack - BoxMeshList[index].addFacets( - BoxList[index].Shape.tessellate(tessellationTollerance) - ) + BoxMeshList[index].addFacets(BoxList[index].Shape.tessellate(tessellationTollerance)) nmesh.addMesh(BoxMeshList[index]) nmesh.removeDuplicatedPoints() @@ -348,4 +326,5 @@ def createMesh(): if beVerbose == 1: Console.PrintMessage("\nScript finished without errors.") + ## @} diff --git a/src/Mod/Fem/feminout/exportNastranMesh.py b/src/Mod/Fem/feminout/exportNastranMesh.py index 185ac219a2..891e4ab40c 100644 --- a/src/Mod/Fem/feminout/exportNastranMesh.py +++ b/src/Mod/Fem/feminout/exportNastranMesh.py @@ -49,10 +49,8 @@ from femmesh import meshtools # names are fix given from FreeCAD, these methods are called from FreeCAD # they are set in FEM modules Init.py -def export( - objectslist, - filename -): + +def export(objectslist, filename): "called when freecad exports a file" if len(objectslist) != 1: Console.PrintError("This exporter can only export one object.\n") @@ -72,10 +70,7 @@ def export( # ********* writer ******************************************************************************* -def write( - fem_mesh, - filename -): +def write(fem_mesh, filename): """directly write a FemMesh to a pyNastran mesh file format fem_mesh: a FemMesh""" @@ -91,17 +86,14 @@ def write( mesh_pynas_code += missing_code_pnynasmesh # pynas file - basefilename = filename[:len(filename) - 4] # TODO basename is more failsafe + basefilename = filename[: len(filename) - 4] # TODO basename is more failsafe pynasf = open(basefilename + ".py", "w") pynasf.write("# written by FreeCAD\n\n\n") pynasf.write("from pyNastran.bdf.bdf import BDF\n") pynasf.write("model = BDF()\n\n\n") pynasf.write(mesh_pynas_code) - pynasf.write( - "model.write_bdf('{}', enddata=True)\n" - .format(basefilename + "_pyNas.bdf") - ) + pynasf.write("model.write_bdf('{}', enddata=True)\n".format(basefilename + "_pyNas.bdf")) pynasf.close() # execute pyNastran code to add grid to the model @@ -128,7 +120,7 @@ def get_pynastran_mesh( pynas_nodes = "# grid cards, geometric mesh points\n" for node in femnodes_mesh: vec = femnodes_mesh[node] - pynas_nodes += "model.add_grid({}, [{}, {}, {}])\n".format(node, vec.x, vec.y, vec.z) + pynas_nodes += f"model.add_grid({node}, [{vec.x}, {vec.y}, {vec.z}])\n" # print(pynas_nodes) # elements @@ -142,14 +134,13 @@ def get_pynastran_mesh( if export_element_type == "cbar": pynas_elements += ( "model.add_{ele_keyword}({eid}, {pid}, {nodes}, " - "{orientation_vec}, {gnull})\n" - .format( + "{orientation_vec}, {gnull})\n".format( ele_keyword=export_element_type, eid=element, pid=1, nodes=nodes, orientation_vec="x=[0.0, 0.0, 1.0]", - gnull="g0=None" + gnull="g0=None", ) ) else: @@ -161,28 +152,31 @@ def get_pynastran_mesh( ele_keyword = "ctetra" # N1, N3, N2, N4, N7, N6, N5, N8, N10, N9 the_nodes = [ - nodes[0], nodes[2], nodes[1], nodes[3], - nodes[6], nodes[5], nodes[4], - nodes[7], nodes[9], nodes[8], + nodes[0], + nodes[2], + nodes[1], + nodes[3], + nodes[6], + nodes[5], + nodes[4], + nodes[7], + nodes[9], + nodes[8], ] else: ele_keyword = export_element_type the_nodes = nodes - pynas_elements += ( - "model.add_{ele_keyword}({eid}, {pid}, {nodes})\n" - .format(ele_keyword=ele_keyword, eid=element, pid=1, nodes=the_nodes) + pynas_elements += "model.add_{ele_keyword}({eid}, {pid}, {nodes})\n".format( + ele_keyword=ele_keyword, eid=element, pid=1, nodes=the_nodes ) # print(pynas_elements) - mesh_pynas_code = "{}\n\n{}\n\n".format(pynas_nodes, pynas_elements) + mesh_pynas_code = f"{pynas_nodes}\n\n{pynas_elements}\n\n" return mesh_pynas_code # Helper -def get_export_element_type( - femmesh, - femelement_table=None -): +def get_export_element_type(femmesh, femelement_table=None): return nastran_ele_types[meshtools.get_femmesh_eletype(femmesh, femelement_table)] diff --git a/src/Mod/Fem/feminout/importCcxDatResults.py b/src/Mod/Fem/feminout/importCcxDatResults.py index 86bf48c207..321944527e 100644 --- a/src/Mod/Fem/feminout/importCcxDatResults.py +++ b/src/Mod/Fem/feminout/importCcxDatResults.py @@ -43,19 +43,13 @@ EIGENVALUE_OUTPUT_SECTION = " E I G E N V A L U E O U T P U T" # ********* generic FreeCAD import and export methods ********* - -def open( - filename -): +def open(filename): "called when freecad opens a file" docname = os.path.splitext(os.path.basename(filename))[0] insert(filename, docname) -def insert( - filename, - docname -): +def insert(filename, docname): "called when freecad wants to import a file" try: doc = FreeCAD.getDocument(docname) @@ -66,19 +60,14 @@ def insert( # ********* module specific methods ********* -def import_dat( - filename, - Analysis=None -): +def import_dat(filename, Analysis=None): r = readResult(filename) return r # read a calculix result file and extract the data -def readResult( - dat_input -): - Console.PrintMessage("Read ccx results from dat file: {}\n".format(dat_input)) +def readResult(dat_input): + Console.PrintMessage(f"Read ccx results from dat file: {dat_input}\n") dat_file = pyopen(dat_input, "r") eigenvalue_output_section_found = False mode_reading = False diff --git a/src/Mod/Fem/feminout/importCcxFrdResults.py b/src/Mod/Fem/feminout/importCcxFrdResults.py index effc473f87..8f9378c3da 100644 --- a/src/Mod/Fem/feminout/importCcxFrdResults.py +++ b/src/Mod/Fem/feminout/importCcxFrdResults.py @@ -41,17 +41,13 @@ from builtins import open as pyopen # ********* generic FreeCAD import and export methods ********* - def open(filename): "called when freecad opens a file" docname = os.path.splitext(os.path.basename(filename))[0] insert(filename, docname) -def insert( - filename, - docname -): +def insert(filename, docname): "called when freecad wants to import a file" try: doc = FreeCAD.getDocument(docname) @@ -62,12 +58,7 @@ def insert( # ********* module specific methods ********* -def importFrd( - filename, - analysis=None, - result_name_prefix="", - result_analysis_type="" -): +def importFrd(filename, analysis=None, result_name_prefix="", result_analysis_type=""): import ObjectsFem from . import importToolsFem @@ -86,9 +77,7 @@ def importFrd( nodenumbers_for_compacted_mesh = [] number_of_increments = len(m["Results"]) - Console.PrintLog( - "Increments: " + str(number_of_increments) + "\n" - ) + Console.PrintLog("Increments: " + str(number_of_increments) + "\n") def make_result_mesh(result_name): res_obj = ObjectsFem.makeResultMechanical(doc, results_name) @@ -107,26 +96,18 @@ def importFrd( step_time = result_set["time"] step_time = round(step_time, 2) if eigenmode_number > 0: - results_name = ( - "{}EigenMode_{}_Results" - .format(result_name_prefix, eigenmode_number) + results_name = "{}EigenMode_{}_Results".format( + result_name_prefix, eigenmode_number ) elif number_of_increments > 1: if result_analysis_type == "buckling": - results_name = ( - "{}BucklingFactor_{}_Results" - .format(result_name_prefix, step_time) + results_name = "{}BucklingFactor_{}_Results".format( + result_name_prefix, step_time ) else: - results_name = ( - "{}Time_{}_Results" - .format(result_name_prefix, step_time) - ) + results_name = f"{result_name_prefix}Time_{step_time}_Results" else: - results_name = ( - "{}Results" - .format(result_name_prefix) - ) + results_name = f"{result_name_prefix}Results" res_obj = make_result_mesh(results_name) res_obj = importToolsFem.fill_femresult_mechanical(res_obj, result_set) @@ -138,6 +119,7 @@ def importFrd( # more result object calculations from femresult import resulttools from femtools import femutils + if not res_obj.MassFlowRate: # information 1: # only compact result if not Flow 1D results @@ -220,7 +202,7 @@ def importFrd( pipeline_obj.ViewObject.Visibility = pipeline_visibility elif result_analysis_type == "check": - results_name = "{}Check".format(result_name_prefix) + results_name = f"{result_name_prefix}Check" res_obj = make_result_mesh(results_name) if analysis: analysis.addObject(res_obj) @@ -241,7 +223,7 @@ def importFrd( # see error message above for more information if not res_obj: if result_name_prefix: - results_name = "{}_Results".format(result_name_prefix) + results_name = f"{result_name_prefix}_Results" else: results_name = "Results" res_obj = ObjectsFem.makeResultMechanical(doc, results_name) @@ -253,13 +235,12 @@ def importFrd( if FreeCAD.GuiUp: if analysis: import FemGui + FemGui.setActiveAnalysis(analysis) doc.recompute() else: - Console.PrintError( - "Problem on frd file import. No nodes found in frd file.\n" - ) + Console.PrintError("Problem on frd file import. No nodes found in frd file.\n") # None will be returned # or would it be better to raise an exception if there are not even nodes in frd file? @@ -268,26 +249,19 @@ def importFrd( # read a calculix result file and extract the nodes # displacement vectors and stress values. -def read_frd_result( - frd_input -): - Console.PrintMessage( - "Read ccx results from frd file: {}\n" - .format(frd_input) - ) +def read_frd_result(frd_input): + Console.PrintMessage(f"Read ccx results from frd file: {frd_input}\n") inout_nodes = [] inout_nodes_file = frd_input.rsplit(".", 1)[0] + "_inout_nodes.txt" if os.path.exists(inout_nodes_file): - Console.PrintMessage( - "Read special 1DFlow nodes data form: {}\n".format(inout_nodes_file) - ) + Console.PrintMessage(f"Read special 1DFlow nodes data form: {inout_nodes_file}\n") f = pyopen(inout_nodes_file, "r") lines = f.readlines() for line in lines: a = line.split(",") inout_nodes.append(a) f.close() - Console.PrintMessage("{}\n".format(inout_nodes)) + Console.PrintMessage(f"{inout_nodes}\n") frd_file = pyopen(frd_input, "r") nodes = {} elements_hexa8 = {} @@ -443,8 +417,26 @@ def read_frd_result( hexa20 import works with the following frd file node assignment """ elements_hexa20[elem] = ( - nd8, nd5, nd6, nd7, nd4, nd1, nd2, nd3, nd20, nd17, - nd18, nd19, nd12, nd9, nd10, nd11, nd16, nd13, nd14, nd15 + nd8, + nd5, + nd6, + nd7, + nd4, + nd1, + nd2, + nd3, + nd20, + nd17, + nd18, + nd19, + nd12, + nd9, + nd10, + nd11, + nd16, + nd13, + nd14, + nd15, ) elif elemType == 5 and input_continues is False: # first line @@ -479,8 +471,21 @@ def read_frd_result( ) # order of the *.inp file """ elements_penta15[elem] = ( - nd5, nd6, nd4, nd2, nd3, nd1, nd14, nd15, nd13, nd8, - nd9, nd7, nd11, nd12, nd10 + nd5, + nd6, + nd4, + nd2, + nd3, + nd1, + nd14, + nd15, + nd13, + nd8, + nd9, + nd7, + nd11, + nd12, + nd10, ) elif elemType == 6: # C3D10 Calculix --> tetra10 FreeCAD @@ -632,7 +637,7 @@ def read_frd_result( # we found an equivalent plastic strain line elem = int(line[4:13]) peeq = float(line[13:25]) - mode_peeq[elem] = (peeq) + mode_peeq[elem] = peeq # Check if we found a temperature section if line[5:11] == "NDTEMP": @@ -641,7 +646,7 @@ def read_frd_result( # we found a temperature line elem = int(line[4:13]) temperature = float(line[13:25]) - mode_temp[elem] = (temperature) + mode_temp[elem] = temperature # Check if we found heat flux section if line[5:9] == "FLUX": @@ -654,8 +659,6 @@ def read_frd_result( mode_heatflux_z = float(line[37:49]) mode_heatflux[elem] = FreeCAD.Vector(mode_heatflux_x, mode_heatflux_y, mode_heatflux_z) - - # Check if we found a mass flow section if line[5:11] == "MAFLOW": mode_massflow_found = True @@ -663,13 +666,13 @@ def read_frd_result( # we found a mass flow line elem = int(line[4:13]) massflow = float(line[13:25]) - mode_massflow[elem] = (massflow * 1000) # convert units to kg/s from t/s + mode_massflow[elem] = massflow * 1000 # convert units to kg/s from t/s if inout_nodes: for i in range(len(inout_nodes)): if elem == int(inout_nodes[i][1]): node = int(inout_nodes[i][2]) # convert units to kg/s from t/s - mode_massflow[node] = (massflow * 1000) + mode_massflow[node] = massflow * 1000 # Check if we found a network pressure section if line[5:11] == "STPRES": @@ -678,12 +681,12 @@ def read_frd_result( # we found a network pressure line elem = int(line[4:13]) networkpressure = float(line[13:25]) - mode_networkpressure[elem] = (networkpressure) + mode_networkpressure[elem] = networkpressure if inout_nodes: for i in range(len(inout_nodes)): if elem == int(inout_nodes[i][1]): node = int(inout_nodes[i][2]) - mode_networkpressure[node] = (networkpressure) + mode_networkpressure[node] = networkpressure # Check if we found the end of a section if line[1:3] == "-3": @@ -760,9 +763,11 @@ def read_frd_result( if line[1:5] == "9999": end_of_frd_data_found = True - if (mode_eigen_changed or mode_time_changed or end_of_frd_data_found) \ - and end_of_section_found \ - and not node_element_section: + if ( + (mode_eigen_changed or mode_time_changed or end_of_frd_data_found) + and end_of_section_found + and not node_element_section + ): """ print("\n\n----Append mode_results to results") @@ -813,9 +818,7 @@ def read_frd_result( if not inout_nodes: if results: if "mflow" in results[0] or "npressure" in results[0]: - Console.PrintError( - "We have mflow or npressure, but no inout_nodes file.\n" - ) + Console.PrintError("We have mflow or npressure, but no inout_nodes file.\n") if not nodes: Console.PrintError("FEM: No nodes found in Frd file.\n") @@ -833,5 +836,5 @@ def read_frd_result( "Hexa20Elem": elements_hexa20, "Penta6Elem": elements_penta6, "Penta15Elem": elements_penta15, - "Results": results + "Results": results, } diff --git a/src/Mod/Fem/feminout/importFenicsMesh.py b/src/Mod/Fem/feminout/importFenicsMesh.py index 5a52f7d227..3af8292f1d 100644 --- a/src/Mod/Fem/feminout/importFenicsMesh.py +++ b/src/Mod/Fem/feminout/importFenicsMesh.py @@ -50,6 +50,7 @@ if FreeCAD.GuiUp: if FreeCAD.GuiUp: + class WriteXDMFTaskPanel: """ This task panel is used to write mesh groups with user defined values. @@ -57,10 +58,9 @@ if FreeCAD.GuiUp: """ def __init__(self, fem_mesh_obj, fileString): - self.form = FreeCADGui.PySideUic.loadUi(os.path.join( - FreeCAD.getHomePath(), - "Mod/Fem/Resources/ui/MeshGroupXDMFExport.ui" - )) + self.form = FreeCADGui.PySideUic.loadUi( + os.path.join(FreeCAD.getHomePath(), "Mod/Fem/Resources/ui/MeshGroupXDMFExport.ui") + ) self.result_dict = {} self.fem_mesh_obj = fem_mesh_obj self.fileString = fileString @@ -73,34 +73,27 @@ if FreeCAD.GuiUp: item.setFlags(~QtCore.Qt.ItemIsEditable & ~QtCore.Qt.ItemIsEnabled) return item - gmshgroups = importToolsFem.get_FemMeshObjectMeshGroups( - self.fem_mesh_obj - ) + gmshgroups = importToolsFem.get_FemMeshObjectMeshGroups(self.fem_mesh_obj) fem_mesh = self.fem_mesh_obj.FemMesh self.form.tableGroups.setRowCount(0) self.form.tableGroups.setRowCount(len(gmshgroups)) - for (ind, gind) in enumerate(gmshgroups): + for ind, gind in enumerate(gmshgroups): # group number - self.form.tableGroups.setItem(ind, 0, - ro(QtGui.QTableWidgetItem( - str(gind)))) + self.form.tableGroups.setItem(ind, 0, ro(QtGui.QTableWidgetItem(str(gind)))) # group name - self.form.tableGroups.setItem(ind, 1, - ro(QtGui.QTableWidgetItem( - fem_mesh.getGroupName(gind)))) + self.form.tableGroups.setItem( + ind, 1, ro(QtGui.QTableWidgetItem(fem_mesh.getGroupName(gind))) + ) # group elements - self.form.tableGroups.setItem(ind, 2, - ro(QtGui.QTableWidgetItem( - fem_mesh.getGroupElementType( - gind)))) + self.form.tableGroups.setItem( + ind, 2, ro(QtGui.QTableWidgetItem(fem_mesh.getGroupElementType(gind))) + ) # default value for not marked elements - self.form.tableGroups.setItem(ind, 3, - QtGui.QTableWidgetItem(str(0))) + self.form.tableGroups.setItem(ind, 3, QtGui.QTableWidgetItem(str(0))) # default value for marked elements - self.form.tableGroups.setItem(ind, 4, - QtGui.QTableWidgetItem(str(1))) + self.form.tableGroups.setItem(ind, 4, QtGui.QTableWidgetItem(str(1))) header = self.form.tableGroups.horizontalHeader() header.setResizeMode(0, QtGui.QHeaderView.ResizeToContents) @@ -136,8 +129,8 @@ if FreeCAD.GuiUp: group_values_dict = self.convert_table_to_group_dict() writeFenicsXDMF.write_fenics_mesh_xdmf( - self.fem_mesh_obj, self.fileString, - group_values_dict=group_values_dict) + self.fem_mesh_obj, self.fileString, group_values_dict=group_values_dict + ) FreeCADGui.Control.closeDialog() @@ -165,8 +158,7 @@ def export(objectslist, fileString, group_values_dict_nogui=None): of (marked_value (default=1), default_value (default=0)) """ if len(objectslist) != 1: - Console.PrintError( - "This exporter can only export one object.\n") + Console.PrintError("This exporter can only export one object.\n") return obj = objectslist[0] if not obj.isDerivedFrom("Fem::FemMeshObject"): @@ -178,9 +170,10 @@ def export(objectslist, fileString, group_values_dict_nogui=None): if fileExtension.lower() == ".xml": if obj.ElementOrder != "1st": Console.PrintWarning( - "XML is not designed to save higher order elements.\n" + - "Reducing order for second order mesh.\n" + - "Tri6 -> Tri3, Tet10 -> Tet4, etc.\n") + "XML is not designed to save higher order elements.\n" + + "Reducing order for second order mesh.\n" + + "Tri6 -> Tri3, Tet10 -> Tet4, etc.\n" + ) writeFenicsXML.write_fenics_mesh_xml(obj, fileString) elif fileExtension.lower() == ".xdmf": mesh_groups = importToolsFem.get_FemMeshObjectMeshGroups(obj) @@ -192,19 +185,17 @@ def export(objectslist, fileString, group_values_dict_nogui=None): else: # create default dict if groupdict_nogui is not None if group_values_dict_nogui is None: - group_values_dict_nogui = dict([(g, (1, 0)) - for g in mesh_groups]) + group_values_dict_nogui = {g: (1, 0) for g in mesh_groups} writeFenicsXDMF.write_fenics_mesh_xdmf( - obj, fileString, - group_values_dict=group_values_dict_nogui) + obj, fileString, group_values_dict=group_values_dict_nogui + ) else: writeFenicsXDMF.write_fenics_mesh_xdmf(obj, fileString) # ********* module specific methods ********* def import_fenics_mesh(filename, analysis=None): - """insert a FreeCAD FEM Mesh object in the ActiveDocument - """ + """insert a FreeCAD FEM Mesh object in the ActiveDocument""" mesh_data = readFenicsXML.read_fenics_mesh_xml(filename) # xdmf not operational diff --git a/src/Mod/Fem/feminout/importInpMesh.py b/src/Mod/Fem/feminout/importInpMesh.py index 1fab942412..8334ba778d 100644 --- a/src/Mod/Fem/feminout/importInpMesh.py +++ b/src/Mod/Fem/feminout/importInpMesh.py @@ -41,7 +41,6 @@ from builtins import open as pyopen # ********* generic FreeCAD import and export methods ********* - def open(filename): "called when freecad opens a file" docname = os.path.splitext(os.path.basename(filename))[0] @@ -60,17 +59,16 @@ def insert(filename, docname): # ********* module specific methods ********* def read(filename): - """read a FemMesh from a inp mesh file and return the FemMesh - """ + """read a FemMesh from a inp mesh file and return the FemMesh""" # no document object is created, just the FemMesh is returned mesh_data = read_inp(filename) from . import importToolsFem + return importToolsFem.make_femmesh(mesh_data) def import_inp(filename): - """read a FEM mesh from a Z88 mesh file and insert a FreeCAD FEM Mesh object in the ActiveDocument - """ + """read a FEM mesh from a Z88 mesh file and insert a FreeCAD FEM Mesh object in the ActiveDocument""" femmesh = read(filename) mesh_name = os.path.splitext(os.path.basename(filename))[0] if femmesh: @@ -79,10 +77,10 @@ def import_inp(filename): def read_inp(file_name): - """read .inp file """ + """read .inp file""" # ATM only mesh reading is supported (no boundary conditions) - class elements(): + class elements: tria3 = {} tria6 = {} @@ -96,6 +94,7 @@ def read_inp(file_name): penta15 = {} seg2 = {} seg3 = {} + error_seg3 = False # to print "not supported" nodes = {} model_definition = True @@ -161,12 +160,10 @@ def read_inp(file_name): elif elm_type in ["S6", "CPS6", "CPE6", "CAX6"]: elm_category = elements.tria6 number_of_nodes = 6 - elif elm_type in ["S4", "S4R", "CPS4", "CPS4R", "CPE4", "CPE4R", - "CAX4", "CAX4R"]: + elif elm_type in ["S4", "S4R", "CPS4", "CPS4R", "CPE4", "CPE4R", "CAX4", "CAX4R"]: elm_category = elements.quad4 number_of_nodes = 4 - elif elm_type in ["S8", "S8R", "CPS8", "CPS8R", "CPE8", "CPE8R", - "CAX8", "CAX8R"]: + elif elm_type in ["S8", "S8R", "CPS8", "CPS8R", "CPE8", "CPE8R", "CAX8", "CAX8R"]: elm_category = elements.quad8 number_of_nodes = 8 elif elm_type == "C3D4": @@ -219,7 +216,7 @@ def read_inp(file_name): if error_seg3 is True: # to print "not supported" Console.PrintError("Error: seg3 (3-node beam element type) not supported, yet.\n") elif error_not_supported_elemtype is True: - Console.PrintError("Error: {} not supported.\n".format(elm_type)) + Console.PrintError(f"Error: {elm_type} not supported.\n") f.close() # switch from the CalculiX node numbering to the FreeCAD node numbering @@ -229,24 +226,56 @@ def read_inp(file_name): elements.tetra4[en] = [n[1], n[0], n[2], n[3]] for en in elements.tetra10: n = elements.tetra10[en] - elements.tetra10[en] = [n[1], n[0], n[2], n[3], n[4], n[6], n[5], - n[8], n[7], n[9]] + elements.tetra10[en] = [n[1], n[0], n[2], n[3], n[4], n[6], n[5], n[8], n[7], n[9]] for en in elements.hexa8: n = elements.hexa8[en] elements.hexa8[en] = [n[5], n[6], n[7], n[4], n[1], n[2], n[3], n[0]] for en in elements.hexa20: n = elements.hexa20[en] - elements.hexa20[en] = [n[5], n[6], n[7], n[4], n[1], n[2], n[3], n[0], - n[13], n[14], n[15], n[12], n[9], n[10], n[11], - n[8], n[17], n[18], n[19], n[16]] + elements.hexa20[en] = [ + n[5], + n[6], + n[7], + n[4], + n[1], + n[2], + n[3], + n[0], + n[13], + n[14], + n[15], + n[12], + n[9], + n[10], + n[11], + n[8], + n[17], + n[18], + n[19], + n[16], + ] for en in elements.penta6: n = elements.penta6[en] elements.penta6[en] = [n[4], n[5], n[3], n[1], n[2], n[0]] for en in elements.penta15: n = elements.penta15[en] - elements.penta15[en] = [n[4], n[5], n[3], n[1], n[2], n[0], - n[10], n[11], n[9], n[7], n[8], n[6], n[13], - n[14], n[12]] + elements.penta15[en] = [ + n[4], + n[5], + n[3], + n[1], + n[2], + n[0], + n[10], + n[11], + n[9], + n[7], + n[8], + n[6], + n[13], + n[14], + n[12], + ] for en in elements.seg3: n = elements.seg3[en] elements.seg3[en] = [n[0], n[2], n[1]] @@ -264,5 +293,5 @@ def read_inp(file_name): "Hexa8Elem": elements.hexa8, "Hexa20Elem": elements.hexa20, "Penta6Elem": elements.penta6, - "Penta15Elem": elements.penta15 + "Penta15Elem": elements.penta15, } diff --git a/src/Mod/Fem/feminout/importPyMesh.py b/src/Mod/Fem/feminout/importPyMesh.py index 4ebb2eea6e..ff1c1af399 100644 --- a/src/Mod/Fem/feminout/importPyMesh.py +++ b/src/Mod/Fem/feminout/importPyMesh.py @@ -40,13 +40,8 @@ from builtins import open as pyopen # they are set in FEM modules Init.py - - # export mesh to python -def export( - objectslist, - filename -): +def export(objectslist, filename): "called when freecad exports a file" if len(objectslist) != 1: FreeCAD.Console.PrintError("This exporter can only export one object.\n") @@ -79,10 +74,8 @@ def export( # ********* writer ******************************************************************************* -def write( - fem_mesh, - filename -): + +def write(fem_mesh, filename): """directly write a FemMesh to a Python mesh file fem_mesh: a FemMesh""" @@ -115,10 +108,7 @@ def write_python_mesh_to_file(femnodes_mesh, femelement_table, fem_mesh_type, f) for node in femnodes_mesh: # print(node, ' --> ', femnodes_mesh[node]) vec = femnodes_mesh[node] - f.write( - " {0}.addNode({1}, {2}, {3}, {4})\n" - .format(mesh_name, vec.x, vec.y, vec.z, node) - ) + f.write(f" {mesh_name}.addNode({vec.x}, {vec.y}, {vec.z}, {node})\n") f.write(" return True\n") f.write("\n\n") @@ -129,17 +119,20 @@ def write_python_mesh_to_file(femnodes_mesh, femelement_table, fem_mesh_type, f) # print(element, ' --> ', femelement_table[element]) if fem_mesh_type == "Solid": f.write( - " {0}.addVolume({1}, {2})\n" - .format(mesh_name, list(femelement_table[element]), element) + " {}.addVolume({}, {})\n".format( + mesh_name, list(femelement_table[element]), element + ) ) elif fem_mesh_type == "Face": f.write( - " {0}.addFace({1}, {2})\n" - .format(mesh_name, list(femelement_table[element]), element) + " {}.addFace({}, {})\n".format( + mesh_name, list(femelement_table[element]), element + ) ) elif fem_mesh_type == "Edge": f.write( - " {0}.addEdge({1}, {2})\n" - .format(mesh_name, list(femelement_table[element]), element) + " {}.addEdge({}, {})\n".format( + mesh_name, list(femelement_table[element]), element + ) ) f.write(" return True\n") diff --git a/src/Mod/Fem/feminout/importToolsFem.py b/src/Mod/Fem/feminout/importToolsFem.py index 2c0aa9c671..8e8a0420d1 100644 --- a/src/Mod/Fem/feminout/importToolsFem.py +++ b/src/Mod/Fem/feminout/importToolsFem.py @@ -33,11 +33,9 @@ import FreeCAD from FreeCAD import Console -def get_FemMeshObjectMeshGroups( - fem_mesh_obj -): +def get_FemMeshObjectMeshGroups(fem_mesh_obj): """ - Get mesh groups from mesh. + Get mesh groups from mesh. """ # this method is not really needed. It is used in Fenics mesh only. # there was an exception handling if there was no Group property, but @@ -47,16 +45,14 @@ def get_FemMeshObjectMeshGroups( return fem_mesh_obj.FemMesh.Groups -def get_FemMeshObjectOrder( - fem_mesh_obj -): +def get_FemMeshObjectOrder(fem_mesh_obj): """ - Gets element order. Element order counting based on number of nodes on - edges. Edge with 2 nodes -> linear elements, Edge with 3 nodes -> - quadratic elements, and so on. No edges in mesh -> not determined. - (Is this possible? Seems to be a very degenerate case.) - If there are edges with different number of nodes appearing, return - list of orders. + Gets element order. Element order counting based on number of nodes on + edges. Edge with 2 nodes -> linear elements, Edge with 3 nodes -> + quadratic elements, and so on. No edges in mesh -> not determined. + (Is this possible? Seems to be a very degenerate case.) + If there are edges with different number of nodes appearing, return + list of orders. """ presumable_order = None @@ -78,11 +74,9 @@ def get_FemMeshObjectOrder( return presumable_order -def get_FemMeshObjectDimension( - fem_mesh_obj -): - """ Count all entities in an abstract sense, to distinguish which dimension the mesh is - (i.e. linemesh, facemesh, volumemesh) +def get_FemMeshObjectDimension(fem_mesh_obj): + """Count all entities in an abstract sense, to distinguish which dimension the mesh is + (i.e. linemesh, facemesh, volumemesh) """ dim = None @@ -98,21 +92,28 @@ def get_FemMeshObjectDimension( return dim -def get_FemMeshObjectElementTypes( - fem_mesh_obj, - remove_zero_element_entries=True -): +def get_FemMeshObjectElementTypes(fem_mesh_obj, remove_zero_element_entries=True): """ - Spit out all elements in the mesh with their appropriate dimension. + Spit out all elements in the mesh with their appropriate dimension. """ FreeCAD_element_names_dims = { - "Node": 0, "Edge": 1, "Hexa": 3, "Polygon": 2, "Polyhedron": 3, - "Prism": 3, "Pyramid": 3, "Quadrangle": 2, "Tetra": 3, "Triangle": 2} + "Node": 0, + "Edge": 1, + "Hexa": 3, + "Polygon": 2, + "Polyhedron": 3, + "Prism": 3, + "Pyramid": 3, + "Quadrangle": 2, + "Tetra": 3, + "Triangle": 2, + } eval_dict = locals() # to access local variables from eval - elements_list_with_zero = [( - eval("fem_mesh_obj.FemMesh." + s + "Count", eval_dict), s, d - ) for (s, d) in FreeCAD_element_names_dims.items()] + elements_list_with_zero = [ + (eval("fem_mesh_obj.FemMesh." + s + "Count", eval_dict), s, d) + for (s, d) in FreeCAD_element_names_dims.items() + ] # ugly but necessary if remove_zero_element_entries: elements_list = [(num, s, d) for (num, s, d) in elements_list_with_zero if num > 0] @@ -122,22 +123,18 @@ def get_FemMeshObjectElementTypes( return elements_list -def get_MaxDimElementFromList( - elem_list -): +def get_MaxDimElementFromList(elem_list): """ - Gets element with the maximal dimension in the mesh to determine cells. + Gets element with the maximal dimension in the mesh to determine cells. """ elem_list.sort(key=lambda t: t[2]) return elem_list[-1] -def make_femmesh( - mesh_data -): - """ makes an FreeCAD FEM Mesh object from FEM Mesh data - """ +def make_femmesh(mesh_data): + """makes an FreeCAD FEM Mesh object from FEM Mesh data""" import Fem + mesh = Fem.FemMesh() m = mesh_data if ("Nodes" in m) and (len(m["Nodes"]) > 0): @@ -181,15 +178,54 @@ def make_femmesh( elms_penta15 = m["Penta15Elem"] for i in elms_penta15: e = elms_penta15[i] - mesh.addVolume([e[0], e[1], e[2], e[3], e[4], e[5], e[6], e[7], e[8], e[9], - e[10], e[11], e[12], e[13], e[14]], i) + mesh.addVolume( + [ + e[0], + e[1], + e[2], + e[3], + e[4], + e[5], + e[6], + e[7], + e[8], + e[9], + e[10], + e[11], + e[12], + e[13], + e[14], + ], + i, + ) elms_hexa20 = m["Hexa20Elem"] for i in elms_hexa20: e = elms_hexa20[i] - mesh.addVolume([ - e[0], e[1], e[2], e[3], e[4], e[5], e[6], e[7], e[8], e[9], - e[10], e[11], e[12], e[13], e[14], e[15], e[16], e[17], e[18], e[19] - ], i) + mesh.addVolume( + [ + e[0], + e[1], + e[2], + e[3], + e[4], + e[5], + e[6], + e[7], + e[8], + e[9], + e[10], + e[11], + e[12], + e[13], + e[14], + e[15], + e[16], + e[17], + e[18], + e[19], + ], + i, + ) elms_tria3 = m["Tria3Elem"] for i in elms_tria3: e = elms_tria3[i] @@ -215,27 +251,25 @@ def make_femmesh( e = elms_seg3[i] mesh.addEdge([e[0], e[1], e[2]], i) Console.PrintLog( - "imported mesh: {} nodes, {} HEXA8, {} PENTA6, {} TETRA4, {} TETRA10, {} PENTA15\n" - .format( + "imported mesh: {} nodes, {} HEXA8, {} PENTA6, {} TETRA4, {} TETRA10, {} PENTA15\n".format( len(nds), len(elms_hexa8), len(elms_penta6), len(elms_tetra4), len(elms_tetra10), - len(elms_penta15) + len(elms_penta15), ) ) Console.PrintLog( "imported mesh: {} " - "HEXA20, {} TRIA3, {} TRIA6, {} QUAD4, {} QUAD8, {} SEG2, {} SEG3\n" - .format( + "HEXA20, {} TRIA3, {} TRIA6, {} QUAD4, {} QUAD8, {} SEG2, {} SEG3\n".format( len(elms_hexa20), len(elms_tria3), len(elms_tria6), len(elms_quad4), len(elms_quad8), len(elms_seg2), - len(elms_seg3) + len(elms_seg3), ) ) else: @@ -245,9 +279,7 @@ def make_femmesh( return mesh -def make_dict_from_femmesh( - femmesh -): +def make_dict_from_femmesh(femmesh): """ Converts FemMesh into dictionary structure which can immediately used from importToolsFem.make_femmesh(mesh_data) to create a valid FEM mesh. @@ -277,14 +309,7 @@ def make_dict_from_femmesh( len_to_edge = {2: seg2, 3: seg3} len_to_face = {3: tri3, 6: tri6, 4: quad4, 8: quad8} - len_to_volume = { - 4: tet4, - 10: tet10, - 8: hex8, - 20: hex20, - 6: pent6, - 15: pent15 - } + len_to_volume = {4: tet4, 10: tet10, 8: hex8, 20: hex20, 6: pent6, 15: pent15} # analyze edges @@ -305,42 +330,31 @@ def make_dict_from_femmesh( len_to_volume[len(t)].append((v, t)) mesh_data = { - "Nodes": dict([(k, (v.x, v.y, v.z)) - for (k, v) in femmesh.Nodes.items()]), + "Nodes": {k: (v.x, v.y, v.z) for (k, v) in femmesh.Nodes.items()}, "Seg2Elem": dict(seg2), "Seg3Elem": dict(seg3), - "Tria3Elem": dict(tri3), "Tria6Elem": dict(tri6), "Quad4Elem": dict(quad4), "Quad8Elem": dict(quad8), - "Tetra4Elem": dict(tet4), "Tetra10Elem": dict(tet10), "Hexa8Elem": dict(hex8), "Hexa20Elem": dict(hex20), "Penta6Elem": dict(pent6), "Penta15Elem": dict(pent15), - - "Groups": dict([( - group_num, ( - femmesh.getGroupName(group_num), - femmesh.getGroupElements(group_num) - ) - ) for group_num in femmesh.Groups]) - + "Groups": { + group_num: (femmesh.getGroupName(group_num), femmesh.getGroupElements(group_num)) + for group_num in femmesh.Groups + }, } # no pyr5, pyr13? # no groups? return mesh_data -def fill_femresult_mechanical( - res_obj, - result_set -): - """ fills a FreeCAD FEM mechanical result object with result data - """ +def fill_femresult_mechanical(res_obj, result_set): + """fills a FreeCAD FEM mechanical result object with result data""" if "number" in result_set: eigenmode_number = result_set["number"] else: diff --git a/src/Mod/Fem/feminout/importVTKResults.py b/src/Mod/Fem/feminout/importVTKResults.py index ea8938a2d1..6c60b1316f 100644 --- a/src/Mod/Fem/feminout/importVTKResults.py +++ b/src/Mod/Fem/feminout/importVTKResults.py @@ -42,19 +42,13 @@ from builtins import open as pyopen # ********* generic FreeCAD import and export methods ********* - -def open( - filename -): +def open(filename): "called when freecad opens a file" docname = os.path.splitext(os.path.basename(filename))[0] insert(filename, docname) -def insert( - filename, - docname -): +def insert(filename, docname): "called when freecad wants to import a file" try: doc = FreeCAD.getDocument(docname) @@ -64,15 +58,10 @@ def insert( importVtk(filename) -def export( - objectslist, - filename -): +def export(objectslist, filename): "called when freecad exports an object to vtk" if len(objectslist) > 1: # the case of no selected obj is caught by FreeCAD already - Console.PrintError( - "This exporter can only export one object at once\n" - ) + Console.PrintError("This exporter can only export one object at once\n") return obj = objectslist[0] @@ -80,29 +69,19 @@ def export( obj.writeVTK(filename) return elif obj.isDerivedFrom("Fem::FemMeshObject"): - Console.PrintError( - "Use export to FEM mesh formats to export a FEM mesh object to vtk!\n" - ) + Console.PrintError("Use export to FEM mesh formats to export a FEM mesh object to vtk!\n") return elif obj.isDerivedFrom("Fem::FemResultObject"): Fem.writeResult(filename, obj) else: - Console.PrintError( - "Selected object is not supported by export to VTK.\n" - ) + Console.PrintError("Selected object is not supported by export to VTK.\n") return # ********* module specific methods ********* -def importVtk( - filename, - object_name=None, - object_type=None -): +def importVtk(filename, object_name=None, object_type=None): if not object_type: - vtkinout_prefs = FreeCAD.ParamGet( - "User parameter:BaseApp/Preferences/Mod/Fem/InOutVtk" - ) + vtkinout_prefs = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Fem/InOutVtk") object_type = vtkinout_prefs.GetInt("ImportObject", 0) if not object_name: object_name = os.path.splitext(os.path.basename(filename))[0] @@ -116,16 +95,10 @@ def importVtk( # FreeCAD result object importVtkFCResult(filename, object_name) else: - Console.PrintError( - "Error, wrong parameter in VTK import pref: {}\n" - .format(object_type) - ) + Console.PrintError(f"Error, wrong parameter in VTK import pref: {object_type}\n") -def importVtkVtkResult( - filename, - resultname -): +def importVtkVtkResult(filename, resultname): vtk_result_obj = FreeCAD.ActiveDocument.addObject("Fem::FemPostPipeline", resultname) vtk_result_obj.read(filename) # set display mode to "Surface" like for any other new pipeline to assure the user sees @@ -136,10 +109,7 @@ def importVtkVtkResult( return vtk_result_obj -def importVtkFemMesh( - filename, - meshname -): +def importVtkFemMesh(filename, meshname): meshobj = FreeCAD.ActiveDocument.addObject("Fem::FemMeshObject", meshname) meshobj.FemMesh = Fem.read(filename) meshobj.touch() @@ -147,16 +117,12 @@ def importVtkFemMesh( return meshobj -def importVtkFCResult( - filename, - resultname, - analysis=None, - result_name_prefix=None -): +def importVtkFCResult(filename, resultname, analysis=None, result_name_prefix=None): # only fields from vtk are imported if they exactly named as the FreeCAD result properties # See _getFreeCADMechResultProperties() in FemVTKTools.cpp for the supported names import ObjectsFem + if result_name_prefix is None: result_name_prefix = "" if analysis: @@ -170,6 +136,7 @@ def importVtkFCResult( # add missing DisplacementLengths (They should have been added by Fem.readResult) if not result_obj.DisplacementLengths: import femresult.resulttools as restools + result_obj = restools.add_disp_apps(result_obj) # DisplacementLengths """ seems unused at the moment diff --git a/src/Mod/Fem/feminout/importYamlJsonMesh.py b/src/Mod/Fem/feminout/importYamlJsonMesh.py index 29e88dcf2e..e326320ed3 100644 --- a/src/Mod/Fem/feminout/importYamlJsonMesh.py +++ b/src/Mod/Fem/feminout/importYamlJsonMesh.py @@ -42,10 +42,7 @@ has_yaml = True try: import yaml except ImportError: - Console.PrintMessage( - "No YAML available (import yaml failure), " - "yaml import/export won't work\n" - ) + Console.PrintMessage("No YAML available (import yaml failure), yaml import/export won't work\n") has_yaml = False @@ -55,11 +52,7 @@ except ImportError: # they are set in FEM modules Init.py - - -def open( - filename -): +def open(filename): """called when freecad opens a file a FEM mesh object is created in a new document""" @@ -67,10 +60,7 @@ def open( return insert(filename, docname) -def insert( - filename, - docname -): +def insert(filename, docname): """called when freecad wants to import a file" a FEM mesh object is created in a existing document""" @@ -87,9 +77,7 @@ def insert( def export(objectslist, fileString): "called when freecad exports a file" if len(objectslist) != 1: - Console.PrintError( - "This exporter can only " - "export one object.\n") + Console.PrintError("This exporter can only export one object.\n") return obj = objectslist[0] if not obj.isDerivedFrom("Fem::FemMeshObject"): @@ -113,10 +101,9 @@ def export(objectslist, fileString): # writer: # - a method directly writes a FemMesh to the mesh file + # ********* reader *********************************************************** -def import_yaml_json_mesh( - fileString -): +def import_yaml_json_mesh(fileString): """ read a FemMesh from a yaml/json mesh file insert a FreeCAD FEM Mesh object in the ActiveDocument @@ -127,43 +114,34 @@ def import_yaml_json_mesh( femmesh = read(fileString) if femmesh: - mesh_object = FreeCAD.ActiveDocument.addObject( - "Fem::FemMeshObject", - mesh_name - ) + mesh_object = FreeCAD.ActiveDocument.addObject("Fem::FemMeshObject", mesh_name) mesh_object.FemMesh = femmesh return mesh_object -def read( - fileString -): - """read a FemMesh from a yaml/json mesh file and return the FemMesh - """ +def read(fileString): + """read a FemMesh from a yaml/json mesh file and return the FemMesh""" # no document object is created, just the FemMesh is returned fileExtension = os.path.basename(os.path.splitext(fileString)[1]) raw_mesh_data = {} - if fileExtension.lower() == ".meshjson" or\ - fileExtension.lower() == ".json": + if fileExtension.lower() == ".meshjson" or fileExtension.lower() == ".json": fp = pyopen(fileString, "rt") raw_mesh_data = json.load(fp) fp.close() elif ( - fileExtension.lower() == ".meshyaml" - or fileExtension.lower() == ".meshyml" - or fileExtension.lower() == ".yaml" - or fileExtension.lower() == ".yml" + fileExtension.lower() == ".meshyaml" + or fileExtension.lower() == ".meshyml" + or fileExtension.lower() == ".yaml" + or fileExtension.lower() == ".yml" ) and has_yaml: fp = pyopen(fileString, "rt") raw_mesh_data = yaml.load(fp, Loader=yaml.SafeLoader) fp.close() else: - Console.PrintError( - "Unknown extension, " - "please select other importer.\n") + Console.PrintError("Unknown extension, please select other importer.\n") Console.PrintMessage("Converting indices to integer numbers ...") mesh_data = convert_raw_data_to_mesh_data(raw_mesh_data) @@ -172,9 +150,7 @@ def read( return importToolsFem.make_femmesh(mesh_data) -def convert_raw_data_to_mesh_data( - raw_mesh_data -): +def convert_raw_data_to_mesh_data(raw_mesh_data): """ Converts raw dictionary data from JSON or YAML file to proper dict for importToolsFem.make_femmesh(mesh_data). This is necessary since @@ -183,19 +159,14 @@ def convert_raw_data_to_mesh_data( """ mesh_data = {} - for (type_key, type_dict) in raw_mesh_data.items(): + for type_key, type_dict in raw_mesh_data.items(): if type_key.lower() != "groups": - mesh_data[type_key] = dict([ - (int(k), v) for (k, v) in type_dict.items() - ]) + mesh_data[type_key] = {int(k): v for (k, v) in type_dict.items()} return mesh_data # ********* writer *********************************************************** -def write( - fileString, - fem_mesh -): +def write(fileString, fem_mesh): """directly write a FemMesh to a yaml/json mesh file fem_mesh: a FemMesh""" @@ -203,8 +174,7 @@ def write( if fileString != "": fileName, fileExtension = os.path.splitext(fileString) - if fileExtension.lower() == ".json" \ - or fileExtension.lower() == ".meshjson": + if fileExtension.lower() == ".json" or fileExtension.lower() == ".meshjson": fp = pyopen(fileString, "wt") json.dump(mesh_data, fp, indent=4) fp.close() diff --git a/src/Mod/Fem/feminout/importZ88Mesh.py b/src/Mod/Fem/feminout/importZ88Mesh.py index 82f3cc11f5..b9ba2f5787 100644 --- a/src/Mod/Fem/feminout/importZ88Mesh.py +++ b/src/Mod/Fem/feminout/importZ88Mesh.py @@ -43,11 +43,7 @@ from builtins import open as pyopen # they are set in FEM modules Init.py - - -def open( - filename -): +def open(filename): """called when freecad opens a file a FEM mesh object is created in a new document""" @@ -55,10 +51,7 @@ def open( return insert(filename, docname) -def insert( - filename, - docname -): +def insert(filename, docname): """called when freecad wants to import a file a FEM mesh object is created in a existing document""" @@ -72,10 +65,7 @@ def insert( return doc -def export( - objectslist, - filename -): +def export(objectslist, filename): "called when freecad exports a file" if len(objectslist) != 1: Console.PrintError("This exporter can only export one object.\n") @@ -103,12 +93,9 @@ def export( # - a method directly writes a FemMesh to the mesh file # - a method takes a file handle, mesh data and writes to the file handle + # ********* reader ******************************************************************************* -def import_z88_mesh( - filename, - analysis=None, - docname=None -): +def import_z88_mesh(filename, analysis=None, docname=None): """read a FEM mesh from a Z88 mesh file and insert a FreeCAD FEM Mesh object in the ActiveDocument """ @@ -132,11 +119,8 @@ def import_z88_mesh( return mesh_object -def read( - filename -): - """read a FemMesh from a Z88 mesh file and return the FemMesh - """ +def read(filename): + """read a FemMesh from a Z88 mesh file and return the FemMesh""" # no document object is created, just the FemMesh is returned mesh_data = read_z88_mesh(filename) @@ -145,11 +129,9 @@ def read( return importToolsFem.make_femmesh(mesh_data) -def read_z88_mesh( - z88_mesh_input -): - """ reads a z88 mesh file z88i1.txt (Z88OSV14) or z88structure.txt (Z88AuroraV3) - and extracts the nodes and elements +def read_z88_mesh(z88_mesh_input): + """reads a z88 mesh file z88i1.txt (Z88OSV14) or z88structure.txt (Z88AuroraV3) + and extracts the nodes and elements """ nodes = {} elements_hexa8 = {} @@ -178,20 +160,18 @@ def read_z88_mesh( kflag = int(mesh_info[4]) # for non rotational elements is --> kflag = 0 --> cartesian, kflag = 1 polar coordinates if kflag: - Console.PrintError( - "KFLAG = 1, Rotational coordinates not supported at the moment\n" - ) + Console.PrintError("KFLAG = 1, Rotational coordinates not supported at the moment\n") return {} nodes_first_line = 2 # first line is mesh_info nodes_last_line = nodes_count + 1 elemts_first_line = nodes_last_line + 1 elements_last_line = elemts_first_line - 1 + elements_count * 2 - Console.PrintLog("{}\n".format(nodes_count)) - Console.PrintLog("{}\n".format(elements_count)) - Console.PrintLog("{}\n".format(nodes_last_line)) - Console.PrintLog("{}\n".format(elemts_first_line)) - Console.PrintLog("{}\n".format(elements_last_line)) + Console.PrintLog(f"{nodes_count}\n") + Console.PrintLog(f"{elements_count}\n") + Console.PrintLog(f"{nodes_last_line}\n") + Console.PrintLog(f"{elemts_first_line}\n") + Console.PrintLog(f"{elements_last_line}\n") z88_mesh_file.seek(0) # go back to the beginning of the file for no, line in enumerate(z88_mesh_file): @@ -221,66 +201,44 @@ def read_z88_mesh( # not supported elements if z88_element_type == 8: # torus8 - Console.PrintError( - "Z88 Element No. 8, torus8\n" - ) - Console.PrintError( - "Rotational elements are not supported at the moment\n" - ) + Console.PrintError("Z88 Element No. 8, torus8\n") + Console.PrintError("Rotational elements are not supported at the moment\n") return {} elif z88_element_type == 12: # torus12 - Console.PrintError( - "Z88 Element No. 12, torus12\n" - ) - Console.PrintError( - "Rotational elements are not supported at the moment\n" - ) + Console.PrintError("Z88 Element No. 12, torus12\n") + Console.PrintError("Rotational elements are not supported at the moment\n") return {} elif z88_element_type == 15: # torus6 - Console.PrintError( - "Z88 Element No. 15, torus6\n" - ) - Console.PrintError( - "Rotational elements are not supported at the moment\n" - ) + Console.PrintError("Z88 Element No. 15, torus6\n") + Console.PrintError("Rotational elements are not supported at the moment\n") return {} elif z88_element_type == 19: # platte16 - Console.PrintError( - "Z88 Element No. 19, platte16\n" - ) - Console.PrintError( - "Not supported at the moment\n" - ) + Console.PrintError("Z88 Element No. 19, platte16\n") + Console.PrintError("Not supported at the moment\n") return {} elif z88_element_type == 21: # schale16, mixture made from hexa8 and hexa20 (thickness is linear) - Console.PrintError( - "Z88 Element No. 21, schale16\n" - ) - Console.PrintError( - "Not supported at the moment\n" - ) + Console.PrintError("Z88 Element No. 21, schale16\n") + Console.PrintError("Not supported at the moment\n") return {} elif z88_element_type == 22: # schale12, mixtrue made from prism6 and prism15 (thickness is linear) - Console.PrintError( - "Z88 Element No. 22, schale12\n" - ) - Console.PrintError( - "Not supported at the moment\n" - ) + Console.PrintError("Z88 Element No. 22, schale12\n") + Console.PrintError("Not supported at the moment\n") return {} # supported elements - elif z88_element_type == 2 \ - or z88_element_type == 4 \ - or z88_element_type == 5 \ - or z88_element_type == 9 \ - or z88_element_type == 13 \ - or z88_element_type == 25: + elif ( + z88_element_type == 2 + or z88_element_type == 4 + or z88_element_type == 5 + or z88_element_type == 9 + or z88_element_type == 13 + or z88_element_type == 25 + ): # stab4 or stab5 or welle5 or beam13 or beam25 Z88 --> seg2 FreeCAD # N1, N2 nd1 = int(linecolumns[0]) @@ -334,9 +292,7 @@ def read_z88_mesh( nd8 = int(linecolumns[7]) nd9 = int(linecolumns[8]) nd10 = int(linecolumns[9]) - elements_tetra10[elem_no] = ( - nd1, nd2, nd4, nd3, nd5, nd8, nd10, nd7, nd6, nd9 - ) + elements_tetra10[elem_no] = (nd1, nd2, nd4, nd3, nd5, nd8, nd10, nd7, nd6, nd9) input_continues = False elif z88_element_type == 1: # volume1 Z88 --> hexa8 FreeCAD @@ -379,8 +335,26 @@ def read_z88_mesh( nd19 = int(linecolumns[18]) nd20 = int(linecolumns[19]) elements_hexa20[elem_no] = ( - nd1, nd2, nd3, nd4, nd5, nd6, nd7, nd8, nd9, nd10, - nd11, nd12, nd13, nd14, nd15, nd16, nd17, nd18, nd19, nd20 + nd1, + nd2, + nd3, + nd4, + nd5, + nd6, + nd7, + nd8, + nd9, + nd10, + nd11, + nd12, + nd13, + nd14, + nd15, + nd16, + nd17, + nd18, + nd19, + nd20, ) input_continues = False @@ -411,15 +385,12 @@ def read_z88_mesh( "Hexa8Elem": elements_hexa8, "Hexa20Elem": elements_hexa20, "Penta6Elem": elements_penta6, - "Penta15Elem": elements_penta15 + "Penta15Elem": elements_penta15, } # ********* writer ******************************************************************************* -def write( - fem_mesh, - filename -): +def write(fem_mesh, filename): """directly write a FemMesh to a Z88 mesh file format fem_mesh: a FemMesh""" @@ -434,12 +405,7 @@ def write( f.close() -def write_z88_mesh_to_file( - femnodes_mesh, - femelement_table, - z88_element_type, - f -): +def write_z88_mesh_to_file(femnodes_mesh, femelement_table, z88_element_type, f): node_dimension = 3 # 2 for 2D not supported if ( z88_element_type == 4 @@ -449,10 +415,7 @@ def write_z88_mesh_to_file( or z88_element_type == 10 ): node_dof = 3 - elif ( - z88_element_type == 23 - or z88_element_type == 24 - ): + elif z88_element_type == 23 or z88_element_type == 24: node_dof = 6 # schalenelemente else: Console.PrintError("Error: wrong z88_element_type.\n") @@ -464,16 +427,15 @@ def write_z88_mesh_to_file( written_by = "written by FreeCAD" # first line, some z88 specific stuff - f.write("{0} {1} {2} {3} {4} {5}\n".format( - node_dimension, node_count, element_count, dofs, unknown_flag, written_by) + f.write( + "{} {} {} {} {} {}\n".format( + node_dimension, node_count, element_count, dofs, unknown_flag, written_by + ) ) # nodes for node in femnodes_mesh: vec = femnodes_mesh[node] - f.write( - "{0} {1} {2:.6f} {3:.6f} {4:.6f}\n" - .format(node, node_dof, vec.x, vec.y, vec.z) - ) + f.write(f"{node} {node_dof} {vec.x:.6f} {vec.y:.6f} {vec.z:.6f}\n") # elements for element in femelement_table: # z88_element_type is checked for every element @@ -489,39 +451,37 @@ def write_z88_mesh_to_file( ): # seg2 FreeCAD --> stab4 Z88 # N1, N2 - f.write("{0} {1}\n".format(element, z88_element_type)) - f.write("{0} {1}\n".format( - n[0], n[1])) + f.write(f"{element} {z88_element_type}\n") + f.write(f"{n[0]} {n[1]}\n") elif z88_element_type == 3 or z88_element_type == 14 or z88_element_type == 24: # tria6 FreeCAD --> schale24 Z88 # N1, N2, N3, N4, N5, N6 - f.write("{0} {1}\n".format(element, z88_element_type)) - f.write("{0} {1} {2} {3} {4} {5}\n".format( - n[0], n[1], n[2], n[3], n[4], n[5])) + f.write(f"{element} {z88_element_type}\n") + f.write(f"{n[0]} {n[1]} {n[2]} {n[3]} {n[4]} {n[5]}\n") elif z88_element_type == 7 or z88_element_type == 20 or z88_element_type == 23: # quad8 FreeCAD --> schale23 Z88 # N1, N2, N3, N4, N5, N6, N7, N8 - f.write("{0} {1}\n".format(element, z88_element_type)) - f.write("{0} {1} {2} {3} {4} {5} {6} {7}\n".format( - n[0], n[1], n[2], n[3], n[4], n[5], n[6], n[7])) + f.write(f"{element} {z88_element_type}\n") + f.write(f"{n[0]} {n[1]} {n[2]} {n[3]} {n[4]} {n[5]} {n[6]} {n[7]}\n") elif z88_element_type == 17: # tetra4 FreeCAD --> volume17 Z88 # N4, N2, N3, N1 - f.write("{0} {1}\n".format(element, z88_element_type)) - f.write("{0} {1} {2} {3}\n".format( - n[3], n[1], n[2], n[0])) + f.write(f"{element} {z88_element_type}\n") + f.write(f"{n[3]} {n[1]} {n[2]} {n[0]}\n") elif z88_element_type == 16: # tetra10 FreeCAD --> volume16 Z88 # N1, N2, N4, N3, N5, N9, N8, N6, N10, N7, FC to Z88 is different as Z88 to FC - f.write("{0} {1}\n".format(element, z88_element_type)) - f.write("{0} {1} {2} {3} {4} {5} {6} {7} {8} {9}\n".format( - n[0], n[1], n[3], n[2], n[4], n[8], n[7], n[5], n[9], n[6])) + f.write(f"{element} {z88_element_type}\n") + f.write( + "{} {} {} {} {} {} {} {} {} {}\n".format( + n[0], n[1], n[3], n[2], n[4], n[8], n[7], n[5], n[9], n[6] + ) + ) elif z88_element_type == 1: # hexa8 FreeCAD --> volume1 Z88 # N1, N2, N3, N4, N5, N6, N7, N8 - f.write("{0} {1}\n".format(element, z88_element_type)) - f.write("{0} {1} {2} {3} {4} {5} {6} {7}\n".format( - n[0], n[1], n[2], n[3], n[4], n[5], n[6], n[7])) + f.write(f"{element} {z88_element_type}\n") + f.write(f"{n[0]} {n[1]} {n[2]} {n[3]} {n[4]} {n[5]} {n[6]} {n[7]}\n") elif z88_element_type == 10: # hexa20 FreeCAD --> volume10 Z88 # N2, N3, N4, N1, N6, N7, N8, N5, N10, N11 @@ -529,28 +489,40 @@ def write_z88_mesh_to_file( # or turn by 90 degree and they match ! # N1, N2, N3, N4, N5, N6, N7, N8, N9, N10 # N11, N12, N13, N14, N15, N16, N17, N18, N19, N20 - f.write("{0} {1}\n".format(element, z88_element_type)) + f.write(f"{element} {z88_element_type}\n") f.write( - "{0} {1} {2} {3} {4} {5} {6} {7} {8} {9} " - "{10} {11} {12} {13} {14} {15} {16} {17} {18} {19}\n" - .format( - n[0], n[1], n[2], n[3], n[4], n[5], n[6], n[7], n[8], n[9], - n[10], n[11], n[12], n[13], n[14], n[15], n[16], n[17], n[18], n[19] + "{} {} {} {} {} {} {} {} {} {} " + "{} {} {} {} {} {} {} {} {} {}\n".format( + n[0], + n[1], + n[2], + n[3], + n[4], + n[5], + n[6], + n[7], + n[8], + n[9], + n[10], + n[11], + n[12], + n[13], + n[14], + n[15], + n[16], + n[17], + n[18], + n[19], ) ) else: - Console.PrintError( - "Writing of Z88 elementtype {0} not supported.\n".format(z88_element_type) - ) + Console.PrintError(f"Writing of Z88 elementtype {z88_element_type} not supported.\n") # TODO support schale12 (made from prism15) and schale16 (made from hexa20) return # Helper -def get_z88_element_type( - femmesh, - femelement_table=None -): +def get_z88_element_type(femmesh, femelement_table=None): return z88_ele_types[meshtools.get_femmesh_eletype(femmesh, femelement_table)] diff --git a/src/Mod/Fem/feminout/importZ88O2Results.py b/src/Mod/Fem/feminout/importZ88O2Results.py index 4abd383913..39e4a56fe1 100644 --- a/src/Mod/Fem/feminout/importZ88O2Results.py +++ b/src/Mod/Fem/feminout/importZ88O2Results.py @@ -39,19 +39,13 @@ from builtins import open as pyopen # ********* generic FreeCAD import and export methods ********* - -def open( - filename -): +def open(filename): "called when freecad opens a file" docname = os.path.splitext(os.path.basename(filename))[0] insert(filename, docname) -def insert( - filename, - docname -): +def insert(filename, docname): "called when freecad wants to import a file" try: doc = FreeCAD.getDocument(docname) @@ -62,11 +56,7 @@ def insert( # ********* module specific methods ********* -def import_z88_disp( - filename, - analysis=None, - result_name_prefix=None -): +def import_z88_disp(filename, analysis=None, result_name_prefix=None): """insert a FreeCAD FEM mechanical result object in the ActiveDocument pure usage: import feminout.importZ88O2Results as importZ88O2Results @@ -80,6 +70,7 @@ def import_z88_disp( from . import importZ88Mesh from . import importToolsFem from femresult import resulttools + if result_name_prefix is None: result_name_prefix = "" disp_read = read_z88_disp(filename) @@ -93,10 +84,7 @@ def import_z88_disp( mesh_file = filename.replace("o2", "i1") mesh_data = importZ88Mesh.read_z88_mesh(mesh_file) femmesh = importToolsFem.make_femmesh(mesh_data) - result_mesh_object = ObjectsFem.makeMeshResult( - FreeCAD.ActiveDocument, - "Result_mesh" - ) + result_mesh_object = ObjectsFem.makeMeshResult(FreeCAD.ActiveDocument, "Result_mesh") result_mesh_object.FemMesh = femmesh else: Console.PrintError("Z88 mesh file z88i1.txt not found.\n") @@ -118,6 +106,7 @@ def import_z88_disp( if FreeCAD.GuiUp: if analysis: import FemGui + FemGui.setActiveAnalysis(analysis_object) FreeCAD.ActiveDocument.recompute() @@ -129,9 +118,7 @@ def import_z88_disp( return res_obj -def read_z88_disp( - z88_disp_input -): +def read_z88_disp(z88_disp_input): """ read a z88 disp file and extract the nodes and elements z88 Displacement output file is z88o2.txt diff --git a/src/Mod/Fem/feminout/readFenicsXDMF.py b/src/Mod/Fem/feminout/readFenicsXDMF.py index 67394a6b14..9aeaae149b 100644 --- a/src/Mod/Fem/feminout/readFenicsXDMF.py +++ b/src/Mod/Fem/feminout/readFenicsXDMF.py @@ -48,5 +48,5 @@ def read_fenics_mesh_xdmf(xdmffilename): "Tria6Elem": {}, "Quad4Elem": {}, "Quad8Elem": {}, - "Seg2Elem": {} + "Seg2Elem": {}, } diff --git a/src/Mod/Fem/feminout/readFenicsXML.py b/src/Mod/Fem/feminout/readFenicsXML.py index 0c497e0f32..dddfc326d0 100644 --- a/src/Mod/Fem/feminout/readFenicsXML.py +++ b/src/Mod/Fem/feminout/readFenicsXML.py @@ -38,7 +38,7 @@ from FreeCAD import Console def read_fenics_mesh_xml(xmlfilename): """ - Returns element dictionary to be evaluated by make_femmesh later + Returns element dictionary to be evaluated by make_femmesh later """ Fenics_to_FreeCAD_dict = { @@ -51,8 +51,8 @@ def read_fenics_mesh_xml(xmlfilename): def read_mesh_block(mesh_block): """ - Reading mesh block from XML file. - The mesh block only contains cells and vertices. + Reading mesh block from XML file. + The mesh block only contains cells and vertices. """ dim = int(mesh_block.get("dim")) cell_type = mesh_block.get("celltype") @@ -64,12 +64,14 @@ def read_fenics_mesh_xml(xmlfilename): # every cell type contains a dict with key=dimension and value=number - cells_parts_dim = {"point": {0: 1}, - "interval": {0: 2, 1: 1}, - "triangle": {0: 3, 1: 3, 2: 1}, - "tetrahedron": {0: 4, 1: 6, 2: 4, 3: 1}, - "quadrilateral": {0: 4, 1: 4, 2: 1}, - "hexahedron": {0: 8, 1: 12, 2: 6, 3: 1}} + cells_parts_dim = { + "point": {0: 1}, + "interval": {0: 2, 1: 1}, + "triangle": {0: 3, 1: 3, 2: 1}, + "tetrahedron": {0: 4, 1: 6, 2: 4, 3: 1}, + "quadrilateral": {0: 4, 1: 4, 2: 1}, + "hexahedron": {0: 8, 1: 12, 2: 6, 3: 1}, + } find_vertices = mesh_block.find("vertices") find_cells = mesh_block.find("cells") @@ -88,7 +90,7 @@ def read_fenics_mesh_xml(xmlfilename): if vertex.tag.lower() == "vertex": [node_x, node_y, node_z] = [ - float(vertex.get(coord, 0.)) for coord in ["x", "y", "z"] + float(vertex.get(coord, 0.0)) for coord in ["x", "y", "z"] ] nodes_dict[ind + 1] = FreeCAD.Vector(node_x, node_y, node_z) @@ -105,14 +107,14 @@ def read_fenics_mesh_xml(xmlfilename): ind = int(cell.get("index")) if cell.tag.lower() != cell_type.lower(): - Console.PrintWarning("Strange mismatch between cell type " + - f"{cell_type} and " + - f"cell tag {cell.tag.lower()}\n") + Console.PrintWarning( + "Strange mismatch between cell type " + + f"{cell_type} and " + + f"cell tag {cell.tag.lower()}\n" + ) num_vertices = cells_parts_dim[cell_type][0] - vtupel = tuple([ - int(cell.get("v" + str(vnum))) + 1 for vnum in range(num_vertices) - ]) + vtupel = tuple([int(cell.get("v" + str(vnum))) + 1 for vnum in range(num_vertices)]) # generate "v0", "v1", ... from dimension lookup table # increase numbers by one to match FC numbering convention @@ -127,14 +129,14 @@ def read_fenics_mesh_xml(xmlfilename): def correct_volume_det(element_dict): """ - Checks whether the cell elements - all have the same volume (<0?) - sign (is necessary to avoid negative - Jacobian errors). - Works only with tet4 and tri3 elements at the moment + Checks whether the cell elements + all have the same volume (<0?) + sign (is necessary to avoid negative + Jacobian errors). + Works only with tet4 and tri3 elements at the moment """ if dim == 3: - for (ind, tet) in list(element_dict["tetra4"].items()): + for ind, tet in list(element_dict["tetra4"].items()): v0 = nodes[tet[0]] v1 = nodes[tet[1]] v2 = nodes[tet[2]] @@ -145,8 +147,8 @@ def read_fenics_mesh_xml(xmlfilename): if a.dot(b.cross(c)) > 0: element_dict["tetra4"][ind] = (tet[1], tet[0], tet[2], tet[3]) if dim == 2: - nz = FreeCAD.Vector(0., 0., 1.) - for (ind, tria) in list(element_dict["tria3"].items()): + nz = FreeCAD.Vector(0.0, 0.0, 1.0) + for ind, tria in list(element_dict["tria3"].items()): v0 = nodes[tria[0]] v1 = nodes[tria[1]] v2 = nodes[tria[2]] @@ -159,7 +161,7 @@ def read_fenics_mesh_xml(xmlfilename): element_counter = {} # TODO: remove upper level lookup - for (key, val) in list(Fenics_to_FreeCAD_dict.items()): + for key, val in list(Fenics_to_FreeCAD_dict.items()): element_dict[val] = {} element_counter[key] = 0 # count every distinct element and sub element type @@ -172,43 +174,46 @@ def read_fenics_mesh_xml(xmlfilename): def invertdict(dic): invdic = {} - for (key, it) in list(dic.items()): + for key, it in list(dic.items()): invdic[it] = key return invdic - num_vert_dict = {"interval": 2, - "triangle": 3, - "tetrahedron": 4, - "hexahedron": 8, - "quadrilateral": 4} - lower_dims_dict = {"interval": [], - "triangle": ["interval"], - "tetrahedron": ["triangle", "interval"], - "hexahedron": ["quadrilateral", "interval"], - "quadrilateral": ["interval"]} + num_vert_dict = { + "interval": 2, + "triangle": 3, + "tetrahedron": 4, + "hexahedron": 8, + "quadrilateral": 4, + } + lower_dims_dict = { + "interval": [], + "triangle": ["interval"], + "tetrahedron": ["triangle", "interval"], + "hexahedron": ["quadrilateral", "interval"], + "quadrilateral": ["interval"], + } # generate cell list from file # read vertex list from cells # generate lower dimensional objects in mesh from cell - for (cell_index, cell) in list(cell_dict.items()): + for cell_index, cell in list(cell_dict.items()): cell_lower_dims = lower_dims_dict[cell_type] element_counter[cell_type] += 1 element_dict[Fenics_to_FreeCAD_dict[cell_type]][cell] = element_counter[cell_type] for ld in cell_lower_dims: for vertextuple in itertools.combinations(cell, num_vert_dict[ld]): element_counter[ld] = addtupletodict( - element_dict[Fenics_to_FreeCAD_dict[ld]], - vertextuple, - element_counter[ld]) + element_dict[Fenics_to_FreeCAD_dict[ld]], vertextuple, element_counter[ld] + ) length_counter = len(nodes) # maintain distinct counting values # print("nodes") # print("len & len counter", length_counter) - for (key, val_dict) in list(element_dict.items()): + for key, val_dict in list(element_dict.items()): # to ensure distinct indices for FreeCAD # print("key: ", key) - for (vkey, it) in list(val_dict.items()): + for vkey, it in list(val_dict.items()): val_dict[vkey] = it + length_counter # maintain distinct element numbers len_val_dict = len(val_dict) if len_val_dict > 0: @@ -240,7 +245,7 @@ def read_fenics_mesh_xml(xmlfilename): (nodes, cells_dict, cell_type, dim) = read_mesh_block(find_mesh) element_dict = generate_lower_dimensional_structures(nodes, cells_dict, cell_type, dim) Console.PrintMessage("Show min max element dict\n") - for (elm, numbers) in list(element_dict.items()): + for elm, numbers in list(element_dict.items()): lst = sorted(list(numbers.items()), key=lambda x: x[0]) if lst != []: Console.PrintMessage(f"{elm} min: {lst[0]} max: {lst[-1]}\n") @@ -263,5 +268,5 @@ def read_fenics_mesh_xml(xmlfilename): "Hexa8Elem": {}, "Hexa20Elem": {}, "Penta6Elem": {}, - "Penta15Elem": {} + "Penta15Elem": {}, } diff --git a/src/Mod/Fem/feminout/writeFenicsXDMF.py b/src/Mod/Fem/feminout/writeFenicsXDMF.py index ce58937487..e9b13134c2 100644 --- a/src/Mod/Fem/feminout/writeFenicsXDMF.py +++ b/src/Mod/Fem/feminout/writeFenicsXDMF.py @@ -44,12 +44,7 @@ from .importToolsFem import get_MaxDimElementFromList ENCODING_ASCII = "ASCII" ENCODING_HDF5 = "HDF5" -FreeCAD_Group_Dimensions = { - "Vertex": 0, - "Edge": 1, - "Face": 2, - "Volume": 3 -} +FreeCAD_Group_Dimensions = {"Vertex": 0, "Edge": 1, "Face": 2, "Volume": 3} FreeCAD_to_Fenics_XDMF_dict = { ("Node", 1): ("Polyvertex", 1), @@ -58,16 +53,14 @@ FreeCAD_to_Fenics_XDMF_dict = { ("Triangle", 1): ("Triangle", 3), ("Triangle", 2): ("Tri_6", 6), ("Tetra", 1): ("Tetrahedron", 4), - ("Tetra", 2): ("Tet_10", 10) + ("Tetra", 2): ("Tet_10", 10), } # we need numpy functions to later access and process large data sets in a fast manner # also the hd5 support works better together with numpy -def numpy_array_to_str( - npa -): +def numpy_array_to_str(npa): res = "" dt = str(npa.dtype) if "int" in dt: @@ -77,27 +70,17 @@ def numpy_array_to_str( return res -def points_to_numpy( - pts, - dim=3 -): +def points_to_numpy(pts, dim=3): return np.array([[p.x, p.y, p.z] for p in pts])[:, :dim] -def tuples_to_numpy( - tpls, - numbers_per_line -): +def tuples_to_numpy(tpls, numbers_per_line): return np.array([list(t) for t in tpls])[:, :numbers_per_line] -def write_fenics_mesh_points_xdmf( - fem_mesh_obj, - geometrynode, - encoding=ENCODING_ASCII -): +def write_fenics_mesh_points_xdmf(fem_mesh_obj, geometrynode, encoding=ENCODING_ASCII): """ - Writes either into hdf5 file or into open mesh file + Writes either into hdf5 file or into open mesh file """ numnodes = fem_mesh_obj.FemMesh.NodeCount @@ -114,13 +97,10 @@ def write_fenics_mesh_points_xdmf( if encoding == ENCODING_ASCII: dataitem = ET.SubElement( - geometrynode, - "DataItem", - Dimensions="%d %d" % (numnodes, effective_dim), - Format="XML" + geometrynode, "DataItem", Dimensions="%d %d" % (numnodes, effective_dim), Format="XML" ) nodes = [] - for (ind, (key, node)) in enumerate(list(fem_mesh_obj.FemMesh.Nodes.items())): + for ind, (key, node) in enumerate(list(fem_mesh_obj.FemMesh.Nodes.items())): nodes.append(node) recalc_nodes_ind_dict[key] = ind @@ -132,11 +112,7 @@ def write_fenics_mesh_points_xdmf( def write_fenics_mesh_codim_xdmf( - fem_mesh_obj, - topologynode, - nodes_dict, - codim=0, - encoding=ENCODING_ASCII + fem_mesh_obj, topologynode, nodes_dict, codim=0, encoding=ENCODING_ASCII ): mesh_dimension = get_FemMeshObjectDimension(fem_mesh_obj) @@ -151,7 +127,7 @@ def write_fenics_mesh_codim_xdmf( writeout_element_dimension = mesh_dimension - codim (num_topo, name_topo, dim_topo) = (0, "", 0) - for (num, name, dim) in element_types: + for num, name, dim in element_types: if writeout_element_dimension == dim: (num_topo, name_topo, dim_topo) = (num, name, dim) @@ -171,19 +147,22 @@ def write_fenics_mesh_codim_xdmf( fc_topo = fem_mesh_obj.FemMesh.Nodes else: fc_topo = [] - Console.PrintError("Dimension of mesh incompatible with export" + - f" XDMF function: {dim_topo}\n") + Console.PrintError( + "Dimension of mesh incompatible with export" + f" XDMF function: {dim_topo}\n" + ) - nodeindices = [( - nodes_dict[ind] for ind in fem_mesh_obj.FemMesh.getElementNodes(fc_topo_ind) - ) for (fen_ind, fc_topo_ind) in enumerate(fc_topo)] + nodeindices = [ + (nodes_dict[ind] for ind in fem_mesh_obj.FemMesh.getElementNodes(fc_topo_ind)) + for (fen_ind, fc_topo_ind) in enumerate(fc_topo) + ] if encoding == ENCODING_ASCII: dataitem = ET.SubElement( - topologynode, "DataItem", + topologynode, + "DataItem", NumberType="UInt", Dimensions="%d %d" % (num_topo, nodes_per_element), - Format="XML" + Format="XML", ) dataitem.text = numpy_array_to_str(tuples_to_numpy(nodeindices, nodes_per_element)) elif encoding == ENCODING_HDF5: @@ -193,9 +172,7 @@ def write_fenics_mesh_codim_xdmf( def write_fenics_mesh_scalar_cellfunctions( - name, cell_array, - attributenode, - encoding=ENCODING_ASCII + name, cell_array, attributenode, encoding=ENCODING_ASCII ): attributenode.set("AttributeType", "Scalar") attributenode.set("Center", "Cell") @@ -205,9 +182,7 @@ def write_fenics_mesh_scalar_cellfunctions( if encoding == ENCODING_ASCII: dataitem = ET.SubElement( - attributenode, "DataItem", - Dimensions="%d %d" % (num_cells, num_dims), - Format="XML" + attributenode, "DataItem", Dimensions="%d %d" % (num_cells, num_dims), Format="XML" ) dataitem.text = numpy_array_to_str(cell_array) elif encoding == ENCODING_HDF5: @@ -253,14 +228,9 @@ Example: mesh with two topologies and one mesh function for the facet one """ -def write_fenics_mesh_xdmf( - fem_mesh_obj, - outputfile, - group_values_dict={}, - encoding=ENCODING_ASCII -): +def write_fenics_mesh_xdmf(fem_mesh_obj, outputfile, group_values_dict={}, encoding=ENCODING_ASCII): """ - For the export of xdmf. + For the export of xdmf. """ Console.PrintMessage(f"Converting {fem_mesh_obj.Label} to fenics XDMF File\n") @@ -283,16 +253,9 @@ def write_fenics_mesh_xdmf( # *********************************** # write base topo and geometry - nodes_dict = write_fenics_mesh_points_xdmf( - fem_mesh_obj, - base_geometry, - encoding=encoding - ) + nodes_dict = write_fenics_mesh_points_xdmf(fem_mesh_obj, base_geometry, encoding=encoding) write_fenics_mesh_codim_xdmf( - fem_mesh_obj, base_topology, - nodes_dict, - codim=0, - encoding=encoding + fem_mesh_obj, base_topology, nodes_dict, codim=0, encoding=encoding ) # *********************************** @@ -307,14 +270,14 @@ def write_fenics_mesh_xdmf( mesh_function_codim = dim_cell - FreeCAD_Group_Dimensions[mesh_function_type] mesh_function_name = fem_mesh.getGroupName(g) - Console.PrintMessage(f"group id: {g} (label: {mesh_function_name})" + - f" with element type {mesh_function_type} and" + - " codim {mesh_function_codim}\n") + Console.PrintMessage( + f"group id: {g} (label: {mesh_function_name})" + + f" with element type {mesh_function_type} and" + + " codim {mesh_function_codim}\n" + ) mesh_function_grid = ET.SubElement( - domain, "Grid", - Name=mesh_function_name + "_mesh", - GridType="Uniform" + domain, "Grid", Name=mesh_function_name + "_mesh", GridType="Uniform" ) mesh_function_topology = ET.SubElement(mesh_function_grid, "Topology") @@ -322,11 +285,11 @@ def write_fenics_mesh_xdmf( fem_mesh_obj, mesh_function_topology, nodes_dict, - codim=mesh_function_codim, encoding=encoding + codim=mesh_function_codim, + encoding=encoding, ) - mesh_function_geometry = ET.SubElement(mesh_function_grid, "Geometry", - Reference="XML") + mesh_function_geometry = ET.SubElement(mesh_function_grid, "Geometry", Reference="XML") mesh_function_geometry.text = "/Xdmf/Domain/Grid/Geometry" mesh_function_attribute = ET.SubElement(mesh_function_grid, "Attribute") @@ -341,21 +304,18 @@ def write_fenics_mesh_xdmf( for e in fem_mesh.getGroupElements(g): elem_dict[e] = elem_mark_group - val_array = np.array([ - elem_dict.get(e, elem_mark_default) for e in mesh_function_topology_description - ]) + val_array = np.array( + [elem_dict.get(e, elem_mark_default) for e in mesh_function_topology_description] + ) topo_array = np.vstack((val_array,)).T write_fenics_mesh_scalar_cellfunctions( - mesh_function_name, - topo_array, - mesh_function_attribute, - encoding=ENCODING_ASCII + mesh_function_name, topo_array, mesh_function_attribute, encoding=ENCODING_ASCII ) # TODO: improve cell functions support fp = open(outputfile, "wb") - fp.write(b'''\n\n''') + fp.write(b"""\n\n""") fp.write(ET.tostring(root)) # xml core functionality does not support pretty printing # so the output file looks quite ugly diff --git a/src/Mod/Fem/feminout/writeFenicsXML.py b/src/Mod/Fem/feminout/writeFenicsXML.py index 5f2b764fba..a21e8ad20c 100644 --- a/src/Mod/Fem/feminout/writeFenicsXML.py +++ b/src/Mod/Fem/feminout/writeFenicsXML.py @@ -41,9 +41,9 @@ from .importToolsFem import get_MaxDimElementFromList def write_fenics_mesh_xml(fem_mesh_obj, outputfile): """ - For the export, we only have to use the highest dimensional entities and their - vertices to be exported. - For second order elements, we have to delete the mid element nodes. + For the export, we only have to use the highest dimensional entities and their + vertices to be exported. + For second order elements, we have to delete the mid element nodes. """ # TODO: check for second order elements @@ -57,9 +57,10 @@ def write_fenics_mesh_xml(fem_mesh_obj, outputfile): "Edge": "interval", "Node": "point", "Quadrangle": "quadrilateral", - - "Polygon": "unknown", "Polyhedron": "unknown", - "Prism": "unknown", "Pyramid": "unknown", + "Polygon": "unknown", + "Polyhedron": "unknown", + "Prism": "unknown", + "Pyramid": "unknown", } XML_Number_of_Nodes_dict = { @@ -68,7 +69,7 @@ def write_fenics_mesh_xml(fem_mesh_obj, outputfile): "triangle": 3, "quadrilateral": 4, "tetrahedron": 4, - "hexahedron": 8 + "hexahedron": 8, } Console.PrintMessage(f"Converting {fem_mesh_obj.Label} to fenics XML File\n") @@ -80,18 +81,25 @@ def write_fenics_mesh_xml(fem_mesh_obj, outputfile): (num_cells, cellname_fc, dim_cell) = celltype_in_mesh cellname_fenics = FreeCAD_to_Fenics_dict[cellname_fc] num_verts_cell = XML_Number_of_Nodes_dict[cellname_fenics] - Console.PrintMessage(f"Celltype in mesh -> {str(celltype_in_mesh)} " + - f"and its Fenics name: {cellname_fenics}\n") + Console.PrintMessage( + f"Celltype in mesh -> {str(celltype_in_mesh)} " + + f"and its Fenics name: {cellname_fenics}\n" + ) root = ET.Element("dolfin", dolfin="http://fenicsproject.org") meshchild = ET.SubElement(root, "mesh", celltype=cellname_fenics, dim=str(dim_cell)) vertices = ET.SubElement(meshchild, "vertices", size=str(fem_mesh_obj.FemMesh.NodeCount)) - for (nodeind, fc_vec) in list(fem_mesh_obj.FemMesh.Nodes.items()): + for nodeind, fc_vec in list(fem_mesh_obj.FemMesh.Nodes.items()): ET.SubElement( - vertices, "vertex", index=str(nodeind - 1), + vertices, + "vertex", + index=str(nodeind - 1), # FC starts from 1, fenics starts from 0 to size-1 - x=str(fc_vec[0]), y=str(fc_vec[1]), z=str(fc_vec[2])) + x=str(fc_vec[0]), + y=str(fc_vec[1]), + z=str(fc_vec[2]), + ) cells = ET.SubElement(meshchild, "cells", size=str(num_cells)) if dim_cell == 3: @@ -103,12 +111,12 @@ def write_fenics_mesh_xml(fem_mesh_obj, outputfile): else: fc_cells = () - for (fen_ind, fc_volume_ind) in enumerate(fc_cells): + for fen_ind, fc_volume_ind in enumerate(fc_cells): # FC starts after all other entities, fenics start from 0 to size-1 nodeindices = fem_mesh_obj.FemMesh.getElementNodes(fc_volume_ind) cell_args = {} - for (vi, ni) in enumerate(nodeindices): + for vi, ni in enumerate(nodeindices): if vi < num_verts_cell: # XML only supports first order meshs cell_args["v" + str(vi)] = str(ni - 1) # generate as many v entries in dict as nodes are listed in cell diff --git a/src/Mod/Fem/femmesh/femmesh2mesh.py b/src/Mod/Fem/femmesh/femmesh2mesh.py index a2b3e1786d..d7280925f6 100644 --- a/src/Mod/Fem/femmesh/femmesh2mesh.py +++ b/src/Mod/Fem/femmesh/femmesh2mesh.py @@ -36,6 +36,7 @@ import time import FreeCAD import Fem + # import Mesh @@ -55,33 +56,26 @@ Mesh.show(Mesh.Mesh(out_mesh)) # These dictionaries list the nodes, that define faces of an element. # The key is the face number, used internally by FreeCAD. # The list contains the nodes in the element for each face. -tetFaces = { - 1: [0, 1, 2], - 2: [0, 3, 1], - 3: [1, 3, 2], - 4: [2, 3, 0]} +tetFaces = {1: [0, 1, 2], 2: [0, 3, 1], 3: [1, 3, 2], 4: [2, 3, 0]} -pentaFaces = { - 1: [0, 1, 2], - 2: [3, 5, 4], - 3: [0, 3, 4, 1], - 4: [1, 4, 5, 2], - 5: [0, 2, 5, 3]} +pentaFaces = {1: [0, 1, 2], 2: [3, 5, 4], 3: [0, 3, 4, 1], 4: [1, 4, 5, 2], 5: [0, 2, 5, 3]} -hexaFaces = { # hexa8 or hexa20 (ignoring mid-nodes) +hexaFaces = { # hexa8 or hexa20 (ignoring mid-nodes) 1: [0, 1, 2, 3], 2: [4, 7, 6, 5], 3: [0, 4, 5, 1], 4: [1, 5, 6, 2], 5: [2, 6, 7, 3], - 6: [3, 7, 4, 0]} + 6: [3, 7, 4, 0], +} -pyraFaces = { # pyra5 or pyra13 (ignoring mid-nodes) +pyraFaces = { # pyra5 or pyra13 (ignoring mid-nodes) 1: [0, 1, 2, 3], 2: [0, 4, 1], 3: [1, 4, 2], 4: [2, 4, 3], - 5: [3, 4, 0]} + 5: [3, 4, 0], +} face_dicts = { 4: tetFaces, @@ -91,7 +85,8 @@ face_dicts = { 10: tetFaces, 13: pyraFaces, 15: pentaFaces, - 20: hexaFaces} + 20: hexaFaces, +} def femmesh_2_mesh(myFemMesh, myResults=None, myDispScale=1): @@ -120,7 +115,7 @@ def femmesh_2_mesh(myFemMesh, myResults=None, myDispScale=1): codeList.append(element_nodes[nodeIdx]) codeList.sort() for node in codeList: - faceCode += (node << shifter) + faceCode += node << shifter # x << n: x shifted left by n bits = Multiplication shifter += shiftBits # print("codeList: ", codeList) @@ -142,7 +137,7 @@ def femmesh_2_mesh(myFemMesh, myResults=None, myDispScale=1): codeList.append(element_nodes[nodeIdx]) codeList.sort() for node in codeList: - faceCode += (node << shifter) + faceCode += node << shifter # x << n: x shifted left by n bits = Multiplication shifter += shiftBits # print("codeList: ", codeList) @@ -164,83 +159,90 @@ def femmesh_2_mesh(myFemMesh, myResults=None, myDispScale=1): singleFaces.append(faceCodeList[actFaceIdx]) actFaceIdx += 1 else: - FreeCAD.Console.PrintMessage("Found a last Face: {}\n".format(faceCodeList[actFaceIdx])) + FreeCAD.Console.PrintMessage(f"Found a last Face: {faceCodeList[actFaceIdx]}\n") singleFaces.append(faceCodeList[actFaceIdx]) actFaceIdx += 1 output_mesh = [] if myResults: - FreeCAD.Console.PrintMessage("{}\n".format(myResults.Name)) + FreeCAD.Console.PrintMessage(f"{myResults.Name}\n") for myFace in singleFaces: face_nodes = faceCodeDict[myFace] dispVec0 = myResults.DisplacementVectors[myResults.NodeNumbers.index(face_nodes[0])] dispVec1 = myResults.DisplacementVectors[myResults.NodeNumbers.index(face_nodes[1])] dispVec2 = myResults.DisplacementVectors[myResults.NodeNumbers.index(face_nodes[2])] - triangle = [myFemMesh.getNodeById(face_nodes[0]) + dispVec0 * myDispScale, - myFemMesh.getNodeById(face_nodes[1]) + dispVec1 * myDispScale, - myFemMesh.getNodeById(face_nodes[2]) + dispVec2 * myDispScale] + triangle = [ + myFemMesh.getNodeById(face_nodes[0]) + dispVec0 * myDispScale, + myFemMesh.getNodeById(face_nodes[1]) + dispVec1 * myDispScale, + myFemMesh.getNodeById(face_nodes[2]) + dispVec2 * myDispScale, + ] output_mesh.extend(triangle) # print("my triangle: ", triangle) if len(face_nodes) == 4: dispVec3 = myResults.DisplacementVectors[myResults.NodeNumbers.index(face_nodes[3])] - triangle = [myFemMesh.getNodeById(face_nodes[2]) + dispVec2 * myDispScale, - myFemMesh.getNodeById(face_nodes[3]) + dispVec3 * myDispScale, - myFemMesh.getNodeById(face_nodes[0]) + dispVec0 * myDispScale] + triangle = [ + myFemMesh.getNodeById(face_nodes[2]) + dispVec2 * myDispScale, + myFemMesh.getNodeById(face_nodes[3]) + dispVec3 * myDispScale, + myFemMesh.getNodeById(face_nodes[0]) + dispVec0 * myDispScale, + ] output_mesh.extend(triangle) # print("my 2. triangle: ", triangle) else: for myFace in singleFaces: face_nodes = faceCodeDict[myFace] - triangle = [myFemMesh.getNodeById(face_nodes[0]), - myFemMesh.getNodeById(face_nodes[1]), - myFemMesh.getNodeById(face_nodes[2])] + triangle = [ + myFemMesh.getNodeById(face_nodes[0]), + myFemMesh.getNodeById(face_nodes[1]), + myFemMesh.getNodeById(face_nodes[2]), + ] output_mesh.extend(triangle) # print("my triangle: ", triangle) if len(face_nodes) == 4: - triangle = [myFemMesh.getNodeById(face_nodes[2]), - myFemMesh.getNodeById(face_nodes[3]), - myFemMesh.getNodeById(face_nodes[0])] + triangle = [ + myFemMesh.getNodeById(face_nodes[2]), + myFemMesh.getNodeById(face_nodes[3]), + myFemMesh.getNodeById(face_nodes[0]), + ] output_mesh.extend(triangle) # print("my 2. triangle: ", triangle) end_time = time.process_time() - FreeCAD.Console.PrintMessage( - "Mesh by surface search method: {}\n".format(end_time - start_time) - ) -# call to mesh_2_femmesh to convert mesh to femmesh before return statement + FreeCAD.Console.PrintMessage(f"Mesh by surface search method: {end_time - start_time}\n") + # call to mesh_2_femmesh to convert mesh to femmesh before return statement mesh2femmesh = mesh_2_femmesh(myFemMesh, singleFaces, faceCodeDict) return output_mesh + # additional function to convert mesh to femmesh def mesh_2_femmesh(myFemMesh, singleFaces, faceCodeDict): start_time = time.process_time() femmesh = Fem.FemMesh() myfemmesh = myFemMesh.Nodes -# nodes contains the nodes that are used + # nodes contains the nodes that are used nodes = {} for myFace in singleFaces: face_nodes = faceCodeDict[myFace] for j in (0, 1, 2): - try: - nodes[face_nodes[j]] += 1 - except: - nodes[face_nodes[j]] = 0 + try: + nodes[face_nodes[j]] += 1 + except: + nodes[face_nodes[j]] = 0 if len(face_nodes) == 4: - j = 3 - try: - nodes[face_nodes[j]] += 1 - except: - nodes[face_nodes[j]] = 0 + j = 3 + try: + nodes[face_nodes[j]] += 1 + except: + nodes[face_nodes[j]] = 0 sfNode = femmesh.addNode sfFace = femmesh.addFace for key in myFemMesh.Nodes: mynode = myfemmesh[key] try: - if(nodes[key] >= 0): - sfNode(mynode[0], mynode[1], mynode[2], key) + if nodes[key] >= 0: + sfNode(mynode[0], mynode[1], mynode[2], key) except: - pass + pass output_mesh = [] @@ -248,13 +250,12 @@ def mesh_2_femmesh(myFemMesh, singleFaces, faceCodeDict): face_nodes = faceCodeDict[myFace] sfFace(face_nodes[0], face_nodes[1], face_nodes[2]) if len(face_nodes) == 4: - sfFace(face_nodes[2], face_nodes[3], face_nodes[0]) - obj = FreeCAD.ActiveDocument.addObject( - "Fem::FemMeshObject", "Mesh2Fem") + sfFace(face_nodes[2], face_nodes[3], face_nodes[0]) + obj = FreeCAD.ActiveDocument.addObject("Fem::FemMeshObject", "Mesh2Fem") obj.FemMesh = femmesh end_time = time.process_time() - FreeCAD.Console.PrintMessage( - "Convert to FemMesh: {}\n".format(end_time - start_time) - ) + FreeCAD.Console.PrintMessage(f"Convert to FemMesh: {end_time - start_time}\n") return obj + + # end of mesh_2_femmesh diff --git a/src/Mod/Fem/femmesh/gmshtools.py b/src/Mod/Fem/femmesh/gmshtools.py index 0bcfc6597b..800c543ebc 100644 --- a/src/Mod/Fem/femmesh/gmshtools.py +++ b/src/Mod/Fem/femmesh/gmshtools.py @@ -44,7 +44,7 @@ class GmshError(Exception): pass -class GmshTools(): +class GmshTools: def __init__(self, gmsh_mesh_obj, analysis=None): # mesh obj @@ -62,7 +62,7 @@ class GmshTools(): # clmax, CharacteristicLengthMax: float, 0.0 = 1e+22 self.clmax = Units.Quantity(self.mesh_obj.CharacteristicLengthMax).Value if self.clmax == 0.0: - self.clmax = 1e+22 + self.clmax = 1e22 # clmin, CharacteristicLengthMin: float self.clmin = Units.Quantity(self.mesh_obj.CharacteristicLengthMin).Value @@ -210,14 +210,14 @@ class GmshTools(): def start_logs(self): Console.PrintLog("\nGmsh FEM mesh run is being started.\n") - Console.PrintLog(" Part to mesh: Name --> {}, Label --> {}, ShapeType --> {}\n".format( - self.part_obj.Name, - self.part_obj.Label, - self.part_obj.Shape.ShapeType - )) - Console.PrintLog(" CharacteristicLengthMax: {}\n".format(self.clmax)) - Console.PrintLog(" CharacteristicLengthMin: {}\n".format(self.clmin)) - Console.PrintLog(" ElementOrder: {}\n".format(self.order)) + Console.PrintLog( + " Part to mesh: Name --> {}, Label --> {}, ShapeType --> {}\n".format( + self.part_obj.Name, self.part_obj.Label, self.part_obj.Shape.ShapeType + ) + ) + Console.PrintLog(f" CharacteristicLengthMax: {self.clmax}\n") + Console.PrintLog(f" CharacteristicLengthMin: {self.clmin}\n") + Console.PrintLog(f" ElementOrder: {self.order}\n") def get_dimension(self): # Dimension @@ -269,36 +269,26 @@ class GmshTools(): if femutils.check_working_dir(self.working_dir) is not True: if create is True: Console.PrintMessage( - "Dir given as parameter \'{}\' doesn't exist, " + "Dir given as parameter '{}' doesn't exist, " "but parameter to create it is set to True. " "Dir will be created.\n".format(self.working_dir) ) os.mkdir(param_working_dir) else: Console.PrintError( - "Dir given as parameter \'{}\' doesn't exist " - "and create parameter is set to False.\n" - .format(self.working_dir) + "Dir given as parameter '{}' doesn't exist " + "and create parameter is set to False.\n".format(self.working_dir) ) self.working_dir = femutils.get_pref_working_dir(self.mesh_obj) - Console.PrintMessage( - "Dir \'{}\' will be used instead.\n" - .format(self.working_dir) - ) + Console.PrintMessage(f"Dir '{self.working_dir}' will be used instead.\n") else: self.working_dir = femutils.get_pref_working_dir(self.mesh_obj) # check working_dir exist, if not use a tmp dir and inform the user if femutils.check_working_dir(self.working_dir) is not True: - Console.PrintError( - "Dir \'{}\' doesn't exist or cannot be created.\n" - .format(self.working_dir) - ) + Console.PrintError(f"Dir '{self.working_dir}' doesn't exist or cannot be created.\n") self.working_dir = femutils.get_temp_dir(self.mesh_obj) - Console.PrintMessage( - "Dir \'{}\' will be used instead.\n" - .format(self.working_dir) - ) + Console.PrintMessage(f"Dir '{self.working_dir}' will be used instead.\n") # file paths _geometry_name = self.part_obj.Name + "_Geometry" @@ -315,15 +305,16 @@ class GmshTools(): def get_gmsh_command(self): from platform import system + 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) + 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) @@ -343,9 +334,9 @@ class GmshTools(): elif system() == "Darwin": # https://forum.freecad.org/viewtopic.php?f=13&t=73041&p=642026#p642022 gmsh_path = "/Applications/Gmsh.app/Contents/MacOS/gmsh" - FreeCAD.ParamGet( - "User parameter:BaseApp/Preferences/Mod/Fem/Gmsh" - ).SetString("gmshBinaryPath", gmsh_path) + FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Fem/Gmsh").SetString( + "gmshBinaryPath", gmsh_path + ) self.gmsh_bin = gmsh_path else: error_message = ( @@ -396,10 +387,7 @@ class GmshTools(): "Are you really sure about this? You could run into trouble!\n" ) self.group_nodes_export = True - new_group_elements = meshtools.get_analysis_group_elements( - self.analysis, - self.part_obj - ) + new_group_elements = meshtools.get_analysis_group_elements(self.analysis, self.part_obj) for ge in new_group_elements: if ge not in self.group_elements: self.group_elements[ge] = new_group_elements[ge] @@ -428,7 +416,7 @@ class GmshTools(): shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE, - universal_newlines=True + universal_newlines=True, ) except Exception as e: Console.PrintMessage(str(e) + "\n") @@ -440,6 +428,7 @@ class GmshTools(): Console.PrintError("Gmsh: StdErr:\n" + gmsh_stderr + "\n") from re import search + # use raw string mode to get pep8 quiet # https://stackoverflow.com/q/61497292 # https://github.com/MathSci/fecon236/issues/6 @@ -465,7 +454,8 @@ class GmshTools(): # https://forum.freecad.org/viewtopic.php?f=18&t=18780&p=149520#p149520 part = self.part_obj if ( - self.mesh_obj.MeshRegionList and part.Shape.ShapeType == "Compound" + self.mesh_obj.MeshRegionList + and part.Shape.ShapeType == "Compound" and ( femutils.is_of_type(part, "FeatureBooleanFragments") or femutils.is_of_type(part, "FeatureSlice") @@ -490,8 +480,7 @@ class GmshTools(): " One element of the mesh refinement {} is " "not an element of the Part to mesh.\n" "But we are going to try to find it in " - "the Shape to mesh :-)\n" - .format(mr_obj.Name) + "the Shape to mesh :-)\n".format(mr_obj.Name) ) search_ele_in_shape_to_mesh = True for elems in sub[1]: @@ -510,8 +499,9 @@ class GmshTools(): else: Console.PrintError( "One element of the meshregion {} could not be found " - "in the Part to mesh. It will be ignored.\n" - .format(mr_obj.Name) + "in the Part to mesh. It will be ignored.\n".format( + mr_obj.Name + ) ) # print(elems) # element if elems not in self.ele_length_map: @@ -521,20 +511,19 @@ class GmshTools(): else: Console.PrintError( "The element {} of the mesh refinement {} has " - "been added to another mesh region.\n" - .format(elems, mr_obj.Name) + "been added to another mesh region.\n".format( + elems, mr_obj.Name + ) ) else: Console.PrintError( "The mesh refinement: {} is not used to create the mesh " - "because the reference list is empty.\n" - .format(mr_obj.Name) + "because the reference list is empty.\n".format(mr_obj.Name) ) else: Console.PrintError( "The mesh refinement: {} is not used to create the " - "mesh because the CharacteristicLength is 0.0 mm.\n" - .format(mr_obj.Name) + "mesh because the CharacteristicLength is 0.0 mm.\n".format(mr_obj.Name) ) for eleml in self.ele_length_map: # the method getElement(element) does not return Solid elements @@ -574,8 +563,7 @@ class GmshTools(): " One element of the mesh boundary layer {} is " "not an element of the Part to mesh.\n" "But we are going to try to find it in " - "the Shape to mesh :-)\n" - .format(mr_obj.Name) + "the Shape to mesh :-)\n".format(mr_obj.Name) ) search_ele_in_shape_to_mesh = True for elems in sub[1]: @@ -586,8 +574,7 @@ class GmshTools(): # the method getElement(element) does not return Solid elements ele_shape = geomtools.get_element(sub[0], elems) found_element = geomtools.find_element_in_shape( - self.part_obj.Shape, - ele_shape + self.part_obj.Shape, ele_shape ) if found_element: # also elems = found_element @@ -595,8 +582,7 @@ class GmshTools(): Console.PrintError( "One element of the mesh boundary layer {} could " "not be found in the Part to mesh. " - "It will be ignored.\n" - .format(mr_obj.Name) + "It will be ignored.\n".format(mr_obj.Name) ) # print(elems) # element if elems not in self.bl_boundary_list: @@ -608,24 +594,28 @@ class GmshTools(): Console.PrintError( "The element {} of the mesh boundary " "layer {} has been added " - "to another mesh boundary layer.\n" - .format(elems, mr_obj.Name) + "to another mesh boundary layer.\n".format( + elems, mr_obj.Name + ) ) setting = {} setting["hwall_n"] = Units.Quantity(mr_obj.MinimumThickness).Value setting["ratio"] = mr_obj.GrowthRate - setting["thickness"] = sum([ - setting["hwall_n"] * setting["ratio"] ** i for i in range( - mr_obj.NumberOfLayers - ) - ]) + setting["thickness"] = sum( + [ + setting["hwall_n"] * setting["ratio"] ** i + for i in range(mr_obj.NumberOfLayers) + ] + ) # setting["hwall_n"] * 5 # tangential cell dimension setting["hwall_t"] = setting["thickness"] # hfar: cell dimension outside boundary # should be set later if some character length is set - if self.clmax > setting["thickness"] * 0.8 \ - and self.clmax < setting["thickness"] * 1.6: + if ( + self.clmax > setting["thickness"] * 0.8 + and self.clmax < setting["thickness"] * 1.6 + ): setting["hfar"] = self.clmax else: # set a value for safety, it may works as background mesh cell size @@ -644,16 +634,14 @@ class GmshTools(): else: Console.PrintError( "The mesh boundary layer: {} is not used to create " - "the mesh because the reference list is empty.\n" - .format(mr_obj.Name) + "the mesh because the reference list is empty.\n".format(mr_obj.Name) ) else: Console.PrintError( "The mesh boundary layer: {} is not used to create " - "the mesh because the min thickness is 0.0 mm.\n" - .format(mr_obj.Name) + "the mesh because the min thickness is 0.0 mm.\n".format(mr_obj.Name) ) - Console.PrintMessage(" {}\n".format(self.bl_setting_list)) + Console.PrintMessage(f" {self.bl_setting_list}\n") def write_groups(self, geo): if self.group_elements: @@ -670,19 +658,19 @@ class GmshTools(): if gdata[0].startswith("Solid"): physical_type = "Volume" for ele in gdata: - ele_nr += (ele.lstrip("Solid") + ", ") + ele_nr += ele.lstrip("Solid") + ", " elif gdata[0].startswith("Face"): physical_type = "Surface" for ele in gdata: - ele_nr += (ele.lstrip("Face") + ", ") + ele_nr += ele.lstrip("Face") + ", " elif gdata[0].startswith("Edge"): physical_type = "Line" for ele in gdata: - ele_nr += (ele.lstrip("Edge") + ", ") + ele_nr += ele.lstrip("Edge") + ", " elif gdata[0].startswith("Vertex"): physical_type = "Point" for ele in gdata: - ele_nr += (ele.lstrip("Vertex") + ", ") + ele_nr += ele.lstrip("Vertex") + ", " if ele_nr: ele_nr = ele_nr.rstrip(", ") # print(ele_nr) @@ -690,8 +678,9 @@ class GmshTools(): curly_br_e = "}" # explicit use double quotes in geo file geo.write( - 'Physical {}("{}") = {}{}{};\n' - .format(physical_type, group, curly_br_s, ele_nr, curly_br_e) + 'Physical {}("{}") = {}{}{};\n'.format( + physical_type, group, curly_br_s, ele_nr, curly_br_e + ) ) geo.write("\n") @@ -706,7 +695,7 @@ class GmshTools(): geo.write(prefix + " = BoundaryLayer;\n") for k in item: v = item[k] - if k in set(["EdgesList", "FacesList"]): + if k in {"EdgesList", "FacesList"}: # the element name of FreeCAD which starts # with 1 (example: "Face1"), same as Gmsh # el_id = int(el[4:]) # FIXME: strip `face` or `edge` prefix @@ -716,7 +705,7 @@ class GmshTools(): else: line = prefix + "." + str(k) + " = " + str(v) + ";\n" geo.write(line) - Console.PrintMessage("{}\n".format(line)) + Console.PrintMessage(f"{line}\n") geo.write("BoundaryLayer Field = " + str(field_number) + ";\n") geo.write("// end of this boundary layer setup \n") field_number += 1 @@ -749,7 +738,7 @@ class GmshTools(): geo.write("// open brep geometry\n") # explicit use double quotes in geo file - geo.write('Merge "{}";\n'.format(os.path.relpath(self.temp_file_geometry, temp_dir))) + geo.write(f'Merge "{os.path.relpath(self.temp_file_geometry, temp_dir)}";\n') geo.write("\n") # groups @@ -762,19 +751,15 @@ class GmshTools(): # we need to add 1 for the index in Gmsh geo.write("// Characteristic Length according CharacteristicLengthMap\n") for e in self.ele_length_map: - ele_nodes = ( - "".join((str(n + 1) + ", ") for n in self.ele_node_map[e]) - ).rstrip(", ") + ele_nodes = ("".join((str(n + 1) + ", ") for n in self.ele_node_map[e])).rstrip( + ", " + ) geo.write("// " + e + "\n") elestr1 = "{" elestr2 = "}" geo.write( - "Characteristic Length {} {} {} = {};\n" - .format( - elestr1, - ele_nodes, - elestr2, - self.ele_length_map[e] + "Characteristic Length {} {} {} = {};\n".format( + elestr1, ele_nodes, elestr2, self.ele_length_map[e] ) ) geo.write("\n") @@ -795,8 +780,9 @@ class GmshTools(): if hasattr(self.mesh_obj, "MeshSizeFromCurvature"): geo.write( "Mesh.MeshSizeFromCurvature = {}" - "; // number of elements per 2*pi radians, 0 to deactivate\n" - .format(self.mesh_obj.MeshSizeFromCurvature) + "; // number of elements per 2*pi radians, 0 to deactivate\n".format( + self.mesh_obj.MeshSizeFromCurvature + ) ) geo.write("\n") if hasattr(self.mesh_obj, "RecombineAll") and self.mesh_obj.RecombineAll is True: @@ -805,9 +791,8 @@ class GmshTools(): if hasattr(self.mesh_obj, "Recombine3DAll") and self.mesh_obj.Recombine3DAll is True: geo.write("// recombination for volumes\n") geo.write("Mesh.Recombine3DAll = 1;\n") - if ( - (hasattr(self.mesh_obj, "RecombineAll") and self.mesh_obj.RecombineAll is True) - or (hasattr(self.mesh_obj, "Recombine3DAll") and self.mesh_obj.Recombine3DAll is True) + if (hasattr(self.mesh_obj, "RecombineAll") and self.mesh_obj.RecombineAll is True) or ( + hasattr(self.mesh_obj, "Recombine3DAll") and self.mesh_obj.Recombine3DAll is True ): geo.write("// recombination algorithm\n") geo.write("Mesh.RecombinationAlgorithm = " + self.RecombinationAlgorithm + ";\n") @@ -874,9 +859,11 @@ class GmshTools(): geo.write("\n") geo.write("// incomplete second order elements\n") - if (self.SubdivisionAlgorithm == "1" - or self.SubdivisionAlgorithm == "2" - or self.mesh_obj.RecombineAll): + if ( + self.SubdivisionAlgorithm == "1" + or self.SubdivisionAlgorithm == "2" + or self.mesh_obj.RecombineAll + ): sec_order_inc = "1" else: sec_order_inc = "0" @@ -889,8 +876,7 @@ class GmshTools(): if hasattr(self.mesh_obj, "CoherenceMesh") and self.mesh_obj.CoherenceMesh is True: geo.write( "Geometry.Tolerance = {}; // set geometrical " - "tolerance (also used for merging nodes)\n" - .format(self.geotol) + "tolerance (also used for merging nodes)\n".format(self.geotol) ) geo.write("Mesh " + self.dimension + ";\n") geo.write("Coherence Mesh; // Remove duplicate vertices\n") @@ -906,11 +892,12 @@ class GmshTools(): # belongs to Mesh.SaveAll but only needed if there are groups geo.write( "// Needed for Group meshing too, because " - "for one material there is no group defined;\n") + "for one material there is no group defined;\n" + ) geo.write("// Ignore Physical definitions and save all elements;\n") geo.write("Mesh.SaveAll = 1;\n") # explicit use double quotes in geo file - geo.write('Save "{}";\n'.format(os.path.relpath(self.temp_file_mesh, temp_dir))) + geo.write(f'Save "{os.path.relpath(self.temp_file_mesh, temp_dir)}";\n') geo.write("\n\n") # some useful information @@ -935,10 +922,7 @@ class GmshTools(): # print(command_list) try: p = subprocess.Popen( - command_list, - shell=False, - stdout=subprocess.PIPE, - stderr=subprocess.PIPE + command_list, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) output, error = p.communicate() error = error.decode("utf-8") @@ -950,7 +934,7 @@ class GmshTools(): if os.path.exists(self.gmsh_bin): error = "Error executing: {}\n".format(" ".join(command_list)) else: - error = "Gmsh executable not found: {}\n".format(self.gmsh_bin) + error = f"Gmsh executable not found: {self.gmsh_bin}\n" Console.PrintError(error) self.error = True @@ -986,6 +970,7 @@ class GmshTools(): ) Console.PrintWarning(error_message + "\n") + ## @} diff --git a/src/Mod/Fem/femmesh/meshsetsgetter.py b/src/Mod/Fem/femmesh/meshsetsgetter.py index 3093b55c9c..8aeaa81da0 100644 --- a/src/Mod/Fem/femmesh/meshsetsgetter.py +++ b/src/Mod/Fem/femmesh/meshsetsgetter.py @@ -36,7 +36,7 @@ from femmesh import meshtools from femtools.femutils import type_of_obj -class MeshSetsGetter(): +class MeshSetsGetter: def __init__( self, analysis_obj, @@ -74,12 +74,9 @@ class MeshSetsGetter(): ) # ATM only used in meshtools.get_femelement_direction1D_set # TODO somehow this is not smart, pur mesh objects might be used often - if ( - self.member.geos_beamsection - and ( - type_of_obj(self.solver_obj) == "Fem::SolverCcxTools" - or type_of_obj(self.solver_obj) == "Fem::SolverCalculix" - ) + if self.member.geos_beamsection and ( + type_of_obj(self.solver_obj) == "Fem::SolverCcxTools" + or type_of_obj(self.solver_obj) == "Fem::SolverCalculix" ): FreeCAD.Console.PrintError( "The mesh does not know the geometry it is made from. " @@ -156,9 +153,7 @@ class MeshSetsGetter(): self.get_constraints_heatflux_faces() setstime = round((time.process_time() - time_start), 3) - FreeCAD.Console.PrintMessage( - "Getting mesh data time: {} seconds.\n".format(setstime) - ) + FreeCAD.Console.PrintMessage(f"Getting mesh data time: {setstime} seconds.\n") # ******************************************************************************************** # ******************************************************************************************** @@ -170,27 +165,18 @@ class MeshSetsGetter(): for femobj in self.member.cons_fixed: # femobj --> dict, FreeCAD document object is femobj["Object"] print_obj_info(femobj["Object"]) - femobj["Nodes"] = meshtools.get_femnodes_by_femobj_with_references( - self.femmesh, - femobj - ) + femobj["Nodes"] = meshtools.get_femnodes_by_femobj_with_references(self.femmesh, femobj) # add nodes to constraint_conflict_nodes, needed by constraint plane rotation for node in femobj["Nodes"]: self.constraint_conflict_nodes.append(node) # if mixed mesh with solids the node set needs to be split # because solid nodes do not have rotational degree of freedom - if ( - self.femmesh.Volumes - and ( - len(self.member.geos_shellthickness) > 0 - or len(self.member.geos_beamsection) > 0 - ) + if self.femmesh.Volumes and ( + len(self.member.geos_shellthickness) > 0 or len(self.member.geos_beamsection) > 0 ): FreeCAD.Console.PrintMessage("We need to find the solid nodes.\n") if not self.femelement_volumes_table: - self.femelement_volumes_table = meshtools.get_femelement_volumes_table( - self.femmesh - ) + self.femelement_volumes_table = meshtools.get_femelement_volumes_table(self.femmesh) for femobj in self.member.cons_fixed: # femobj --> dict, FreeCAD document object is femobj["Object"] nds_solid = [] @@ -214,10 +200,7 @@ class MeshSetsGetter(): for femobj in self.member.cons_rigidbody: # femobj --> dict, FreeCAD document object is femobj["Object"] print_obj_info(femobj["Object"]) - femobj["Nodes"] = meshtools.get_femnodes_by_femobj_with_references( - self.femmesh, - femobj - ) + femobj["Nodes"] = meshtools.get_femnodes_by_femobj_with_references(self.femmesh, femobj) # add nodes to constraint_conflict_nodes, needed by constraint plane rotation for node in femobj["Nodes"]: self.constraint_conflict_nodes.append(node) @@ -229,10 +212,7 @@ class MeshSetsGetter(): for femobj in self.member.cons_displacement: # femobj --> dict, FreeCAD document object is femobj["Object"] print_obj_info(femobj["Object"]) - femobj["Nodes"] = meshtools.get_femnodes_by_femobj_with_references( - self.femmesh, - femobj - ) + femobj["Nodes"] = meshtools.get_femnodes_by_femobj_with_references(self.femmesh, femobj) # add nodes to constraint_conflict_nodes, needed by constraint plane rotation for node in femobj["Nodes"]: self.constraint_conflict_nodes.append(node) @@ -244,10 +224,7 @@ class MeshSetsGetter(): for femobj in self.member.cons_planerotation: # femobj --> dict, FreeCAD document object is femobj["Object"] print_obj_info(femobj["Object"]) - femobj["Nodes"] = meshtools.get_femnodes_by_femobj_with_references( - self.femmesh, - femobj - ) + femobj["Nodes"] = meshtools.get_femnodes_by_femobj_with_references(self.femmesh, femobj) def get_constraints_transform_nodes(self): if not self.member.cons_transform: @@ -256,10 +233,7 @@ class MeshSetsGetter(): for femobj in self.member.cons_transform: # femobj --> dict, FreeCAD document object is femobj["Object"] print_obj_info(femobj["Object"]) - femobj["Nodes"] = meshtools.get_femnodes_by_femobj_with_references( - self.femmesh, - femobj - ) + femobj["Nodes"] = meshtools.get_femnodes_by_femobj_with_references(self.femmesh, femobj) def get_constraints_temperature_nodes(self): if not self.member.cons_temperature: @@ -268,10 +242,7 @@ class MeshSetsGetter(): for femobj in self.member.cons_temperature: # femobj --> dict, FreeCAD document object is femobj["Object"] print_obj_info(femobj["Object"]) - femobj["Nodes"] = meshtools.get_femnodes_by_femobj_with_references( - self.femmesh, - femobj - ) + femobj["Nodes"] = meshtools.get_femnodes_by_femobj_with_references(self.femmesh, femobj) def get_constraints_fluidsection_nodes(self): if not self.member.geos_fluidsection: @@ -280,10 +251,7 @@ class MeshSetsGetter(): for femobj in self.member.geos_fluidsection: # femobj --> dict, FreeCAD document object is femobj["Object"] print_obj_info(femobj["Object"]) - femobj["Nodes"] = meshtools.get_femnodes_by_femobj_with_references( - self.femmesh, - femobj - ) + femobj["Nodes"] = meshtools.get_femnodes_by_femobj_with_references(self.femmesh, femobj) def get_constraints_force_nodeloads(self): if not self.member.cons_force: @@ -297,9 +265,11 @@ class MeshSetsGetter(): " load on vertices --> The femelement_table " "and femnodes_mesh are not needed for node load calculation.\n" ) - elif femobj["RefShapeType"] == "Face" \ - and meshtools.is_solid_femmesh(self.femmesh) \ - and not meshtools.has_no_face_data(self.femmesh): + elif ( + femobj["RefShapeType"] == "Face" + and meshtools.is_solid_femmesh(self.femmesh) + and not meshtools.has_no_face_data(self.femmesh) + ): FreeCAD.Console.PrintLog( " solid_mesh with face data --> The femelement_table is not " "needed but the femnodes_mesh is needed for node load calculation.\n" @@ -314,9 +284,7 @@ class MeshSetsGetter(): if not self.femnodes_mesh: self.femnodes_mesh = self.femmesh.Nodes if not self.femelement_table: - self.femelement_table = meshtools.get_femelement_table( - self.femmesh - ) + self.femelement_table = meshtools.get_femelement_table(self.femmesh) # get node loads FreeCAD.Console.PrintLog( " Finite element mesh nodes will be retrieved by searching " @@ -334,20 +302,15 @@ class MeshSetsGetter(): FreeCAD.Console.PrintMessage(" Warning --> Force = 0\n") if femobj["RefShapeType"] == "Vertex": # point load on vertices femobj["NodeLoadTable"] = meshtools.get_force_obj_vertex_nodeload_table( - self.femmesh, - frc_obj + self.femmesh, frc_obj ) elif femobj["RefShapeType"] == "Edge": # line load on edges femobj["NodeLoadTable"] = meshtools.get_force_obj_edge_nodeload_table( - self.femmesh, - self.femelement_table, - self.femnodes_mesh, frc_obj + self.femmesh, self.femelement_table, self.femnodes_mesh, frc_obj ) elif femobj["RefShapeType"] == "Face": # area load on faces femobj["NodeLoadTable"] = meshtools.get_force_obj_face_nodeload_table( - self.femmesh, - self.femelement_table, - self.femnodes_mesh, frc_obj + self.femmesh, self.femelement_table, self.femnodes_mesh, frc_obj ) # ******************************************************************************************** @@ -377,17 +340,14 @@ class MeshSetsGetter(): self.femelement_table = meshtools.get_femelement_table(self.femmesh) if not self.femnodes_ele_table: self.femnodes_ele_table = meshtools.get_femnodes_ele_table( - self.femnodes_mesh, - self.femelement_table + self.femnodes_mesh, self.femelement_table ) for femobj in self.member.cons_pressure: # femobj --> dict, FreeCAD document object is femobj["Object"] print_obj_info(femobj["Object"]) pressure_faces = meshtools.get_pressure_obj_faces( - self.femmesh, - self.femelement_table, - self.femnodes_ele_table, femobj + self.femmesh, self.femelement_table, self.femnodes_ele_table, femobj ) # the data model is for compatibility reason with deprecated version # get_pressure_obj_faces_depreciated returns the face ids in a tuple per ref_shape @@ -406,17 +366,14 @@ class MeshSetsGetter(): self.femelement_table = meshtools.get_femelement_table(self.femmesh) if not self.femnodes_ele_table: self.femnodes_ele_table = meshtools.get_femnodes_ele_table( - self.femnodes_mesh, - self.femelement_table + self.femnodes_mesh, self.femelement_table ) for femobj in self.member.cons_contact: # femobj --> dict, FreeCAD document object is femobj["Object"] print_obj_info(femobj["Object"]) contact_slave_faces, contact_master_faces = meshtools.get_contact_obj_faces( - self.femmesh, - self.femelement_table, - self.femnodes_ele_table, femobj + self.femmesh, self.femelement_table, self.femnodes_ele_table, femobj ) # [ele_id, ele_face_id], [ele_id, ele_face_id], ...] # whereas the ele_face_id might be ccx specific @@ -441,17 +398,14 @@ class MeshSetsGetter(): self.femelement_table = meshtools.get_femelement_table(self.femmesh) if not self.femnodes_ele_table: self.femnodes_ele_table = meshtools.get_femnodes_ele_table( - self.femnodes_mesh, - self.femelement_table + self.femnodes_mesh, self.femelement_table ) for femobj in self.member.cons_tie: # femobj --> dict, FreeCAD document object is femobj["Object"] print_obj_info(femobj["Object"]) slave_faces, master_faces = meshtools.get_tie_obj_faces( - self.femmesh, - self.femelement_table, - self.femnodes_ele_table, femobj + self.femmesh, self.femelement_table, self.femnodes_ele_table, femobj ) # [ele_id, ele_face_id], [ele_id, ele_face_id], ...] # whereas the ele_face_id might be ccx specific @@ -471,8 +425,9 @@ class MeshSetsGetter(): if len(sectionprint_obj.References) > 1: FreeCAD.Console.PrintError( "Only one reference shape allowed for a section print " - "but {} found: {}\n" - .format(len(sectionprint_obj.References), sectionprint_obj.References) + "but {} found: {}\n".format( + len(sectionprint_obj.References), sectionprint_obj.References + ) ) for o, elem_tup in sectionprint_obj.References: for elem in elem_tup: @@ -485,22 +440,25 @@ class MeshSetsGetter(): femobj["SectionPrintFaces"] = v # volume elements found FreeCAD.Console.PrintLog( - "{}, surface {}, {} touching volume elements found\n" - .format(sectionprint_obj.Label, sectionprint_obj.Name, len(v)) + "{}, surface {}, {} touching volume elements found\n".format( + sectionprint_obj.Label, sectionprint_obj.Name, len(v) + ) ) else: # no volume elements found, shell elements not allowed FreeCAD.Console.PrintError( "{}, surface {}, Error: " - "No volume elements found!\n" - .format(sectionprint_obj.Label, sectionprint_obj.Name) + "No volume elements found!\n".format( + sectionprint_obj.Label, sectionprint_obj.Name + ) ) else: # in Gui only Faces can be added FreeCAD.Console.PrintError( "Wrong reference shape type for {} " - "Only Faces are allowed, but a {} was found.\n" - .format(sectionprint_obj.Name, ref_shape.ShapeType) + "Only Faces are allowed, but a {} was found.\n".format( + sectionprint_obj.Name, ref_shape.ShapeType + ) ) def get_constraints_heatflux_faces(self): @@ -522,7 +480,7 @@ class MeshSetsGetter(): for elem in elem_tup: ho = o.Shape.getElement(elem) if ho.ShapeType == "Face": - elem_info = "{}:{}".format(o.Name, elem) + elem_info = f"{o.Name}:{elem}" face_table = self.mesh_object.FemMesh.getccxVolumesByFace(ho) femobj["HeatFluxFaceTable"].append((elem_info, face_table)) @@ -560,10 +518,7 @@ class MeshSetsGetter(): # get element ids and write them into the femobj all_found = False if self.femmesh.GroupCount: - all_found = meshtools.get_femelement_sets_from_group_data( - self.femmesh, - femobjs - ) + all_found = meshtools.get_femelement_sets_from_group_data(self.femmesh, femobjs) FreeCAD.Console.PrintMessage(all_found) FreeCAD.Console.PrintMessage("\n") if all_found is False: @@ -575,14 +530,10 @@ class MeshSetsGetter(): self.femnodes_mesh = self.femmesh.Nodes if not self.femnodes_ele_table: self.femnodes_ele_table = meshtools.get_femnodes_ele_table( - self.femnodes_mesh, - self.femelement_table + self.femnodes_mesh, self.femelement_table ) control = meshtools.get_femelement_sets( - self.femmesh, - self.femelement_table, - femobjs, - self.femnodes_ele_table + self.femmesh, self.femelement_table, femobjs, self.femnodes_ele_table ) # we only need to set it, if it is still True if (self.femelement_count_test is True) and (control is False): @@ -592,26 +543,18 @@ class MeshSetsGetter(): # get element ids and write them into the objects FreeCAD.Console.PrintMessage("Shell thicknesses\n") if not self.femelement_faces_table: - self.femelement_faces_table = meshtools.get_femelement_faces_table( - self.femmesh - ) + self.femelement_faces_table = meshtools.get_femelement_faces_table(self.femmesh) meshtools.get_femelement_sets( - self.femmesh, - self.femelement_faces_table, - self.member.geos_shellthickness + self.femmesh, self.femelement_faces_table, self.member.geos_shellthickness ) def get_element_geometry1D_elements(self): # get element ids and write them into the objects FreeCAD.Console.PrintMessage("Beam sections\n") if not self.femelement_edges_table: - self.femelement_edges_table = meshtools.get_femelement_edges_table( - self.femmesh - ) + self.femelement_edges_table = meshtools.get_femelement_edges_table(self.femmesh) meshtools.get_femelement_sets( - self.femmesh, - self.femelement_edges_table, - self.member.geos_beamsection + self.femmesh, self.femelement_edges_table, self.member.geos_beamsection ) def get_element_rotation1D_elements(self): @@ -624,27 +567,18 @@ class MeshSetsGetter(): ) return if not self.femelement_edges_table: - self.femelement_edges_table = meshtools.get_femelement_edges_table( - self.femmesh - ) + self.femelement_edges_table = meshtools.get_femelement_edges_table(self.femmesh) meshtools.get_femelement_direction1D_set( - self.femmesh, - self.femelement_edges_table, - self.member.geos_beamrotation, - self.theshape + self.femmesh, self.femelement_edges_table, self.member.geos_beamrotation, self.theshape ) def get_element_fluid1D_elements(self): # get element ids and write them into the objects FreeCAD.Console.PrintMessage("Fluid sections\n") if not self.femelement_edges_table: - self.femelement_edges_table = meshtools.get_femelement_edges_table( - self.femmesh - ) + self.femelement_edges_table = meshtools.get_femelement_edges_table(self.femmesh) meshtools.get_femelement_sets( - self.femmesh, - self.femelement_edges_table, - self.member.geos_fluidsection + self.femmesh, self.femelement_edges_table, self.member.geos_fluidsection ) def get_material_elements(self): @@ -665,23 +599,15 @@ class MeshSetsGetter(): self.get_solid_element_sets(self.member.mats_linear) if self.member.geos_shellthickness: if not self.femelement_faces_table: - self.femelement_faces_table = meshtools.get_femelement_faces_table( - self.femmesh - ) + self.femelement_faces_table = meshtools.get_femelement_faces_table(self.femmesh) meshtools.get_femelement_sets( - self.femmesh, - self.femelement_faces_table, - self.member.mats_linear + self.femmesh, self.femelement_faces_table, self.member.mats_linear ) if self.member.geos_beamsection or self.member.geos_fluidsection: if not self.femelement_edges_table: - self.femelement_edges_table = meshtools.get_femelement_edges_table( - self.femmesh - ) + self.femelement_edges_table = meshtools.get_femelement_edges_table(self.femmesh) meshtools.get_femelement_sets( - self.femmesh, - self.femelement_edges_table, - self.member.mats_linear + self.femmesh, self.femelement_edges_table, self.member.mats_linear ) def get_element_sets_material_and_femelement_geometry(self): @@ -777,7 +703,7 @@ class MeshSetsGetter(): {"short": "M0"}, {"short": "B0"}, {"short": beamrot_data["ShortName"]}, - {"short": "D" + str(i)} + {"short": "D" + str(i)}, ] matgeoset = {} matgeoset["ccx_elset"] = elset_data @@ -804,7 +730,7 @@ class MeshSetsGetter(): {"short": "M0"}, {"short": beamsec_data["ShortName"]}, {"short": beamrot_data["ShortName"]}, - {"short": "D" + str(i)} + {"short": "D" + str(i)}, ] matgeoset = {} matgeoset["ccx_elset"] = elset_data @@ -830,7 +756,7 @@ class MeshSetsGetter(): {"short": mat_data["ShortName"]}, {"short": "B0"}, {"short": beamrot_data["ShortName"]}, - {"short": "D" + str(i)} + {"short": "D" + str(i)}, ] matgeoset = {} matgeoset["ccx_elset"] = elset_data @@ -853,15 +779,15 @@ class MeshSetsGetter(): for i, beamdirection in enumerate(beamrot_data["FEMRotations1D"]): beamdir_ids = set(beamdirection["ids"]) # empty intersection sets possible - elset_data = list(sorted( - beamsec_ids.intersection(mat_ids).intersection(beamdir_ids) - )) + elset_data = list( + sorted(beamsec_ids.intersection(mat_ids).intersection(beamdir_ids)) + ) if elset_data: names = [ {"short": mat_data["ShortName"]}, {"short": beamsec_data["ShortName"]}, {"short": beamrot_data["ShortName"]}, - {"short": "D" + str(i)} + {"short": "D" + str(i)}, ] matgeoset = {} matgeoset["ccx_elset"] = elset_data @@ -927,7 +853,7 @@ class MeshSetsGetter(): if elset_data: names = [ {"short": mat_data["ShortName"]}, - {"short": fluidsec_data["ShortName"]} + {"short": fluidsec_data["ShortName"]}, ] matgeoset = {} matgeoset["ccx_elset"] = elset_data @@ -942,10 +868,7 @@ class MeshSetsGetter(): mat_obj = self.member.mats_linear[0]["Object"] shellth_obj = self.member.geos_shellthickness[0]["Object"] elset_data = self.ccx_efaces - names = [ - {"long": mat_obj.Name, "short": "M0"}, - {"long": shellth_obj.Name, "short": "S0"} - ] + names = [{"long": mat_obj.Name, "short": "M0"}, {"long": shellth_obj.Name, "short": "S0"}] matgeoset = {} matgeoset["ccx_elset"] = elset_data matgeoset["ccx_elset_name"] = get_elset_name_standard(names) @@ -961,7 +884,7 @@ class MeshSetsGetter(): elset_data = shellth_data["FEMElements"] names = [ {"long": mat_obj.Name, "short": "M0"}, - {"long": shellth_obj.Name, "short": shellth_data["ShortName"]} + {"long": shellth_obj.Name, "short": shellth_data["ShortName"]}, ] matgeoset = {} matgeoset["ccx_elset"] = elset_data @@ -978,7 +901,7 @@ class MeshSetsGetter(): elset_data = mat_data["FEMElements"] names = [ {"long": mat_obj.Name, "short": mat_data["ShortName"]}, - {"long": shellth_obj.Name, "short": "S0"} + {"long": shellth_obj.Name, "short": "S0"}, ] matgeoset = {} matgeoset["ccx_elset"] = elset_data @@ -1000,7 +923,7 @@ class MeshSetsGetter(): if elset_data: names = [ {"long": mat_obj.Name, "short": mat_data["ShortName"]}, - {"long": shellth_obj.Name, "short": shellth_data["ShortName"]} + {"long": shellth_obj.Name, "short": shellth_data["ShortName"]}, ] matgeoset = {} matgeoset["ccx_elset"] = elset_data @@ -1014,10 +937,7 @@ class MeshSetsGetter(): def get_mat_geo_sets_single_mat_solid(self): mat_obj = self.member.mats_linear[0]["Object"] elset_data = self.ccx_evolumes - names = [ - {"long": mat_obj.Name, "short": "M0"}, - {"long": "Solid", "short": "Solid"} - ] + names = [{"long": mat_obj.Name, "short": "M0"}, {"long": "Solid", "short": "Solid"}] matgeoset = {} matgeoset["ccx_elset"] = elset_data matgeoset["ccx_elset_name"] = get_elset_name_standard(names) @@ -1032,7 +952,7 @@ class MeshSetsGetter(): elset_data = mat_data["FEMElements"] names = [ {"long": mat_obj.Name, "short": mat_data["ShortName"]}, - {"long": "Solid", "short": "Solid"} + {"long": "Solid", "short": "Solid"}, ] matgeoset = {} matgeoset["ccx_elset"] = elset_data @@ -1072,8 +992,7 @@ def get_elset_name_standard(names): else: error = ( "FEM: Trouble in elset name, because an " - "elset name is longer than 80 character! {}\n" - .format(elset_name) + "elset name is longer than 80 character! {}\n".format(elset_name) ) raise Exception(error) @@ -1089,22 +1008,18 @@ def get_elset_name_short(names): else: error = ( "FEM: Trouble in elset name, because an" - "short elset name is longer than 20 characters! {}\n" - .format(elset_name) + "short elset name is longer than 20 characters! {}\n".format(elset_name) ) raise Exception(error) def print_obj_info(obj, log=False): if log is False: - FreeCAD.Console.PrintMessage("{}:\n".format(obj.Label)) - FreeCAD.Console.PrintMessage( - " Type: {}, Name: {}\n".format(type_of_obj(obj), obj.Name) - ) + FreeCAD.Console.PrintMessage(f"{obj.Label}:\n") + FreeCAD.Console.PrintMessage(f" Type: {type_of_obj(obj)}, Name: {obj.Name}\n") else: - FreeCAD.Console.PrintLog("{}:\n".format(obj.Label)) - FreeCAD.Console.PrintLog( - " Type: {}, Name: {}\n".format(type_of_obj(obj), obj.Name) - ) + FreeCAD.Console.PrintLog(f"{obj.Label}:\n") + FreeCAD.Console.PrintLog(f" Type: {type_of_obj(obj)}, Name: {obj.Name}\n") + ## @} diff --git a/src/Mod/Fem/femmesh/meshtools.py b/src/Mod/Fem/femmesh/meshtools.py index 615a04d203..6783b264bd 100644 --- a/src/Mod/Fem/femmesh/meshtools.py +++ b/src/Mod/Fem/femmesh/meshtools.py @@ -35,10 +35,7 @@ from femtools import geomtools # ************************************************************************************************ -def get_femnodes_by_femobj_with_references( - femmesh, - femobj -): +def get_femnodes_by_femobj_with_references(femmesh, femobj): node_set = [] if femmesh.GroupCount: node_set = get_femmesh_groupdata_sets_by_name(femmesh, femobj, "Node") @@ -63,14 +60,8 @@ def get_femnodes_by_femobj_with_references( # ************************************************************************************************ -def get_femelements_by_references( - femmesh, - femelement_table, - references, - femnodes_ele_table=None -): - """get the femelements for a list of references - """ +def get_femelements_by_references(femmesh, femelement_table, references, femnodes_ele_table=None): + """get the femelements for a list of references""" references_femelements = [] for ref in references: # femnodes for the current ref @@ -79,27 +70,20 @@ def get_femelements_by_references( # blind fast binary search, works for volumes only # femelements for all references references_femelements += get_femelements_by_femnodes_bin( - femelement_table, - femnodes_ele_table, - ref_femnodes + femelement_table, femnodes_ele_table, ref_femnodes ) else: # standard search # femelements for all references references_femelements += get_femelements_by_femnodes_std( - femelement_table, - ref_femnodes + femelement_table, ref_femnodes ) return references_femelements # ************************************************************************************************ -def get_femnodes_by_references( - femmesh, - references -): - """get the femnodes for a list of references - """ +def get_femnodes_by_references(femmesh, references): + """get the femnodes for a list of references""" references_femnodes = [] for ref in references: references_femnodes += get_femnodes_by_refshape(femmesh, ref) @@ -110,20 +94,16 @@ def get_femnodes_by_references( return list(set(references_femnodes)) # removes duplicate nodes, sorts node order -def get_femnodes_by_refshape( - femmesh, - ref -): +def get_femnodes_by_refshape(femmesh, ref): nodes = [] for refelement in ref[1]: r = sub_shape_at_global_placement(ref[0], refelement) FreeCAD.Console.PrintMessage( " " - "ReferenceShape ... Type: {0}, " - "Object name: {1}, " - "Object label: {2}, " - "Element name: {3}\n" - .format(r.ShapeType, ref[0].Name, ref[0].Label, refelement) + "ReferenceShape ... Type: {}, " + "Object name: {}, " + "Object label: {}, " + "Element name: {}\n".format(r.ShapeType, ref[0].Name, ref[0].Label, refelement) ) if r.ShapeType == "Vertex": nodes += femmesh.getNodesByVertex(r) @@ -134,18 +114,13 @@ def get_femnodes_by_refshape( elif r.ShapeType == "Solid": nodes += femmesh.getNodesBySolid(r) else: - FreeCAD.Console.PrintMessage( - " " - "No Vertice, Edge, Face or Solid as reference shapes!\n" - ) + FreeCAD.Console.PrintMessage(" No Vertice, Edge, Face or Solid as reference shapes!\n") return nodes # ************************************************************************************************ -def get_femelement_table( - femmesh -): - """ get_femelement_table(femmesh): { elementid : [ nodeid, nodeid, ... , nodeid ] }""" +def get_femelement_table(femmesh): + """get_femelement_table(femmesh): { elementid : [ nodeid, nodeid, ... , nodeid ] }""" femelement_table = {} if is_solid_femmesh(femmesh): for i in femmesh.Volumes: @@ -162,10 +137,8 @@ def get_femelement_table( # ************************************************************************************************ -def get_femelement_volumes_table( - femmesh -): - """ get_femelement_volumes_table(femmesh): { elementid : [ nodeid, nodeid, ... , nodeid ] }""" +def get_femelement_volumes_table(femmesh): + """get_femelement_volumes_table(femmesh): { elementid : [ nodeid, nodeid, ... , nodeid ] }""" table = {} for i in femmesh.Volumes: table[i] = femmesh.getElementNodes(i) @@ -173,11 +146,8 @@ def get_femelement_volumes_table( # ************************************************************************************************ -def get_femelement_faces_table( - femmesh, - faces_only=None -): - """ get_femelement_faces_table(femmesh): { elementid : [ nodeid, nodeid, ... , nodeid ] }""" +def get_femelement_faces_table(femmesh, faces_only=None): + """get_femelement_faces_table(femmesh): { elementid : [ nodeid, nodeid, ... , nodeid ] }""" table = {} if not faces_only: faces_only = femmesh.FacesOnly @@ -187,11 +157,8 @@ def get_femelement_faces_table( # ************************************************************************************************ -def get_femelement_edges_table( - femmesh, - edges_only=None -): - """ get_femelement_edges_table(femmesh): { elementid : [ nodeid, nodeid, ... , nodeid ] }""" +def get_femelement_edges_table(femmesh, edges_only=None): + """get_femelement_edges_table(femmesh): { elementid : [ nodeid, nodeid, ... , nodeid ] }""" table = {} if not edges_only: edges_only = femmesh.EdgesOnly @@ -201,10 +168,7 @@ def get_femelement_edges_table( # ************************************************************************************************ -def get_femnodes_ele_table( - femnodes_mesh, - femelement_table -): +def get_femnodes_ele_table(femnodes_mesh, femelement_table): """the femnodes_ele_table contains for each node its membership in elements {nodeID : [[eleID, NodePosition], [], ...], nodeID : [[], [], ...], ...} stored information is: @@ -230,20 +194,14 @@ def get_femnodes_ele_table( for ele_node in ele_list: femnodes_ele_table[ele_node].append([ele, pos]) pos = pos << 1 - FreeCAD.Console.PrintLog( - "len femnodes_ele_table: {}\n" - .format(len(femnodes_ele_table)) - ) - FreeCAD.Console.PrintLog("femnodes_ele_table: {}\n".format(femnodes_ele_table)) + FreeCAD.Console.PrintLog(f"len femnodes_ele_table: {len(femnodes_ele_table)}\n") + FreeCAD.Console.PrintLog(f"femnodes_ele_table: {femnodes_ele_table}\n") return femnodes_ele_table # ************************************************************************************************ -def get_copy_of_empty_femelement_table( - femelement_table -): - """{eleID : 0, eleID : 0, ...} - """ +def get_copy_of_empty_femelement_table(femelement_table): + """{eleID : 0, eleID : 0, ...}""" empty_femelement_table = {} for ele in femelement_table: # initialize it with sorted element keys and empty int empty_femelement_table[ele] = 0 @@ -251,11 +209,7 @@ def get_copy_of_empty_femelement_table( # ************************************************************************************************ -def get_bit_pattern_dict( - femelement_table, - femnodes_ele_table, - node_set -): +def get_bit_pattern_dict(femelement_table, femnodes_ele_table, node_set): """Now we are looking for nodes inside of the Faces = filling the bit_pattern_dict {eleID : [lenEleNodes, binary_position]} see forum post for a very good explanation of what"s really happening @@ -269,7 +223,7 @@ def get_bit_pattern_dict( """ FreeCAD.Console.PrintLog("len femnodes_ele_table: " + str(len(femnodes_ele_table)) + "\n") FreeCAD.Console.PrintLog("len node_set: " + str(len(node_set)) + "\n") - FreeCAD.Console.PrintLog("node_set: {}\n".format(node_set)) + FreeCAD.Console.PrintLog(f"node_set: {node_set}\n") bit_pattern_dict = get_copy_of_empty_femelement_table(femelement_table) # # initializing the bit_pattern_dict for ele in femelement_table: @@ -284,118 +238,68 @@ def get_bit_pattern_dict( # ************************************************************************************************ -def get_ccxelement_faces_from_binary_search( - bit_pattern_dict -): - """get the CalculiX element face numbers - """ +def get_ccxelement_faces_from_binary_search(bit_pattern_dict): + """get the CalculiX element face numbers""" # the forum topic discussion with ulrich1a and others ... Better mesh last instead of mesh first # https://forum.freecad.org/viewtopic.php?f=18&t=17318#p137171 # https://forum.freecad.org/viewtopic.php?f=18&t=17318&start=60#p141484 # https://forum.freecad.org/viewtopic.php?f=18&t=17318&start=50#p141108 # https://forum.freecad.org/viewtopic.php?f=18&t=17318&start=40#p140371 - tet10_mask = { - 119: 1, - 411: 2, - 717: 3, - 814: 4} - tet4_mask = { - 7: 1, - 11: 2, - 13: 3, - 14: 4} - hex8_mask = { - 240: 1, - 15: 2, - 102: 3, - 204: 4, - 153: 5, - 51: 6} - hex20_mask = { - 61680: 1, - 3855: 2, - 402022: 3, - 804044: 4, - 624793: 5, - 201011: 6} - pent6_mask = { - 56: 1, - 7: 2, - 54: 3, - 45: 4, - 27: 5} - pent15_mask = { - 3640: 1, - 455: 2, - 25782: 3, - 22829: 4, - 12891: 5} + tet10_mask = {119: 1, 411: 2, 717: 3, 814: 4} + tet4_mask = {7: 1, 11: 2, 13: 3, 14: 4} + hex8_mask = {240: 1, 15: 2, 102: 3, 204: 4, 153: 5, 51: 6} + hex20_mask = {61680: 1, 3855: 2, 402022: 3, 804044: 4, 624793: 5, 201011: 6} + pent6_mask = {56: 1, 7: 2, 54: 3, 45: 4, 27: 5} + pent15_mask = {3640: 1, 455: 2, 25782: 3, 22829: 4, 12891: 5} vol_dict = { 4: tet4_mask, 6: pent6_mask, 8: hex8_mask, 10: tet10_mask, 15: pent15_mask, - 20: hex20_mask} + 20: hex20_mask, + } faces = [] for ele in bit_pattern_dict: mask_dict = vol_dict[bit_pattern_dict[ele][0]] for key in mask_dict: if (key & bit_pattern_dict[ele][1]) == key: faces.append([ele, mask_dict[key]]) - FreeCAD.Console.PrintLog("found Faces: {}\n".format(len(faces))) + FreeCAD.Console.PrintLog(f"found Faces: {len(faces)}\n") # FreeCAD.Console.PrintMessage("faces: {}\n".format(faces)) return faces # ************************************************************************************************ -def get_femelements_by_femnodes_bin( - femelement_table, - femnodes_ele_table, - node_list -): +def get_femelements_by_femnodes_bin(femelement_table, femnodes_ele_table, node_list): """for every femelement of femelement_table if all nodes of the femelement are in node_list, the femelement is added to the list which is returned blind fast binary search, but works for volumes only """ FreeCAD.Console.PrintMessage("binary search: get_femelements_by_femnodes_bin\n") - vol_masks = { - 4: 15, - 6: 63, - 8: 255, - 10: 1023, - 15: 32767, - 20: 1048575} + vol_masks = {4: 15, 6: 63, 8: 255, 10: 1023, 15: 32767, 20: 1048575} # Now we are looking for nodes inside of the Volumes = filling the bit_pattern_dict - FreeCAD.Console.PrintMessage( - "len femnodes_ele_table: {}\n" - .format(len(femnodes_ele_table)) - ) + FreeCAD.Console.PrintMessage(f"len femnodes_ele_table: {len(femnodes_ele_table)}\n") bit_pattern_dict = get_bit_pattern_dict(femelement_table, femnodes_ele_table, node_list) # search ele_list = [] # The ele_list contains the result of the search. for ele in bit_pattern_dict: - FreeCAD.Console.PrintLog( - "bit_pattern_dict[ele][0]: {}\n".format(bit_pattern_dict[ele][0]) - ) + FreeCAD.Console.PrintLog(f"bit_pattern_dict[ele][0]: {bit_pattern_dict[ele][0]}\n") if bit_pattern_dict[ele][1] == vol_masks[bit_pattern_dict[ele][0]]: ele_list.append(ele) - FreeCAD.Console.PrintMessage("found Volumes: {}\n".format(len(ele_list))) + FreeCAD.Console.PrintMessage(f"found Volumes: {len(ele_list)}\n") # FreeCAD.Console.PrintMessage(" volumes: {}\n".format(ele_list)) return ele_list # ************************************************************************************************ -def get_femelements_by_femnodes_std( - femelement_table, - node_list -): +def get_femelements_by_femnodes_std(femelement_table, node_list): """for every femelement of femelement_table if all nodes of the femelement are in node_list, the femelement is added to the list which is returned e: elementlist - nodes: nodelist """ + nodes: nodelist""" FreeCAD.Console.PrintMessage("std search: get_femelements_by_femnodes_std\n") e = [] # elementlist for elementID in sorted(femelement_table): @@ -409,10 +313,7 @@ def get_femelements_by_femnodes_std( return e -def get_femvolumeelements_by_femfacenodes( - femelement_table, - node_list -): +def get_femvolumeelements_by_femfacenodes(femelement_table, node_list): """assume femelement_table only has volume elements for every femvolumeelement of femelement_table for tetra4 and tetra10 the C++ methods could be used --> test again to be sure @@ -425,7 +326,7 @@ def get_femvolumeelements_by_femfacenodes( if penta15 volume element --> if exact 6 or 8 element nodes are in node_list --> add femelement e: elementlist - nodes: nodelist """ + nodes: nodelist""" e = [] # elementlist for elementID in sorted(femelement_table): nodecount = 0 @@ -469,43 +370,31 @@ def get_femvolumeelements_by_femfacenodes( else: FreeCAD.Console.PrintError( "Error in get_femvolumeelements_by_femfacenodes(): " - "unknown volume element: {}\n" - .format(el_nd_ct) + "unknown volume element: {}\n".format(el_nd_ct) ) # FreeCAD.Console.PrintMessage("{}\n".format(sorted(e))) return e # ************************************************************************************************ -def get_femelement_sets( - femmesh, - femelement_table, - fem_objects, - femnodes_ele_table=None -): +def get_femelement_sets(femmesh, femelement_table, fem_objects, femnodes_ele_table=None): # fem_objects = FreeCAD FEM document objects # get femelements for reference shapes of each obj.References count_femelements = 0 - referenced_femelements = np.zeros( - (max(femelement_table.keys()) + 1,), - dtype=int - ) + referenced_femelements = np.zeros((max(femelement_table.keys()) + 1,), dtype=int) has_remaining_femelements = None for fem_object_i, fem_object in enumerate(fem_objects): obj = fem_object["Object"] FreeCAD.Console.PrintMessage( "Constraint: {} --> We're going to search " - "in the mesh for the element ID's.\n" - .format(obj.Name) + "in the mesh for the element ID's.\n".format(obj.Name) ) # unique short identifier fem_object["ShortName"] = get_elset_short_name(obj, fem_object_i) if obj.References: ref_shape_femelements = [] ref_shape_femelements = get_femelements_by_references( - femmesh, femelement_table, - obj.References, - femnodes_ele_table + femmesh, femelement_table, obj.References, femnodes_ele_table ) ref_shape_femelements_array = np.zeros_like(referenced_femelements) ref_shape_femelements_array[ref_shape_femelements] = 1 @@ -519,9 +408,7 @@ def get_femelement_sets( femelement_table_array = np.zeros_like(referenced_femelements) femelement_table_array[list(femelement_table)] = 1 remaining_femelements_array = femelement_table_array > referenced_femelements - remaining_femelements = [ - i.item() for i in np.nditer(remaining_femelements_array.nonzero()) - ] + remaining_femelements = [i.item() for i in np.nditer(remaining_femelements_array.nonzero())] count_femelements += len(remaining_femelements) for fem_object in fem_objects: obj = fem_object["Object"] @@ -538,12 +425,7 @@ def get_femelement_sets( # ************************************************************************************************ -def get_femelement_direction1D_set( - femmesh, - femelement_table, - beamrotation_objects, - theshape=None -): +def get_femelement_direction1D_set(femmesh, femelement_table, beamrotation_objects, theshape=None): """ get for each geometry edge direction, the local direction m and the element ids and # write all into the beamrotation_objects @@ -707,11 +589,7 @@ def get_beam_main_axis_m(beam_direction: FreeCAD.Vector, defined_angle: int) -> # ************************************************************************************************ -def get_femmesh_groupdata_sets_by_name( - femmesh, - fem_object, - group_data_type -): +def get_femmesh_groupdata_sets_by_name(femmesh, fem_object, group_data_type): # get ids from femmesh groupdata for reference shapes of each obj.References # we assume the mesh group data fits with the reference shapes # no check is done in this regard !!! @@ -725,18 +603,16 @@ def get_femmesh_groupdata_sets_by_name( if grp_name.startswith(obj.Name + "_"): if femmesh.getGroupElementType(g) == group_data_type: FreeCAD.Console.PrintMessage( - " found mesh group for the IDs: {}, Type: {}\n" - .format(grp_name, group_data_type) + " found mesh group for the IDs: {}, Type: {}\n".format( + grp_name, group_data_type + ) ) return femmesh.getGroupElements(g) # == ref_shape_femelements return () # an empty tuple is returned if no group data IDs where found # ************************************************************************************************ -def get_femelement_sets_from_group_data( - femmesh, - fem_objects -): +def get_femelement_sets_from_group_data(femmesh, fem_objects): # get femelements from femmesh groupdata for reference shapes of each obj.References count_femelements = 0 sum_group_elements = [] @@ -744,8 +620,7 @@ def get_femelement_sets_from_group_data( obj = fem_object["Object"] FreeCAD.Console.PrintMessage( "Constraint: {} --> We have mesh groups. " - "We will search for appropriate group data.\n" - .format(obj.Name) + "We will search for appropriate group data.\n".format(obj.Name) ) # unique short identifier fem_object["ShortName"] = get_elset_short_name(obj, fem_object_i) @@ -757,8 +632,7 @@ def get_femelement_sets_from_group_data( # check if all worked out well if not femelements_count_ok(femmesh.VolumeCount, count_femelements): FreeCAD.Console.PrintError( - "Error in get_femelement_sets_from_group_data -- > " - "femelements_count_ok() failed!\n" + "Error in get_femelement_sets_from_group_data -- > femelements_count_ok() failed!\n" ) return False else: @@ -766,12 +640,10 @@ def get_femelement_sets_from_group_data( # ************************************************************************************************ -def get_elset_short_name( - obj, - i -): +def get_elset_short_name(obj, i): # ATM for CalculiX needed for all objects which will write element sets into solver input file from femtools.femutils import is_of_type + if is_of_type(obj, "Fem::MaterialCommon"): return "M" + str(i) elif is_of_type(obj, "Fem::ElementGeometry1D"): @@ -789,18 +661,14 @@ def get_elset_short_name( else: FreeCAD.Console.PrintError( "Error in creating short elset name " - "for obj: {} --> Proxy.Type: {}\n" - .format(obj.Name, obj.Proxy.Type) + "for obj: {} --> Proxy.Type: {}\n".format(obj.Name, obj.Proxy.Type) ) # ************************************************************************************************ # ***** methods for retrieving nodes and node load values for constraint force ******************* # ***** Vertex loads ***************************************************************************** -def get_force_obj_vertex_nodeload_table( - femmesh, - frc_obj -): +def get_force_obj_vertex_nodeload_table(femmesh, frc_obj): # force_obj_node_load_table: # [ # ("refshape_name.elemname", node_load_table), @@ -816,11 +684,10 @@ def get_force_obj_vertex_nodeload_table( ref_node = o.Shape.getElement(elem) FreeCAD.Console.PrintMessage( " " - "ReferenceShape ... Type: {0}, " - "Object name: {1}, " - "Object label: {2}, " - "Element name: {3}\n" - .format(ref_node.ShapeType, o.Name, o.Label, elem) + "ReferenceShape ... Type: {}, " + "Object name: {}, " + "Object label: {}, " + "Element name: {}\n".format(ref_node.ShapeType, o.Name, o.Label, elem) ) node = femmesh.getNodesByVertex(ref_node) elem_info_string = "node load on shape: " + o.Name + ":" + elem @@ -830,8 +697,7 @@ def get_force_obj_vertex_nodeload_table( ) else: FreeCAD.Console.PrintError( - " Problem on retrieving mesh node for: {}\n" - .format(elem_info_string) + f" Problem on retrieving mesh node for: {elem_info_string}\n" ) return force_obj_node_load_table @@ -840,12 +706,7 @@ def get_force_obj_vertex_nodeload_table( # get_force_obj_edge_nodeload_table # get_ref_edgenodes_table # get_ref_edgenodes_lengths -def get_force_obj_edge_nodeload_table( - femmesh, - femelement_table, - femnodes_mesh, - frc_obj -): +def get_force_obj_edge_nodeload_table(femmesh, femelement_table, femnodes_mesh, frc_obj): # force_obj_node_load_table: # [ # ("refshape_name.elemname", node_load_table), @@ -861,11 +722,10 @@ def get_force_obj_edge_nodeload_table( ref_edge = o.Shape.getElement(elem) FreeCAD.Console.PrintMessage( " " - "ReferenceShape ... Type: {0}, " - "Object name: {1}, " - "Object label: {2}, " - "Element name: {3}\n" - .format(ref_edge.ShapeType, o.Name, o.Label, elem) + "ReferenceShape ... Type: {}, " + "Object name: {}, " + "Object label: {}, " + "Element name: {}\n".format(ref_edge.ShapeType, o.Name, o.Label, elem) ) sum_ref_edge_length += ref_edge.Length if sum_ref_edge_length != 0: @@ -902,8 +762,8 @@ def get_force_obj_edge_nodeload_table( FreeCAD.Console.PrintError( "Error on: " + frc_obj.Name + " --> " + o.Name + "." + elem + "\n" ) - FreeCAD.Console.PrintMessage(" sum_node_lengths: {}\n".format(sum_node_lengths)) - FreeCAD.Console.PrintMessage(" refedge_length: {}\n".format(ref_edge.Length)) + FreeCAD.Console.PrintMessage(f" sum_node_lengths: {sum_node_lengths}\n") + FreeCAD.Console.PrintMessage(f" refedge_length: {ref_edge.Length}\n") bad_refedge = ref_edge sum_ref_edge_node_length += sum_node_lengths @@ -918,42 +778,28 @@ def get_force_obj_edge_nodeload_table( ratio = sum_node_load / force_quantity if ratio < 0.99 or ratio > 1.01: FreeCAD.Console.PrintMessage( - "Deviation sum_node_load to frc_obj.Force is more than 1% : {}\n" - .format(ratio) - ) - FreeCAD.Console.PrintMessage( - " sum_ref_edge_node_length: {}\n" - .format(sum_ref_edge_node_length) - ) - FreeCAD.Console.PrintMessage( - " sum_ref_edge_length: {}\n" - .format(sum_ref_edge_length) - ) - FreeCAD.Console.PrintMessage( - " sum_node_load: {}\n" - .format(sum_node_load) - ) - FreeCAD.Console.PrintMessage( - " frc_obj.Force: {}\n" - .format(force_quantity) + f"Deviation sum_node_load to frc_obj.Force is more than 1% : {ratio}\n" ) + FreeCAD.Console.PrintMessage(f" sum_ref_edge_node_length: {sum_ref_edge_node_length}\n") + FreeCAD.Console.PrintMessage(f" sum_ref_edge_length: {sum_ref_edge_length}\n") + FreeCAD.Console.PrintMessage(f" sum_node_load: {sum_node_load}\n") + FreeCAD.Console.PrintMessage(f" frc_obj.Force: {force_quantity}\n") FreeCAD.Console.PrintMessage( " the reason could be simply a circle length --> " "see method get_ref_edge_node_lengths\n" ) FreeCAD.Console.PrintMessage( - " the reason could also be a problem in " - "retrieving the ref_edge_node_length\n" + " the reason could also be a problem in retrieving the ref_edge_node_length\n" ) # try debugging of the last bad refedge FreeCAD.Console.PrintMessage("DEBUGGING\n") - FreeCAD.Console.PrintMessage("{}\n".format(bad_refedge)) + FreeCAD.Console.PrintMessage(f"{bad_refedge}\n") FreeCAD.Console.PrintMessage("bad_refedge_nodes\n") bad_refedge_nodes = femmesh.getNodesByEdge(bad_refedge) - FreeCAD.Console.PrintMessage("{}\n".format(len(bad_refedge_nodes))) - FreeCAD.Console.PrintMessage("{}\n".format(bad_refedge_nodes)) + FreeCAD.Console.PrintMessage(f"{len(bad_refedge_nodes)}\n") + FreeCAD.Console.PrintMessage(f"{bad_refedge_nodes}\n") # import FreeCADGui # frc_obj.Document.Compound_Mesh.HighlightedNodes = bad_refedge_nodes @@ -961,16 +807,16 @@ def get_force_obj_edge_nodeload_table( # bad_edge_table: # { meshedgeID : ( nodeID, ... , nodeID ) } bad_edge_table = get_ref_edgenodes_table(femmesh, femelement_table, bad_refedge) - FreeCAD.Console.PrintMessage("{}\n".format(len(bad_edge_table))) + FreeCAD.Console.PrintMessage(f"{len(bad_edge_table)}\n") bad_edge_table_nodes = [] for elem in bad_edge_table: - FreeCAD.Console.PrintMessage(elem, " --> {}\n".format(bad_edge_table[elem])) + FreeCAD.Console.PrintMessage(elem, f" --> {bad_edge_table[elem]}\n") for node in bad_edge_table[elem]: if node not in bad_edge_table_nodes: bad_edge_table_nodes.append(node) FreeCAD.Console.PrintMessage("sorted(bad_edge_table_nodes)\n") # should be == bad_refedge_nodes - FreeCAD.Console.PrintMessage("{}\n".format(sorted(bad_edge_table_nodes))) + FreeCAD.Console.PrintMessage(f"{sorted(bad_edge_table_nodes)}\n") # import FreeCADGui # frc_obj.Document.Compound_Mesh.HighlightedNodes = bad_edge_table_nodes # bad_node_length_table: @@ -980,22 +826,18 @@ def get_force_obj_edge_nodeload_table( FreeCAD.Console.PrintMessage("good_edge_table\n") good_edge_table = delete_duplicate_mesh_elements(bad_edge_table) for elem in good_edge_table: - FreeCAD.Console.PrintMessage("{} --> {}\n".format(elem, bad_edge_table[elem])) + FreeCAD.Console.PrintMessage(f"{elem} --> {bad_edge_table[elem]}\n") FreeCAD.Console.PrintMessage("bad_node_length_table\n") bad_node_length_table = get_ref_edgenodes_lengths(femnodes_mesh, bad_edge_table) for n, l in bad_node_length_table: - FreeCAD.Console.PrintMessage("{} --> {}\n".format(n, l)) + FreeCAD.Console.PrintMessage(f"{n} --> {l}\n") return force_obj_node_load_table # ************************************************************************************************ -def get_ref_edgenodes_table( - femmesh, - femelement_table, - refedge -): +def get_ref_edgenodes_table(femmesh, femelement_table, refedge): edge_table = {} # { meshedgeID : ( nodeID, ... , nodeID ) } refedge_nodes = femmesh.getNodesByEdge(refedge) if is_solid_femmesh(femmesh): @@ -1045,10 +887,7 @@ def get_ref_edgenodes_table( # the user should decide on which edge the load is applied edge_table = delete_duplicate_mesh_elements(edge_table) elif is_edge_femmesh(femmesh): - refedge_fem_edgeelements = get_femelements_by_femnodes_std( - femelement_table, - refedge_nodes - ) + refedge_fem_edgeelements = get_femelements_by_femnodes_std(femelement_table, refedge_nodes) for elem in refedge_fem_edgeelements: # { edgeID : ( nodeID, ... , nodeID )} # all nodes off this femedgeelement edge_table[elem] = femelement_table[elem] @@ -1056,10 +895,7 @@ def get_ref_edgenodes_table( # ************************************************************************************************ -def get_ref_edgenodes_lengths( - femnodes_mesh, - edge_table -): +def get_ref_edgenodes_lengths(femnodes_mesh, edge_table): # calculate the appropriate node_length for every node of every mesh edge (me) # G. Lakshmi Narasaiah, Finite Element Analysis, p206ff @@ -1067,8 +903,7 @@ def get_ref_edgenodes_lengths( # some nodes will have more than one entry if (not femnodes_mesh) or (not edge_table): FreeCAD.Console.PrintError( - "Error in get_ref_edgenodes_lengths(): " - "Empty femnodes_mesh or edge_table!\n" + "Error in get_ref_edgenodes_lengths(): Empty femnodes_mesh or edge_table!\n" ) return [] node_length_table = [] @@ -1114,12 +949,7 @@ def get_ref_edgenodes_lengths( # get_ref_facenodes_table # get_ref_facenodes_areas # build_mesh_faces_of_volume_elements -def get_force_obj_face_nodeload_table( - femmesh, - femelement_table, - femnodes_mesh, - frc_obj -): +def get_force_obj_face_nodeload_table(femmesh, femelement_table, femnodes_mesh, frc_obj): # force_obj_node_load_table: # [ # ("refshape_name.elemname",node_load_table), @@ -1135,11 +965,10 @@ def get_force_obj_face_nodeload_table( ref_face = sub_shape_at_global_placement(o, elem) FreeCAD.Console.PrintMessage( " " - "ReferenceShape ... Type: {0}, " - "Object name: {1}, " - "Object label: {2}, " - "Element name: {3}\n" - .format(ref_face.ShapeType, o.Name, o.Label, elem) + "ReferenceShape ... Type: {}, " + "Object name: {}, " + "Object label: {}, " + "Element name: {}\n".format(ref_face.ShapeType, o.Name, o.Label, elem) ) sum_ref_face_area += ref_face.Area if sum_ref_face_area != 0: @@ -1176,8 +1005,8 @@ def get_force_obj_face_nodeload_table( FreeCAD.Console.PrintError( "Error on: " + frc_obj.Name + " --> " + o.Name + "." + elem + "\n" ) - FreeCAD.Console.PrintMessage(" sum_node_areas: {}\n".format(sum_node_areas)) - FreeCAD.Console.PrintMessage(" ref_face_area: {}\n".format(ref_face.Area)) + FreeCAD.Console.PrintMessage(f" sum_node_areas: {sum_node_areas}\n") + FreeCAD.Console.PrintMessage(f" ref_face_area: {ref_face.Area}\n") sum_ref_face_node_area += sum_node_areas elem_info_string = "node loads on shape: " + o.Name + ":" + elem @@ -1191,43 +1020,24 @@ def get_force_obj_face_nodeload_table( ratio = sum_node_load / force_quantity if ratio < 0.99 or ratio > 1.01: FreeCAD.Console.PrintMessage( - "Deviation sum_node_load to frc_obj.Force is more than 1% : {}\n" - .format(ratio) + f"Deviation sum_node_load to frc_obj.Force is more than 1% : {ratio}\n" + ) + FreeCAD.Console.PrintMessage(f" sum_ref_face_node_area: {sum_ref_face_node_area}\n") + FreeCAD.Console.PrintMessage(f" sum_ref_face_area: {sum_ref_face_area}\n") + FreeCAD.Console.PrintMessage(f" sum_node_load: {sum_node_load}\n") + FreeCAD.Console.PrintMessage(f" frc_obj.Force: {force_quantity}\n") + FreeCAD.Console.PrintMessage( + " the reason could be simply a circle area --> see method get_ref_face_node_areas\n" ) FreeCAD.Console.PrintMessage( - " sum_ref_face_node_area: {}\n" - .format(sum_ref_face_node_area) - ) - FreeCAD.Console.PrintMessage( - " sum_ref_face_area: {}\n" - .format(sum_ref_face_area) - ) - FreeCAD.Console.PrintMessage( - " sum_node_load: {}\n" - .format(sum_node_load) - ) - FreeCAD.Console.PrintMessage( - " frc_obj.Force: {}\n" - .format(force_quantity) - ) - FreeCAD.Console.PrintMessage( - " the reason could be simply a circle area --> " - "see method get_ref_face_node_areas\n" - ) - FreeCAD.Console.PrintMessage( - " the reason could also be a problem in " - "retrieving the ref_face_node_area\n" + " the reason could also be a problem in retrieving the ref_face_node_area\n" ) return force_obj_node_load_table # ************************************************************************************************ -def get_ref_facenodes_table( - femmesh, - femelement_table, - ref_face -): +def get_ref_facenodes_table(femmesh, femelement_table, ref_face): face_table = {} # { meshfaceID : ( nodeID, ... , nodeID ) } if is_solid_femmesh(femmesh): if has_no_face_data(femmesh): @@ -1268,8 +1078,7 @@ def get_ref_facenodes_table( ) # list of integer [mv] ref_face_volume_elements = get_femvolumeelements_by_femfacenodes( - femelement_table, - ref_face_nodes + femelement_table, ref_face_nodes ) for veID in ref_face_volume_elements: ve_ref_face_nodes = [] @@ -1281,7 +1090,7 @@ def get_ref_facenodes_table( # we need to resort the nodes to make them build an element face face_table = build_mesh_faces_of_volume_elements(face_table, femelement_table) else: # the femmesh has face_data - faces = femmesh.getFacesByFace(ref_face) # (mv, mf) + faces = femmesh.getFacesByFace(ref_face) # (mv, mf) for mf in faces: face_table[mf] = femmesh.getElementNodes(mf) elif is_face_femmesh(femmesh): @@ -1294,10 +1103,7 @@ def get_ref_facenodes_table( # ************************************************************************************************ -def get_ref_facenodes_areas( - femnodes_mesh, - face_table -): +def get_ref_facenodes_areas(femnodes_mesh, face_table): # calculate the appropriate node_areas for every node of every mesh face (mf) # G. Lakshmi Narasaiah, Finite Element Analysis, p206ff # FIXME: only gives exact results in case of a real triangle. If for S6 or C3D10 elements @@ -1382,10 +1188,7 @@ def get_ref_facenodes_areas( mesh_face_t3_area = get_triangle_area(P3, P6, P5) mesh_face_t4_area = get_triangle_area(P4, P5, P6) mesh_face_area = ( - mesh_face_t1_area - + mesh_face_t2_area - + mesh_face_t3_area - + mesh_face_t4_area + mesh_face_t1_area + mesh_face_t2_area + mesh_face_t3_area + mesh_face_t4_area ) middle_node_area = mesh_face_area / 3.0 @@ -1448,10 +1251,7 @@ def get_ref_facenodes_areas( # ************************************************************************************************ -def build_mesh_faces_of_volume_elements( - face_table, - femelement_table -): +def build_mesh_faces_of_volume_elements(face_table, femelement_table): # node index of facenodes in femelementtable volume element # if we know the position of the node # we can build the element face out of the unsorted face nodes @@ -1463,13 +1263,13 @@ def build_mesh_faces_of_volume_elements( # FreeCAD.Console.PrintMessage("{}\n".format(index)) # local node number = index + 1 face_nodenumber_table[veID].append(index + 1) - FreeCAD.Console.PrintLog("VolElement: {}\n".format(veID)) - FreeCAD.Console.PrintLog(" --> {}\n".format(femelement_table[veID])) - FreeCAD.Console.PrintLog(" --> {}\n".format(face_table[veID])) - FreeCAD.Console.PrintLog(" --> {}\n".format(face_nodenumber_table[veID])) + FreeCAD.Console.PrintLog(f"VolElement: {veID}\n") + FreeCAD.Console.PrintLog(f" --> {femelement_table[veID]}\n") + FreeCAD.Console.PrintLog(f" --> {face_table[veID]}\n") + FreeCAD.Console.PrintLog(f" --> {face_nodenumber_table[veID]}\n") for veID in face_nodenumber_table: - FreeCAD.Console.PrintLog("VolElement: {}\n".format(veID)) + FreeCAD.Console.PrintLog(f"VolElement: {veID}\n") vol_node_ct = len(femelement_table[veID]) face_node_indexs = sorted(face_nodenumber_table[veID]) node_numbers = () @@ -1488,8 +1288,7 @@ def build_mesh_faces_of_volume_elements( else: FreeCAD.Console.PrintError( "Error in build_mesh_faces_of_volume_elements(): " - "tetra10: face not found! {}\n" - .format(face_node_indexs) + "tetra10: face not found! {}\n".format(face_node_indexs) ) elif vol_node_ct == 4: FreeCAD.Console.PrintLog(" --> tetra4 --> tria3 face\n") @@ -1506,8 +1305,7 @@ def build_mesh_faces_of_volume_elements( else: FreeCAD.Console.PrintError( "Error in build_mesh_faces_of_volume_elements(): " - "tetra4: face not found! {}\n" - .format(face_node_indexs) + "tetra4: face not found! {}\n".format(face_node_indexs) ) elif vol_node_ct == 20: FreeCAD.Console.PrintLog(" --> hexa20 --> quad8 face\n") @@ -1528,8 +1326,7 @@ def build_mesh_faces_of_volume_elements( else: FreeCAD.Console.PrintError( "Error in build_mesh_faces_of_volume_elements(): " - "hexa20: face not found! {}\n" - .format(face_node_indexs) + "hexa20: face not found! {}\n".format(face_node_indexs) ) elif vol_node_ct == 8: FreeCAD.Console.PrintLog(" --> hexa8 --> quad4 face\n") @@ -1550,8 +1347,7 @@ def build_mesh_faces_of_volume_elements( else: FreeCAD.Console.PrintError( "Error in build_mesh_faces_of_volume_elements(): " - "hexa8: face not found! {}\n" - .format(face_node_indexs) + "hexa8: face not found! {}\n".format(face_node_indexs) ) elif vol_node_ct == 15: FreeCAD.Console.PrintLog(" --> penta15 --> tria6 and quad8 faces\n") @@ -1570,8 +1366,7 @@ def build_mesh_faces_of_volume_elements( else: FreeCAD.Console.PrintError( "Error in build_mesh_faces_of_volume_elements(): " - "penta15: face not found! {}\n" - .format(face_node_indexs) + "penta15: face not found! {}\n".format(face_node_indexs) ) elif vol_node_ct == 6: FreeCAD.Console.PrintLog(" --> penta6 --> tria3 and quad4 faces\n") @@ -1590,14 +1385,12 @@ def build_mesh_faces_of_volume_elements( else: FreeCAD.Console.PrintError( "Error in build_mesh_faces_of_volume_elements(): " - "penta6: face not found! {}\n" - .format(face_node_indexs) + "penta6: face not found! {}\n".format(face_node_indexs) ) else: FreeCAD.Console.PrintError( "Error in build_mesh_faces_of_volume_elements(): " - "Volume not implemented: volume node count {}\n" - .format(vol_node_ct) + "Volume not implemented: volume node count {}\n".format(vol_node_ct) ) face_nodes = [] for i in node_numbers: @@ -1607,14 +1400,12 @@ def build_mesh_faces_of_volume_elements( i -= 1 face_nodes.append(femelement_table[veID][i]) face_table[veID] = face_nodes # reset the entry in face_table - FreeCAD.Console.PrintLog(" --> {}\n".format(face_table[veID])) + FreeCAD.Console.PrintLog(f" --> {face_table[veID]}\n") return face_table # ***** helper for Face and Edge loads *********************************************************** -def get_ref_shape_node_sum_geom_table( - node_geom_table -): +def get_ref_shape_node_sum_geom_table(node_geom_table): # shape could be Edge or Face, geom could be length or area # sum of length or area for each node of the ref_shape node_sum_geom_table = {} @@ -1630,12 +1421,7 @@ def get_ref_shape_node_sum_geom_table( # ************************************************************************************************ # ***** methods for retrieving element face sets ************************************************* # ***** pressure faces *************************************************************************** -def get_pressure_obj_faces( - femmesh, - femelement_table, - femnodes_ele_table, - femobj -): +def get_pressure_obj_faces(femmesh, femelement_table, femnodes_ele_table, femobj): # see get_ccxelement_faces_from_binary_search for more information if is_solid_femmesh(femmesh): # get the nodes @@ -1644,9 +1430,7 @@ def get_pressure_obj_faces( # FreeCAD.Console.PrintMessage("prs_face_node_set: {}\n".format(prs_face_node_set)) # fill the bit_pattern_dict and search for the faces bit_pattern_dict = get_bit_pattern_dict( - femelement_table, - femnodes_ele_table, - prs_face_node_set + femelement_table, femnodes_ele_table, prs_face_node_set ) pressure_faces = get_ccxelement_faces_from_binary_search(bit_pattern_dict) elif is_face_femmesh(femmesh): @@ -1680,35 +1464,26 @@ def get_pressure_obj_faces( return pressure_faces + # ***** deprecated method for retrieving pressure faces ***************************************** # for constraint pressure and finite solid element mesh # it was switched to the method get_ccxelement_faces_from_binary_search # because of performance and the support of all solid elements # see get_ccxelement_faces_from_binary_search for more information -def get_pressure_obj_faces_depreciated( - femmesh, - femobj -): +def get_pressure_obj_faces_depreciated(femmesh, femobj): pressure_faces = [] for o, elem_tup in femobj["Object"].References: for elem in elem_tup: ref_shape = o.Shape.getElement(elem) elem_info_string = "face load on shape: " + o.Name + ":" + elem - FreeCAD.Console.PrintMessage("{}\n".format(elem_info_string)) + FreeCAD.Console.PrintMessage(f"{elem_info_string}\n") if ref_shape.ShapeType == "Face": - pressure_faces.append( - (elem_info_string, femmesh.getccxVolumesByFace(ref_shape)) - ) + pressure_faces.append((elem_info_string, femmesh.getccxVolumesByFace(ref_shape))) return pressure_faces # ***** contact faces **************************************************************************** -def get_contact_obj_faces( - femmesh, - femelement_table, - femnodes_ele_table, - femobj -): +def get_contact_obj_faces(femmesh, femelement_table, femnodes_ele_table, femobj): # see comment on get_pressure_obj_faces_depreciated in the regard of getccxVolumesByFace() # sets are needed for each of the references separated @@ -1752,26 +1527,22 @@ def get_contact_obj_faces( ) return [[], []] - FreeCAD.Console.PrintLog(" Slave: {}, {}\n".format(slave_ref[0].Name, slave_ref)) - FreeCAD.Console.PrintLog(" Master: {}, {}\n".format(master_ref[0].Name, master_ref)) + FreeCAD.Console.PrintLog(f" Slave: {slave_ref[0].Name}, {slave_ref}\n") + FreeCAD.Console.PrintLog(f" Master: {master_ref[0].Name}, {master_ref}\n") if is_solid_femmesh(femmesh): FreeCAD.Console.PrintLog(" Get the nodes, sorted and duplicates removed.\n") slaveface_nds = sorted(list(set(get_femnodes_by_refshape(femmesh, slave_ref)))) masterface_nds = sorted(list(set(get_femnodes_by_refshape(femmesh, master_ref)))) - FreeCAD.Console.PrintLog(" slaveface_nds: {}\n".format(slaveface_nds)) - FreeCAD.Console.PrintLog(" masterface_nds: {}\n".format(slaveface_nds)) + FreeCAD.Console.PrintLog(f" slaveface_nds: {slaveface_nds}\n") + FreeCAD.Console.PrintLog(f" masterface_nds: {slaveface_nds}\n") FreeCAD.Console.PrintLog(" Fill the bit_pattern_dict and search for the faces.\n") slave_bit_pattern_dict = get_bit_pattern_dict( - femelement_table, - femnodes_ele_table, - slaveface_nds + femelement_table, femnodes_ele_table, slaveface_nds ) master_bit_pattern_dict = get_bit_pattern_dict( - femelement_table, - femnodes_ele_table, - masterface_nds + femelement_table, femnodes_ele_table, masterface_nds ) FreeCAD.Console.PrintLog(" Get the FaceIDs.\n") @@ -1795,8 +1566,8 @@ def get_contact_obj_faces( master_faces.append([fid, 2]) FreeCAD.Console.PrintLog(" Master and slave face ready to use for writer:\n") - FreeCAD.Console.PrintLog(" slave_faces: {}\n".format(slave_faces)) - FreeCAD.Console.PrintLog(" master_faces: {}\n".format(master_faces)) + FreeCAD.Console.PrintLog(f" slave_faces: {slave_faces}\n") + FreeCAD.Console.PrintLog(f" master_faces: {master_faces}\n") if len(slave_faces) == 0: FreeCAD.Console.PrintError("No faces found for contact slave face.\n") if len(master_faces) == 0: @@ -1805,12 +1576,7 @@ def get_contact_obj_faces( # ***** tie faces **************************************************************************** -def get_tie_obj_faces( - femmesh, - femelement_table, - femnodes_ele_table, - femobj -): +def get_tie_obj_faces(femmesh, femelement_table, femnodes_ele_table, femobj): # see comment get_contact_obj_faces # solid mesh is same as contact, but face mesh is not allowed for tie # TODO get rid of duplicate code for contact and tie @@ -1844,8 +1610,8 @@ def get_tie_obj_faces( ) return [[], []] - FreeCAD.Console.PrintLog("Slave: {}, {}\n".format(slave_ref[0].Name, slave_ref)) - FreeCAD.Console.PrintLog("Master: {}, {}\n".format(master_ref[0].Name, master_ref)) + FreeCAD.Console.PrintLog(f"Slave: {slave_ref[0].Name}, {slave_ref}\n") + FreeCAD.Console.PrintLog(f"Master: {master_ref[0].Name}, {master_ref}\n") if is_solid_femmesh(femmesh): # get the nodes, sorted and duplicates removed @@ -1856,14 +1622,10 @@ def get_tie_obj_faces( # fill the bit_pattern_dict and search for the faces slave_bit_pattern_dict = get_bit_pattern_dict( - femelement_table, - femnodes_ele_table, - slaveface_nds + femelement_table, femnodes_ele_table, slaveface_nds ) master_bit_pattern_dict = get_bit_pattern_dict( - femelement_table, - femnodes_ele_table, - masterface_nds + femelement_table, femnodes_ele_table, masterface_nds ) # get the faces ids @@ -1871,24 +1633,19 @@ def get_tie_obj_faces( master_faces = get_ccxelement_faces_from_binary_search(master_bit_pattern_dict) elif is_face_femmesh(femmesh): - FreeCAD.Console.PrintError( - "Shell mesh is not allowed for constraint tie.\n" - ) + FreeCAD.Console.PrintError("Shell mesh is not allowed for constraint tie.\n") - FreeCAD.Console.PrintLog("slave_faces: {}\n".format(slave_faces)) - FreeCAD.Console.PrintLog("master_faces: {}\n".format(master_faces)) + FreeCAD.Console.PrintLog(f"slave_faces: {slave_faces}\n") + FreeCAD.Console.PrintLog(f"master_faces: {master_faces}\n") return [slave_faces, master_faces] # ************************************************************************************************ # ***** groups *********************************************************************************** -def get_mesh_group_elements( - mesh_group_obj, - aPart -): +def get_mesh_group_elements(mesh_group_obj, aPart): """the Reference shapes of the mesh_group_object are searched in the Shape of aPart. - If found in shape they are added to a dict - {MeshGroupIdentifier : ["ShapeType of the Elements"], [ElementID, ElementID, ...], ...} + If found in shape they are added to a dict + {MeshGroupIdentifier : ["ShapeType of the Elements"], [ElementID, ElementID, ...], ...} """ group_elements = {} # { name : [element, element, ... , element]} if mesh_group_obj.References: @@ -1896,23 +1653,22 @@ def get_mesh_group_elements( group_elements[grp_ele[0]] = grp_ele[1] else: FreeCAD.Console.PrintError( - " Empty reference in mesh group object: {} {}\n" - .format(mesh_group_obj.Name, mesh_group_obj.Label) + " Empty reference in mesh group object: {} {}\n".format( + mesh_group_obj.Name, mesh_group_obj.Label + ) ) return group_elements # ************************************************************************************************ -def get_analysis_group_elements( - aAnalysis, - aPart -): +def get_analysis_group_elements(aAnalysis, aPart): """ all Reference shapes of all Analysis member are searched in the Shape of aPart. If found in shape they are added to a dict {ConstraintName : ["ShapeType of the Elements"], [ElementID, ElementID, ...], ...} """ from femtools.femutils import is_of_type + group_elements = {} # { name : [element, element, ... , element]} empty_references = [] # find the objects with empty references, if there are more than one of this type @@ -1927,37 +1683,28 @@ def get_analysis_group_elements( if len(m.References) > 0: grp_ele = get_reference_group_elements(m, aPart) group_elements[grp_ele[0]] = grp_ele[1] - elif ( - len(m.References) == 0 - and ( - is_of_type(m, "Fem::MaterialCommon") - # TODO test and implement ElementGeometry1D and ElementGeometry2D - # or is_of_type(m, "Fem::ElementGeometry1D") - # or is_of_type(m, "Fem::ElementGeometry2D") - ) + elif len(m.References) == 0 and ( + is_of_type(m, "Fem::MaterialCommon") + # TODO test and implement ElementGeometry1D and ElementGeometry2D + # or is_of_type(m, "Fem::ElementGeometry1D") + # or is_of_type(m, "Fem::ElementGeometry2D") ): - FreeCAD.Console.PrintMessage(" Empty reference: {}\n".format(m.Name)) + FreeCAD.Console.PrintMessage(f" Empty reference: {m.Name}\n") empty_references.append(m) if empty_references: if len(empty_references) == 1: group_elements = get_anlysis_empty_references_group_elements( - group_elements, - aAnalysis, - aPart.Shape + group_elements, aAnalysis, aPart.Shape ) else: - FreeCAD.Console.PrintError( - "Problem: more than one object with empty references.\n" - ) + FreeCAD.Console.PrintError("Problem: more than one object with empty references.\n") FreeCAD.Console.PrintMessage( "We are going to try to get the empty material references anyway.\n" ) for er in empty_references: - FreeCAD.Console.PrintMessage("{}\n".format(er.Name)) + FreeCAD.Console.PrintMessage(f"{er.Name}\n") group_elements = get_anlysis_empty_references_group_elements( - group_elements, - aAnalysis, - aPart.Shape + group_elements, aAnalysis, aPart.Shape ) # check if all groups have at least one element, # it doesn"t mean ALL reference shapes for a group have been found @@ -1966,18 +1713,14 @@ def get_analysis_group_elements( if len(group_elements[g]) == 0: FreeCAD.Console.PrintError( "Error: The shapes for the mesh group for the reference " - "shapes of analysis member: {} could not be found!\n" - .format(g) + "shapes of analysis member: {} could not be found!\n".format(g) ) return group_elements # ************************************************************************************************ -def get_reference_group_elements( - obj, - aPart -): - """ obj is an FEM object which has reference shapes like the group object +def get_reference_group_elements(obj, aPart): + """obj is an FEM object which has reference shapes like the group object the material, most of the constraints aPart is geometry feature normally CompSolid the method searches all reference shapes of obj inside aPart even if @@ -2008,15 +1751,14 @@ def get_reference_group_elements( # FreeCAD.Console.PrintMessage("{}\n".format(childs)) for child in childs: ref_shape = parent.getSubObject(child) - FreeCAD.Console.PrintLog("{}\n".format(ref_shape)) + FreeCAD.Console.PrintLog(f"{ref_shape}\n") found_element = geomtools.find_element_in_shape(aShape, ref_shape) if found_element is not None: elements.append(found_element) else: FreeCAD.Console.PrintError( "Problem: For the geometry of the " - "following shape was no Shape found: {}\n" - .format(ref_shape) + "following shape was no Shape found: {}\n".format(ref_shape) ) FreeCAD.Console.PrintMessage(" " + obj.Name + "\n") FreeCAD.Console.PrintMessage(" " + str(obj.References) + "\n") @@ -2024,18 +1766,15 @@ def get_reference_group_elements( if parent.Name != aPart.Name: FreeCAD.Console.PrintError( "The reference Shape is not a child " - "nor it is the shape the mesh is made of. : {}\n" - .format(ref_shape) + "nor it is the shape the mesh is made of. : {}\n".format(ref_shape) ) FreeCAD.Console.PrintMessage( - "{}--> Name of the Feature we where searching in.\n" - .format(aPart.Name) + f"{aPart.Name}--> Name of the Feature we where searching in.\n" ) FreeCAD.Console.PrintMessage( "{} --> Name of the parent Feature of reference Shape " "(Use the same as in the line before and you " - "will have less trouble :-) !!!!!!).\n" - .format(parent.Name) + "will have less trouble :-) !!!!!!).\n".format(parent.Name) ) # import Part # Part.show(aShape) @@ -2050,11 +1789,7 @@ def get_reference_group_elements( # ************************************************************************************************ -def get_anlysis_empty_references_group_elements( - group_elements, - aAnalysis, - aShape -): +def get_anlysis_empty_references_group_elements(group_elements, aAnalysis, aShape): """ get the elementIDs if the Reference shape is empty see get_analysis_group_elements() for more information @@ -2121,31 +1856,22 @@ def get_anlysis_empty_references_group_elements( # ************************************************************************************************ -def femelements_count_ok( - len_femelement_table, - count_femelements -): +def femelements_count_ok(len_femelement_table, count_femelements): FreeCAD.Console.PrintMessage( - "Count finite elements as sum of constraints: {}\n" - .format(count_femelements) + f"Count finite elements as sum of constraints: {count_femelements}\n" ) FreeCAD.Console.PrintMessage( - "Count finite elements of the finite element mesh: {}\n" - .format(len_femelement_table) + f"Count finite elements of the finite element mesh: {len_femelement_table}\n" ) if count_femelements == len_femelement_table: return True else: - FreeCAD.Console.PrintMessage( - "ERROR: femelement_table != count_femelements\n" - ) + FreeCAD.Console.PrintMessage("ERROR: femelement_table != count_femelements\n") return False # ************************************************************************************************ -def delete_duplicate_mesh_elements( - refelement_table -): +def delete_duplicate_mesh_elements(refelement_table): new_refelement_table = {} # duplicates deleted for elem, nodes in refelement_table.items(): if sorted(nodes) not in sortlistoflistvalues(new_refelement_table.values()): @@ -2154,11 +1880,7 @@ def delete_duplicate_mesh_elements( # ************************************************************************************************ -def get_triangle_area( - P1, - P2, - P3 -): +def get_triangle_area(P1, P2, P3): # import Part # W = Part.Wire([Part.makeLine(P1,P2), Part.makeLine(P2,P3), Part.makeLine(P3,P1)]) # Part.show(Part.Face(W)) @@ -2169,9 +1891,7 @@ def get_triangle_area( # ************************************************************************************************ -def sortlistoflistvalues( - listoflists -): +def sortlistoflistvalues(listoflists): new_list = [] for li in listoflists: new_list.append(sorted(li)) @@ -2179,45 +1899,35 @@ def sortlistoflistvalues( # ************************************************************************************************ -def is_solid_femmesh( - femmesh -): +def is_solid_femmesh(femmesh): # solid femmesh if femmesh.VolumeCount > 0: return True # ************************************************************************************************ -def has_no_face_data( - femmesh -): +def has_no_face_data(femmesh): # femmesh has no face data, could be a edge femmesh or a solid femmesh without face data if femmesh.FaceCount == 0: return True # ************************************************************************************************ -def is_face_femmesh( - femmesh -): +def is_face_femmesh(femmesh): # face femmesh if femmesh.VolumeCount == 0 and femmesh.FaceCount > 0: return True # ************************************************************************************************ -def is_edge_femmesh( - femmesh -): +def is_edge_femmesh(femmesh): # edge femmesh if femmesh.VolumeCount == 0 and femmesh.FaceCount == 0 and femmesh.EdgeCount > 0: return True # ************************************************************************************************ -def is_zplane_2D_mesh( - femmesh -): +def is_zplane_2D_mesh(femmesh): # used in oofem writer to distinguish between 3D and 2D plane stress if is_face_femmesh(femmesh) is True: tol = 0.0001 @@ -2231,10 +1941,7 @@ def is_zplane_2D_mesh( # ************************************************************************************************ -def get_femmesh_eletype( - femmesh, - femelement_table=None -): +def get_femmesh_eletype(femmesh, femelement_table=None): if not femmesh: FreeCAD.Console.PrintError("Error: No femmesh.\n") if not femelement_table: @@ -2243,7 +1950,7 @@ def get_femmesh_eletype( # in some cases lowest key in femelement_table is not [1] for elem in sorted(femelement_table): elem_length = len(femelement_table[elem]) - FreeCAD.Console.PrintLog("Node count of first element: {}\n".format(elem_length)) + FreeCAD.Console.PrintLog(f"Node count of first element: {elem_length}\n") break # break after the first elem if is_solid_femmesh(femmesh): if femmesh.TetraCount == femmesh.VolumeCount: @@ -2299,13 +2006,11 @@ def get_femmesh_eletype( # ************************************************************************************************ -def get_three_non_colinear_nodes( - nodes_coords -): +def get_three_non_colinear_nodes(nodes_coords): # Code to obtain three non-colinear nodes on the PlaneRotation support face # nodes_coords --> [(nodenumber, x, y, z), (nodenumber, x, y, z), ...] if not nodes_coords: - FreeCAD.Console.PrintMessage("{}\n".format(len(nodes_coords))) + FreeCAD.Console.PrintMessage(f"{len(nodes_coords)}\n") FreeCAD.Console.PrintMessage("Error: No nodes in nodes_coords\n") return [] dum_max = [1, 2, 3, 4, 5, 6, 7, 8, 0] @@ -2341,17 +2046,13 @@ def get_three_non_colinear_nodes( node_dis = [node_3, tot] node_1 = int(dum_max[0]) node_2 = int(dum_max[4]) - FreeCAD.Console.PrintMessage("{}\n".format([node_1, node_2, node_3])) + FreeCAD.Console.PrintMessage(f"{[node_1, node_2, node_3]}\n") return [node_1, node_2, node_3] # ************************************************************************************************ -def use_correct_fluidinout_ele_def( - FluidInletoutlet_ele, - fileName, - fluid_inout_nodes_file -): - f = open(fileName, "r") +def use_correct_fluidinout_ele_def(FluidInletoutlet_ele, fileName, fluid_inout_nodes_file): + f = open(fileName) cnt = 0 line = f.readline() @@ -2363,11 +2064,11 @@ def use_correct_fluidinout_ele_def( cnt = cnt + 1 # obtain element line numbers for inlet and outlet - while (len(line) > 1): + while len(line) > 1: ind = line.find(",") elem = line[0:ind] for i in range(len(FluidInletoutlet_ele)): - if (elem == FluidInletoutlet_ele[i][0]): + if elem == FluidInletoutlet_ele[i][0]: FluidInletoutlet_ele[i][2] = cnt line = f.readline() cnt = cnt + 1 @@ -2379,15 +2080,12 @@ def use_correct_fluidinout_ele_def( f.seek(0) cnt = 0 elem_counter = 0 - FreeCAD.Console.PrintMessage( - "1DFlow inout nodes file: {}\n" - .format(fluid_inout_nodes_file) - ) + FreeCAD.Console.PrintMessage(f"1DFlow inout nodes file: {fluid_inout_nodes_file}\n") inout_nodes_file = open(fluid_inout_nodes_file, "w") for line in lines: new_line = "" for i in range(len(FluidInletoutlet_ele)): - if (cnt == FluidInletoutlet_ele[i][2]): + if cnt == FluidInletoutlet_ele[i][2]: elem_counter = elem_counter + 1 a = line.split(",") for j in range(len(a)): @@ -2397,12 +2095,11 @@ def use_correct_fluidinout_ele_def( node1 = int(a[j + 2]) node2 = int(a[j + 1]) node3 = int(a[j]) - inout_nodes_file.write("{},{},{},{}\n".format( - node1, - node2, - node3, - FluidInletoutlet_ele[i][1] - )) + inout_nodes_file.write( + "{},{},{},{}\n".format( + node1, node2, node3, FluidInletoutlet_ele[i][1] + ) + ) elif j == 3: new_line = new_line + a[j] else: @@ -2413,12 +2110,11 @@ def use_correct_fluidinout_ele_def( node1 = int(a[j - 2]) node2 = int(a[j - 1]) node3 = int(a[j]) - inout_nodes_file.write("{},{},{},{}\n".format( - node1, - node2, - node3, - FluidInletoutlet_ele[i][1] - )) + inout_nodes_file.write( + "{},{},{},{}\n".format( + node1, node2, node3, FluidInletoutlet_ele[i][1] + ) + ) else: new_line = new_line + a[j] + "," if new_line == "": @@ -2432,9 +2128,7 @@ def use_correct_fluidinout_ele_def( # ************************************************************************************************ -def compact_mesh( - old_femmesh -): +def compact_mesh(old_femmesh): """ removes all gaps in node and element ids, start ids with 1 returns a tuple (FemMesh, node_assignment_map, element_assignment_map) @@ -2443,6 +2137,7 @@ def compact_mesh( elem_map = {} # {old_elem_id: new_elem_id, ...} old_nodes = old_femmesh.Nodes import Fem + new_mesh = Fem.FemMesh() if old_nodes: @@ -2489,14 +2184,15 @@ def compact_mesh( # may be return another value if the mesh was compacted, just check last map entries return (new_mesh, node_map, elem_map) + # ************************************************************************************************ def sub_shape_at_global_placement(obj, sub_name): sub_sh = obj.getSubObject(sub_name) # get partner shape partner = sub_sh.transformed(FreeCAD.Placement().Matrix) - partner.Placement = obj.getGlobalPlacement() \ - * obj.Placement.inverse() \ - * sub_sh.Placement + partner.Placement = obj.getGlobalPlacement() * obj.Placement.inverse() * sub_sh.Placement return partner + + ## @} diff --git a/src/Mod/Fem/femobjects/base_femelement.py b/src/Mod/Fem/femobjects/base_femelement.py index 92dc307c5d..bec2b0cc82 100644 --- a/src/Mod/Fem/femobjects/base_femelement.py +++ b/src/Mod/Fem/femobjects/base_femelement.py @@ -1,6 +1,6 @@ # SPDX-License-Identifier: LGPL-2.1-or-later -#/*************************************************************************** +# /*************************************************************************** # * Copyright (c) 2024 Mario Passaglia * # * * # * This file is part of FreeCAD. * @@ -34,6 +34,7 @@ from . import base_fempythonobject _PropHelper = base_fempythonobject._PropHelper + class BaseFemElement(base_fempythonobject.BaseFemPythonObject): BaseType = "Fem::BaseFemElement" @@ -44,16 +45,16 @@ class BaseFemElement(base_fempythonobject.BaseFemPythonObject): for prop in self._get_properties(): prop.add_to_object(obj) - def _get_properties(self): prop = [] - prop.append(_PropHelper( - type = "App::PropertyLinkSubList", - name = "References", - group = "Element", - doc = "List of element shapes", - value = [] + prop.append( + _PropHelper( + type="App::PropertyLinkSubList", + name="References", + group="Element", + doc="List of element shapes", + value=[], ) ) diff --git a/src/Mod/Fem/femobjects/base_femmeshelement.py b/src/Mod/Fem/femobjects/base_femmeshelement.py index 12520b2d80..e7c5dfa56c 100644 --- a/src/Mod/Fem/femobjects/base_femmeshelement.py +++ b/src/Mod/Fem/femobjects/base_femmeshelement.py @@ -1,6 +1,6 @@ # SPDX-License-Identifier: LGPL-2.1-or-later -#/*************************************************************************** +# /*************************************************************************** # * Copyright (c) 2024 Mario Passaglia * # * * # * This file is part of FreeCAD. * @@ -34,6 +34,7 @@ from . import base_fempythonobject _PropHelper = base_fempythonobject._PropHelper + class BaseFemMeshElement(base_fempythonobject.BaseFemPythonObject): BaseType = "Fem::BaseFemMeshElement" @@ -44,16 +45,16 @@ class BaseFemMeshElement(base_fempythonobject.BaseFemPythonObject): for prop in self._get_properties(): prop.add_to_object(obj) - def _get_properties(self): prop = [] - prop.append(_PropHelper( - type = "App::PropertyLinkSubList", - name = "References", - group = "Mesh Element", - doc = "List of reference shapes", - value = [] + prop.append( + _PropHelper( + type="App::PropertyLinkSubList", + name="References", + group="Mesh Element", + doc="List of reference shapes", + value=[], ) ) diff --git a/src/Mod/Fem/femobjects/base_fempythonobject.py b/src/Mod/Fem/femobjects/base_fempythonobject.py index 8dfa5a602c..226f37fb8c 100644 --- a/src/Mod/Fem/femobjects/base_fempythonobject.py +++ b/src/Mod/Fem/femobjects/base_fempythonobject.py @@ -31,7 +31,7 @@ __url__ = "https://www.freecad.org" # \brief base object for FEM Python Features -class BaseFemPythonObject(object): +class BaseFemPythonObject: BaseType = "Fem::BaseFemPythonObject" @@ -55,6 +55,7 @@ class _PropHelper: Initialization keywords are the same used with PropertyContainer to add dynamics properties plus "value" for the initial value. """ + def __init__(self, **kwds): self.value = kwds.pop("value") self.info = kwds diff --git a/src/Mod/Fem/femobjects/constant_vacuumpermittivity.py b/src/Mod/Fem/femobjects/constant_vacuumpermittivity.py index a844a5fbac..36016f6a76 100644 --- a/src/Mod/Fem/femobjects/constant_vacuumpermittivity.py +++ b/src/Mod/Fem/femobjects/constant_vacuumpermittivity.py @@ -40,12 +40,12 @@ class ConstantVacuumPermittivity(base_fempythonobject.BaseFemPythonObject): Type = "Fem::ConstantVacuumPermittivity" def __init__(self, obj): - super(ConstantVacuumPermittivity, self).__init__(obj) + super().__init__(obj) obj.addProperty( "App::PropertyVacuumPermittivity", "VacuumPermittivity", "Constants", - "Overwrites default permittivity of vacuum" + "Overwrites default permittivity of vacuum", ) obj.setPropertyStatus("VacuumPermittivity", "LockDynamic") # we must set an expression so that the small value can actually be entered diff --git a/src/Mod/Fem/femobjects/constraint_bodyheatsource.py b/src/Mod/Fem/femobjects/constraint_bodyheatsource.py index ac1f4d23ac..bf3e9c3957 100644 --- a/src/Mod/Fem/femobjects/constraint_bodyheatsource.py +++ b/src/Mod/Fem/femobjects/constraint_bodyheatsource.py @@ -43,43 +43,44 @@ class ConstraintBodyHeatSource(base_fempythonobject.BaseFemPythonObject): Type = "Fem::ConstraintBodyHeatSource" def __init__(self, obj): - super(ConstraintBodyHeatSource, self).__init__(obj) + super().__init__(obj) for prop in self._get_properties(): prop.add_to_object(obj) - def _get_properties(self): prop = [] - prop.append(_PropHelper( - type = "App::PropertyDissipationRate", - name = "DissipationRate", - group = "Constraint Body Heat Source", - doc = "Power dissipated per unit mass", - value = "0 W/kg" + prop.append( + _PropHelper( + type="App::PropertyDissipationRate", + name="DissipationRate", + group="Constraint Body Heat Source", + doc="Power dissipated per unit mass", + value="0 W/kg", ) ) - prop.append(_PropHelper( - type = "App::PropertyPower", - name = "TotalPower", - group = "Constraint Body Heat Source", - doc = "Total power dissipated", - value = "0 W" + prop.append( + _PropHelper( + type="App::PropertyPower", + name="TotalPower", + group="Constraint Body Heat Source", + doc="Total power dissipated", + value="0 W", ) ) - prop.append(_PropHelper( - type = "App::PropertyEnumeration", - name = "Mode", - group = "Constraint Body Heat Source", - doc = "Switch quantity input mode", - value = ["Dissipation Rate", "Total Power"] + prop.append( + _PropHelper( + type="App::PropertyEnumeration", + name="Mode", + group="Constraint Body Heat Source", + doc="Switch quantity input mode", + value=["Dissipation Rate", "Total Power"], ) ) return prop - def onDocumentRestored(self, obj): # update old project with new properties for prop in self._get_properties(): diff --git a/src/Mod/Fem/femobjects/constraint_centrif.py b/src/Mod/Fem/femobjects/constraint_centrif.py index 25dd8e3108..e2ef2b63d9 100644 --- a/src/Mod/Fem/femobjects/constraint_centrif.py +++ b/src/Mod/Fem/femobjects/constraint_centrif.py @@ -40,13 +40,13 @@ class ConstraintCentrif(base_fempythonobject.BaseFemPythonObject): Type = "Fem::ConstraintCentrif" def __init__(self, obj): - super(ConstraintCentrif, self).__init__(obj) + super().__init__(obj) obj.addProperty( "App::PropertyFrequency", "RotationFrequency", "Constraint CENTRIF", - "set rotation frequency frot" + "set rotation frequency frot", ) obj.setPropertyStatus("RotationFrequency", "LockDynamic") @@ -54,6 +54,6 @@ class ConstraintCentrif(base_fempythonobject.BaseFemPythonObject): "App::PropertyLinkSubList", "RotationAxis", "Constraint CENTRIF", - "set line as axis of rotation" + "set line as axis of rotation", ) obj.setPropertyStatus("RotationAxis", "LockDynamic") diff --git a/src/Mod/Fem/femobjects/constraint_currentdensity.py b/src/Mod/Fem/femobjects/constraint_currentdensity.py index f7f869ef88..1c3f6499ff 100644 --- a/src/Mod/Fem/femobjects/constraint_currentdensity.py +++ b/src/Mod/Fem/femobjects/constraint_currentdensity.py @@ -37,7 +37,7 @@ class ConstraintCurrentDensity(base_fempythonobject.BaseFemPythonObject): Type = "Fem::ConstraintCurrentDensity" def __init__(self, obj): - super(ConstraintCurrentDensity, self).__init__(obj) + super().__init__(obj) self.add_properties(obj) def onDocumentRestored(self, obj): @@ -49,7 +49,7 @@ class ConstraintCurrentDensity(base_fempythonobject.BaseFemPythonObject): "App::PropertyCurrentDensity", "CurrentDensity_re_1", "Vector Potential", - "Real part of current density x-component" + "Real part of current density x-component", ) obj.setPropertyStatus("CurrentDensity_re_1", "LockDynamic") obj.CurrentDensity_re_1 = "0 A/m^2" @@ -58,7 +58,7 @@ class ConstraintCurrentDensity(base_fempythonobject.BaseFemPythonObject): "App::PropertyCurrentDensity", "CurrentDensity_re_2", "Vector Potential", - "Real part of current density y-component" + "Real part of current density y-component", ) obj.setPropertyStatus("CurrentDensity_re_2", "LockDynamic") obj.CurrentDensity_re_2 = "0 A/m^2" @@ -67,7 +67,7 @@ class ConstraintCurrentDensity(base_fempythonobject.BaseFemPythonObject): "App::PropertyCurrentDensity", "CurrentDensity_re_3", "Vector Potential", - "Real part of current density z-component" + "Real part of current density z-component", ) obj.setPropertyStatus("CurrentDensity_re_3", "LockDynamic") obj.CurrentDensity_re_3 = "0 A/m^2" @@ -76,7 +76,7 @@ class ConstraintCurrentDensity(base_fempythonobject.BaseFemPythonObject): "App::PropertyCurrentDensity", "CurrentDensity_im_1", "Vector Potential", - "Imaginary part of current density x-component" + "Imaginary part of current density x-component", ) obj.setPropertyStatus("CurrentDensity_im_1", "LockDynamic") obj.CurrentDensity_im_1 = "0 A/m^2" @@ -85,7 +85,7 @@ class ConstraintCurrentDensity(base_fempythonobject.BaseFemPythonObject): "App::PropertyCurrentDensity", "CurrentDensity_im_2", "Vector Potential", - "Imaginary part of current density y-component" + "Imaginary part of current density y-component", ) obj.setPropertyStatus("CurrentDensity_im_2", "LockDynamic") obj.CurrentDensity_im_2 = "0 A/m^2" @@ -94,7 +94,7 @@ class ConstraintCurrentDensity(base_fempythonobject.BaseFemPythonObject): "App::PropertyCurrentDensity", "CurrentDensity_im_3", "Vector Potential", - "Imaginary part of current density z-component" + "Imaginary part of current density z-component", ) obj.setPropertyStatus("CurrentDensity_im_3", "LockDynamic") obj.CurrentDensity_im_3 = "0 A/m^2" @@ -102,55 +102,37 @@ class ConstraintCurrentDensity(base_fempythonobject.BaseFemPythonObject): # now the enable bools if not hasattr(obj, "CurrentDensity_re_1_Disabled"): obj.addProperty( - "App::PropertyBool", - "CurrentDensity_re_1_Disabled", - "Vector Potential", - "" + "App::PropertyBool", "CurrentDensity_re_1_Disabled", "Vector Potential", "" ) obj.setPropertyStatus("CurrentDensity_re_1_Disabled", "LockDynamic") obj.CurrentDensity_re_1_Disabled = True if not hasattr(obj, "CurrentDensity_re_2_Disabled"): obj.addProperty( - "App::PropertyBool", - "CurrentDensity_re_2_Disabled", - "Vector Potential", - "" + "App::PropertyBool", "CurrentDensity_re_2_Disabled", "Vector Potential", "" ) obj.setPropertyStatus("CurrentDensity_re_2_Disabled", "LockDynamic") obj.CurrentDensity_re_2_Disabled = True if not hasattr(obj, "CurrentDensity_re_3_Disabled"): obj.addProperty( - "App::PropertyBool", - "CurrentDensity_re_3_Disabled", - "Vector Potential", - "" + "App::PropertyBool", "CurrentDensity_re_3_Disabled", "Vector Potential", "" ) obj.setPropertyStatus("CurrentDensity_re_3_Disabled", "LockDynamic") obj.CurrentDensity_re_3_Disabled = True if not hasattr(obj, "CurrentDensity_im_1_Disabled"): obj.addProperty( - "App::PropertyBool", - "CurrentDensity_im_1_Disabled", - "Vector Potential", - "" + "App::PropertyBool", "CurrentDensity_im_1_Disabled", "Vector Potential", "" ) obj.setPropertyStatus("CurrentDensity_im_1_Disabled", "LockDynamic") obj.CurrentDensity_im_1_Disabled = True if not hasattr(obj, "CurrentDensity_im_2_Disabled"): obj.addProperty( - "App::PropertyBool", - "CurrentDensity_im_2_Disabled", - "Vector Potential", - "" + "App::PropertyBool", "CurrentDensity_im_2_Disabled", "Vector Potential", "" ) obj.setPropertyStatus("CurrentDensity_im_2_Disabled", "LockDynamic") obj.CurrentDensity_im_2_Disabled = True if not hasattr(obj, "CurrentDensity_im_3_Disabled"): obj.addProperty( - "App::PropertyBool", - "CurrentDensity_im_3_Disabled", - "Vector Potential", - "" + "App::PropertyBool", "CurrentDensity_im_3_Disabled", "Vector Potential", "" ) obj.setPropertyStatus("CurrentDensity_im_3_Disabled", "LockDynamic") obj.CurrentDensity_im_3_Disabled = True diff --git a/src/Mod/Fem/femobjects/constraint_electrostaticpotential.py b/src/Mod/Fem/femobjects/constraint_electrostaticpotential.py index 6fe988c755..e3e9554531 100644 --- a/src/Mod/Fem/femobjects/constraint_electrostaticpotential.py +++ b/src/Mod/Fem/femobjects/constraint_electrostaticpotential.py @@ -39,7 +39,7 @@ class ConstraintElectrostaticPotential(base_fempythonobject.BaseFemPythonObject) Type = "Fem::ConstraintElectrostaticPotential" def __init__(self, obj): - super(ConstraintElectrostaticPotential, self).__init__(obj) + super().__init__(obj) self.add_properties(obj) def onDocumentRestored(self, obj): @@ -48,10 +48,7 @@ class ConstraintElectrostaticPotential(base_fempythonobject.BaseFemPythonObject) def add_properties(self, obj): if not hasattr(obj, "Potential"): obj.addProperty( - "App::PropertyElectricPotential", - "Potential", - "Parameter", - "Electric Potential" + "App::PropertyElectricPotential", "Potential", "Parameter", "Electric Potential" ) obj.setPropertyStatus("Potential", "LockDynamic") # setting 1 V assures that the unit does not switch to mV @@ -63,7 +60,7 @@ class ConstraintElectrostaticPotential(base_fempythonobject.BaseFemPythonObject) "App::PropertyElectricPotential", "AV_re_1", "Vector Potential", - "Real part of potential x-component" + "Real part of potential x-component", ) obj.setPropertyStatus("AV_re_1", "LockDynamic") obj.AV_re_1 = "0 V" @@ -72,7 +69,7 @@ class ConstraintElectrostaticPotential(base_fempythonobject.BaseFemPythonObject) "App::PropertyElectricPotential", "AV_re_2", "Vector Potential", - "Real part of potential y-component" + "Real part of potential y-component", ) obj.setPropertyStatus("AV_re_2", "LockDynamic") obj.AV_re_2 = "0 V" @@ -81,7 +78,7 @@ class ConstraintElectrostaticPotential(base_fempythonobject.BaseFemPythonObject) "App::PropertyElectricPotential", "AV_re_3", "Vector Potential", - "Real part of potential z-component" + "Real part of potential z-component", ) obj.setPropertyStatus("AV_re_3", "LockDynamic") obj.AV_re_3 = "0 V" @@ -90,7 +87,7 @@ class ConstraintElectrostaticPotential(base_fempythonobject.BaseFemPythonObject) "App::PropertyElectricPotential", "AV_im", "Vector Potential", - "Imaginary part of scalar potential" + "Imaginary part of scalar potential", ) obj.setPropertyStatus("AV_im", "LockDynamic") obj.AV_im = "0 V" @@ -99,7 +96,7 @@ class ConstraintElectrostaticPotential(base_fempythonobject.BaseFemPythonObject) "App::PropertyElectricPotential", "AV_im_1", "Vector Potential", - "Imaginary part of potential x-component" + "Imaginary part of potential x-component", ) obj.setPropertyStatus("AV_im_1", "LockDynamic") obj.AV_im_1 = "0 V" @@ -108,7 +105,7 @@ class ConstraintElectrostaticPotential(base_fempythonobject.BaseFemPythonObject) "App::PropertyElectricPotential", "AV_im_2", "Vector Potential", - "Imaginary part of potential y-component" + "Imaginary part of potential y-component", ) obj.setPropertyStatus("AV_im_2", "LockDynamic") obj.AV_im_2 = "0 V" @@ -117,7 +114,7 @@ class ConstraintElectrostaticPotential(base_fempythonobject.BaseFemPythonObject) "App::PropertyElectricPotential", "AV_im_3", "Vector Potential", - "Imaginary part of potential z-component" + "Imaginary part of potential z-component", ) obj.setPropertyStatus("AV_im_3", "LockDynamic") obj.AV_im_3 = "0 V" @@ -125,93 +122,49 @@ class ConstraintElectrostaticPotential(base_fempythonobject.BaseFemPythonObject) # now the enable bools if not hasattr(obj, "PotentialEnabled"): obj.addProperty( - "App::PropertyBool", - "PotentialEnabled", - "Parameter", - "Potential Enabled" + "App::PropertyBool", "PotentialEnabled", "Parameter", "Potential Enabled" ) obj.setPropertyStatus("PotentialEnabled", "LockDynamic") obj.PotentialEnabled = True if not hasattr(obj, "AV_re_1_Disabled"): - obj.addProperty( - "App::PropertyBool", - "AV_re_1_Disabled", - "Vector Potential", - "" - ) + obj.addProperty("App::PropertyBool", "AV_re_1_Disabled", "Vector Potential", "") obj.setPropertyStatus("AV_re_1_Disabled", "LockDynamic") obj.AV_re_1_Disabled = True if not hasattr(obj, "AV_re_2_Disabled"): - obj.addProperty( - "App::PropertyBool", - "AV_re_2_Disabled", - "Vector Potential", - "" - ) + obj.addProperty("App::PropertyBool", "AV_re_2_Disabled", "Vector Potential", "") obj.setPropertyStatus("AV_re_2_Disabled", "LockDynamic") obj.AV_re_2_Disabled = True if not hasattr(obj, "AV_re_3_Disabled"): - obj.addProperty( - "App::PropertyBool", - "AV_re_3_Disabled", - "Vector Potential", - "" - ) + obj.addProperty("App::PropertyBool", "AV_re_3_Disabled", "Vector Potential", "") obj.setPropertyStatus("AV_re_3_Disabled", "LockDynamic") obj.AV_re_3_Disabled = True if not hasattr(obj, "AV_im_Disabled"): - obj.addProperty( - "App::PropertyBool", - "AV_im_Disabled", - "Vector Potential", - "" - ) + obj.addProperty("App::PropertyBool", "AV_im_Disabled", "Vector Potential", "") obj.setPropertyStatus("AV_im_Disabled", "LockDynamic") obj.AV_im_Disabled = True if not hasattr(obj, "AV_im_1_Disabled"): - obj.addProperty( - "App::PropertyBool", - "AV_im_1_Disabled", - "Vector Potential", - "" - ) + obj.addProperty("App::PropertyBool", "AV_im_1_Disabled", "Vector Potential", "") obj.setPropertyStatus("AV_im_1_Disabled", "LockDynamic") obj.AV_im_1_Disabled = True if not hasattr(obj, "AV_im_2_Disabled"): - obj.addProperty( - "App::PropertyBool", - "AV_im_2_Disabled", - "Vector Potential", - "" - ) + obj.addProperty("App::PropertyBool", "AV_im_2_Disabled", "Vector Potential", "") obj.setPropertyStatus("AV_im_2_Disabled", "LockDynamic") obj.AV_im_2_Disabled = True if not hasattr(obj, "AV_im_3_Disabled"): - obj.addProperty( - "App::PropertyBool", - "AV_im_3_Disabled", - "Vector Potential", - "" - ) + obj.addProperty("App::PropertyBool", "AV_im_3_Disabled", "Vector Potential", "") obj.setPropertyStatus("AV_im_3_Disabled", "LockDynamic") obj.AV_im_3_Disabled = True if not hasattr(obj, "PotentialConstant"): obj.addProperty( - "App::PropertyBool", - "PotentialConstant", - "Parameter", - "Potential Constant" + "App::PropertyBool", "PotentialConstant", "Parameter", "Potential Constant" ) obj.setPropertyStatus("PotentialConstant", "LockDynamic") obj.PotentialConstant = False if not hasattr(obj, "ElectricInfinity"): obj.addProperty( - "App::PropertyBool", - "ElectricInfinity", - "Parameter", - "Electric Infinity" + "App::PropertyBool", "ElectricInfinity", "Parameter", "Electric Infinity" ) obj.setPropertyStatus("ElectricInfinity", "LockDynamic") obj.ElectricInfinity = False @@ -221,17 +174,14 @@ class ConstraintElectrostaticPotential(base_fempythonobject.BaseFemPythonObject) "App::PropertyBool", "ElectricForcecalculation", "Parameter", - "Electric Force Calculation" + "Electric Force Calculation", ) obj.setPropertyStatus("ElectricForcecalculation", "LockDynamic") obj.ElectricForcecalculation = False if not hasattr(obj, "CapacitanceBody"): obj.addProperty( - "App::PropertyInteger", - "CapacitanceBody", - "Parameter", - "Capacitance Body" + "App::PropertyInteger", "CapacitanceBody", "Parameter", "Capacitance Body" ) obj.setPropertyStatus("CapacitanceBody", "LockDynamic") obj.CapacitanceBody = 0 @@ -241,7 +191,7 @@ class ConstraintElectrostaticPotential(base_fempythonobject.BaseFemPythonObject) "App::PropertyBool", "CapacitanceBodyEnabled", "Parameter", - "Capacitance Body Enabled" + "Capacitance Body Enabled", ) obj.setPropertyStatus("CapacitanceBodyEnabled", "LockDynamic") obj.CapacitanceBodyEnabled = False diff --git a/src/Mod/Fem/femobjects/constraint_flowvelocity.py b/src/Mod/Fem/femobjects/constraint_flowvelocity.py index e5bc938063..ab0d329541 100644 --- a/src/Mod/Fem/femobjects/constraint_flowvelocity.py +++ b/src/Mod/Fem/femobjects/constraint_flowvelocity.py @@ -39,26 +39,20 @@ class ConstraintFlowVelocity(base_fempythonobject.BaseFemPythonObject): Type = "Fem::ConstraintFlowVelocity" def __init__(self, obj): - super(ConstraintFlowVelocity, self).__init__(obj) + super().__init__(obj) obj.addProperty( - "App::PropertyVelocity", - "VelocityX", - "Parameter", - "Velocity in x-direction" + "App::PropertyVelocity", "VelocityX", "Parameter", "Velocity in x-direction" ) obj.setPropertyStatus("VelocityX", "LockDynamic") obj.addProperty( "App::PropertyString", "VelocityXFormula", "Parameter", - "Velocity formula in x-direction" + "Velocity formula in x-direction", ) obj.setPropertyStatus("VelocityXFormula", "LockDynamic") obj.addProperty( - "App::PropertyBool", - "VelocityXUnspecified", - "Parameter", - "Use velocity in x-direction" + "App::PropertyBool", "VelocityXUnspecified", "Parameter", "Use velocity in x-direction" ) obj.setPropertyStatus("VelocityXUnspecified", "LockDynamic") obj.VelocityXUnspecified = True @@ -66,29 +60,23 @@ class ConstraintFlowVelocity(base_fempythonobject.BaseFemPythonObject): "App::PropertyBool", "VelocityXHasFormula", "Parameter", - "Use formula for velocity in x-direction" + "Use formula for velocity in x-direction", ) obj.setPropertyStatus("VelocityXHasFormula", "LockDynamic") obj.addProperty( - "App::PropertyVelocity", - "VelocityY", - "Parameter", - "Velocity in y-direction" + "App::PropertyVelocity", "VelocityY", "Parameter", "Velocity in y-direction" ) obj.setPropertyStatus("VelocityY", "LockDynamic") obj.addProperty( "App::PropertyString", "VelocityYFormula", "Parameter", - "Velocity formula in y-direction" + "Velocity formula in y-direction", ) obj.setPropertyStatus("VelocityYFormula", "LockDynamic") obj.addProperty( - "App::PropertyBool", - "VelocityYUnspecified", - "Parameter", - "Use velocity in y-direction" + "App::PropertyBool", "VelocityYUnspecified", "Parameter", "Use velocity in y-direction" ) obj.setPropertyStatus("VelocityYUnspecified", "LockDynamic") obj.VelocityYUnspecified = True @@ -96,29 +84,23 @@ class ConstraintFlowVelocity(base_fempythonobject.BaseFemPythonObject): "App::PropertyBool", "VelocityYHasFormula", "Parameter", - "Use formula for velocity in y-direction" + "Use formula for velocity in y-direction", ) obj.setPropertyStatus("VelocityYHasFormula", "LockDynamic") obj.addProperty( - "App::PropertyVelocity", - "VelocityZ", - "Parameter", - "Velocity in z-direction" + "App::PropertyVelocity", "VelocityZ", "Parameter", "Velocity in z-direction" ) obj.setPropertyStatus("VelocityZ", "LockDynamic") obj.addProperty( "App::PropertyString", "VelocityZFormula", "Parameter", - "Velocity formula in z-direction" + "Velocity formula in z-direction", ) obj.setPropertyStatus("VelocityZFormula", "LockDynamic") obj.addProperty( - "App::PropertyBool", - "VelocityZUnspecified", - "Parameter", - "Use velocity in z-direction" + "App::PropertyBool", "VelocityZUnspecified", "Parameter", "Use velocity in z-direction" ) obj.setPropertyStatus("VelocityZUnspecified", "LockDynamic") obj.VelocityZUnspecified = True @@ -126,14 +108,11 @@ class ConstraintFlowVelocity(base_fempythonobject.BaseFemPythonObject): "App::PropertyBool", "VelocityZHasFormula", "Parameter", - "Use formula for velocity in z-direction" + "Use formula for velocity in z-direction", ) obj.setPropertyStatus("VelocityZHasFormula", "LockDynamic") obj.addProperty( - "App::PropertyBool", - "NormalToBoundary", - "Parameter", - "Flow is in normal direction" + "App::PropertyBool", "NormalToBoundary", "Parameter", "Flow is in normal direction" ) obj.setPropertyStatus("NormalToBoundary", "LockDynamic") diff --git a/src/Mod/Fem/femobjects/constraint_initialflowvelocity.py b/src/Mod/Fem/femobjects/constraint_initialflowvelocity.py index e5816b5f9d..febd4dd551 100644 --- a/src/Mod/Fem/femobjects/constraint_initialflowvelocity.py +++ b/src/Mod/Fem/femobjects/constraint_initialflowvelocity.py @@ -38,26 +38,20 @@ class ConstraintInitialFlowVelocity(base_fempythonobject.BaseFemPythonObject): Type = "Fem::ConstraintInitialFlowVelocity" def __init__(self, obj): - super(ConstraintInitialFlowVelocity, self).__init__(obj) + super().__init__(obj) obj.addProperty( - "App::PropertyVelocity", - "VelocityX", - "Parameter", - "Velocity in x-direction" + "App::PropertyVelocity", "VelocityX", "Parameter", "Velocity in x-direction" ) obj.setPropertyStatus("VelocityX", "LockDynamic") obj.addProperty( "App::PropertyString", "VelocityXFormula", "Parameter", - "Velocity formula in x-direction" + "Velocity formula in x-direction", ) obj.setPropertyStatus("VelocityXFormula", "LockDynamic") obj.addProperty( - "App::PropertyBool", - "VelocityXUnspecified", - "Parameter", - "Use velocity in x-direction" + "App::PropertyBool", "VelocityXUnspecified", "Parameter", "Use velocity in x-direction" ) obj.setPropertyStatus("VelocityXUnspecified", "LockDynamic") obj.VelocityXUnspecified = True @@ -65,29 +59,23 @@ class ConstraintInitialFlowVelocity(base_fempythonobject.BaseFemPythonObject): "App::PropertyBool", "VelocityXHasFormula", "Parameter", - "Use formula for velocity in x-direction" + "Use formula for velocity in x-direction", ) obj.setPropertyStatus("VelocityXHasFormula", "LockDynamic") obj.addProperty( - "App::PropertyVelocity", - "VelocityY", - "Parameter", - "Velocity in y-direction" + "App::PropertyVelocity", "VelocityY", "Parameter", "Velocity in y-direction" ) obj.setPropertyStatus("VelocityY", "LockDynamic") obj.addProperty( "App::PropertyString", "VelocityYFormula", "Parameter", - "Velocity formula in y-direction" + "Velocity formula in y-direction", ) obj.setPropertyStatus("VelocityYFormula", "LockDynamic") obj.addProperty( - "App::PropertyBool", - "VelocityYUnspecified", - "Parameter", - "Use velocity in y-direction" + "App::PropertyBool", "VelocityYUnspecified", "Parameter", "Use velocity in y-direction" ) obj.setPropertyStatus("VelocityYUnspecified", "LockDynamic") obj.VelocityYUnspecified = True @@ -95,29 +83,23 @@ class ConstraintInitialFlowVelocity(base_fempythonobject.BaseFemPythonObject): "App::PropertyBool", "VelocityYHasFormula", "Parameter", - "Use formula for velocity in y-direction" + "Use formula for velocity in y-direction", ) obj.setPropertyStatus("VelocityYHasFormula", "LockDynamic") obj.addProperty( - "App::PropertyVelocity", - "VelocityZ", - "Parameter", - "Velocity in z-direction" + "App::PropertyVelocity", "VelocityZ", "Parameter", "Velocity in z-direction" ) obj.setPropertyStatus("VelocityZ", "LockDynamic") obj.addProperty( "App::PropertyString", "VelocityZFormula", "Parameter", - "Velocity formula in z-direction" + "Velocity formula in z-direction", ) obj.setPropertyStatus("VelocityZFormula", "LockDynamic") obj.addProperty( - "App::PropertyBool", - "VelocityZUnspecified", - "Parameter", - "Use velocity in z-direction" + "App::PropertyBool", "VelocityZUnspecified", "Parameter", "Use velocity in z-direction" ) obj.setPropertyStatus("VelocityZUnspecified", "LockDynamic") obj.VelocityZUnspecified = True @@ -125,6 +107,6 @@ class ConstraintInitialFlowVelocity(base_fempythonobject.BaseFemPythonObject): "App::PropertyBool", "VelocityZHasFormula", "Parameter", - "Use formula for velocity in z-direction" + "Use formula for velocity in z-direction", ) obj.setPropertyStatus("VelocityZHasFormula", "LockDynamic") diff --git a/src/Mod/Fem/femobjects/constraint_initialpressure.py b/src/Mod/Fem/femobjects/constraint_initialpressure.py index 919fc80362..410c6cfa5b 100644 --- a/src/Mod/Fem/femobjects/constraint_initialpressure.py +++ b/src/Mod/Fem/femobjects/constraint_initialpressure.py @@ -37,7 +37,7 @@ class ConstraintInitialPressure(base_fempythonobject.BaseFemPythonObject): Type = "Fem::ConstraintInitialPressure" def __init__(self, obj): - super(ConstraintInitialPressure, self).__init__(obj) + super().__init__(obj) self.add_properties(obj) def onDocumentRestored(self, obj): @@ -45,12 +45,7 @@ class ConstraintInitialPressure(base_fempythonobject.BaseFemPythonObject): def add_properties(self, obj): if not hasattr(obj, "Pressure"): - obj.addProperty( - "App::PropertyPressure", - "Pressure", - "Parameter", - "Initial Pressure" - ) + obj.addProperty("App::PropertyPressure", "Pressure", "Parameter", "Initial Pressure") obj.setPropertyStatus("Pressure", "LockDynamic") # we initialize 1 bar obj.Pressure = "100 kPa" diff --git a/src/Mod/Fem/femobjects/constraint_magnetization.py b/src/Mod/Fem/femobjects/constraint_magnetization.py index 5cdacab845..d978a343d2 100644 --- a/src/Mod/Fem/femobjects/constraint_magnetization.py +++ b/src/Mod/Fem/femobjects/constraint_magnetization.py @@ -37,7 +37,7 @@ class ConstraintMagnetization(base_fempythonobject.BaseFemPythonObject): Type = "Fem::ConstraintMagnetization" def __init__(self, obj): - super(ConstraintMagnetization, self).__init__(obj) + super().__init__(obj) self.add_properties(obj) def onDocumentRestored(self, obj): @@ -49,7 +49,7 @@ class ConstraintMagnetization(base_fempythonobject.BaseFemPythonObject): "App::PropertyMagnetization", "Magnetization_re_1", "Vector Potential", - "Real part of magnetization x-component" + "Real part of magnetization x-component", ) obj.setPropertyStatus("Magnetization_re_1", "LockDynamic") obj.Magnetization_re_1 = "0 A/m" @@ -58,7 +58,7 @@ class ConstraintMagnetization(base_fempythonobject.BaseFemPythonObject): "App::PropertyMagnetization", "Magnetization_re_2", "Vector Potential", - "Real part of magnetization y-component" + "Real part of magnetization y-component", ) obj.setPropertyStatus("Magnetization_re_2", "LockDynamic") obj.Magnetization_re_2 = "0 A/m" @@ -67,7 +67,7 @@ class ConstraintMagnetization(base_fempythonobject.BaseFemPythonObject): "App::PropertyMagnetization", "Magnetization_re_3", "Vector Potential", - "Real part of magnetization z-component" + "Real part of magnetization z-component", ) obj.setPropertyStatus("Magnetization_re_3", "LockDynamic") obj.Magnetization_re_3 = "0 A/m" @@ -76,7 +76,7 @@ class ConstraintMagnetization(base_fempythonobject.BaseFemPythonObject): "App::PropertyMagnetization", "Magnetization_im_1", "Vector Potential", - "Imaginary part of magnetization x-component" + "Imaginary part of magnetization x-component", ) obj.setPropertyStatus("Magnetization_im_1", "LockDynamic") obj.Magnetization_im_1 = "0 A/m" @@ -85,7 +85,7 @@ class ConstraintMagnetization(base_fempythonobject.BaseFemPythonObject): "App::PropertyMagnetization", "Magnetization_im_2", "Vector Potential", - "Imaginary part of magnetization y-component" + "Imaginary part of magnetization y-component", ) obj.setPropertyStatus("Magnetization_im_2", "LockDynamic") obj.Magnetization_im_2 = "0 A/m" @@ -94,7 +94,7 @@ class ConstraintMagnetization(base_fempythonobject.BaseFemPythonObject): "App::PropertyMagnetization", "Magnetization_im_3", "Vector Potential", - "Imaginary part of magnetization z-component" + "Imaginary part of magnetization z-component", ) obj.setPropertyStatus("Magnetization_im_3", "LockDynamic") obj.Magnetization_im_3 = "0 A/m" @@ -102,55 +102,37 @@ class ConstraintMagnetization(base_fempythonobject.BaseFemPythonObject): # now the enable bools if not hasattr(obj, "Magnetization_re_1_Disabled"): obj.addProperty( - "App::PropertyBool", - "Magnetization_re_1_Disabled", - "Vector Potential", - "" + "App::PropertyBool", "Magnetization_re_1_Disabled", "Vector Potential", "" ) obj.setPropertyStatus("Magnetization_re_1_Disabled", "LockDynamic") obj.Magnetization_re_1_Disabled = True if not hasattr(obj, "Magnetization_re_2_Disabled"): obj.addProperty( - "App::PropertyBool", - "Magnetization_re_2_Disabled", - "Vector Potential", - "" + "App::PropertyBool", "Magnetization_re_2_Disabled", "Vector Potential", "" ) obj.setPropertyStatus("Magnetization_re_2_Disabled", "LockDynamic") obj.Magnetization_re_2_Disabled = True if not hasattr(obj, "Magnetization_re_3_Disabled"): obj.addProperty( - "App::PropertyBool", - "Magnetization_re_3_Disabled", - "Vector Potential", - "" + "App::PropertyBool", "Magnetization_re_3_Disabled", "Vector Potential", "" ) obj.setPropertyStatus("Magnetization_re_3_Disabled", "LockDynamic") obj.Magnetization_re_3_Disabled = True if not hasattr(obj, "Magnetization_im_1_Disabled"): obj.addProperty( - "App::PropertyBool", - "Magnetization_im_1_Disabled", - "Vector Potential", - "" + "App::PropertyBool", "Magnetization_im_1_Disabled", "Vector Potential", "" ) obj.setPropertyStatus("Magnetization_im_1_Disabled", "LockDynamic") obj.Magnetization_im_1_Disabled = True if not hasattr(obj, "Magnetization_im_2_Disabled"): obj.addProperty( - "App::PropertyBool", - "Magnetization_im_2_Disabled", - "Vector Potential", - "" + "App::PropertyBool", "Magnetization_im_2_Disabled", "Vector Potential", "" ) obj.setPropertyStatus("Magnetization_im_2_Disabled", "LockDynamic") obj.Magnetization_im_2_Disabled = True if not hasattr(obj, "Magnetization_im_3_Disabled"): obj.addProperty( - "App::PropertyBool", - "Magnetization_im_3_Disabled", - "Vector Potential", - "" + "App::PropertyBool", "Magnetization_im_3_Disabled", "Vector Potential", "" ) obj.setPropertyStatus("Magnetization_im_3_Disabled", "LockDynamic") obj.Magnetization_im_3_Disabled = True diff --git a/src/Mod/Fem/femobjects/constraint_sectionprint.py b/src/Mod/Fem/femobjects/constraint_sectionprint.py index 8fbbeee087..fd59b3c9cf 100644 --- a/src/Mod/Fem/femobjects/constraint_sectionprint.py +++ b/src/Mod/Fem/femobjects/constraint_sectionprint.py @@ -33,6 +33,7 @@ from . import base_fempythonobject _PropHelper = base_fempythonobject._PropHelper + class ConstraintSectionPrint(base_fempythonobject.BaseFemPythonObject): """ The FemConstraintSectionPrint object @@ -41,27 +42,26 @@ class ConstraintSectionPrint(base_fempythonobject.BaseFemPythonObject): Type = "Fem::ConstraintSectionPrint" def __init__(self, obj): - super(ConstraintSectionPrint, self).__init__(obj) + super().__init__(obj) for prop in self._get_properties(): prop.add_to_object(obj) - def _get_properties(self): prop = [] - prop.append(_PropHelper( - type = "App::PropertyEnumeration", - name = "Variable", - group = "Constraint Section Print", - doc = "Set facial variable", - value = ["Section Force", "Heat Flux", "Drag Stress"] + prop.append( + _PropHelper( + type="App::PropertyEnumeration", + name="Variable", + group="Constraint Section Print", + doc="Set facial variable", + value=["Section Force", "Heat Flux", "Drag Stress"], ) ) return prop - def onDocumentRestored(self, obj): # update old project with new properties for prop in self._get_properties(): diff --git a/src/Mod/Fem/femobjects/constraint_selfweight.py b/src/Mod/Fem/femobjects/constraint_selfweight.py index dcaa4f5c97..3a0add6152 100644 --- a/src/Mod/Fem/femobjects/constraint_selfweight.py +++ b/src/Mod/Fem/femobjects/constraint_selfweight.py @@ -42,7 +42,7 @@ class ConstraintSelfWeight(base_fempythonobject.BaseFemPythonObject): Type = "Fem::ConstraintSelfWeight" def __init__(self, obj): - super(ConstraintSelfWeight, self).__init__(obj) + super().__init__(obj) self.addProperty(obj) @@ -53,17 +53,15 @@ class ConstraintSelfWeight(base_fempythonobject.BaseFemPythonObject): obj.setEditorMode("References", 2) # do not show in Editor def addProperty(self, obj): - obj.addProperty("App::PropertyAcceleration", - "GravityAcceleration", - "Gravity", - "Gravity acceleration") + obj.addProperty( + "App::PropertyAcceleration", "GravityAcceleration", "Gravity", "Gravity acceleration" + ) obj.setPropertyStatus("GravityAcceleration", "LockDynamic") obj.GravityAcceleration = constants.gravity() - obj.addProperty("App::PropertyVector", - "GravityDirection", - "Gravity", - "Normalized gravity direction") + obj.addProperty( + "App::PropertyVector", "GravityDirection", "Gravity", "Normalized gravity direction" + ) obj.setPropertyStatus("GravityDirection", "LockDynamic") obj.GravityDirection = FreeCAD.Vector(0, 0, -1) diff --git a/src/Mod/Fem/femobjects/constraint_tie.py b/src/Mod/Fem/femobjects/constraint_tie.py index 9301d9fddf..e8b1707a88 100644 --- a/src/Mod/Fem/femobjects/constraint_tie.py +++ b/src/Mod/Fem/femobjects/constraint_tie.py @@ -44,7 +44,7 @@ class ConstraintTie(base_fempythonobject.BaseFemPythonObject): Type = "Fem::ConstraintTie" def __init__(self, obj): - super(ConstraintTie, self).__init__(obj) + super().__init__(obj) for prop in self._get_properties(): prop.add_to_object(obj) @@ -52,58 +52,63 @@ class ConstraintTie(base_fempythonobject.BaseFemPythonObject): def _get_properties(self): prop = [] - prop.append(_PropHelper( - type = "App::PropertyLength", - name = "Tolerance", - group = "Geometry", - doc = "Set max gap between tied faces", - value = "0.0 mm" + prop.append( + _PropHelper( + type="App::PropertyLength", + name="Tolerance", + group="Geometry", + doc="Set max gap between tied faces", + value="0.0 mm", ) ) - prop.append(_PropHelper( - type = "App::PropertyBool", - name = "Adjust", - group = "Geometry", - doc = "Adjust connected nodes", - value = False + prop.append( + _PropHelper( + type="App::PropertyBool", + name="Adjust", + group="Geometry", + doc="Adjust connected nodes", + value=False, ) ) - prop.append(_PropHelper( - type = "App::PropertyBool", - name = "CyclicSymmetry", - group = "Geometry", - doc = "Define cyclic symmetry model", - value = False + prop.append( + _PropHelper( + type="App::PropertyBool", + name="CyclicSymmetry", + group="Geometry", + doc="Define cyclic symmetry model", + value=False, ) ) - prop.append(_PropHelper( - type = "App::PropertyPlacement", - name = "SymmetryAxis", - group = "Geometry", - doc = "Placement of axis of symmetry", - value = FreeCAD.Placement() + prop.append( + _PropHelper( + type="App::PropertyPlacement", + name="SymmetryAxis", + group="Geometry", + doc="Placement of axis of symmetry", + value=FreeCAD.Placement(), ) ) - prop.append(_PropHelper( - type = "App::PropertyInteger", - name = "Sectors", - group = "Geometry", - doc = "Number of sectors", - value = 0 + prop.append( + _PropHelper( + type="App::PropertyInteger", + name="Sectors", + group="Geometry", + doc="Number of sectors", + value=0, ) ) - prop.append(_PropHelper( - type = "App::PropertyInteger", - name = "ConnectedSectors", - group = "Geometry", - doc = "Number of connected sectors", - value = 1 + prop.append( + _PropHelper( + type="App::PropertyInteger", + name="ConnectedSectors", + group="Geometry", + doc="Number of connected sectors", + value=1, ) ) return prop - def onDocumentRestored(self, obj): # update old project with new properties for prop in self._get_properties(): diff --git a/src/Mod/Fem/femobjects/element_fluid1D.py b/src/Mod/Fem/femobjects/element_fluid1D.py index 822f6871ae..bd3672fa70 100644 --- a/src/Mod/Fem/femobjects/element_fluid1D.py +++ b/src/Mod/Fem/femobjects/element_fluid1D.py @@ -31,10 +31,10 @@ __url__ = "https://www.freecad.org" # \ingroup FEM # \brief element fluid 1D object -from . import base_femelement +from . import base_fempythonobject -class ElementFluid1D(base_femelement.BaseFemElement): +class ElementFluid1D(base_fempythonobject.BaseFemPythonObject): """ The element_fluid1D object """ @@ -55,19 +55,21 @@ class ElementFluid1D(base_femelement.BaseFemElement): "PIPE BEND", "PIPE GATE VALVE", "LIQUID PUMP", - "PIPE WHITE-COLEBROOK" + "PIPE WHITE-COLEBROOK", ] known_gas_types = ["NONE"] known_channel_types = ["NONE"] def __init__(self, obj): - super(ElementFluid1D, self).__init__(obj) + super().__init__(obj) obj.addProperty( - "App::PropertyEnumeration", - "SectionType", - "FluidSection", - "select fluid section type" + "App::PropertyLinkSubList", "References", "FluidSection", "List of fluid section shapes" + ) + obj.setPropertyStatus("References", "LockDynamic") + + obj.addProperty( + "App::PropertyEnumeration", "SectionType", "FluidSection", "select fluid section type" ) obj.setPropertyStatus("SectionType", "LockDynamic") @@ -75,7 +77,7 @@ class ElementFluid1D(base_femelement.BaseFemElement): "App::PropertyEnumeration", "LiquidSectionType", "LiquidSection", - "select liquid section type" + "select liquid section type", ) obj.setPropertyStatus("LiquidSectionType", "LockDynamic") @@ -83,7 +85,7 @@ class ElementFluid1D(base_femelement.BaseFemElement): "App::PropertyArea", "ManningArea", "LiquidManning", - "set area of the manning fluid section" + "set area of the manning fluid section", ) obj.setPropertyStatus("ManningArea", "LockDynamic") @@ -91,7 +93,7 @@ class ElementFluid1D(base_femelement.BaseFemElement): "App::PropertyLength", "ManningRadius", "LiquidManning", - "set hydraulic radius of manning fluid section" + "set hydraulic radius of manning fluid section", ) obj.setPropertyStatus("ManningRadius", "LockDynamic") @@ -99,7 +101,7 @@ class ElementFluid1D(base_femelement.BaseFemElement): "App::PropertyFloat", "ManningCoefficient", "LiquidManning", - "set coefficient of manning fluid section" + "set coefficient of manning fluid section", ) obj.setPropertyStatus("ManningCoefficient", "LockDynamic") @@ -107,14 +109,14 @@ class ElementFluid1D(base_femelement.BaseFemElement): "App::PropertyArea", "EnlargeArea1", "LiquidEnlargement", - "set initial area of the enlargement fluid section" + "set initial area of the enlargement fluid section", ) obj.setPropertyStatus("EnlargeArea1", "LockDynamic") obj.addProperty( "App::PropertyArea", "EnlargeArea2", "LiquidEnlargement", - "set enlarged area of enlargement fluid section" + "set enlarged area of enlargement fluid section", ) obj.setPropertyStatus("EnlargeArea2", "LockDynamic") @@ -122,7 +124,7 @@ class ElementFluid1D(base_femelement.BaseFemElement): "App::PropertyArea", "ContractArea1", "LiquidContraction", - "set initial area of the contraction fluid section" + "set initial area of the contraction fluid section", ) obj.setPropertyStatus("ContractArea1", "LockDynamic") @@ -130,7 +132,7 @@ class ElementFluid1D(base_femelement.BaseFemElement): "App::PropertyArea", "ContractArea2", "LiquidContraction", - "set contracted area of contraction fluid section" + "set contracted area of contraction fluid section", ) obj.setPropertyStatus("ContractArea2", "LockDynamic") @@ -138,7 +140,7 @@ class ElementFluid1D(base_femelement.BaseFemElement): "App::PropertyFloat", "InletPressure", "LiquidInlet", - "set inlet pressure for fluid section" + "set inlet pressure for fluid section", ) obj.setPropertyStatus("InletPressure", "LockDynamic") @@ -146,7 +148,7 @@ class ElementFluid1D(base_femelement.BaseFemElement): "App::PropertyFloat", "OutletPressure", "LiquidOutlet", - "set outlet pressure for fluid section" + "set outlet pressure for fluid section", ) obj.setPropertyStatus("OutletPressure", "LockDynamic") @@ -154,7 +156,7 @@ class ElementFluid1D(base_femelement.BaseFemElement): "App::PropertyFloat", "InletFlowRate", "LiquidInlet", - "set inlet mass flow rate for fluid section" + "set inlet mass flow rate for fluid section", ) obj.setPropertyStatus("InletFlowRate", "LockDynamic") @@ -162,7 +164,7 @@ class ElementFluid1D(base_femelement.BaseFemElement): "App::PropertyFloat", "OutletFlowRate", "LiquidOutlet", - "set outlet mass flow rate for fluid section" + "set outlet mass flow rate for fluid section", ) obj.setPropertyStatus("OutletFlowRate", "LockDynamic") @@ -170,7 +172,7 @@ class ElementFluid1D(base_femelement.BaseFemElement): "App::PropertyBool", "InletPressureActive", "LiquidInlet", - "activates or deactivates inlet pressure for fluid section" + "activates or deactivates inlet pressure for fluid section", ) obj.setPropertyStatus("InletPressureActive", "LockDynamic") @@ -178,7 +180,7 @@ class ElementFluid1D(base_femelement.BaseFemElement): "App::PropertyBool", "OutletPressureActive", "LiquidOutlet", - "activates or deactivates outlet pressure for fluid section" + "activates or deactivates outlet pressure for fluid section", ) obj.setPropertyStatus("OutletPressureActive", "LockDynamic") @@ -186,7 +188,7 @@ class ElementFluid1D(base_femelement.BaseFemElement): "App::PropertyBool", "InletFlowRateActive", "LiquidInlet", - "activates or deactivates inlet flow rate for fluid section" + "activates or deactivates inlet flow rate for fluid section", ) obj.setPropertyStatus("InletFlowRateActive", "LockDynamic") @@ -194,7 +196,7 @@ class ElementFluid1D(base_femelement.BaseFemElement): "App::PropertyBool", "OutletFlowRateActive", "LiquidOutlet", - "activates or deactivates outlet flow rate for fluid section" + "activates or deactivates outlet flow rate for fluid section", ) obj.setPropertyStatus("OutletFlowRateActive", "LockDynamic") @@ -202,7 +204,7 @@ class ElementFluid1D(base_femelement.BaseFemElement): "App::PropertyArea", "EntrancePipeArea", "LiquidEntrance", - "set the pipe area of the entrance fluid section" + "set the pipe area of the entrance fluid section", ) obj.setPropertyStatus("EntrancePipeArea", "LockDynamic") @@ -210,7 +212,7 @@ class ElementFluid1D(base_femelement.BaseFemElement): "App::PropertyArea", "EntranceArea", "LiquidEntrance", - "set the entrance area of the entrance fluid section" + "set the entrance area of the entrance fluid section", ) obj.setPropertyStatus("EntranceArea", "LockDynamic") @@ -218,7 +220,7 @@ class ElementFluid1D(base_femelement.BaseFemElement): "App::PropertyArea", "DiaphragmPipeArea", "LiquidDiaphragm", - "set the pipe area of the diaphragm fluid section" + "set the pipe area of the diaphragm fluid section", ) obj.setPropertyStatus("DiaphragmPipeArea", "LockDynamic") @@ -226,7 +228,7 @@ class ElementFluid1D(base_femelement.BaseFemElement): "App::PropertyArea", "DiaphragmArea", "LiquidDiaphragm", - "set the diaphragm area of the diaphragm fluid section" + "set the diaphragm area of the diaphragm fluid section", ) obj.setPropertyStatus("DiaphragmArea", "LockDynamic") @@ -234,7 +236,7 @@ class ElementFluid1D(base_femelement.BaseFemElement): "App::PropertyArea", "BendPipeArea", "LiquidBend", - "set pipe area of the bend fluid section" + "set pipe area of the bend fluid section", ) obj.setPropertyStatus("BendPipeArea", "LockDynamic") @@ -242,7 +244,7 @@ class ElementFluid1D(base_femelement.BaseFemElement): "App::PropertyFloat", "BendRadiusDiameter", "LiquidBend", - "set ratio of bend radius over pipe diameter of the bend fluid section" + "set ratio of bend radius over pipe diameter of the bend fluid section", ) obj.setPropertyStatus("BendRadiusDiameter", "LockDynamic") @@ -250,7 +252,7 @@ class ElementFluid1D(base_femelement.BaseFemElement): "App::PropertyFloat", "BendAngle", "LiquidBend", - "set bend angle of the bend fluid section" + "set bend angle of the bend fluid section", ) obj.setPropertyStatus("BendAngle", "LockDynamic") @@ -258,7 +260,7 @@ class ElementFluid1D(base_femelement.BaseFemElement): "App::PropertyFloat", "BendLossCoefficient", "LiquidBend", - "set loss coefficient of the bend fluid section" + "set loss coefficient of the bend fluid section", ) obj.setPropertyStatus("BendLossCoefficient", "LockDynamic") @@ -266,7 +268,7 @@ class ElementFluid1D(base_femelement.BaseFemElement): "App::PropertyArea", "GateValvePipeArea", "LiquidGateValve", - "set pipe area of the gate valve fluid section" + "set pipe area of the gate valve fluid section", ) obj.setPropertyStatus("GateValvePipeArea", "LockDynamic") @@ -274,7 +276,7 @@ class ElementFluid1D(base_femelement.BaseFemElement): "App::PropertyFloat", "GateValveClosingCoeff", "LiquidGateValve", - "set closing coefficient of the gate valve fluid section" + "set closing coefficient of the gate valve fluid section", ) obj.setPropertyStatus("GateValveClosingCoeff", "LockDynamic") @@ -282,7 +284,7 @@ class ElementFluid1D(base_femelement.BaseFemElement): "App::PropertyFloatList", "PumpFlowRate", "LiquidPump", - "set the pump characteristic flow rate of the pump fluid section" + "set the pump characteristic flow rate of the pump fluid section", ) obj.setPropertyStatus("PumpFlowRate", "LockDynamic") @@ -290,7 +292,7 @@ class ElementFluid1D(base_femelement.BaseFemElement): "App::PropertyFloatList", "PumpHeadLoss", "LiquidPump", - "set the pump characteristic head loss of the pump fluid section" + "set the pump characteristic head loss of the pump fluid section", ) obj.setPropertyStatus("PumpHeadLoss", "LockDynamic") @@ -298,7 +300,7 @@ class ElementFluid1D(base_femelement.BaseFemElement): "App::PropertyArea", "ColebrookeArea", "LiquidColebrooke", - "set pipe area of the colebrooke fluid section" + "set pipe area of the colebrooke fluid section", ) obj.setPropertyStatus("ColebrookeArea", "LockDynamic") @@ -306,7 +308,7 @@ class ElementFluid1D(base_femelement.BaseFemElement): "App::PropertyLength", "ColebrookeRadius", "LiquidColebrooke", - "set hydraulic radius of the colebrooke fluid section" + "set hydraulic radius of the colebrooke fluid section", ) obj.setPropertyStatus("ColebrookeRadius", "LockDynamic") @@ -314,7 +316,7 @@ class ElementFluid1D(base_femelement.BaseFemElement): "App::PropertyLength", "ColebrookeGrainDiameter", "LiquidColebrooke", - "set grain diameter of the colebrooke fluid section" + "set grain diameter of the colebrooke fluid section", ) obj.setPropertyStatus("ColebrookeGrainDiameter", "LockDynamic") @@ -322,15 +324,12 @@ class ElementFluid1D(base_femelement.BaseFemElement): "App::PropertyFloat", "ColebrookeFormFactor", "LiquidColebrooke", - "set coefficient of the colebrooke fluid section" + "set coefficient of the colebrooke fluid section", ) obj.setPropertyStatus("ColebrookeFormFactor", "LockDynamic") obj.addProperty( - "App::PropertyEnumeration", - "GasSectionType", - "GasSection", - "select gas section type" + "App::PropertyEnumeration", "GasSectionType", "GasSection", "select gas section type" ) obj.setPropertyStatus("GasSectionType", "LockDynamic") @@ -338,7 +337,7 @@ class ElementFluid1D(base_femelement.BaseFemElement): "App::PropertyEnumeration", "ChannelSectionType", "ChannelSection", - "select channel section type" + "select channel section type", ) obj.setPropertyStatus("ChannelSectionType", "LockDynamic") diff --git a/src/Mod/Fem/femobjects/element_geometry1D.py b/src/Mod/Fem/femobjects/element_geometry1D.py index c7419ad5f4..0dbce423b7 100644 --- a/src/Mod/Fem/femobjects/element_geometry1D.py +++ b/src/Mod/Fem/femobjects/element_geometry1D.py @@ -29,10 +29,10 @@ __url__ = "https://www.freecad.org" # \ingroup FEM # \brief element geometry 1D object -from . import base_femelement +from . import base_fempythonobject -class ElementGeometry1D(base_femelement.BaseFemElement): +class ElementGeometry1D(base_fempythonobject.BaseFemPythonObject): """ The ElementGeometry1D object """ @@ -41,13 +41,13 @@ class ElementGeometry1D(base_femelement.BaseFemElement): known_beam_types = ["Rectangular", "Circular", "Pipe"] def __init__(self, obj): - super(ElementGeometry1D, self).__init__(obj) + super().__init__(obj) obj.addProperty( "App::PropertyLength", "RectWidth", "RectBeamSection", - "set width of the rectangular beam elements" + "set width of the rectangular beam elements", ) obj.setPropertyStatus("RectWidth", "LockDynamic") @@ -55,7 +55,7 @@ class ElementGeometry1D(base_femelement.BaseFemElement): "App::PropertyLength", "RectHeight", "RectBeamSection", - "set height of therectangular beam elements" + "set height of therectangular beam elements", ) obj.setPropertyStatus("RectHeight", "LockDynamic") @@ -63,7 +63,7 @@ class ElementGeometry1D(base_femelement.BaseFemElement): "App::PropertyLength", "CircDiameter", "CircBeamSection", - "set diameter of the circular beam elements" + "set diameter of the circular beam elements", ) obj.setPropertyStatus("CircDiameter", "LockDynamic") @@ -71,7 +71,7 @@ class ElementGeometry1D(base_femelement.BaseFemElement): "App::PropertyLength", "PipeDiameter", "PipeBeamSection", - "set outer diameter of the pipe beam elements" + "set outer diameter of the pipe beam elements", ) obj.setPropertyStatus("PipeDiameter", "LockDynamic") @@ -79,17 +79,18 @@ class ElementGeometry1D(base_femelement.BaseFemElement): "App::PropertyLength", "PipeThickness", "PipeBeamSection", - "set thickness of the pipe beam elements" + "set thickness of the pipe beam elements", ) obj.setPropertyStatus("PipeThickness", "LockDynamic") obj.addProperty( - "App::PropertyEnumeration", - "SectionType", - "BeamSection", - "select beam section type" + "App::PropertyEnumeration", "SectionType", "BeamSection", "select beam section type" ) obj.setPropertyStatus("SectionType", "LockDynamic") + obj.addProperty( + "App::PropertyLinkSubList", "References", "BeamSection", "List of beam section shapes" + ) + obj.setPropertyStatus("References", "LockDynamic") obj.SectionType = ElementGeometry1D.known_beam_types obj.SectionType = "Rectangular" diff --git a/src/Mod/Fem/femobjects/element_geometry2D.py b/src/Mod/Fem/femobjects/element_geometry2D.py index d9e1c2f1f5..ad520197cb 100644 --- a/src/Mod/Fem/femobjects/element_geometry2D.py +++ b/src/Mod/Fem/femobjects/element_geometry2D.py @@ -29,10 +29,10 @@ __url__ = "https://www.freecad.org" # \ingroup FEM # \brief element geometry 2D object -from . import base_femelement +from . import base_fempythonobject -class ElementGeometry2D(base_femelement.BaseFemElement): +class ElementGeometry2D(base_fempythonobject.BaseFemPythonObject): """ The ElementGeometry2D object """ @@ -40,12 +40,20 @@ class ElementGeometry2D(base_femelement.BaseFemElement): Type = "Fem::ElementGeometry2D" def __init__(self, obj): - super(ElementGeometry2D, self).__init__(obj) + super().__init__(obj) obj.addProperty( "App::PropertyLength", "Thickness", "ShellThickness", - "set thickness of the shell elements" + "set thickness of the shell elements", ) obj.setPropertyStatus("Thickness", "LockDynamic") + + obj.addProperty( + "App::PropertyLinkSubList", + "References", + "ShellThickness", + "List of shell thickness shapes", + ) + obj.setPropertyStatus("References", "LockDynamic") diff --git a/src/Mod/Fem/femobjects/element_rotation1D.py b/src/Mod/Fem/femobjects/element_rotation1D.py index ab6cf669bc..ddfefa84da 100644 --- a/src/Mod/Fem/femobjects/element_rotation1D.py +++ b/src/Mod/Fem/femobjects/element_rotation1D.py @@ -29,10 +29,10 @@ __url__ = "https://www.freecad.org" # \ingroup FEM # \brief element rotation 1D object -from . import base_femelement +from . import base_fempythonobject -class ElementRotation1D(base_femelement.BaseFemElement): +class ElementRotation1D(base_fempythonobject.BaseFemPythonObject): """ The ElementRotation1D object """ @@ -40,12 +40,14 @@ class ElementRotation1D(base_femelement.BaseFemElement): Type = "Fem::ElementRotation1D" def __init__(self, obj): - super(ElementRotation1D, self).__init__(obj) + super().__init__(obj) obj.addProperty( - "App::PropertyAngle", - "Rotation", - "BeamRotation", - "Set the rotation of beam elements" + "App::PropertyAngle", "Rotation", "BeamRotation", "Set the rotation of beam elements" ) obj.setPropertyStatus("Rotation", "LockDynamic") + + obj.addProperty( + "App::PropertyLinkSubList", "References", "BeamRotation", "List of beam rotation shapes" + ) + obj.setPropertyStatus("References", "LockDynamic") diff --git a/src/Mod/Fem/femobjects/material_common.py b/src/Mod/Fem/femobjects/material_common.py index 163dc306d5..a069318915 100644 --- a/src/Mod/Fem/femobjects/material_common.py +++ b/src/Mod/Fem/femobjects/material_common.py @@ -41,7 +41,7 @@ class MaterialCommon(base_fempythonobject.BaseFemPythonObject): Type = "Fem::MaterialCommon" def __init__(self, obj): - super(MaterialCommon, self).__init__(obj) + super().__init__(obj) self.add_properties(obj) def onDocumentRestored(self, obj): @@ -51,20 +51,14 @@ class MaterialCommon(base_fempythonobject.BaseFemPythonObject): # References if not hasattr(obj, "References"): obj.addProperty( - "App::PropertyLinkSubList", - "References", - "Material", - "List of material shapes" + "App::PropertyLinkSubList", "References", "Material", "List of material shapes" ) obj.setPropertyStatus("References", "LockDynamic") # Category # attribute Category was added in commit 61fb3d429a if not hasattr(obj, "Category"): obj.addProperty( - "App::PropertyEnumeration", - "Category", - "Material", - "Material type: fluid or solid" + "App::PropertyEnumeration", "Category", "Material", "Material type: fluid or solid" ) obj.setPropertyStatus("Category", "LockDynamic") obj.Category = ["Solid", "Fluid"] # used in TaskPanel diff --git a/src/Mod/Fem/femobjects/material_mechanicalnonlinear.py b/src/Mod/Fem/femobjects/material_mechanicalnonlinear.py index 77d8ebaf13..8aa8ca4c94 100644 --- a/src/Mod/Fem/femobjects/material_mechanicalnonlinear.py +++ b/src/Mod/Fem/femobjects/material_mechanicalnonlinear.py @@ -40,7 +40,7 @@ class MaterialMechanicalNonlinear(base_fempythonobject.BaseFemPythonObject): Type = "Fem::MaterialMechanicalNonlinear" def __init__(self, obj): - super(MaterialMechanicalNonlinear, self).__init__(obj) + super().__init__(obj) self.add_properties(obj) def onDocumentRestored(self, obj): @@ -77,24 +77,30 @@ class MaterialMechanicalNonlinear(base_fempythonobject.BaseFemPythonObject): "App::PropertyLink", "LinearBaseMaterial", "Base", - "Set the linear material the nonlinear builds upon." + "Set the linear material the nonlinear builds upon.", ) obj.setPropertyStatus("LinearBaseMaterial", "LockDynamic") if not hasattr(obj, "MaterialModelNonlinearity"): - choices_nonlinear_material_models = ["isotropic hardening","kinematic hardening"] + choices_nonlinear_material_models = ["isotropic hardening", "kinematic hardening"] obj.addProperty( "App::PropertyEnumeration", "MaterialModelNonlinearity", "Fem", - "Set the type on nonlinear material model" + "Set the type on nonlinear material model", ) obj.setPropertyStatus("MaterialModelNonlinearity", "LockDynamic") obj.MaterialModelNonlinearity = choices_nonlinear_material_models obj.MaterialModelNonlinearity = choices_nonlinear_material_models[0] - if hasattr(obj, "MaterialModelNonlinearity") and obj.MaterialModelNonlinearity == "simple hardening": - updated_choices_nonlinear_material_models = ["isotropic hardening", "kinematic hardening"] + if ( + hasattr(obj, "MaterialModelNonlinearity") + and obj.MaterialModelNonlinearity == "simple hardening" + ): + updated_choices_nonlinear_material_models = [ + "isotropic hardening", + "kinematic hardening", + ] obj.MaterialModelNonlinearity = updated_choices_nonlinear_material_models obj.MaterialModelNonlinearity = updated_choices_nonlinear_material_models[0] @@ -104,7 +110,7 @@ class MaterialMechanicalNonlinear(base_fempythonobject.BaseFemPythonObject): "YieldPoints", "Fem", "Set stress and strain for yield points as a list of strings, " - "each point \"stress, plastic strain\"" + 'each point "stress, plastic strain"', ) obj.setPropertyStatus("YieldPoints", "LockDynamic") obj.YieldPoints = [] diff --git a/src/Mod/Fem/femobjects/material_reinforced.py b/src/Mod/Fem/femobjects/material_reinforced.py index 19081e835a..13f984ea01 100644 --- a/src/Mod/Fem/femobjects/material_reinforced.py +++ b/src/Mod/Fem/femobjects/material_reinforced.py @@ -40,29 +40,20 @@ class MaterialReinforced(base_fempythonobject.BaseFemPythonObject): Type = "Fem::MaterialReinforced" def __init__(self, obj): - super(MaterialReinforced, self).__init__(obj) + super().__init__(obj) obj.addProperty( - "App::PropertyLinkSubList", - "References", - "Material", - "List of material shapes" + "App::PropertyLinkSubList", "References", "Material", "List of material shapes" ) obj.setPropertyStatus("References", "LockDynamic") obj.addProperty( - "App::PropertyMap", - "Reinforcement", - "Composites", - "Reinforcement material properties" + "App::PropertyMap", "Reinforcement", "Composites", "Reinforcement material properties" ) obj.setPropertyStatus("Reinforcement", "LockDynamic") obj.addProperty( - "App::PropertyEnumeration", - "Category", - "Material", - "Matrix material properties" + "App::PropertyEnumeration", "Category", "Material", "Matrix material properties" ) obj.setPropertyStatus("Category", "LockDynamic") diff --git a/src/Mod/Fem/femobjects/mesh_boundarylayer.py b/src/Mod/Fem/femobjects/mesh_boundarylayer.py index 0e339ee970..0945227d8f 100644 --- a/src/Mod/Fem/femobjects/mesh_boundarylayer.py +++ b/src/Mod/Fem/femobjects/mesh_boundarylayer.py @@ -29,10 +29,10 @@ __url__ = "https://www.freecad.org" # \ingroup FEM # \brief mesh boundary layer object -from . import base_femmeshelement +from . import base_fempythonobject -class MeshBoundaryLayer(base_femmeshelement.BaseFemMeshElement): +class MeshBoundaryLayer(base_fempythonobject.BaseFemPythonObject): """ The MeshBoundaryLayer object """ @@ -40,13 +40,13 @@ class MeshBoundaryLayer(base_femmeshelement.BaseFemMeshElement): Type = "Fem::MeshBoundaryLayer" def __init__(self, obj): - super(MeshBoundaryLayer, self).__init__(obj) + super().__init__(obj) obj.addProperty( "App::PropertyInteger", "NumberOfLayers", "MeshBoundaryLayerProperties", - "set number of inflation layers for this boundary" + "set number of inflation layers for this boundary", ) obj.setPropertyStatus("NumberOfLayers", "LockDynamic") obj.NumberOfLayers = 3 @@ -55,7 +55,7 @@ class MeshBoundaryLayer(base_femmeshelement.BaseFemMeshElement): "App::PropertyLength", "MinimumThickness", "MeshBoundaryLayerProperties", - "set minimum thickness,usually the first inflation layer" + "set minimum thickness,usually the first inflation layer", ) obj.setPropertyStatus("MinimumThickness", "LockDynamic") # default to zero, user must specify a proper value for this property @@ -64,7 +64,15 @@ class MeshBoundaryLayer(base_femmeshelement.BaseFemMeshElement): "App::PropertyFloat", "GrowthRate", "MeshBoundaryLayerProperties", - "set growth rate of inflation layers for smooth transition" + "set growth rate of inflation layers for smooth transition", ) obj.setPropertyStatus("GrowthRate", "LockDynamic") obj.GrowthRate = 1.5 + + obj.addProperty( + "App::PropertyLinkSubList", + "References", + "MeshBoundaryLayerShapes", + "List of FEM mesh region shapes", + ) + obj.setPropertyStatus("References", "LockDynamic") diff --git a/src/Mod/Fem/femobjects/mesh_gmsh.py b/src/Mod/Fem/femobjects/mesh_gmsh.py index 91572d1cf5..5c7beefd17 100644 --- a/src/Mod/Fem/femobjects/mesh_gmsh.py +++ b/src/Mod/Fem/femobjects/mesh_gmsh.py @@ -49,7 +49,7 @@ class MeshGmsh(base_fempythonobject.BaseFemPythonObject): "Frontal", "BAMG", "DelQuad", - "Packing Parallelograms" + "Packing Parallelograms", ] known_mesh_algorithm_3D = [ "Automatic", @@ -58,30 +58,25 @@ class MeshGmsh(base_fempythonobject.BaseFemPythonObject): "Frontal", "MMG3D", "R-tree", - "HXT" + "HXT", ] known_mesh_RecombinationAlgorithms = [ "Simple", "Blossom", "Simple full-quad", - "Blossom full-quad" + "Blossom full-quad", ] known_mesh_HighOrderOptimizers = [ "None", "Optimization", "Elastic+Optimization", "Elastic", - "Fast curving" - ] - known_mesh_SubdivisionAlgorithms = [ - "None", - "All Quadrangles", - "All Hexahedra", - "Barycentric" + "Fast curving", ] + known_mesh_SubdivisionAlgorithms = ["None", "All Quadrangles", "All Hexahedra", "Barycentric"] def __init__(self, obj): - super(MeshGmsh, self).__init__(obj) + super().__init__(obj) self.add_properties(obj) def onDocumentRestored(self, obj): @@ -116,27 +111,21 @@ class MeshGmsh(base_fempythonobject.BaseFemPythonObject): "App::PropertyLinkList", "MeshBoundaryLayerList", "Base", - "Mesh boundaries need inflation layers" + "Mesh boundaries need inflation layers", ) obj.setPropertyStatus("MeshBoundaryLayerList", "LockDynamic") obj.MeshBoundaryLayerList = [] if not hasattr(obj, "MeshRegionList"): obj.addProperty( - "App::PropertyLinkList", - "MeshRegionList", - "Base", - "Mesh refinments of the mesh" + "App::PropertyLinkList", "MeshRegionList", "Base", "Mesh refinments of the mesh" ) obj.setPropertyStatus("MeshRegionList", "LockDynamic") obj.MeshRegionList = [] if not hasattr(obj, "MeshGroupList"): obj.addProperty( - "App::PropertyLinkList", - "MeshGroupList", - "Base", - "Mesh groups of the mesh" + "App::PropertyLinkList", "MeshGroupList", "Base", "Mesh groups of the mesh" ) obj.setPropertyStatus("MeshGroupList", "LockDynamic") obj.MeshGroupList = [] @@ -146,7 +135,7 @@ class MeshGmsh(base_fempythonobject.BaseFemPythonObject): "App::PropertyLink", "Part", "FEM Mesh", - "Geometry object, the mesh is made from. The geometry object has to have a Shape." + "Geometry object, the mesh is made from. The geometry object has to have a Shape.", ) obj.setPropertyStatus("Part", "LockDynamic") obj.Part = None @@ -156,7 +145,7 @@ class MeshGmsh(base_fempythonobject.BaseFemPythonObject): "App::PropertyLength", "CharacteristicLengthMax", "FEM Gmsh Mesh Params", - "Max mesh element size (0.0 = infinity)" + "Max mesh element size (0.0 = infinity)", ) obj.setPropertyStatus("CharacteristicLengthMax", "LockDynamic") obj.CharacteristicLengthMax = 0.0 # will be 1e+22 @@ -166,7 +155,7 @@ class MeshGmsh(base_fempythonobject.BaseFemPythonObject): "App::PropertyLength", "CharacteristicLengthMin", "FEM Gmsh Mesh Params", - "Min mesh element size" + "Min mesh element size", ) obj.setPropertyStatus("CharacteristicLengthMin", "LockDynamic") obj.CharacteristicLengthMin = 0.0 @@ -176,7 +165,7 @@ class MeshGmsh(base_fempythonobject.BaseFemPythonObject): "App::PropertyEnumeration", "ElementDimension", "FEM Gmsh Mesh Params", - "Dimension of mesh elements (Auto = according ShapeType of part to mesh)" + "Dimension of mesh elements (Auto = according ShapeType of part to mesh)", ) obj.setPropertyStatus("ElementDimension", "LockDynamic") obj.ElementDimension = MeshGmsh.known_element_dimensions @@ -187,7 +176,7 @@ class MeshGmsh(base_fempythonobject.BaseFemPythonObject): "App::PropertyEnumeration", "ElementOrder", "FEM Gmsh Mesh Params", - "Order of mesh elements" + "Order of mesh elements", ) obj.setPropertyStatus("ElementOrder", "LockDynamic") obj.ElementOrder = MeshGmsh.known_element_orders @@ -198,7 +187,7 @@ class MeshGmsh(base_fempythonobject.BaseFemPythonObject): "App::PropertyBool", "OptimizeStd", "FEM Gmsh Mesh Params", - "Optimize tetrahedral elements" + "Optimize tetrahedral elements", ) obj.setPropertyStatus("OptimizeStd", "LockDynamic") obj.OptimizeStd = True @@ -208,7 +197,7 @@ class MeshGmsh(base_fempythonobject.BaseFemPythonObject): "App::PropertyBool", "OptimizeNetgen", "FEM Gmsh Mesh Params", - "Optimize tetra elements by use of Netgen" + "Optimize tetra elements by use of Netgen", ) obj.setPropertyStatus("OptimizeNetgen", "LockDynamic") obj.OptimizeNetgen = False @@ -218,7 +207,7 @@ class MeshGmsh(base_fempythonobject.BaseFemPythonObject): "App::PropertyEnumeration", "HighOrderOptimize", "FEM Gmsh Mesh Params", - "Optimization of high order meshes" + "Optimization of high order meshes", ) obj.setPropertyStatus("HighOrderOptimize", "LockDynamic") obj.HighOrderOptimize = MeshGmsh.known_mesh_HighOrderOptimizers @@ -229,7 +218,7 @@ class MeshGmsh(base_fempythonobject.BaseFemPythonObject): "App::PropertyBool", "RecombineAll", "FEM Gmsh Mesh Params", - "Apply recombination algorithm to all surfaces" + "Apply recombination algorithm to all surfaces", ) obj.setPropertyStatus("RecombineAll", "LockDynamic") obj.RecombineAll = False @@ -239,7 +228,7 @@ class MeshGmsh(base_fempythonobject.BaseFemPythonObject): "App::PropertyBool", "Recombine3DAll", "FEM Gmsh Mesh Params", - "Apply recombination algorithm to all volumes" + "Apply recombination algorithm to all volumes", ) obj.setPropertyStatus("Recombine3DAll", "LockDynamic") obj.Recombine3DAll = False @@ -249,7 +238,7 @@ class MeshGmsh(base_fempythonobject.BaseFemPythonObject): "App::PropertyEnumeration", "RecombinationAlgorithm", "FEM Gmsh Mesh Params", - "Recombination algorithm" + "Recombination algorithm", ) obj.setPropertyStatus("RecombinationAlgorithm", "LockDynamic") obj.RecombinationAlgorithm = MeshGmsh.known_mesh_RecombinationAlgorithms @@ -260,7 +249,7 @@ class MeshGmsh(base_fempythonobject.BaseFemPythonObject): "App::PropertyBool", "CoherenceMesh", "FEM Gmsh Mesh Params", - "Removes all duplicate mesh vertices" + "Removes all duplicate mesh vertices", ) obj.setPropertyStatus("CoherenceMesh", "LockDynamic") obj.CoherenceMesh = True @@ -270,7 +259,7 @@ class MeshGmsh(base_fempythonobject.BaseFemPythonObject): "App::PropertyFloat", "GeometryTolerance", "FEM Gmsh Mesh Params", - "Geometrical Tolerance (0.0 = GMSH std = 1e-08)" + "Geometrical Tolerance (0.0 = GMSH std = 1e-08)", ) obj.setPropertyStatus("GeometryTolerance", "LockDynamic") obj.GeometryTolerance = 1e-06 @@ -280,7 +269,7 @@ class MeshGmsh(base_fempythonobject.BaseFemPythonObject): "App::PropertyBool", "SecondOrderLinear", "FEM Gmsh Mesh Params", - "Second order nodes are created by linear interpolation" + "Second order nodes are created by linear interpolation", ) obj.setPropertyStatus("SecondOrderLinear", "LockDynamic") obj.SecondOrderLinear = False @@ -296,7 +285,7 @@ class MeshGmsh(base_fempythonobject.BaseFemPythonObject): "App::PropertyIntegerConstraint", "MeshSizeFromCurvature", "FEM Gmsh Mesh Params", - "number of elements per 2*pi radians, 0 to deactivate" + "number of elements per 2*pi radians, 0 to deactivate", ) obj.setPropertyStatus("MeshSizeFromCurvature", "LockDynamic") obj.MeshSizeFromCurvature = (12, 0, 10000, 1) @@ -306,7 +295,7 @@ class MeshGmsh(base_fempythonobject.BaseFemPythonObject): "App::PropertyEnumeration", "Algorithm2D", "FEM Gmsh Mesh Params", - "mesh algorithm 2D" + "mesh algorithm 2D", ) obj.setPropertyStatus("Algorithm2D", "LockDynamic") obj.Algorithm2D = MeshGmsh.known_mesh_algorithm_2D @@ -317,7 +306,7 @@ class MeshGmsh(base_fempythonobject.BaseFemPythonObject): "App::PropertyEnumeration", "Algorithm3D", "FEM Gmsh Mesh Params", - "mesh algorithm 3D" + "mesh algorithm 3D", ) obj.setPropertyStatus("Algorithm3D", "LockDynamic") obj.Algorithm3D = MeshGmsh.known_mesh_algorithm_3D @@ -328,7 +317,7 @@ class MeshGmsh(base_fempythonobject.BaseFemPythonObject): "App::PropertyBool", "GroupsOfNodes", "FEM Gmsh Mesh Params", - "For each group create not only the elements but the nodes too." + "For each group create not only the elements but the nodes too.", ) obj.setPropertyStatus("GroupsOfNodes", "LockDynamic") obj.GroupsOfNodes = False @@ -338,7 +327,7 @@ class MeshGmsh(base_fempythonobject.BaseFemPythonObject): "App::PropertyEnumeration", "SubdivisionAlgorithm", "FEM Gmsh Mesh Params", - "Mesh subdivision algorithm" + "Mesh subdivision algorithm", ) obj.setPropertyStatus("SubdivisionAlgorithm", "LockDynamic") obj.SubdivisionAlgorithm = MeshGmsh.known_mesh_SubdivisionAlgorithms diff --git a/src/Mod/Fem/femobjects/mesh_group.py b/src/Mod/Fem/femobjects/mesh_group.py index 82fd957b31..9f4f8502f2 100644 --- a/src/Mod/Fem/femobjects/mesh_group.py +++ b/src/Mod/Fem/femobjects/mesh_group.py @@ -29,10 +29,10 @@ __url__ = "https://www.freecad.org" # \ingroup FEM # \brief mesh group object -from . import base_femmeshelement +from . import base_fempythonobject -class MeshGroup(base_femmeshelement.BaseFemMeshElement): +class MeshGroup(base_fempythonobject.BaseFemPythonObject): """ The MeshGroup object """ @@ -40,12 +40,20 @@ class MeshGroup(base_femmeshelement.BaseFemMeshElement): Type = "Fem::MeshGroup" def __init__(self, obj): - super(MeshGroup, self).__init__(obj) + super().__init__(obj) obj.addProperty( "App::PropertyBool", "UseLabel", "MeshGroupProperties", - "The identifier used for export (True: Label, False: Name)" + "The identifier used for export (True: Label, False: Name)", ) obj.setPropertyStatus("UseLabel", "LockDynamic") + + obj.addProperty( + "App::PropertyLinkSubList", + "References", + "MeshGroupShapes", + "List of FEM mesh group shapes", + ) + obj.setPropertyStatus("References", "LockDynamic") diff --git a/src/Mod/Fem/femobjects/mesh_region.py b/src/Mod/Fem/femobjects/mesh_region.py index dbdc4e36a3..f7673999eb 100644 --- a/src/Mod/Fem/femobjects/mesh_region.py +++ b/src/Mod/Fem/femobjects/mesh_region.py @@ -29,10 +29,10 @@ __url__ = "https://www.freecad.org" # \ingroup FEM # \brief mesh region object -from . import base_femmeshelement +from . import base_fempythonobject -class MeshRegion(base_femmeshelement.BaseFemMeshElement): +class MeshRegion(base_fempythonobject.BaseFemPythonObject): """ The FemMeshRegion object """ @@ -40,12 +40,20 @@ class MeshRegion(base_femmeshelement.BaseFemMeshElement): Type = "Fem::MeshRegion" def __init__(self, obj): - super(MeshRegion, self).__init__(obj) + super().__init__(obj) obj.addProperty( "App::PropertyLength", "CharacteristicLength", "MeshRegionProperties", - "set characteristic length of FEM elements for this refinement" + "set characteristic length of FEM elements for this refinement", ) obj.setPropertyStatus("CharacteristicLength", "LockDynamic") + + obj.addProperty( + "App::PropertyLinkSubList", + "References", + "MeshRegionShapes", + "List of FEM mesh refinement shapes", + ) + obj.setPropertyStatus("References", "LockDynamic") diff --git a/src/Mod/Fem/femobjects/mesh_result.py b/src/Mod/Fem/femobjects/mesh_result.py index ac7ed9f9c0..ee093b3c7f 100644 --- a/src/Mod/Fem/femobjects/mesh_result.py +++ b/src/Mod/Fem/femobjects/mesh_result.py @@ -40,4 +40,4 @@ class MeshResult(base_fempythonobject.BaseFemPythonObject): Type = "Fem::MeshResult" def __init__(self, obj): - super(MeshResult, self).__init__(obj) + super().__init__(obj) diff --git a/src/Mod/Fem/femobjects/result_mechanical.py b/src/Mod/Fem/femobjects/result_mechanical.py index 6887b09679..619bcdcc1a 100644 --- a/src/Mod/Fem/femobjects/result_mechanical.py +++ b/src/Mod/Fem/femobjects/result_mechanical.py @@ -41,33 +41,23 @@ class ResultMechanical(base_fempythonobject.BaseFemPythonObject): Type = "Fem::ResultMechanical" def __init__(self, obj): - super(ResultMechanical, self).__init__(obj) + super().__init__(obj) obj.addProperty( "App::PropertyString", "ResultType", "Base", "Type of the result", - 1 # the 1 set the property to ReadOnly + 1, # the 1 set the property to ReadOnly ) obj.setPropertyStatus("ResultType", "LockDynamic") obj.ResultType = str(self.Type) # for frequency analysis - obj.addProperty( - "App::PropertyInteger", - "Eigenmode", - "Data", - "", - True - ) + obj.addProperty("App::PropertyInteger", "Eigenmode", "Data", "", True) obj.setPropertyStatus("Eigenmode", "LockDynamic") obj.addProperty( - "App::PropertyFloat", - "EigenmodeFrequency", - "Data", - "User Defined Results", - True + "App::PropertyFloat", "EigenmodeFrequency", "Data", "User Defined Results", True ) obj.setPropertyStatus("EigenmodeFrequency", "LockDynamic") @@ -80,7 +70,7 @@ class ResultMechanical(base_fempythonobject.BaseFemPythonObject): "DisplacementVectors", "NodeData", "List of displacement vectors", - True + True, ) obj.setPropertyStatus("DisplacementVectors", "LockDynamic") obj.addProperty( @@ -88,7 +78,7 @@ class ResultMechanical(base_fempythonobject.BaseFemPythonObject): "Peeq", "NodeData", "List of equivalent plastic strain values", - True + True, ) obj.setPropertyStatus("Peeq", "LockDynamic") obj.addProperty( @@ -96,7 +86,7 @@ class ResultMechanical(base_fempythonobject.BaseFemPythonObject): "MohrCoulomb", "NodeData", "List of Mohr Coulomb stress values", - True + True, ) obj.setPropertyStatus("MohrCoulomb", "LockDynamic") obj.addProperty( @@ -104,7 +94,7 @@ class ResultMechanical(base_fempythonobject.BaseFemPythonObject): "ReinforcementRatio_x", "NodeData", "Reinforcement ratio x-direction", - True + True, ) obj.setPropertyStatus("ReinforcementRatio_x", "LockDynamic") obj.addProperty( @@ -112,7 +102,7 @@ class ResultMechanical(base_fempythonobject.BaseFemPythonObject): "ReinforcementRatio_y", "NodeData", "Reinforcement ratio y-direction", - True + True, ) obj.setPropertyStatus("ReinforcementRatio_y", "LockDynamic") obj.addProperty( @@ -120,7 +110,7 @@ class ResultMechanical(base_fempythonobject.BaseFemPythonObject): "ReinforcementRatio_z", "NodeData", "Reinforcement ratio z-direction", - True + True, ) obj.setPropertyStatus("ReinforcementRatio_z", "LockDynamic") # these three principal vectors are used only if there is a reinforced mat obj @@ -130,7 +120,7 @@ class ResultMechanical(base_fempythonobject.BaseFemPythonObject): "PS1Vector", "NodeData", "List of 1st Principal Stress Vectors", - True + True, ) obj.setPropertyStatus("PS1Vector", "LockDynamic") obj.addProperty( @@ -138,7 +128,7 @@ class ResultMechanical(base_fempythonobject.BaseFemPythonObject): "PS2Vector", "NodeData", "List of 2nd Principal Stress Vectors", - True + True, ) obj.setPropertyStatus("PS2Vector", "LockDynamic") obj.addProperty( @@ -146,7 +136,7 @@ class ResultMechanical(base_fempythonobject.BaseFemPythonObject): "PS3Vector", "NodeData", "List of 3rd Principal Stress Vectors", - True + True, ) obj.setPropertyStatus("PS3Vector", "LockDynamic") @@ -156,7 +146,7 @@ class ResultMechanical(base_fempythonobject.BaseFemPythonObject): "DisplacementLengths", "NodeData", "List of displacement lengths", - True + True, ) obj.setPropertyStatus("DisplacementLengths", "LockDynamic") obj.addProperty( @@ -164,39 +154,21 @@ class ResultMechanical(base_fempythonobject.BaseFemPythonObject): "vonMises", "NodeData", "List of von Mises equivalent stresses", - True + True, ) obj.setPropertyStatus("vonMises", "LockDynamic") - obj.addProperty( - "App::PropertyFloatList", - "PrincipalMax", - "NodeData", - "", - True - ) + obj.addProperty("App::PropertyFloatList", "PrincipalMax", "NodeData", "", True) obj.setPropertyStatus("PrincipalMax", "LockDynamic") - obj.addProperty( - "App::PropertyFloatList", - "PrincipalMed", - "NodeData", - "", - True - ) + obj.addProperty("App::PropertyFloatList", "PrincipalMed", "NodeData", "", True) obj.setPropertyStatus("PrincipalMed", "LockDynamic") - obj.addProperty( - "App::PropertyFloatList", - "PrincipalMin", - "NodeData", - "", - True - ) + obj.addProperty("App::PropertyFloatList", "PrincipalMin", "NodeData", "", True) obj.setPropertyStatus("PrincipalMin", "LockDynamic") obj.addProperty( "App::PropertyFloatList", "MaxShear", "NodeData", "List of Maximum Shear stress values", - True + True, ) obj.setPropertyStatus("MaxShear", "LockDynamic") obj.addProperty( @@ -204,7 +176,7 @@ class ResultMechanical(base_fempythonobject.BaseFemPythonObject): "MassFlowRate", "NodeData", "List of mass flow rate values", - True + True, ) obj.setPropertyStatus("MassFlowRate", "LockDynamic") obj.addProperty( @@ -212,137 +184,47 @@ class ResultMechanical(base_fempythonobject.BaseFemPythonObject): "NetworkPressure", "NodeData", "List of network pressure values", - True + True, ) obj.setPropertyStatus("NetworkPressure", "LockDynamic") obj.addProperty( - "App::PropertyFloatList", - "UserDefined", - "NodeData", - "User Defined Results", - True + "App::PropertyFloatList", "UserDefined", "NodeData", "User Defined Results", True ) obj.setPropertyStatus("UserDefined", "LockDynamic") obj.addProperty( - "App::PropertyFloatList", - "Temperature", - "NodeData", - "Temperature field", - True + "App::PropertyFloatList", "Temperature", "NodeData", "Temperature field", True ) obj.addProperty( - "App::PropertyVectorList", - "HeatFlux", - "NodeData", - "List of heat flux vectors", - True + "App::PropertyVectorList", "HeatFlux", "NodeData", "List of heat flux vectors", True ) obj.setPropertyStatus("HeatFlux", "LockDynamic") - obj.setPropertyStatus("Temperature", "LockDynamic") - obj.addProperty( - "App::PropertyFloatList", - "NodeStressXX", - "NodeData", - "", - True - ) + obj.addProperty("App::PropertyFloatList", "NodeStressXX", "NodeData", "", True) obj.setPropertyStatus("NodeStressXX", "LockDynamic") - obj.addProperty( - "App::PropertyFloatList", - "NodeStressYY", - "NodeData", - "", - True - ) + obj.addProperty("App::PropertyFloatList", "NodeStressYY", "NodeData", "", True) obj.setPropertyStatus("NodeStressYY", "LockDynamic") - obj.addProperty( - "App::PropertyFloatList", - "NodeStressZZ", - "NodeData", - "", - True - ) + obj.addProperty("App::PropertyFloatList", "NodeStressZZ", "NodeData", "", True) obj.setPropertyStatus("NodeStressZZ", "LockDynamic") - obj.addProperty( - "App::PropertyFloatList", - "NodeStressXY", - "NodeData", - "", - True - ) + obj.addProperty("App::PropertyFloatList", "NodeStressXY", "NodeData", "", True) obj.setPropertyStatus("NodeStressXY", "LockDynamic") - obj.addProperty( - "App::PropertyFloatList", - "NodeStressXZ", - "NodeData", - "", - True - ) + obj.addProperty("App::PropertyFloatList", "NodeStressXZ", "NodeData", "", True) obj.setPropertyStatus("NodeStressXZ", "LockDynamic") - obj.addProperty( - "App::PropertyFloatList", - "NodeStressYZ", - "NodeData", - "", - True - ) + obj.addProperty("App::PropertyFloatList", "NodeStressYZ", "NodeData", "", True) obj.setPropertyStatus("NodeStressYZ", "LockDynamic") - obj.addProperty( - "App::PropertyFloatList", - "NodeStrainXX", - "NodeData", - "", - True - ) + obj.addProperty("App::PropertyFloatList", "NodeStrainXX", "NodeData", "", True) obj.setPropertyStatus("NodeStrainXX", "LockDynamic") - obj.addProperty( - "App::PropertyFloatList", - "NodeStrainYY", - "NodeData", - "", - True - ) + obj.addProperty("App::PropertyFloatList", "NodeStrainYY", "NodeData", "", True) obj.setPropertyStatus("NodeStrainYY", "LockDynamic") - obj.addProperty( - "App::PropertyFloatList", - "NodeStrainZZ", - "NodeData", - "", - True - ) + obj.addProperty("App::PropertyFloatList", "NodeStrainZZ", "NodeData", "", True) obj.setPropertyStatus("NodeStrainZZ", "LockDynamic") - obj.addProperty( - "App::PropertyFloatList", - "NodeStrainXY", "NodeData", - "", - True - ) + obj.addProperty("App::PropertyFloatList", "NodeStrainXY", "NodeData", "", True) obj.setPropertyStatus("NodeStrainXY", "LockDynamic") - obj.addProperty( - "App::PropertyFloatList", - "NodeStrainXZ", - "NodeData", - "", - True - ) + obj.addProperty("App::PropertyFloatList", "NodeStrainXZ", "NodeData", "", True) obj.setPropertyStatus("NodeStrainXZ", "LockDynamic") - obj.addProperty( - "App::PropertyFloatList", - "NodeStrainYZ", - "NodeData", - "", - True - ) + obj.addProperty("App::PropertyFloatList", "NodeStrainYZ", "NodeData", "", True) obj.setPropertyStatus("NodeStrainYZ", "LockDynamic") - obj.addProperty( - "App::PropertyFloatList", - "CriticalStrainRatio", - "NodeData", - "", - True - ) + obj.addProperty("App::PropertyFloatList", "CriticalStrainRatio", "NodeData", "", True) obj.setPropertyStatus("CriticalStrainRatio", "LockDynamic") # initialize the Stats with the appropriate count of items @@ -359,7 +241,7 @@ class ResultMechanical(base_fempythonobject.BaseFemPythonObject): "vonMises", "NodeData", "List of von Mises equivalent stresses", - True + True, ) obj.setPropertyStatus("vonMises", "LockDynamic") obj.vonMises = obj.StressValues diff --git a/src/Mod/Fem/femobjects/solver_ccxtools.py b/src/Mod/Fem/femobjects/solver_ccxtools.py index 4a8a26cdfa..2e9c06f148 100644 --- a/src/Mod/Fem/femobjects/solver_ccxtools.py +++ b/src/Mod/Fem/femobjects/solver_ccxtools.py @@ -36,13 +36,12 @@ from femsolver.calculix.solver import _BaseSolverCalculix class SolverCcxTools(base_fempythonobject.BaseFemPythonObject, _BaseSolverCalculix): - """The Fem::FemSolver's Proxy python type, add solver specific properties - """ + """The Fem::FemSolver's Proxy python type, add solver specific properties""" Type = "Fem::SolverCcxTools" def __init__(self, obj): - super(SolverCcxTools, self).__init__(obj) + super().__init__(obj) # implemented in framework calculix solver module self.add_attributes(obj) @@ -51,7 +50,7 @@ class SolverCcxTools(base_fempythonobject.BaseFemPythonObject, _BaseSolverCalcul "App::PropertyPath", "WorkingDir", "Fem", - "Working directory for calculations, will only be used it is left blank in preferences" + "Working directory for calculations, will only be used it is left blank in preferences", ) obj.setPropertyStatus("WorkingDir", "LockDynamic") # the working directory is not set, the solver working directory is diff --git a/src/Mod/Fem/femresult/resulttools.py b/src/Mod/Fem/femresult/resulttools.py index 385786d351..2afdf36e3c 100644 --- a/src/Mod/Fem/femresult/resulttools.py +++ b/src/Mod/Fem/femresult/resulttools.py @@ -175,9 +175,7 @@ def show_color_by_scalar_with_cutoff(resultobj, values, limit=None): if FreeCAD.GuiUp: if resultobj.Mesh.ViewObject.Visibility is False: resultobj.Mesh.ViewObject.Visibility = True - resultobj.Mesh.ViewObject.setNodeColorByScalars( - resultobj.NodeNumbers, filtered_values - ) + resultobj.Mesh.ViewObject.setNodeColorByScalars(resultobj.NodeNumbers, filtered_values) def get_stats(res_obj, result_type): @@ -255,7 +253,7 @@ def get_all_stats(res_obj): "Peeq": (m[18], m[19]), "Temp": (m[20], m[21]), "MFlow": (m[22], m[23]), - "NPress": (m[24], m[25]) + "NPress": (m[24], m[25]), } return stats_dict @@ -269,9 +267,7 @@ def fill_femresult_stats(res_obj): FreeCAD FEM mechanical result object """ - FreeCAD.Console.PrintLog( - "Calculate stats list for result obj: " + res_obj.Name + "\n" - ) + FreeCAD.Console.PrintLog("Calculate stats list for result obj: " + res_obj.Name + "\n") # set stats values to 0, they may not exist in res_obj x_min = y_min = z_min = x_max = y_max = z_max = 0 a_max = a_min = s_max = s_min = 0 @@ -315,19 +311,34 @@ def fill_femresult_stats(res_obj): npress_min = min(res_obj.NetworkPressure) npress_max = max(res_obj.NetworkPressure) - res_obj.Stats = [x_min, x_max, - y_min, y_max, - z_min, z_max, - a_min, a_max, - s_min, s_max, - p1_min, p1_max, - p2_min, p2_max, - p3_min, p3_max, - ms_min, ms_max, - peeq_min, peeq_max, - temp_min, temp_max, - mflow_min, mflow_max, - npress_min, npress_max] + res_obj.Stats = [ + x_min, + x_max, + y_min, + y_max, + z_min, + z_max, + a_min, + a_max, + s_min, + s_max, + p1_min, + p1_max, + p2_min, + p2_max, + p3_min, + p3_max, + ms_min, + ms_max, + peeq_min, + peeq_max, + temp_min, + temp_max, + mflow_min, + mflow_max, + npress_min, + npress_max, + ] """ stat_types = [ "U1", @@ -372,7 +383,7 @@ def add_von_mises(res_obj): res_obj.NodeStressZZ, res_obj.NodeStressXY, res_obj.NodeStressXZ, - res_obj.NodeStressYZ + res_obj.NodeStressYZ, ) for Sxx, Syy, Szz, Sxy, Sxz, Syz in iterator: mstress.append(calculate_von_mises((Sxx, Syy, Szz, Sxy, Sxz, Syz))) @@ -396,12 +407,10 @@ def add_principal_stress_std(res_obj): res_obj.NodeStressZZ, res_obj.NodeStressXY, res_obj.NodeStressXZ, - res_obj.NodeStressYZ + res_obj.NodeStressYZ, ) for Sxx, Syy, Szz, Sxy, Sxz, Syz in iterator: - prin1, prin2, prin3, shear = calculate_principal_stress_std( - (Sxx, Syy, Szz, Sxy, Sxz, Syz) - ) + prin1, prin2, prin3, shear = calculate_principal_stress_std((Sxx, Syy, Szz, Sxy, Sxz, Syz)) prinstress1.append(prin1) prinstress2.append(prin2) prinstress3.append(prin3) @@ -427,7 +436,7 @@ def add_principal_stress_std(res_obj): # T = pressure / von Mises stress (stress triaxiality) # - MatMechNon = FreeCAD.ActiveDocument.getObject('MaterialMechanicalNonlinear') + MatMechNon = FreeCAD.ActiveDocument.getObject("MaterialMechanicalNonlinear") if MatMechNon: stress_strain = MatMechNon.YieldPoints if stress_strain: @@ -440,12 +449,7 @@ def add_principal_stress_std(res_obj): beta = 1.5 if res_obj.Peeq: res_obj.CriticalStrainRatio = calculate_csr( - prinstress1, - prinstress2, - prinstress3, - alpha, - beta, - res_obj + prinstress1, prinstress2, prinstress3, alpha, beta, res_obj ) return res_obj @@ -473,10 +477,10 @@ def calculate_csr(ps1, ps2, ps3, alpha, beta, res_obj): svm = np.sqrt( 1.5 * (ps1[i] - p) ** 2 + 1.5 * (ps2[i] - p) ** 2 + 1.5 * (ps3[i] - p) ** 2 ) # von Mises stress: https://en.wikipedia.org/wiki/Von_Mises_yield_criterion - if svm != 0.: + if svm != 0.0: T = p / svm # stress triaxiality else: - T = 0. + T = 0.0 critical_strain = alpha * np.exp(-beta * T) # critical strain csr.append(abs(res_obj.Peeq[i]) / critical_strain) # critical strain ratio return csr @@ -485,6 +489,7 @@ def calculate_csr(ps1, ps2, ps3, alpha, beta, res_obj): def get_concrete_nodes(res_obj): """Determine concrete / non-concrete nodes.""" from femmesh.meshtools import get_femnodes_by_refshape + femmesh = res_obj.Mesh.FemMesh nsr = femmesh.NodeCount # nsr number of stress results @@ -496,8 +501,9 @@ def get_concrete_nodes(res_obj): ic = np.zeros(nsr) for obj in res_obj.getParentGroup().Group: - if obj.isDerivedFrom("App::MaterialObjectPython") \ - and is_of_type(obj, "Fem::MaterialReinforced"): + if obj.isDerivedFrom("App::MaterialObjectPython") and is_of_type( + obj, "Fem::MaterialReinforced" + ): FreeCAD.Console.PrintMessage("ReinforcedMaterial\n") if obj.References == []: for iic in range(nsr): @@ -508,8 +514,9 @@ def get_concrete_nodes(res_obj): concrete_nodes = get_femnodes_by_refshape(femmesh, ref) for cn in concrete_nodes: ic[cn - 1] = 1 - elif obj.isDerivedFrom("App::MaterialObjectPython") \ - and is_of_type(obj, "Fem::MaterialCommon"): + elif obj.isDerivedFrom("App::MaterialObjectPython") and is_of_type( + obj, "Fem::MaterialCommon" + ): FreeCAD.Console.PrintMessage("No ReinforcedMaterial\n") if obj.References == []: for iic in range(nsr): @@ -574,14 +581,14 @@ def add_principal_stress_reinforced(res_obj): res_obj.NodeStressZZ, res_obj.NodeStressXY, res_obj.NodeStressXZ, - res_obj.NodeStressYZ + res_obj.NodeStressYZ, ) for isv, stress_tensor in enumerate(iterator): - rhox = 0. - rhoy = 0. - rhoz = 0. - mc = 0. + rhox = 0.0 + rhoy = 0.0 + rhoz = 0.0 + mc = 0.0 if ic[isv] == 1: # @@ -589,14 +596,9 @@ def add_principal_stress_reinforced(res_obj): # reinforcement (see calculate_rho(stress_tensor)). for all other # materials scxx etc. are the original stresses # - rhox, rhoy, rhoz = calculate_rho( - stress_tensor, - reinforce_yield - ) + rhox, rhoy, rhoz = calculate_rho(stress_tensor, reinforce_yield) - prin1, prin2, prin3, shear, psv = calculate_principal_stress_reinforced( - stress_tensor - ) + prin1, prin2, prin3, shear, psv = calculate_principal_stress_reinforced(stress_tensor) prinstress1.append(prin1) prinstress2.append(prin2) @@ -648,6 +650,7 @@ def compact_result(res_obj): # get compact mesh data from femmesh.meshtools import compact_mesh + compact_femmesh_data = compact_mesh(res_obj.Mesh.FemMesh) compact_femmesh = compact_femmesh_data[0] node_map = compact_femmesh_data[1] @@ -682,9 +685,7 @@ def calculate_von_mises(stress_tensor): return von_mises -def calculate_principal_stress_std( - stress_tensor -): +def calculate_principal_stress_std(stress_tensor): # if NaN is inside the array, which can happen on Calculix frd result files return NaN # https://forum.freecad.org/viewtopic.php?f=22&t=33911&start=10#p284229 # https://forum.freecad.org/viewtopic.php?f=18&t=32649#p274291 @@ -698,11 +699,9 @@ def calculate_principal_stress_std( s12 = stress_tensor[3] # Sxy s31 = stress_tensor[4] # Sxz s23 = stress_tensor[5] # Syz - sigma = np.array([ - [s11, s12, s31], - [s12, s22, s23], - [s31, s23, s33] - ]) # https://forum.freecad.org/viewtopic.php?f=18&t=24637&start=10#p240408 + sigma = np.array( + [[s11, s12, s31], [s12, s22, s23], [s31, s23, s33]] + ) # https://forum.freecad.org/viewtopic.php?f=18&t=24637&start=10#p240408 eigvals = list(np.linalg.eigvalsh(sigma)) eigvals.sort() @@ -728,11 +727,9 @@ def calculate_principal_stress_reinforced(stress_tensor): s12 = stress_tensor[3] # Sxy s31 = stress_tensor[4] # Sxz s23 = stress_tensor[5] # Syz - sigma = np.array([ - [s11, s12, s31], - [s12, s22, s23], - [s31, s23, s33] - ]) # https://forum.freecad.org/viewtopic.php?f=18&t=24637&start=10#p240408 + sigma = np.array( + [[s11, s12, s31], [s12, s22, s23], [s31, s23, s33]] + ) # https://forum.freecad.org/viewtopic.php?f=18&t=24637&start=10#p240408 eigenvalues, eigenvectors = np.linalg.eig(sigma) @@ -754,8 +751,13 @@ def calculate_principal_stress_reinforced(stress_tensor): maxshear = (eigenvalues[0] - eigenvalues[2]) / 2.0 - return (eigenvalues[0], eigenvalues[1], eigenvalues[2], maxshear, - tuple([tuple(row) for row in eigenvectors.T])) + return ( + eigenvalues[0], + eigenvalues[1], + eigenvalues[2], + maxshear, + tuple([tuple(row) for row in eigenvectors.T]), + ) def calculate_rho(stress_tensor, fy): @@ -787,29 +789,28 @@ def calculate_rho(stress_tensor, fy): # i1=sxx+syy+szz NOT USED # i2=sxx*syy+syy*szz+szz*sxx-sxy**2-sxz**2-syz**2 NOT USED - i3 = (sxx * syy * szz + 2 * sxy * sxz * syz - sxx * syz ** 2 - - syy * sxz ** 2 - szz * sxy ** 2) + i3 = sxx * syy * szz + 2 * sxy * sxz * syz - sxx * syz**2 - syy * sxz**2 - szz * sxy**2 # Solution (5) - d = (sxx * syy - sxy ** 2) - if d != 0.: + d = sxx * syy - sxy**2 + if d != 0.0: rhoz[0] = i3 / d / fy # Solution (6) - d = (sxx * szz - sxz ** 2) - if d != 0.: + d = sxx * szz - sxz**2 + if d != 0.0: rhoy[1] = i3 / d / fy # Solution (7) - d = (syy * szz - syz ** 2) - if d != 0.: + d = syy * szz - syz**2 + if d != 0.0: rhox[2] = i3 / d / fy # Solution (9) - if sxx != 0.: + if sxx != 0.0: fc = sxz * sxy / sxx - syz - fxy = sxy ** 2 / sxx - fxz = sxz ** 2 / sxx + fxy = sxy**2 / sxx + fxz = sxz**2 / sxx # Solution (9+) rhoy[3] = syy - fxy + fc @@ -824,10 +825,10 @@ def calculate_rho(stress_tensor, fy): rhoz[4] /= fy # Solution (10) - if syy != 0.: + if syy != 0.0: fc = syz * sxy / syy - sxz - fxy = sxy ** 2 / syy - fyz = syz ** 2 / syy + fxy = sxy**2 / syy + fyz = syz**2 / syy # Solution (10+) rhox[5] = sxx - fxy + fc @@ -843,10 +844,10 @@ def calculate_rho(stress_tensor, fy): rhoz[6] /= fy # Solution (11) - if szz != 0.: + if szz != 0.0: fc = sxz * syz / szz - sxy - fxz = sxz ** 2 / szz - fyz = syz ** 2 / szz + fxz = sxz**2 / szz + fyz = syz**2 / szz # Solution (11+) rhox[7] = sxx - fxz + fc @@ -881,32 +882,36 @@ def calculate_rho(stress_tensor, fy): rhoz[12] = (szz + sxz - syz) / fy # Solution (17) - if syz != 0.: + if syz != 0.0: rhox[13] = (sxx - sxy * sxz / syz) / fy - if sxz != 0.: + if sxz != 0.0: rhoy[13] = (syy - sxy * syz / sxz) / fy - if sxy != 0.: + if sxy != 0.0: rhoz[13] = (szz - sxz * syz / sxy) / fy for ir in range(0, rhox.size): - if rhox[ir] >= -1.e-10 and rhoy[ir] >= -1.e-10 and rhoz[ir] > -1.e-10: + if rhox[ir] >= -1.0e-10 and rhoy[ir] >= -1.0e-10 and rhoz[ir] > -1.0e-10: # Concrete Stresses scxx = sxx - rhox[ir] * fy scyy = syy - rhoy[ir] * fy sczz = szz - rhoz[ir] * fy - ic1 = (scxx + scyy + sczz) - ic2 = (scxx * scyy + scyy * sczz + sczz * scxx - sxy ** 2 - - sxz ** 2 - syz ** 2) - ic3 = (scxx * scyy * sczz + 2 * sxy * sxz * syz - scxx * syz ** 2 - - scyy * sxz ** 2 - sczz * sxy ** 2) + ic1 = scxx + scyy + sczz + ic2 = scxx * scyy + scyy * sczz + sczz * scxx - sxy**2 - sxz**2 - syz**2 + ic3 = ( + scxx * scyy * sczz + + 2 * sxy * sxz * syz + - scxx * syz**2 + - scyy * sxz**2 + - sczz * sxy**2 + ) - if ic1 <= 1.e-6 and ic2 >= -1.e-6 and ic3 <= 1.0e-6: + if ic1 <= 1.0e-6 and ic2 >= -1.0e-6 and ic3 <= 1.0e-6: rsum = rhox[ir] + rhoy[ir] + rhoz[ir] - if rsum < rmin and rsum > 0.: + if rsum < rmin and rsum > 0.0: rmin = rsum eqmin = ir @@ -925,11 +930,10 @@ def calculate_mohr_coulomb(prin1, prin3, phi, fck): coh = fck * (1 - np.sin(phi)) / 2 / np.cos(phi) - mc_stress = ((prin1 - prin3) + (prin1 + prin3) * np.sin(phi) - - 2. * coh * np.cos(phi)) + mc_stress = (prin1 - prin3) + (prin1 + prin3) * np.sin(phi) - 2.0 * coh * np.cos(phi) - if mc_stress < 0.: - mc_stress = 0. + if mc_stress < 0.0: + mc_stress = 0.0 return mc_stress @@ -938,4 +942,5 @@ def calculate_disp_abs(displacements): # see https://forum.freecad.org/viewtopic.php?f=18&t=33106&start=100#p296657 return [np.linalg.norm(nd) for nd in displacements] + ## @} diff --git a/src/Mod/Fem/femsolver/calculix/solver.py b/src/Mod/Fem/femsolver/calculix/solver.py index 0bf2587257..e8a2f22839 100644 --- a/src/Mod/Fem/femsolver/calculix/solver.py +++ b/src/Mod/Fem/femsolver/calculix/solver.py @@ -45,8 +45,7 @@ ANALYSIS_TYPES = ["static", "frequency", "thermomech", "check", "buckling"] def create(doc, name="SolverCalculiX"): - return femutils.createObject( - doc, name, Proxy, ViewProxy) + return femutils.createObject(doc, name, Proxy, ViewProxy) class _BaseSolverCalculix: @@ -58,21 +57,16 @@ class _BaseSolverCalculix: obj.AnalysisType = temp_analysis_type else: FreeCAD.Console.PrintWarning( - "Analysis type {} not found. Standard is used.\n" - .format(temp_analysis_type) + f"Analysis type {temp_analysis_type} not found. Standard is used.\n" ) obj.AnalysisType = ANALYSIS_TYPES[0] self.add_attributes(obj) - def add_attributes(self, obj): if not hasattr(obj, "AnalysisType"): obj.addProperty( - "App::PropertyEnumeration", - "AnalysisType", - "Fem", - "Type of the analysis" + "App::PropertyEnumeration", "AnalysisType", "Fem", "Type of the analysis" ) obj.AnalysisType = ANALYSIS_TYPES obj.AnalysisType = ANALYSIS_TYPES[0] @@ -83,7 +77,7 @@ class _BaseSolverCalculix: "App::PropertyEnumeration", "GeometricalNonlinearity", "Fem", - "Set geometrical nonlinearity" + "Set geometrical nonlinearity", ) obj.GeometricalNonlinearity = choices_geom_nonlinear obj.GeometricalNonlinearity = choices_geom_nonlinear[0] @@ -94,7 +88,7 @@ class _BaseSolverCalculix: "App::PropertyEnumeration", "MaterialNonlinearity", "Fem", - "Set material nonlinearity" + "Set material nonlinearity", ) obj.MaterialNonlinearity = choices_material_nonlinear obj.MaterialNonlinearity = choices_material_nonlinear[0] @@ -104,7 +98,7 @@ class _BaseSolverCalculix: "App::PropertyIntegerConstraint", "EigenmodesCount", "Fem", - "Number of modes for frequency calculations" + "Number of modes for frequency calculations", ) obj.EigenmodesCount = (10, 1, 100, 1) @@ -113,7 +107,7 @@ class _BaseSolverCalculix: "App::PropertyFloatConstraint", "EigenmodeLowLimit", "Fem", - "Low frequency limit for eigenmode calculations" + "Low frequency limit for eigenmode calculations", ) obj.EigenmodeLowLimit = (0.0, 0.0, 1000000.0, 10000.0) @@ -122,20 +116,19 @@ class _BaseSolverCalculix: "App::PropertyFloatConstraint", "EigenmodeHighLimit", "Fem", - "High frequency limit for eigenmode calculations" + "High frequency limit for eigenmode calculations", ) obj.EigenmodeHighLimit = (1000000.0, 0.0, 1000000.0, 10000.0) if not hasattr(obj, "IterationsMaximum"): help_string_IterationsMaximum = ( - "Maximum Number of iterations " - "in each time step before stopping jobs" + "Maximum Number of iterations in each time step before stopping jobs" ) obj.addProperty( "App::PropertyIntegerConstraint", "IterationsMaximum", "Fem", - help_string_IterationsMaximum + help_string_IterationsMaximum, ) obj.IterationsMaximum = 2000 @@ -148,43 +141,29 @@ class _BaseSolverCalculix: "App::PropertyIntegerConstraint", "BucklingFactors", "Fem", - "Calculates the lowest buckling modes to the corresponding buckling factors" + "Calculates the lowest buckling modes to the corresponding buckling factors", ) obj.BucklingFactors = 1 if not hasattr(obj, "TimeInitialStep"): obj.addProperty( - "App::PropertyFloatConstraint", - "TimeInitialStep", - "Fem", - "Initial time steps" + "App::PropertyFloatConstraint", "TimeInitialStep", "Fem", "Initial time steps" ) obj.TimeInitialStep = 0.01 if not hasattr(obj, "TimeEnd"): - obj.addProperty( - "App::PropertyFloatConstraint", - "TimeEnd", - "Fem", - "End time analysis" - ) + obj.addProperty("App::PropertyFloatConstraint", "TimeEnd", "Fem", "End time analysis") obj.TimeEnd = 1.0 if not hasattr(obj, "TimeMinimumStep"): obj.addProperty( - "App::PropertyFloatConstraint", - "TimeMinimumStep", - "Fem", - "Minimum time step" + "App::PropertyFloatConstraint", "TimeMinimumStep", "Fem", "Minimum time step" ) obj.TimeMinimumStep = 0.00001 if not hasattr(obj, "TimeMaximumStep"): obj.addProperty( - "App::PropertyFloatConstraint", - "TimeMaximumStep", - "Fem", - "Maximum time step" + "App::PropertyFloatConstraint", "TimeMaximumStep", "Fem", "Maximum time step" ) obj.TimeMaximumStep = 1.0 @@ -193,7 +172,7 @@ class _BaseSolverCalculix: "App::PropertyBool", "ThermoMechSteadyState", "Fem", - "Choose between steady state thermo mech or transient thermo mech analysis" + "Choose between steady state thermo mech or transient thermo mech analysis", ) obj.ThermoMechSteadyState = True @@ -202,16 +181,13 @@ class _BaseSolverCalculix: "App::PropertyBool", "IterationsControlParameterTimeUse", "Fem", - "Use the user defined time incrementation control parameter" + "Use the user defined time incrementation control parameter", ) obj.IterationsControlParameterTimeUse = False if not hasattr(obj, "SplitInputWriter"): obj.addProperty( - "App::PropertyBool", - "SplitInputWriter", - "Fem", - "Split writing of ccx input file" + "App::PropertyBool", "SplitInputWriter", "Fem", "Split writing of ccx input file" ) obj.SplitInputWriter = False @@ -234,28 +210,26 @@ class _BaseSolverCalculix: "App::PropertyString", "IterationsControlParameterIter", "Fem", - "User defined time incrementation iterations control parameter" + "User defined time incrementation iterations control parameter", ) obj.IterationsControlParameterIter = control_parameter_iterations if not hasattr(obj, "IterationsControlParameterCutb"): - control_parameter_cutback = ( - "{D_f},{D_C},{D_B},{D_A},{D_S},{D_H},{D_D},{W_G}".format( - D_f=0.25, - D_C=0.5, - D_B=0.75, - D_A=0.85, - D_S="", - D_H="", - D_D=1.5, - W_G="", - ) + control_parameter_cutback = "{D_f},{D_C},{D_B},{D_A},{D_S},{D_H},{D_D},{W_G}".format( + D_f=0.25, + D_C=0.5, + D_B=0.75, + D_A=0.85, + D_S="", + D_H="", + D_D=1.5, + W_G="", ) obj.addProperty( "App::PropertyString", "IterationsControlParameterCutb", "Fem", - "User defined time incrementation cutbacks control parameter" + "User defined time incrementation cutbacks control parameter", ) obj.IterationsControlParameterCutb = control_parameter_cutback @@ -268,7 +242,7 @@ class _BaseSolverCalculix: "App::PropertyBool", "IterationsUserDefinedIncrementations", "Fem", - stringIterationsUserDefinedIncrementations + stringIterationsUserDefinedIncrementations, ) obj.IterationsUserDefinedIncrementations = False @@ -281,7 +255,7 @@ class _BaseSolverCalculix: "App::PropertyBool", "IterationsUserDefinedTimeStepLength", "Fem", - help_string_IterationsUserDefinedTimeStepLength + help_string_IterationsUserDefinedTimeStepLength, ) obj.IterationsUserDefinedTimeStepLength = False @@ -292,13 +266,10 @@ class _BaseSolverCalculix: "pardiso", "spooles", "iterativescaling", - "iterativecholesky" + "iterativecholesky", ] obj.addProperty( - "App::PropertyEnumeration", - "MatrixSolverType", - "Fem", - "Type of solver to use" + "App::PropertyEnumeration", "MatrixSolverType", "Fem", "Type of solver to use" ) obj.MatrixSolverType = known_ccx_solver_types obj.MatrixSolverType = known_ccx_solver_types[0] @@ -308,7 +279,7 @@ class _BaseSolverCalculix: "App::PropertyBool", "BeamShellResultOutput3D", "Fem", - "Output 3D results for 1D and 2D analysis " + "Output 3D results for 1D and 2D analysis ", ) obj.BeamShellResultOutput3D = True @@ -317,7 +288,7 @@ class _BaseSolverCalculix: "App::PropertyBool", "BeamReducedIntegration", "Fem", - "Set to True to use beam elements with reduced integration" + "Set to True to use beam elements with reduced integration", ) obj.BeamReducedIntegration = True @@ -326,48 +297,33 @@ class _BaseSolverCalculix: "App::PropertyIntegerConstraint", "OutputFrequency", "Fem", - "Set the output frequency in increments" + "Set the output frequency in increments", ) obj.OutputFrequency = 1 if not hasattr(obj, "ModelSpace"): - model_space_types = [ - "3D", - "plane stress", - "plane strain", - "axisymmetric" - ] - obj.addProperty( - "App::PropertyEnumeration", - "ModelSpace", - "Fem", - "Type of model space" - ) + model_space_types = ["3D", "plane stress", "plane strain", "axisymmetric"] + obj.addProperty("App::PropertyEnumeration", "ModelSpace", "Fem", "Type of model space") obj.ModelSpace = model_space_types if not hasattr(obj, "ThermoMechType"): - thermomech_types = [ - "coupled", - "uncoupled", - "pure heat transfer" - ] + thermomech_types = ["coupled", "uncoupled", "pure heat transfer"] obj.addProperty( "App::PropertyEnumeration", "ThermoMechType", "Fem", - "Type of thermomechanical analysis" + "Type of thermomechanical analysis", ) obj.ThermoMechType = thermomech_types class Proxy(solverbase.Proxy, _BaseSolverCalculix): - """The Fem::FemSolver's Proxy python type, add solver specific properties - """ + """The Fem::FemSolver's Proxy python type, add solver specific properties""" Type = "Fem::SolverCalculix" def __init__(self, obj): - super(Proxy, self).__init__(obj) + super().__init__(obj) obj.Proxy = self self.add_attributes(obj) @@ -376,19 +332,21 @@ class Proxy(solverbase.Proxy, _BaseSolverCalculix): def createMachine(self, obj, directory, testmode=False): return run.Machine( - solver=obj, directory=directory, + solver=obj, + directory=directory, check=tasks.Check(), prepare=tasks.Prepare(), solve=tasks.Solve(), results=tasks.Results(), - testmode=testmode) + testmode=testmode, + ) def editSupported(self): return True def edit(self, directory): pattern = os.path.join(directory, "*.inp") - FreeCAD.Console.PrintMessage("{}\n".format(pattern)) + FreeCAD.Console.PrintMessage(f"{pattern}\n") f = glob.glob(pattern)[0] FemGui.open(f) diff --git a/src/Mod/Fem/femsolver/calculix/tasks.py b/src/Mod/Fem/femsolver/calculix/tasks.py index 18f4086d00..66034d0f7e 100644 --- a/src/Mod/Fem/femsolver/calculix/tasks.py +++ b/src/Mod/Fem/femsolver/calculix/tasks.py @@ -56,15 +56,16 @@ class Check(run.Check): # workaround use Calculix ccxtools pre checks from femtools.checksanalysis import check_member_for_solver_calculix + message = check_member_for_solver_calculix( self.analysis, self.solver, membertools.get_mesh_to_solve(self.analysis)[0], - membertools.AnalysisMember(self.analysis) + membertools.AnalysisMember(self.analysis), ) if message: text = "CalculiX can not be started...\n" - self.report.error("{}{}".format(text, message)) + self.report.error(f"{text}{message}") self.fail() return @@ -94,7 +95,7 @@ class Prepare(run.Prepare): mesh_obj, meshdatagetter.member, self.directory, - meshdatagetter.mat_geo_sets + meshdatagetter.mat_geo_sets, ) path = w.write_solver_input() # report to user if task succeeded @@ -124,7 +125,7 @@ class Solve(run.Solve): [binary, "-i", _inputFileName], cwd=self.directory, stdout=subprocess.PIPE, - stderr=subprocess.PIPE + stderr=subprocess.PIPE, ) self.signalAbort.add(self._process.terminate) # output = self._observeSolver(self._process) @@ -138,8 +139,7 @@ class Solve(run.Solve): class Results(run.Results): def run(self): - prefs = FreeCAD.ParamGet( - "User parameter:BaseApp/Preferences/Mod/Fem/General") + prefs = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Fem/General") if not prefs.GetBool("KeepResultsOnReRun", False): self.purge_results() self.load_results() @@ -163,32 +163,22 @@ class Results(run.Results): self.load_ccxdat_results() def load_ccxfrd_results(self): - frd_result_file = os.path.join( - self.directory, _inputFileName + ".frd") + frd_result_file = os.path.join(self.directory, _inputFileName + ".frd") if os.path.isfile(frd_result_file): result_name_prefix = "CalculiX_" + self.solver.AnalysisType + "_" - importCcxFrdResults.importFrd( - frd_result_file, self.analysis, result_name_prefix) + importCcxFrdResults.importFrd(frd_result_file, self.analysis, result_name_prefix) else: # TODO: use solver framework status message system - FreeCAD.Console.PrintError( - "FEM: No results found at {}!\n" - .format(frd_result_file) - ) + FreeCAD.Console.PrintError(f"FEM: No results found at {frd_result_file}!\n") self.fail() def load_ccxdat_results(self): - dat_result_file = os.path.join( - self.directory, _inputFileName + ".dat") + dat_result_file = os.path.join(self.directory, _inputFileName + ".dat") if os.path.isfile(dat_result_file): - mode_frequencies = importCcxDatResults.import_dat( - dat_result_file, self.analysis) + mode_frequencies = importCcxDatResults.import_dat(dat_result_file, self.analysis) else: # TODO: use solver framework status message system - FreeCAD.Console.PrintError( - "FEM: No results found at {}!\n" - .format(dat_result_file) - ) + FreeCAD.Console.PrintError(f"FEM: No results found at {dat_result_file}!\n") self.fail() if mode_frequencies: for m in membertools.get_member(self.analysis, "Fem::FemResultObject"): @@ -197,4 +187,5 @@ class Results(run.Results): if m.Eigenmode == mf["eigenmode"]: m.EigenmodeFrequency = mf["frequency"] + ## @} diff --git a/src/Mod/Fem/femsolver/calculix/write_constraint_bodyheatsource.py b/src/Mod/Fem/femsolver/calculix/write_constraint_bodyheatsource.py index 16232acc55..e73273bf2b 100644 --- a/src/Mod/Fem/femsolver/calculix/write_constraint_bodyheatsource.py +++ b/src/Mod/Fem/femsolver/calculix/write_constraint_bodyheatsource.py @@ -1,6 +1,6 @@ # SPDX-License-Identifier: LGPL-2.1-or-later -#/*************************************************************************** +# /*************************************************************************** # * Copyright (c) 2024 Mario Passaglia * # * * # * This file is part of FreeCAD. * @@ -58,12 +58,12 @@ def get_after_write_constraint(): def write_meshdata_constraint(f, femobj, bodyheatsource_obj, ccxwriter): - f.write("*ELSET,ELSET={}\n".format(bodyheatsource_obj.Name)) + f.write(f"*ELSET,ELSET={bodyheatsource_obj.Name}\n") if isinstance(femobj["FEMElements"], str): f.write("{}\n".format(femobj["FEMElements"])) else: for e in femobj["FEMElements"]: - f.write("{},\n".format(e)) + f.write(f"{e},\n") def write_constraint(f, femobj, bodyheatsource_obj, ccxwriter): @@ -75,7 +75,9 @@ def write_constraint(f, femobj, bodyheatsource_obj, ccxwriter): ref_sub_obj = ref[1][0] density = None for mat in ccxwriter.member.mats_linear: - mat_ref = [*itertools.chain(*[itertools.product([i[0]],i[1]) for i in mat["Object"].References])] + mat_ref = [ + *itertools.chain(*[itertools.product([i[0]], i[1]) for i in mat["Object"].References]) + ] if (ref_feat, ref_sub_obj) in mat_ref: density = FreeCAD.Units.Quantity(mat["Object"].Material["Density"]) break @@ -95,9 +97,5 @@ def write_constraint(f, femobj, bodyheatsource_obj, ccxwriter): heat = bodyheatsource_obj.TotalPower / FreeCAD.Units.Quantity(volume, "mm^3") # write to file f.write("*DFLUX\n") - f.write( - "{},BF,{:.13G}\n".format( - bodyheatsource_obj.Name, heat.getValueAs("t/(mm*s^3)").Value - ) - ) + f.write("{},BF,{:.13G}\n".format(bodyheatsource_obj.Name, heat.getValueAs("t/(mm*s^3)").Value)) f.write("\n") diff --git a/src/Mod/Fem/femsolver/calculix/write_constraint_centrif.py b/src/Mod/Fem/femsolver/calculix/write_constraint_centrif.py index 1b9f2bc00f..a140f48a2e 100644 --- a/src/Mod/Fem/femsolver/calculix/write_constraint_centrif.py +++ b/src/Mod/Fem/femsolver/calculix/write_constraint_centrif.py @@ -60,12 +60,12 @@ def get_after_write_constraint(): def write_meshdata_constraint(f, femobj, centrif_obj, ccxwriter): - f.write("*ELSET,ELSET={}\n".format(centrif_obj.Name)) + f.write(f"*ELSET,ELSET={centrif_obj.Name}\n") if isinstance(femobj["FEMElements"], str): f.write("{}\n".format(femobj["FEMElements"])) else: for e in femobj["FEMElements"]: - f.write("{},\n".format(e)) + f.write(f"{e},\n") def write_constraint(f, femobj, centrif_obj, ccxwriter): @@ -85,22 +85,21 @@ def write_constraint(f, femobj, centrif_obj, ccxwriter): else: # no line found, set default # TODO: No test at all in the writer # they should all be before in prechecks - location = FreeCAD.Vector(0., 0., 0.) - direction = FreeCAD.Vector(0., 0., 1.) + location = FreeCAD.Vector(0.0, 0.0, 0.0) + direction = FreeCAD.Vector(0.0, 0.0, 1.0) # write to file f.write("*DLOAD\n") f.write( - "{},CENTRIF,{:.13G},{:.13G},{:.13G},{:.13G},{:.13G},{:.13G},{:.13G}\n" - .format( + "{},CENTRIF,{:.13G},{:.13G},{:.13G},{:.13G},{:.13G},{:.13G},{:.13G}\n".format( centrif_obj.Name, - (2. * math.pi * float(centrif_obj.RotationFrequency.getValueAs("1/s"))) ** 2, + (2.0 * math.pi * float(centrif_obj.RotationFrequency.getValueAs("1/s"))) ** 2, location.x, location.y, location.z, direction.x, direction.y, - direction.z + direction.z, ) ) f.write("\n") diff --git a/src/Mod/Fem/femsolver/calculix/write_constraint_contact.py b/src/Mod/Fem/femsolver/calculix/write_constraint_contact.py index a9c0bcc9dd..fca26b40a1 100644 --- a/src/Mod/Fem/femsolver/calculix/write_constraint_contact.py +++ b/src/Mod/Fem/femsolver/calculix/write_constraint_contact.py @@ -27,7 +27,7 @@ __url__ = "https://www.freecad.org" def get_analysis_types(): - return "all" # write for all analysis types + return "all" # write for all analysis types def get_sets_name(): @@ -56,13 +56,13 @@ def get_after_write_constraint(): def write_meshdata_constraint(f, femobj, contact_obj, ccxwriter): # slave DEP - f.write("*SURFACE, NAME=DEP{}\n".format(contact_obj.Name)) + f.write(f"*SURFACE, NAME=DEP{contact_obj.Name}\n") for i in femobj["ContactSlaveFaces"]: - f.write("{},S{}\n".format(i[0], i[1])) + f.write(f"{i[0]},S{i[1]}\n") # master IND - f.write("*SURFACE, NAME=IND{}\n".format(contact_obj.Name)) + f.write(f"*SURFACE, NAME=IND{contact_obj.Name}\n") for i in femobj["ContactMasterFaces"]: - f.write("{},S{}\n".format(i[0], i[1])) + f.write(f"{i[0]},S{i[1]}\n") def write_constraint(f, femobj, contact_obj, ccxwriter): @@ -70,22 +70,22 @@ def write_constraint(f, femobj, contact_obj, ccxwriter): # floats read from ccx should use {:.13G}, see comment in writer module adjust = "" if contact_obj.Adjust.Value > 0: - adjust = ", ADJUST={:.13G}".format( - contact_obj.Adjust.getValueAs("mm").Value) + adjust = ", ADJUST={:.13G}".format(contact_obj.Adjust.getValueAs("mm").Value) f.write( - "*CONTACT PAIR, INTERACTION=INT{}, TYPE=SURFACE TO SURFACE{}\n" - .format(contact_obj.Name, adjust) + "*CONTACT PAIR, INTERACTION=INT{}, TYPE=SURFACE TO SURFACE{}\n".format( + contact_obj.Name, adjust + ) ) ind_surf = "IND" + contact_obj.Name dep_surf = "DEP" + contact_obj.Name - f.write("{}, {}\n".format(dep_surf, ind_surf)) - f.write("*SURFACE INTERACTION, NAME=INT{}\n".format(contact_obj.Name)) + f.write(f"{dep_surf}, {ind_surf}\n") + f.write(f"*SURFACE INTERACTION, NAME=INT{contact_obj.Name}\n") f.write("*SURFACE BEHAVIOR, PRESSURE-OVERCLOSURE=LINEAR\n") slope = contact_obj.Slope.getValueAs("MPa/mm").Value - f.write("{:.13G}\n".format(slope)) + f.write(f"{slope:.13G}\n") if contact_obj.Friction: f.write("*FRICTION\n") friction = contact_obj.FrictionCoefficient stick = contact_obj.StickSlope.getValueAs("MPa/mm").Value - f.write("{:.13G}, {:.13G}\n".format(friction, stick)) + f.write(f"{friction:.13G}, {stick:.13G}\n") diff --git a/src/Mod/Fem/femsolver/calculix/write_constraint_displacement.py b/src/Mod/Fem/femsolver/calculix/write_constraint_displacement.py index e75ef2b6e6..43f6d70769 100644 --- a/src/Mod/Fem/femsolver/calculix/write_constraint_displacement.py +++ b/src/Mod/Fem/femsolver/calculix/write_constraint_displacement.py @@ -29,7 +29,7 @@ import FreeCAD def get_analysis_types(): - return "all" # write for all analysis types + return "all" # write for all analysis types def get_sets_name(): @@ -57,9 +57,9 @@ def get_after_write_constraint(): def write_meshdata_constraint(f, femobj, disp_obj, ccxwriter): - f.write("*NSET,NSET={}\n".format(disp_obj.Name)) + f.write(f"*NSET,NSET={disp_obj.Name}\n") for n in femobj["Nodes"]: - f.write("{},\n".format(n)) + f.write(f"{n},\n") def write_constraint(f, femobj, disp_obj, ccxwriter): @@ -68,7 +68,7 @@ def write_constraint(f, femobj, disp_obj, ccxwriter): f.write("*BOUNDARY\n") if disp_obj.xFix: - f.write("{},1\n".format(disp_obj.Name)) + f.write(f"{disp_obj.Name},1\n") elif not disp_obj.xFree: f.write( "{},1,1,{}\n".format( @@ -76,7 +76,7 @@ def write_constraint(f, femobj, disp_obj, ccxwriter): ) ) if disp_obj.yFix: - f.write("{},2\n".format(disp_obj.Name)) + f.write(f"{disp_obj.Name},2\n") elif not disp_obj.yFree: f.write( "{},2,2,{}\n".format( @@ -84,7 +84,7 @@ def write_constraint(f, femobj, disp_obj, ccxwriter): ) ) if disp_obj.zFix: - f.write("{},3\n".format(disp_obj.Name)) + f.write(f"{disp_obj.Name},3\n") elif not disp_obj.zFree: f.write( "{},3,3,{}\n".format( @@ -94,7 +94,7 @@ def write_constraint(f, femobj, disp_obj, ccxwriter): if ccxwriter.member.geos_beamsection or ccxwriter.member.geos_shellthickness: if disp_obj.rotxFix: - f.write("{},4\n".format(disp_obj.Name)) + f.write(f"{disp_obj.Name},4\n") elif not disp_obj.rotxFree: f.write( "{},4,4,{}\n".format( @@ -102,7 +102,7 @@ def write_constraint(f, femobj, disp_obj, ccxwriter): ) ) if disp_obj.rotyFix: - f.write("{},5\n".format(disp_obj.Name)) + f.write(f"{disp_obj.Name},5\n") elif not disp_obj.rotyFree: f.write( "{},5,5,{}\n".format( @@ -110,7 +110,7 @@ def write_constraint(f, femobj, disp_obj, ccxwriter): ) ) if disp_obj.rotzFix: - f.write("{},6\n".format(disp_obj.Name)) + f.write(f"{disp_obj.Name},6\n") elif not disp_obj.rotzFree: f.write( "{},6,6,{}\n".format( diff --git a/src/Mod/Fem/femsolver/calculix/write_constraint_fixed.py b/src/Mod/Fem/femsolver/calculix/write_constraint_fixed.py index 8d71388d97..0a47a8d407 100644 --- a/src/Mod/Fem/femsolver/calculix/write_constraint_fixed.py +++ b/src/Mod/Fem/femsolver/calculix/write_constraint_fixed.py @@ -27,7 +27,7 @@ __url__ = "https://www.freecad.org" def get_analysis_types(): - return "all" # write for all analysis types + return "all" # write for all analysis types def get_sets_name(): @@ -55,37 +55,29 @@ def get_after_write_constraint(): def write_meshdata_constraint(f, femobj, fix_obj, ccxwriter): - if ( - ccxwriter.femmesh.Volumes - and ( - len(ccxwriter.member.geos_shellthickness) > 0 - or len(ccxwriter.member.geos_beamsection) > 0 - ) + if ccxwriter.femmesh.Volumes and ( + len(ccxwriter.member.geos_shellthickness) > 0 or len(ccxwriter.member.geos_beamsection) > 0 ): if len(femobj["NodesSolid"]) > 0: - f.write("*NSET,NSET={}Solid\n".format(fix_obj.Name)) + f.write(f"*NSET,NSET={fix_obj.Name}Solid\n") for n in femobj["NodesSolid"]: - f.write("{},\n".format(n)) + f.write(f"{n},\n") if len(femobj["NodesFaceEdge"]) > 0: - f.write("*NSET,NSET={}FaceEdge\n".format(fix_obj.Name)) + f.write(f"*NSET,NSET={fix_obj.Name}FaceEdge\n") for n in femobj["NodesFaceEdge"]: - f.write("{},\n".format(n)) + f.write(f"{n},\n") else: f.write("*NSET,NSET=" + fix_obj.Name + "\n") for n in femobj["Nodes"]: - f.write("{},\n".format(n)) + f.write(f"{n},\n") def write_constraint(f, femobj, fix_obj, ccxwriter): # floats read from ccx should use {:.13G}, see comment in writer module - if ( - ccxwriter.femmesh.Volumes - and ( - len(ccxwriter.member.geos_shellthickness) > 0 - or len(ccxwriter.member.geos_beamsection) > 0 - ) + if ccxwriter.femmesh.Volumes and ( + len(ccxwriter.member.geos_shellthickness) > 0 or len(ccxwriter.member.geos_beamsection) > 0 ): if len(femobj["NodesSolid"]) > 0: f.write("*BOUNDARY\n") diff --git a/src/Mod/Fem/femsolver/calculix/write_constraint_fluidsection.py b/src/Mod/Fem/femsolver/calculix/write_constraint_fluidsection.py index f8157b97e5..7acbcb5f50 100644 --- a/src/Mod/Fem/femsolver/calculix/write_constraint_fluidsection.py +++ b/src/Mod/Fem/femsolver/calculix/write_constraint_fluidsection.py @@ -53,8 +53,7 @@ def handle_fluidsection_liquid_inlet_outlet(inpfile, ccxwriter): ccxwriter.FluidInletoutlet_ele = [] ccxwriter.fluid_inout_nodes_file = join( - ccxwriter.dir_name, - "{}_inout_nodes.txt".format(ccxwriter.mesh_name) + ccxwriter.dir_name, f"{ccxwriter.mesh_name}_inout_nodes.txt" ) def get_fluidsection_inoutlet_obj_if_setdata(matgeoset): @@ -64,29 +63,20 @@ def handle_fluidsection_liquid_inlet_outlet(inpfile, ccxwriter): and "fluidsection_obj" in matgeoset # fluid mesh ): fluidsec_obj = matgeoset["fluidsection_obj"] - if ( - fluidsec_obj.SectionType == "Liquid" - and ( - fluidsec_obj.LiquidSectionType == "PIPE INLET" - or fluidsec_obj.LiquidSectionType == "PIPE OUTLET" - ) + if fluidsec_obj.SectionType == "Liquid" and ( + fluidsec_obj.LiquidSectionType == "PIPE INLET" + or fluidsec_obj.LiquidSectionType == "PIPE OUTLET" ): return fluidsec_obj return None def is_fluidsection_inoutlet_setnames_possible(mat_geo_sets): for matgeoset in mat_geo_sets: - if ( - matgeoset["ccx_elset"] - and "fluidsection_obj" in matgeoset # fluid mesh - ): + if matgeoset["ccx_elset"] and "fluidsection_obj" in matgeoset: # fluid mesh fluidsec_obj = matgeoset["fluidsection_obj"] - if ( - fluidsec_obj.SectionType == "Liquid" - and ( - fluidsec_obj.LiquidSectionType == "PIPE INLET" - or fluidsec_obj.LiquidSectionType == "PIPE OUTLET" - ) + if fluidsec_obj.SectionType == "Liquid" and ( + fluidsec_obj.LiquidSectionType == "PIPE INLET" + or fluidsec_obj.LiquidSectionType == "PIPE OUTLET" ): return True return False @@ -101,15 +91,15 @@ def handle_fluidsection_liquid_inlet_outlet(inpfile, ccxwriter): counter = 0 for elid in matgeoset["ccx_elset"]: counter = counter + 1 - if (elsetchanged is False) \ - and (fluidsec_obj.LiquidSectionType == "PIPE INLET"): + if (elsetchanged is False) and (fluidsec_obj.LiquidSectionType == "PIPE INLET"): # 3rd index is to track which line nr the element is defined ccxwriter.FluidInletoutlet_ele.append( [str(elid), fluidsec_obj.LiquidSectionType, 0] ) elsetchanged = True - elif (fluidsec_obj.LiquidSectionType == "PIPE OUTLET") \ - and (counter == len(matgeoset["ccx_elset"])): + elif (fluidsec_obj.LiquidSectionType == "PIPE OUTLET") and ( + counter == len(matgeoset["ccx_elset"]) + ): # 3rd index is to track which line nr the element is defined ccxwriter.FluidInletoutlet_ele.append( [str(elid), fluidsec_obj.LiquidSectionType, 0] @@ -123,9 +113,7 @@ def handle_fluidsection_liquid_inlet_outlet(inpfile, ccxwriter): # for split input file the main file is just closed and reopend even if not needed inpfile.close() meshtools.use_correct_fluidinout_ele_def( - ccxwriter.FluidInletoutlet_ele, - ccxwriter.femmesh_file, - ccxwriter.fluid_inout_nodes_file + ccxwriter.FluidInletoutlet_ele, ccxwriter.femmesh_file, ccxwriter.fluid_inout_nodes_file ) inpfile = codecs.open(ccxwriter.file_name, "a", encoding="utf-8") @@ -146,13 +134,12 @@ def write_constraints_fluidsection(f, ccxwriter): f.write("\n***********************************************************\n") f.write("** FluidSection constraints\n") if os.path.exists(ccxwriter.fluid_inout_nodes_file): - inout_nodes_file = open(ccxwriter.fluid_inout_nodes_file, "r") + inout_nodes_file = open(ccxwriter.fluid_inout_nodes_file) lines = inout_nodes_file.readlines() inout_nodes_file.close() else: FreeCAD.Console.PrintError( - "1DFlow inout nodes file not found: {}\n" - .format(ccxwriter.fluid_inout_nodes_file) + f"1DFlow inout nodes file not found: {ccxwriter.fluid_inout_nodes_file}\n" ) # get nodes ccxwriter.get_constraints_fluidsection_nodes() @@ -170,12 +157,11 @@ def write_constraints_fluidsection(f, ccxwriter): b = line.split(",") if int(b[0]) == n and b[3] == "PIPE INLET\n": # degree of freedom 2 is for defining pressure - f.write("{},{},{},{}\n".format( - b[0], - "2", - "2", - fluidsection_obj.InletPressure - )) + f.write( + "{},{},{},{}\n".format( + b[0], "2", "2", fluidsection_obj.InletPressure + ) + ) if fluidsection_obj.InletFlowRateActive is True: f.write("*BOUNDARY,MASS FLOW \n") for n in femobj["Nodes"]: @@ -184,12 +170,11 @@ def write_constraints_fluidsection(f, ccxwriter): if int(b[0]) == n and b[3] == "PIPE INLET\n": # degree of freedom 1 is for defining flow rate # factor applied to convert unit from kg/s to t/s - f.write("{},{},{},{}\n".format( - b[1], - "1", - "1", - fluidsection_obj.InletFlowRate * 0.001 - )) + f.write( + "{},{},{},{}\n".format( + b[1], "1", "1", fluidsection_obj.InletFlowRate * 0.001 + ) + ) elif fluidsection_obj.LiquidSectionType == "PIPE OUTLET": f.write("**Fluid Section Outlet \n") if fluidsection_obj.OutletPressureActive is True: @@ -199,12 +184,11 @@ def write_constraints_fluidsection(f, ccxwriter): b = line.split(",") if int(b[0]) == n and b[3] == "PIPE OUTLET\n": # degree of freedom 2 is for defining pressure - f.write("{},{},{},{}\n".format( - b[0], - "2", - "2", - fluidsection_obj.OutletPressure - )) + f.write( + "{},{},{},{}\n".format( + b[0], "2", "2", fluidsection_obj.OutletPressure + ) + ) if fluidsection_obj.OutletFlowRateActive is True: f.write("*BOUNDARY,MASS FLOW \n") for n in femobj["Nodes"]: @@ -213,9 +197,8 @@ def write_constraints_fluidsection(f, ccxwriter): if int(b[0]) == n and b[3] == "PIPE OUTLET\n": # degree of freedom 1 is for defining flow rate # factor applied to convert unit from kg/s to t/s - f.write("{},{},{},{}\n".format( - b[1], - "1", - "1", - fluidsection_obj.OutletFlowRate * 0.001 - )) + f.write( + "{},{},{},{}\n".format( + b[1], "1", "1", fluidsection_obj.OutletFlowRate * 0.001 + ) + ) diff --git a/src/Mod/Fem/femsolver/calculix/write_constraint_force.py b/src/Mod/Fem/femsolver/calculix/write_constraint_force.py index 785fbade16..d899913590 100644 --- a/src/Mod/Fem/femsolver/calculix/write_constraint_force.py +++ b/src/Mod/Fem/femsolver/calculix/write_constraint_force.py @@ -51,18 +51,18 @@ def write_meshdata_constraint(f, femobj, force_obj, ccxwriter): # be careful with raising the tolerance, a big load would have an impact # but compared to the real direction the impact would be small again for ref_shape in femobj["NodeLoadTable"]: - f.write("** {}\n".format(ref_shape[0])) + f.write(f"** {ref_shape[0]}\n") for n in sorted(ref_shape[1]): node_load = ref_shape[1][n] # the loads in ref_shape[1][n] are without unit if abs(direction_vec.x) > dir_zero_tol: - v1 = "{:.13G}".format((direction_vec.x * node_load).Value) - f.write("{},1,{}\n".format(n, v1)) + v1 = f"{(direction_vec.x * node_load).Value:.13G}" + f.write(f"{n},1,{v1}\n") if abs(direction_vec.y) > dir_zero_tol: - v2 = "{:.13G}".format((direction_vec.y * node_load).Value) - f.write("{},2,{}\n".format(n, v2)) + v2 = f"{(direction_vec.y * node_load).Value:.13G}" + f.write(f"{n},2,{v2}\n") if abs(direction_vec.z) > dir_zero_tol: - v3 = "{:.13G}".format((direction_vec.z * node_load).Value) - f.write("{},3,{}\n".format(n, v3)) + v3 = f"{(direction_vec.z * node_load).Value:.13G}" + f.write(f"{n},3,{v3}\n") f.write("\n") f.write("\n") diff --git a/src/Mod/Fem/femsolver/calculix/write_constraint_heatflux.py b/src/Mod/Fem/femsolver/calculix/write_constraint_heatflux.py index 799f9c408d..e9d6e46190 100644 --- a/src/Mod/Fem/femsolver/calculix/write_constraint_heatflux.py +++ b/src/Mod/Fem/femsolver/calculix/write_constraint_heatflux.py @@ -51,33 +51,26 @@ def write_meshdata_constraint(f, femobj, heatflux_obj, ccxwriter): heatflux_facetype = "F" # SvdW: add factor to force heatflux to units system of t/mm/s/K heatflux_values = "{:.13G},{:.13G}".format( - heatflux_obj.AmbientTemp, - heatflux_obj.FilmCoef * 0.001 + heatflux_obj.AmbientTemp, heatflux_obj.FilmCoef * 0.001 ) elif heatflux_obj.ConstraintType == "Radiation": heatflux_key_word = "RADIATE" heatflux_facetype = "R" heatflux_values = "{:.13G},{:.13G}".format( - heatflux_obj.AmbientTemp, - heatflux_obj.Emissivity + heatflux_obj.AmbientTemp, heatflux_obj.Emissivity ) elif heatflux_obj.ConstraintType == "DFlux": heatflux_key_word = "DFLUX" heatflux_facetype = "S" - heatflux_values = "{:.13G}".format(heatflux_obj.DFlux * 0.001) + heatflux_values = f"{heatflux_obj.DFlux * 0.001:.13G}" - f.write("*{}\n".format(heatflux_key_word)) + f.write(f"*{heatflux_key_word}\n") for ref_shape in femobj["HeatFluxFaceTable"]: elem_string = ref_shape[0] face_table = ref_shape[1] - f.write("** Heat flux on face {}\n".format(elem_string)) + f.write(f"** Heat flux on face {elem_string}\n") for i in face_table: # OvG: Only write out the VolumeIDs linked to a particular face - f.write("{},{}{},{}\n".format( - i[0], - heatflux_facetype, - i[1], - heatflux_values - )) + f.write(f"{i[0]},{heatflux_facetype}{i[1]},{heatflux_values}\n") diff --git a/src/Mod/Fem/femsolver/calculix/write_constraint_initialtemperature.py b/src/Mod/Fem/femsolver/calculix/write_constraint_initialtemperature.py index 7460d702f9..c3bf3e5182 100644 --- a/src/Mod/Fem/femsolver/calculix/write_constraint_initialtemperature.py +++ b/src/Mod/Fem/femsolver/calculix/write_constraint_initialtemperature.py @@ -48,10 +48,11 @@ def write_constraint(f, femobj, inittemp_obj, ccxwriter): # floats read from ccx should use {:.13G}, see comment in writer module - f.write("{},{}\n".format( - ccxwriter.ccx_nall, - Units.Quantity(inittemp_obj.initialTemperature.getValueAs("K")) - )) + f.write( + "{},{}\n".format( + ccxwriter.ccx_nall, Units.Quantity(inittemp_obj.initialTemperature.getValueAs("K")) + ) + ) # Should only be one object in the analysis diff --git a/src/Mod/Fem/femsolver/calculix/write_constraint_planerotation.py b/src/Mod/Fem/femsolver/calculix/write_constraint_planerotation.py index 9903c15d6e..c903c22d11 100644 --- a/src/Mod/Fem/femsolver/calculix/write_constraint_planerotation.py +++ b/src/Mod/Fem/femsolver/calculix/write_constraint_planerotation.py @@ -30,7 +30,7 @@ from femmesh import meshtools def get_analysis_types(): - return "all" # write for all analysis types + return "all" # write for all analysis types def get_sets_name(): @@ -69,16 +69,18 @@ def write_meshdata_constraint(f, femobj, fric_obj, ccxwriter): # Thus call write_node_sets_constraints_planerotation has to be # after constraint fixed and constraint displacement l_nodes = femobj["Nodes"] - f.write("*NSET,NSET={}\n".format(fric_obj.Name)) + f.write(f"*NSET,NSET={fric_obj.Name}\n") # Code to extract nodes and coordinates on the PlaneRotation support face nodes_coords = [] for node in l_nodes: - nodes_coords.append(( - node, - ccxwriter.femnodes_mesh[node].x, - ccxwriter.femnodes_mesh[node].y, - ccxwriter.femnodes_mesh[node].z - )) + nodes_coords.append( + ( + node, + ccxwriter.femnodes_mesh[node].x, + ccxwriter.femnodes_mesh[node].y, + ccxwriter.femnodes_mesh[node].z, + ) + ) node_planerotation = meshtools.get_three_non_colinear_nodes(nodes_coords) for i in range(len(l_nodes)): if l_nodes[i] not in node_planerotation: @@ -93,7 +95,7 @@ def write_meshdata_constraint(f, femobj, fric_obj, ccxwriter): MPC = node_planerotation[i] MPC_nodes.append(MPC) for i in range(len(MPC_nodes)): - f.write("{},\n".format(MPC_nodes[i])) + f.write(f"{MPC_nodes[i]},\n") def write_constraint(f, femobj, fric_obj, ccxwriter): @@ -101,4 +103,4 @@ def write_constraint(f, femobj, fric_obj, ccxwriter): # floats read from ccx should use {:.13G}, see comment in writer module f.write("*MPC\n") - f.write("PLANE,{}\n".format(fric_obj.Name)) + f.write(f"PLANE,{fric_obj.Name}\n") diff --git a/src/Mod/Fem/femsolver/calculix/write_constraint_pressure.py b/src/Mod/Fem/femsolver/calculix/write_constraint_pressure.py index 18aee620b0..de8da3d333 100644 --- a/src/Mod/Fem/femsolver/calculix/write_constraint_pressure.py +++ b/src/Mod/Fem/femsolver/calculix/write_constraint_pressure.py @@ -27,6 +27,7 @@ __url__ = "https://www.freecad.org" import FreeCAD + def get_analysis_types(): return ["buckling", "static", "thermomech"] @@ -60,12 +61,12 @@ def write_meshdata_constraint(f, femobj, prs_obj, ccxwriter): f.write("** " + ref_shape[0] + "\n") for face, fno in ref_shape[1]: if fno > 0: # solid mesh face - f.write("{},P{},{}\n".format(face, fno, press_rev)) + f.write(f"{face},P{fno},{press_rev}\n") # on shell mesh face: fno == 0 # normal of element face == face normal elif fno == 0: - f.write("{},P,{}\n".format(face, press_rev)) + f.write(f"{face},P,{press_rev}\n") # on shell mesh face: fno == -1 # normal of element face opposite direction face normal elif fno == -1: - f.write("{},P,{}\n".format(face, -1 * press_rev)) + f.write(f"{face},P,{-1 * press_rev}\n") diff --git a/src/Mod/Fem/femsolver/calculix/write_constraint_rigidbody.py b/src/Mod/Fem/femsolver/calculix/write_constraint_rigidbody.py index 70d6933141..148480829b 100644 --- a/src/Mod/Fem/femsolver/calculix/write_constraint_rigidbody.py +++ b/src/Mod/Fem/femsolver/calculix/write_constraint_rigidbody.py @@ -27,7 +27,7 @@ __url__ = "https://www.freecadweb.org" def get_analysis_types(): - return "all" # write for all analysis types + return "all" # write for all analysis types def get_sets_name(): @@ -58,7 +58,7 @@ def write_meshdata_constraint(f, femobj, rb_obj, ccxwriter): f.write("*NSET,NSET=" + rb_obj.Name + "\n") for n in femobj["Nodes"]: - f.write("{},\n".format(n)) + f.write(f"{n},\n") def write_constraint(f, femobj, rb_obj, ccxwriter): @@ -66,19 +66,18 @@ def write_constraint(f, femobj, rb_obj, ccxwriter): rb_obj_idx = ccxwriter.analysis.Group.index(rb_obj) node_count = ccxwriter.mesh_object.FemMesh.NodeCount # factor 2 is to prevent conflict with other rigid body constraint - ref_node_idx = node_count + 2*rb_obj_idx + 1 - rot_node_idx = node_count + 2*rb_obj_idx + 2 + ref_node_idx = node_count + 2 * rb_obj_idx + 1 + rot_node_idx = node_count + 2 * rb_obj_idx + 2 f.write("*NODE\n") f.write("{},{},{},{}\n".format(ref_node_idx, *rb_obj.ReferenceNode)) f.write("{},{},{},{}\n".format(rot_node_idx, *rb_obj.ReferenceNode)) - f.write("*NSET,NSET={}_RefNode\n".format(rb_obj.Name)) - f.write("{},\n".format(ref_node_idx)) - f.write("*NSET,NSET={}_RotNode\n".format(rb_obj.Name)) - f.write("{},\n".format(rot_node_idx)) + f.write(f"*NSET,NSET={rb_obj.Name}_RefNode\n") + f.write(f"{ref_node_idx},\n") + f.write(f"*NSET,NSET={rb_obj.Name}_RotNode\n") + f.write(f"{rot_node_idx},\n") - kw_line = "*RIGID BODY, NSET={}, REF NODE={}, ROT NODE={}".format(rb_obj.Name, ref_node_idx, rot_node_idx) + kw_line = f"*RIGID BODY, NSET={rb_obj.Name}, REF NODE={ref_node_idx}, ROT NODE={rot_node_idx}" f.write(kw_line + "\n") - diff --git a/src/Mod/Fem/femsolver/calculix/write_constraint_rigidbody_step.py b/src/Mod/Fem/femsolver/calculix/write_constraint_rigidbody_step.py index ad7a27d56f..d93bcdce1b 100644 --- a/src/Mod/Fem/femsolver/calculix/write_constraint_rigidbody_step.py +++ b/src/Mod/Fem/femsolver/calculix/write_constraint_rigidbody_step.py @@ -30,7 +30,7 @@ import FreeCAD def get_analysis_types(): - return "all" # write for all analysis types + return "all" # write for all analysis types def get_sets_name(): @@ -62,16 +62,16 @@ def write_constraint(f, femobj, rb_obj, ccxwriter): rb_obj_idx = ccxwriter.analysis.Group.index(rb_obj) node_count = ccxwriter.mesh_object.FemMesh.NodeCount # factor 2 is to prevent conflict with other rigid body constraint - ref_node_idx = node_count + 2*rb_obj_idx + 1 - rot_node_idx = node_count + 2*rb_obj_idx + 2 + ref_node_idx = node_count + 2 * rb_obj_idx + 1 + rot_node_idx = node_count + 2 * rb_obj_idx + 2 def write_mode(mode, node, dof, constraint, load): if mode == "Constraint": f.write("*BOUNDARY\n") - f.write("{},{},{},{:.13G}\n".format(node, dof, dof, constraint)) + f.write(f"{node},{dof},{dof},{constraint:.13G}\n") elif mode == "Load": f.write("*CLOAD\n") - f.write("{},{},{:.13G}\n".format(node, dof, load)) + f.write(f"{node},{dof},{load:.13G}\n") mode = [rb_obj.TranslationalModeX, rb_obj.TranslationalModeY, rb_obj.TranslationalModeZ] constraint = rb_obj.Displacement @@ -80,9 +80,8 @@ def write_constraint(f, femobj, rb_obj, ccxwriter): for i in range(3): write_mode(mode[i], ref_node_idx, i + 1, constraint[i], load[i].getValueAs("N").Value) - mode = [rb_obj.RotationalModeX, rb_obj.RotationalModeY, rb_obj.RotationalModeZ] - load = [rb_obj.MomentX,rb_obj.MomentY, rb_obj.MomentZ] + load = [rb_obj.MomentX, rb_obj.MomentY, rb_obj.MomentZ] # write rotation components according to rotational mode rot = rb_obj.Rotation @@ -96,5 +95,4 @@ def write_constraint(f, femobj, rb_obj, ccxwriter): for i in range(3): write_mode(mode[i], rot_node_idx, i + 1, constraint[i], load[i].getValueAs("N*mm").Value) - f.write("\n") diff --git a/src/Mod/Fem/femsolver/calculix/write_constraint_sectionprint.py b/src/Mod/Fem/femsolver/calculix/write_constraint_sectionprint.py index 079385e8f6..029f462f78 100644 --- a/src/Mod/Fem/femsolver/calculix/write_constraint_sectionprint.py +++ b/src/Mod/Fem/femsolver/calculix/write_constraint_sectionprint.py @@ -27,7 +27,7 @@ __url__ = "https://www.freecad.org" def get_analysis_types(): - return "all" # write for all analysis types + return "all" # write for all analysis types def get_sets_name(): @@ -55,9 +55,9 @@ def get_after_write_constraint(): def write_meshdata_constraint(f, femobj, sectionprint_obj, ccxwriter): - f.write("*SURFACE, NAME=SECTIONFACE{}\n".format(sectionprint_obj.Name)) + f.write(f"*SURFACE, NAME=SECTIONFACE{sectionprint_obj.Name}\n") for i in femobj["SectionPrintFaces"]: - f.write("{},S{}\n".format(i[0], i[1])) + f.write(f"{i[0]},S{i[1]}\n") def write_constraint(f, femobj, sectionprint_obj, ccxwriter): @@ -73,7 +73,8 @@ def write_constraint(f, femobj, sectionprint_obj, ccxwriter): key = "DRAG" f.write( - "*SECTION PRINT, SURFACE=SECTIONFACE{}, NAME=SECTIONPRINT{}\n" - .format(sectionprint_obj.Name, sectionprint_obj.Name) + "*SECTION PRINT, SURFACE=SECTIONFACE{}, NAME=SECTIONPRINT{}\n".format( + sectionprint_obj.Name, sectionprint_obj.Name + ) ) f.write(key + "\n") diff --git a/src/Mod/Fem/femsolver/calculix/write_constraint_selfweight.py b/src/Mod/Fem/femsolver/calculix/write_constraint_selfweight.py index ee366df41c..cb5f744244 100644 --- a/src/Mod/Fem/femsolver/calculix/write_constraint_selfweight.py +++ b/src/Mod/Fem/femsolver/calculix/write_constraint_selfweight.py @@ -49,13 +49,14 @@ def write_constraint(f, femobj, selwei_obj, ccxwriter): f.write("*DLOAD\n") f.write( # elset, GRAV, magnitude, direction x, dir y ,dir z - "{},GRAV,{:.13G},{:.13G},{:.13G},{:.13G}\n" - .format( + "{},GRAV,{:.13G},{:.13G},{:.13G},{:.13G}\n".format( ccxwriter.ccx_eall, - selwei_obj.GravityAcceleration.getValueAs("mm/s^2").Value, # actual magnitude of gravity vector + selwei_obj.GravityAcceleration.getValueAs( + "mm/s^2" + ).Value, # actual magnitude of gravity vector selwei_obj.GravityDirection.x, # coordinate x of normalized gravity vector selwei_obj.GravityDirection.y, # y - selwei_obj.GravityDirection.z # z + selwei_obj.GravityDirection.z, # z ) ) f.write("\n") diff --git a/src/Mod/Fem/femsolver/calculix/write_constraint_temperature.py b/src/Mod/Fem/femsolver/calculix/write_constraint_temperature.py index 52148fbc72..3c77b73b8d 100644 --- a/src/Mod/Fem/femsolver/calculix/write_constraint_temperature.py +++ b/src/Mod/Fem/femsolver/calculix/write_constraint_temperature.py @@ -42,9 +42,9 @@ def get_constraint_title(): def write_meshdata_constraint(f, femobj, temp_obj, ccxwriter): - f.write("*NSET,NSET={}\n".format(temp_obj.Name)) + f.write(f"*NSET,NSET={temp_obj.Name}\n") for n in femobj["Nodes"]: - f.write("{},\n".format(n)) + f.write(f"{n},\n") def get_before_write_meshdata_constraint(): @@ -82,7 +82,7 @@ def write_constraint(f, femobj, temp_obj, ccxwriter): f.write( "{},11,{}\n".format( temp_obj.Name, - FreeCAD.Units.Quantity(temp_obj.CFlux.getValueAs("mW")) / NumberOfNodes + FreeCAD.Units.Quantity(temp_obj.CFlux.getValueAs("mW")) / NumberOfNodes, ) ) f.write("\n") diff --git a/src/Mod/Fem/femsolver/calculix/write_constraint_tie.py b/src/Mod/Fem/femsolver/calculix/write_constraint_tie.py index a9d35893c8..4f96280f0e 100644 --- a/src/Mod/Fem/femsolver/calculix/write_constraint_tie.py +++ b/src/Mod/Fem/femsolver/calculix/write_constraint_tie.py @@ -30,7 +30,7 @@ from FreeCAD import Units, Vector def get_analysis_types(): - return "all" # write for all analysis types + return "all" # write for all analysis types def get_sets_name(): @@ -59,13 +59,13 @@ def get_after_write_constraint(): def write_meshdata_constraint(f, femobj, tie_obj, ccxwriter): # slave DEP - f.write("*SURFACE, NAME=TIE_DEP{}\n".format(tie_obj.Name)) + f.write(f"*SURFACE, NAME=TIE_DEP{tie_obj.Name}\n") for i in femobj["TieSlaveFaces"]: - f.write("{},S{}\n".format(i[0], i[1])) + f.write(f"{i[0]},S{i[1]}\n") # master IND - f.write("*SURFACE, NAME=TIE_IND{}\n".format(tie_obj.Name)) + f.write(f"*SURFACE, NAME=TIE_IND{tie_obj.Name}\n") for i in femobj["TieMasterFaces"]: - f.write("{},S{}\n".format(i[0], i[1])) + f.write(f"{i[0]},S{i[1]}\n") def write_constraint(f, femobj, tie_obj, ccxwriter): @@ -83,18 +83,20 @@ def write_constraint(f, femobj, tie_obj, ccxwriter): symmetry = ", CYCLIC SYMMETRY" f.write( - "*TIE, POSITION TOLERANCE={:.13G}{}{}, NAME=TIE{}\n" - .format(tolerance, adjust, symmetry, tie_name) + "*TIE, POSITION TOLERANCE={:.13G}{}{}, NAME=TIE{}\n".format( + tolerance, adjust, symmetry, tie_name + ) ) - ind_surf = "TIE_IND{}".format(tie_name) - dep_surf = "TIE_DEP{}".format(tie_name) - f.write("{}, {}\n".format(dep_surf, ind_surf)) + ind_surf = f"TIE_IND{tie_name}" + dep_surf = f"TIE_DEP{tie_name}" + f.write(f"{dep_surf}, {ind_surf}\n") # write CYCLIC SYMMETRY MODEL card if tie_obj.CyclicSymmetry: f.write( - "*CYCLIC SYMMETRY MODEL, N={}, NGRAPH={}, TIE=TIE{}, ELSET=Eall\n" - .format(tie_obj.Sectors, tie_obj.ConnectedSectors, tie_name) + "*CYCLIC SYMMETRY MODEL, N={}, NGRAPH={}, TIE=TIE{}, ELSET=Eall\n".format( + tie_obj.Sectors, tie_obj.ConnectedSectors, tie_name + ) ) # get symmetry axis points @@ -105,7 +107,4 @@ def write_constraint(f, femobj, tie_obj, ccxwriter): point_a = [set_unit(coord) for coord in vec_a] point_b = [set_unit(coord) for coord in vec_b] - f.write( - "{:.13G},{:.13G},{:.13G},{:.13G},{:.13G},{:.13G}\n" - .format(*point_a, *point_b) - ) + f.write("{:.13G},{:.13G},{:.13G},{:.13G},{:.13G},{:.13G}\n".format(*point_a, *point_b)) diff --git a/src/Mod/Fem/femsolver/calculix/write_constraint_transform.py b/src/Mod/Fem/femsolver/calculix/write_constraint_transform.py index 949d8384d9..a7dd67e17c 100644 --- a/src/Mod/Fem/femsolver/calculix/write_constraint_transform.py +++ b/src/Mod/Fem/femsolver/calculix/write_constraint_transform.py @@ -32,7 +32,7 @@ from femtools import geomtools def get_analysis_types(): - return "all" # write for all analysis types + return "all" # write for all analysis types def get_sets_name(): @@ -61,11 +61,11 @@ def get_after_write_constraint(): def write_meshdata_constraint(f, femobj, trans_obj, ccxwriter): if trans_obj.TransformType == "Rectangular": - f.write("*NSET,NSET=Rect{}\n".format(trans_obj.Name)) + f.write(f"*NSET,NSET=Rect{trans_obj.Name}\n") elif trans_obj.TransformType == "Cylindrical": - f.write("*NSET,NSET=Cylin{}\n".format(trans_obj.Name)) + f.write(f"*NSET,NSET=Cylin{trans_obj.Name}\n") for n in femobj["Nodes"]: - f.write("{},\n".format(n)) + f.write(f"{n},\n") def write_constraint(f, femobj, trans_obj, ccxwriter): @@ -86,16 +86,20 @@ def write_constraint(f, femobj, trans_obj, ccxwriter): base = trans_obj.BasePoint axis = trans_obj.Axis coords = list(base) + list(base + axis) - f.write("*TRANSFORM, NSET={}{}, TYPE={}\n".format( - trans_name, - trans_obj.Name, - trans_type, - )) - f.write("{:.13G},{:.13G},{:.13G},{:.13G},{:.13G},{:.13G}\n".format( - coords[0], - coords[1], - coords[2], - coords[3], - coords[4], - coords[5], - )) + f.write( + "*TRANSFORM, NSET={}{}, TYPE={}\n".format( + trans_name, + trans_obj.Name, + trans_type, + ) + ) + f.write( + "{:.13G},{:.13G},{:.13G},{:.13G},{:.13G},{:.13G}\n".format( + coords[0], + coords[1], + coords[2], + coords[3], + coords[4], + coords[5], + ) + ) diff --git a/src/Mod/Fem/femsolver/calculix/write_femelement_geometry.py b/src/Mod/Fem/femsolver/calculix/write_femelement_geometry.py index e2c0176317..c7ee293538 100644 --- a/src/Mod/Fem/femsolver/calculix/write_femelement_geometry.py +++ b/src/Mod/Fem/femsolver/calculix/write_femelement_geometry.py @@ -43,9 +43,7 @@ def write_femelement_geometry(f, ccxwriter): # in CalxuliX called the 1direction # see meshtools.get_beam_main_axis_m(beam_direction, defined_angle) section_nor = "{:.13G}, {:.13G}, {:.13G}\n".format( - beam_axis_m[0], - beam_axis_m[1], - beam_axis_m[2] + beam_axis_m[0], beam_axis_m[1], beam_axis_m[2] ) print(section_nor) if beamsec_obj.SectionType == "Rectangular": @@ -61,31 +59,19 @@ def write_femelement_geometry(f, ccxwriter): len_beam_axis_n = beamsec_obj.RectHeight.getValueAs("mm").Value len_beam_axis_m = beamsec_obj.RectWidth.getValueAs("mm").Value section_type = ", SECTION=RECT" - section_geo = "{:.13G},{:.13G}\n".format(len_beam_axis_m, len_beam_axis_n) - section_def = "*BEAM SECTION, {}{}{}\n".format( - elsetdef, - material, - section_type - ) + section_geo = f"{len_beam_axis_m:.13G},{len_beam_axis_n:.13G}\n" + section_def = f"*BEAM SECTION, {elsetdef}{material}{section_type}\n" elif beamsec_obj.SectionType == "Circular": diameter = beamsec_obj.CircDiameter.getValueAs("mm").Value section_type = ", SECTION=CIRC" - section_geo = "{:.13G}\n".format(diameter) - section_def = "*BEAM SECTION, {}{}{}\n".format( - elsetdef, - material, - section_type - ) + section_geo = f"{diameter:.13G}\n" + section_def = f"*BEAM SECTION, {elsetdef}{material}{section_type}\n" elif beamsec_obj.SectionType == "Pipe": radius = 0.5 * beamsec_obj.PipeDiameter.getValueAs("mm").Value thickness = beamsec_obj.PipeThickness.getValueAs("mm").Value section_type = ", SECTION=PIPE" - section_geo = "{:.13G},{:.13G}\n".format(radius, thickness) - section_def = "*BEAM SECTION, {}{}{}\n".format( - elsetdef, - material, - section_type - ) + section_geo = f"{radius:.13G},{thickness:.13G}\n" + section_def = f"*BEAM SECTION, {elsetdef}{material}{section_type}\n" f.write(section_def) f.write(section_geo) f.write(section_nor) @@ -96,9 +82,7 @@ def write_femelement_geometry(f, ccxwriter): if (section_type == "PIPE INLET") or (section_type == "PIPE OUTLET"): section_type = "PIPE INOUT" section_def = "*FLUID SECTION, {}TYPE={}, {}\n".format( - elsetdef, - section_type, - material + elsetdef, section_type, material ) section_geo = liquid_section_def(fluidsec_obj, section_type) """ @@ -114,15 +98,15 @@ def write_femelement_geometry(f, ccxwriter): elif "shellthickness_obj" in matgeoset: # shell mesh shellth_obj = matgeoset["shellthickness_obj"] if ccxwriter.solver_obj.ModelSpace == "3D": - section_def = "*SHELL SECTION, {}{}\n".format(elsetdef, material) + section_def = f"*SHELL SECTION, {elsetdef}{material}\n" else: - section_def = "*SOLID SECTION, {}{}\n".format(elsetdef, material) + section_def = f"*SOLID SECTION, {elsetdef}{material}\n" thickness = shellth_obj.Thickness.getValueAs("mm").Value - section_geo = "{:.13G}\n".format(thickness) + section_geo = f"{thickness:.13G}\n" f.write(section_def) - f.write(section_geo) + f.write(section_geo) else: # solid mesh - section_def = "*SOLID SECTION, {}{}\n".format(elsetdef, material) + section_def = f"*SOLID SECTION, {elsetdef}{material}\n" f.write(section_def) @@ -134,68 +118,63 @@ def liquid_section_def(obj, section_type): manning_radius = obj.ManningRadius.getValueAs("mm").Value manning_coefficient = obj.ManningCoefficient section_geo = "{:.13G},{:.13G},{:.13G}\n".format( - manning_area, - manning_radius, - manning_coefficient + manning_area, manning_radius, manning_coefficient ) return section_geo elif section_type == "PIPE ENLARGEMENT": enlarge_area1 = obj.EnlargeArea1.getValueAs("mm^2").Value enlarge_area2 = obj.EnlargeArea2.getValueAs("mm^2").Value - section_geo = "{:.13G},{:.13G}\n".format(enlarge_area1, enlarge_area2) + section_geo = f"{enlarge_area1:.13G},{enlarge_area2:.13G}\n" return section_geo elif section_type == "PIPE CONTRACTION": contract_area1 = obj.ContractArea1.getValueAs("mm^2").Value contract_area2 = obj.ContractArea2.getValueAs("mm^2").Value - section_geo = "{:.13G},{:.13G}\n".format(contract_area1, contract_area2) + section_geo = f"{contract_area1:.13G},{contract_area2:.13G}\n" return section_geo elif section_type == "PIPE ENTRANCE": entrance_pipe_area = obj.EntrancePipeArea.getValueAs("mm^2").Value entrance_area = obj.EntranceArea.getValueAs("mm^2").Value - section_geo = "{:.13G},{:.13G}\n".format(entrance_pipe_area, entrance_area) + section_geo = f"{entrance_pipe_area:.13G},{entrance_area:.13G}\n" return section_geo elif section_type == "PIPE DIAPHRAGM": diaphragm_pipe_area = obj.DiaphragmPipeArea.getValueAs("mm^2").Value diaphragm_area = obj.DiaphragmArea.getValueAs("mm^2").Value - section_geo = "{:.13G},{:.13G}\n".format(diaphragm_pipe_area, diaphragm_area) + section_geo = f"{diaphragm_pipe_area:.13G},{diaphragm_area:.13G}\n" return section_geo elif section_type == "PIPE BEND": bend_pipe_area = obj.BendPipeArea.getValueAs("mm^2").Value bend_radius_diameter = obj.BendRadiusDiameter bend_angle = obj.BendAngle bend_loss_coefficient = obj.BendLossCoefficient - section_geo = ("{:.13G},{:.13G},{:.13G},{:.13G}\n".format( - bend_pipe_area, - bend_radius_diameter, - bend_angle, - bend_loss_coefficient - )) + section_geo = "{:.13G},{:.13G},{:.13G},{:.13G}\n".format( + bend_pipe_area, bend_radius_diameter, bend_angle, bend_loss_coefficient + ) return section_geo elif section_type == "PIPE GATE VALVE": gatevalve_pipe_area = obj.GateValvePipeArea.getValueAs("mm^2").Value gatevalve_closing_coeff = obj.GateValveClosingCoeff - section_geo = "{:.13G},{:.13G}\n".format(gatevalve_pipe_area, gatevalve_closing_coeff) + section_geo = f"{gatevalve_pipe_area:.13G},{gatevalve_closing_coeff:.13G}\n" return section_geo elif section_type == "PIPE WHITE-COLEBROOK": colebrooke_area = obj.ColebrookeArea.getValueAs("mm^2").Value colebrooke_diameter = 2 * obj.ColebrookeRadius.getValueAs("mm") colebrooke_grain_diameter = obj.ColebrookeGrainDiameter.getValueAs("mm") colebrooke_form_factor = obj.ColebrookeFormFactor - section_geo = ("{:.13G},{:.13G},{},{:.13G},{:.13G}\n".format( + section_geo = "{:.13G},{:.13G},{},{:.13G},{:.13G}\n".format( colebrooke_area, colebrooke_diameter, "-1", colebrooke_grain_diameter, - colebrooke_form_factor - )) + colebrooke_form_factor, + ) return section_geo elif section_type == "LIQUID PUMP": section_geo = "" for i in range(len(obj.PumpFlowRate)): flow_rate = obj.PumpFlowRate[i] top = obj.PumpHeadLoss[i] - section_geo = "{:.13G},{:.13G},\n".format(section_geo + flow_rate, top) - section_geo = "{}\n".format(section_geo) + section_geo = f"{section_geo + flow_rate:.13G},{top:.13G},\n" + section_geo = f"{section_geo}\n" return section_geo else: return "" diff --git a/src/Mod/Fem/femsolver/calculix/write_femelement_material.py b/src/Mod/Fem/femsolver/calculix/write_femelement_material.py index b290db2df7..481ad5ce00 100644 --- a/src/Mod/Fem/femsolver/calculix/write_femelement_material.py +++ b/src/Mod/Fem/femsolver/calculix/write_femelement_material.py @@ -77,7 +77,7 @@ def write_femelement_material(f, ccxwriter): SH = FreeCAD.Units.Quantity(mat_obj.Material["SpecificHeat"]) # SvdW: Add factor to force units to results base units of t/mm/s/K # FIXME: why not get it directly in the units needed ? - SH_in_JkgK = SH.getValueAs("J/kg/K").Value * 1e+06 + SH_in_JkgK = SH.getValueAs("J/kg/K").Value * 1e06 if mat_obj.Category == "Solid": TEC = FreeCAD.Units.Quantity(mat_obj.Material["ThermalExpansionCoefficient"]) TEC_in_mmK = TEC.getValueAs("mm/mm/K").Value @@ -86,26 +86,26 @@ def write_femelement_material(f, ccxwriter): DV_in_tmms = DV.getValueAs("t/mm/s").Value # write material properties - f.write("** FreeCAD material name: {}\n".format(mat_info_name)) - f.write("** {}\n".format(mat_label)) - f.write("*MATERIAL, NAME={}\n".format(mat_name)) + f.write(f"** FreeCAD material name: {mat_info_name}\n") + f.write(f"** {mat_label}\n") + f.write(f"*MATERIAL, NAME={mat_name}\n") if mat_obj.Category == "Solid": f.write("*ELASTIC\n") - f.write("{:.13G},{:.13G}\n".format(YM_in_MPa, PR)) + f.write(f"{YM_in_MPa:.13G},{PR:.13G}\n") if is_density_needed() is True: f.write("*DENSITY\n") - f.write("{:.13G}\n".format(density_in_tonne_per_mm3)) + f.write(f"{density_in_tonne_per_mm3:.13G}\n") if ccxwriter.analysis_type == "thermomech": if mat_obj.Category == "Solid": f.write("*CONDUCTIVITY\n") - f.write("{:.13G}\n".format(TC_in_WmK)) + f.write(f"{TC_in_WmK:.13G}\n") f.write("*EXPANSION\n") - f.write("{:.13G}\n".format(TEC_in_mmK)) + f.write(f"{TEC_in_mmK:.13G}\n") f.write("*SPECIFIC HEAT\n") - f.write("{:.13G}\n".format(SH_in_JkgK)) + f.write(f"{SH_in_JkgK:.13G}\n") elif mat_obj.Category == "Fluid": f.write("*FLUID CONSTANTS\n") - f.write("{:.13G},{:.13G}\n".format(SH_in_JkgK, DV_in_tmms)) + f.write(f"{SH_in_JkgK:.13G},{DV_in_tmms:.13G}\n") # nonlinear material properties if ccxwriter.solver_obj.MaterialNonlinearity == "nonlinear": @@ -119,5 +119,5 @@ def write_femelement_material(f, ccxwriter): else: f.write("*PLASTIC, HARDENING=KINEMATIC\n") for yield_point in nl_mat_obj.YieldPoints: - f.write("{}\n".format(yield_point)) + f.write(f"{yield_point}\n") f.write("\n") diff --git a/src/Mod/Fem/femsolver/calculix/write_footer.py b/src/Mod/Fem/femsolver/calculix/write_footer.py index 89c8da52f5..1923399d5e 100644 --- a/src/Mod/Fem/femsolver/calculix/write_footer.py +++ b/src/Mod/Fem/femsolver/calculix/write_footer.py @@ -34,20 +34,14 @@ def write_footer(f, ccxwriter): f.write("\n{}\n".format(59 * "*")) f.write("** CalculiX Input file\n") - f.write("** written by --> FreeCAD {}.{}.{}\n".format( - ccxwriter.fc_ver[0], - ccxwriter.fc_ver[1], - ccxwriter.fc_ver[2] - )) - f.write("** written on --> {}\n".format( - time.ctime() - )) - f.write("** file name --> {}\n".format( - os.path.basename(ccxwriter.document.FileName) - )) - f.write("** analysis name --> {}\n".format( - ccxwriter.analysis.Name - )) + f.write( + "** written by --> FreeCAD {}.{}.{}\n".format( + ccxwriter.fc_ver[0], ccxwriter.fc_ver[1], ccxwriter.fc_ver[2] + ) + ) + f.write(f"** written on --> {time.ctime()}\n") + f.write(f"** file name --> {os.path.basename(ccxwriter.document.FileName)}\n") + f.write(f"** analysis name --> {ccxwriter.analysis.Name}\n") f.write("**\n") f.write("**\n") f.write(ccxwriter.units_information) diff --git a/src/Mod/Fem/femsolver/calculix/write_mesh.py b/src/Mod/Fem/femsolver/calculix/write_mesh.py index 4a4b632974..e67bf5e707 100644 --- a/src/Mod/Fem/femsolver/calculix/write_mesh.py +++ b/src/Mod/Fem/femsolver/calculix/write_mesh.py @@ -67,13 +67,13 @@ def write_mesh(ccxwriter): group_param, volVariant=vol_variant, faceVariant=face_variant, - edgeVariant=edge_variant + edgeVariant=edge_variant, ) inpfile = codecs.open(ccxwriter.file_name, "w", encoding="utf-8") inpfile.write("{}\n".format(59 * "*")) - inpfile.write("** {}\n".format(write_name)) - inpfile.write("*INCLUDE,INPUT={}\n".format(file_name_split)) + inpfile.write(f"** {write_name}\n") + inpfile.write(f"*INCLUDE,INPUT={file_name_split}\n") else: ccxwriter.femmesh_file = ccxwriter.file_name @@ -83,7 +83,7 @@ def write_mesh(ccxwriter): group_param, volVariant=vol_variant, faceVariant=face_variant, - edgeVariant=edge_variant + edgeVariant=edge_variant, ) # reopen file with "append" to add all the rest diff --git a/src/Mod/Fem/femsolver/calculix/write_step_equation.py b/src/Mod/Fem/femsolver/calculix/write_step_equation.py index 1620911605..00b6dbfdcc 100644 --- a/src/Mod/Fem/femsolver/calculix/write_step_equation.py +++ b/src/Mod/Fem/femsolver/calculix/write_step_equation.py @@ -47,11 +47,8 @@ def write_step_equation(f, ccxwriter): ) if ccxwriter.solver_obj.IterationsMaximum: if ccxwriter.analysis_type == "thermomech" or ccxwriter.analysis_type == "static": - step += ", INC={}".format(ccxwriter.solver_obj.IterationsMaximum) - elif ( - ccxwriter.analysis_type == "frequency" - or ccxwriter.analysis_type == "buckling" - ): + step += f", INC={ccxwriter.solver_obj.IterationsMaximum}" + elif ccxwriter.analysis_type == "frequency" or ccxwriter.analysis_type == "buckling": # parameter is for thermomechanical analysis only, see ccx manual *STEP pass # write STEP line @@ -126,23 +123,27 @@ def write_step_equation(f, ccxwriter): # ANALYSIS parameter line analysis_parameter = "" if ccxwriter.analysis_type == "static" or ccxwriter.analysis_type == "check": - if ccxwriter.solver_obj.IterationsUserDefinedIncrementations is True \ - or ccxwriter.solver_obj.IterationsUserDefinedTimeStepLength is True: + if ( + ccxwriter.solver_obj.IterationsUserDefinedIncrementations is True + or ccxwriter.solver_obj.IterationsUserDefinedTimeStepLength is True + ): analysis_parameter = "{},{},{},{}".format( ccxwriter.solver_obj.TimeInitialStep, ccxwriter.solver_obj.TimeEnd, ccxwriter.solver_obj.TimeMinimumStep, - ccxwriter.solver_obj.TimeMaximumStep + ccxwriter.solver_obj.TimeMaximumStep, ) elif ccxwriter.analysis_type == "frequency": - if ccxwriter.solver_obj.EigenmodeLowLimit == 0.0 \ - and ccxwriter.solver_obj.EigenmodeHighLimit == 0.0: - analysis_parameter = "{}\n".format(ccxwriter.solver_obj.EigenmodesCount) + if ( + ccxwriter.solver_obj.EigenmodeLowLimit == 0.0 + and ccxwriter.solver_obj.EigenmodeHighLimit == 0.0 + ): + analysis_parameter = f"{ccxwriter.solver_obj.EigenmodesCount}\n" else: analysis_parameter = "{},{},{}\n".format( ccxwriter.solver_obj.EigenmodesCount, ccxwriter.solver_obj.EigenmodeLowLimit, - ccxwriter.solver_obj.EigenmodeHighLimit + ccxwriter.solver_obj.EigenmodeHighLimit, ) elif ccxwriter.analysis_type == "thermomech": # OvG: 1.0 increment, total time 1 for steady state will cut back automatically @@ -150,10 +151,10 @@ def write_step_equation(f, ccxwriter): ccxwriter.solver_obj.TimeInitialStep, ccxwriter.solver_obj.TimeEnd, ccxwriter.solver_obj.TimeMinimumStep, - ccxwriter.solver_obj.TimeMaximumStep + ccxwriter.solver_obj.TimeMaximumStep, ) elif ccxwriter.analysis_type == "buckling": - analysis_parameter = "{}\n".format(ccxwriter.solver_obj.BucklingFactors) + analysis_parameter = f"{ccxwriter.solver_obj.BucklingFactors}\n" # write analysis type line, analysis parameter line f.write(analysis_type + "\n") diff --git a/src/Mod/Fem/femsolver/calculix/write_step_output.py b/src/Mod/Fem/femsolver/calculix/write_step_output.py index 21819d7864..84c5113cf0 100644 --- a/src/Mod/Fem/femsolver/calculix/write_step_output.py +++ b/src/Mod/Fem/femsolver/calculix/write_step_output.py @@ -94,18 +94,22 @@ def write_step_output(f, ccxwriter): or femobj["Object"].TranslationalModeY != "Free" or femobj["Object"].TranslationalModeZ != "Free" ): - f.write("*NODE PRINT, NSET={}_RefNode, TOTALS=ONLY\n".format(femobj["Object"].Name)) + f.write( + "*NODE PRINT, NSET={}_RefNode, TOTALS=ONLY\n".format(femobj["Object"].Name) + ) f.write("RF\n") if ( femobj["Object"].RotationalModeX != "Free" or femobj["Object"].RotationalModeY != "Free" or femobj["Object"].RotationalModeZ != "Free" ): - f.write("*NODE PRINT, NSET={}_RotNode, TOTALS=ONLY\n".format(femobj["Object"].Name)) + f.write( + "*NODE PRINT, NSET={}_RotNode, TOTALS=ONLY\n".format(femobj["Object"].Name) + ) f.write("RF\n") if ccxwriter.member.cons_fixed or ccxwriter.member.cons_displacement: f.write("\n") - f.write("*OUTPUT, FREQUENCY={}".format(ccxwriter.solver_obj.OutputFrequency)) + f.write(f"*OUTPUT, FREQUENCY={ccxwriter.solver_obj.OutputFrequency}") # there is no need to write all integration point results # as long as there is no reader for them diff --git a/src/Mod/Fem/femsolver/calculix/writer.py b/src/Mod/Fem/femsolver/calculix/writer.py index 306d2b95fd..db2a38c9ce 100644 --- a/src/Mod/Fem/femsolver/calculix/writer.py +++ b/src/Mod/Fem/femsolver/calculix/writer.py @@ -108,22 +108,10 @@ units_information = """********************************************************* class FemInputWriterCcx(writerbase.FemInputWriter): def __init__( - self, - analysis_obj, - solver_obj, - mesh_obj, - member, - dir_name=None, - mat_geo_sets=None + self, analysis_obj, solver_obj, mesh_obj, member, dir_name=None, mat_geo_sets=None ): writerbase.FemInputWriter.__init__( - self, - analysis_obj, - solver_obj, - mesh_obj, - member, - dir_name, - mat_geo_sets + self, analysis_obj, solver_obj, mesh_obj, member, dir_name, mat_geo_sets ) self.mesh_name = self.mesh_object.Name self.file_name = join(self.dir_name, self.mesh_name + ".inp") @@ -138,10 +126,7 @@ class FemInputWriterCcx(writerbase.FemInputWriter): time_start = time.process_time() FreeCAD.Console.PrintMessage("\n") # because of time print in separate line FreeCAD.Console.PrintMessage("CalculiX solver input writing...\n") - FreeCAD.Console.PrintMessage( - "Input file:{}\n" - .format(self.file_name) - ) + FreeCAD.Console.PrintMessage(f"Input file:{self.file_name}\n") if self.solver_obj.SplitInputWriter is True: FreeCAD.Console.PrintMessage("Split input file.\n") @@ -161,7 +146,9 @@ class FemInputWriterCcx(writerbase.FemInputWriter): # element sets constraints self.write_constraints_meshsets(inpfile, self.member.cons_centrif, con_centrif) - self.write_constraints_meshsets(inpfile, self.member.cons_bodyheatsource, con_bodyheatsource) + self.write_constraints_meshsets( + inpfile, self.member.cons_bodyheatsource, con_bodyheatsource + ) # node sets self.write_constraints_meshsets(inpfile, self.member.cons_fixed, con_fixed) @@ -193,12 +180,16 @@ class FemInputWriterCcx(writerbase.FemInputWriter): # constraints dependent from steps self.write_constraints_propdata(inpfile, self.member.cons_fixed, con_fixed) - self.write_constraints_propdata(inpfile, self.member.cons_rigidbody_step, con_rigidbody_step) + self.write_constraints_propdata( + inpfile, self.member.cons_rigidbody_step, con_rigidbody_step + ) self.write_constraints_propdata(inpfile, self.member.cons_displacement, con_displacement) self.write_constraints_propdata(inpfile, self.member.cons_sectionprint, con_sectionprint) self.write_constraints_propdata(inpfile, self.member.cons_selfweight, con_selfweight) self.write_constraints_propdata(inpfile, self.member.cons_centrif, con_centrif) - self.write_constraints_propdata(inpfile, self.member.cons_bodyheatsource, con_bodyheatsource) + self.write_constraints_propdata( + inpfile, self.member.cons_bodyheatsource, con_bodyheatsource + ) self.write_constraints_meshsets(inpfile, self.member.cons_force, con_force) self.write_constraints_meshsets(inpfile, self.member.cons_pressure, con_pressure) self.write_constraints_propdata(inpfile, self.member.cons_temperature, con_temperature) @@ -216,17 +207,14 @@ class FemInputWriterCcx(writerbase.FemInputWriter): inpfile.close() writetime = round((time.process_time() - time_start), 3) - FreeCAD.Console.PrintMessage( - "Writing time CalculiX input file: {} seconds.\n".format(writetime) - ) + FreeCAD.Console.PrintMessage(f"Writing time CalculiX input file: {writetime} seconds.\n") # return if self.femelement_count_test is True: return self.file_name else: - FreeCAD.Console.PrintError( - "Problems on writing input file, check report prints.\n\n" - ) + FreeCAD.Console.PrintError("Problems on writing input file, check report prints.\n\n") return "" + ## @} diff --git a/src/Mod/Fem/femsolver/elmer/equations/deformation.py b/src/Mod/Fem/femsolver/elmer/equations/deformation.py index d38afddd51..6b4da216cb 100644 --- a/src/Mod/Fem/femsolver/elmer/equations/deformation.py +++ b/src/Mod/Fem/femsolver/elmer/equations/deformation.py @@ -34,8 +34,7 @@ from ... import equationbase def create(doc, name="Deformation"): - return femutils.createObject( - doc, name, Proxy, ViewProxy) + return femutils.createObject(doc, name, Proxy, ViewProxy) class Proxy(nonlinear.Proxy, equationbase.DeformationProxy): @@ -43,51 +42,40 @@ class Proxy(nonlinear.Proxy, equationbase.DeformationProxy): Type = "Fem::EquationElmerDeformation" def __init__(self, obj): - super(Proxy, self).__init__(obj) + super().__init__(obj) obj.addProperty( - "App::PropertyBool", - "CalculatePangle", - "Deformation", - "Compute principal stress angles" + "App::PropertyBool", "CalculatePangle", "Deformation", "Compute principal stress angles" ) obj.addProperty( "App::PropertyBool", "CalculatePrincipal", "Deformation", - "Compute principal stress components" + "Compute principal stress components", ) obj.addProperty( - "App::PropertyBool", - "CalculateStrains", - "Deformation", - "Compute the strain tensor" + "App::PropertyBool", "CalculateStrains", "Deformation", "Compute the strain tensor" ) obj.addProperty( "App::PropertyBool", "CalculateStresses", "Deformation", - "Compute stress tensor and vanMises" + "Compute stress tensor and vanMises", ) obj.addProperty( "App::PropertyBool", "InitializeStateVariables", "Deformation", - "See Elmer manual for info" + "See Elmer manual for info", ) obj.addProperty( - "App::PropertyBool", - "MixedFormulation", - "Deformation", - "See Elmer manual for info" + "App::PropertyBool", "MixedFormulation", "Deformation", "See Elmer manual for info" ) obj.addProperty( "App::PropertyBool", "NeoHookeanMaterial", "Deformation", - ( - "Uses the neo-Hookean material model" - ) + ("Uses the neo-Hookean material model"), ) obj.addProperty( "App::PropertyBool", @@ -96,13 +84,13 @@ class Proxy(nonlinear.Proxy, equationbase.DeformationProxy): ( "Computes solution according to plane\nstress situation.\n" "Applies only for 2D geometry." - ) + ), ) obj.addProperty( "App::PropertyString", "Variable", "Deformation", - "Only for a 2D model change the '3' to '2'" + "Only for a 2D model change the '3' to '2'", ) obj.Priority = 10 @@ -114,4 +102,5 @@ class Proxy(nonlinear.Proxy, equationbase.DeformationProxy): class ViewProxy(nonlinear.ViewProxy, equationbase.DeformationViewProxy): pass + ## @} diff --git a/src/Mod/Fem/femsolver/elmer/equations/deformation_writer.py b/src/Mod/Fem/femsolver/elmer/equations/deformation_writer.py index f76dd39fe0..6d2894099d 100644 --- a/src/Mod/Fem/femsolver/elmer/equations/deformation_writer.py +++ b/src/Mod/Fem/femsolver/elmer/equations/deformation_writer.py @@ -151,7 +151,7 @@ class DeformationWriter: gravity = self.write.convert(obj.GravityAcceleration.toStr(), "L/T^2") if self.write.getBodyMaterial(name) is None: raise general_writer.WriteError( - "The body {} is not referenced in any material.\n\n".format(name) + f"The body {name} is not referenced in any material.\n\n" ) m = self.write.getBodyMaterial(name).Material @@ -193,17 +193,13 @@ class DeformationWriter: # get the material data for all bodies for obj in self.write.getMember("App::MaterialObject"): m = obj.Material - refs = ( - obj.References[0][1] - if obj.References - else self.write.getAllBodies() - ) + refs = obj.References[0][1] if obj.References else self.write.getAllBodies() for name in (n for n in refs if n in bodies): # don't evaluate fluid material if self.write.isBodyMaterialFluid(name): break if "YoungsModulus" not in m: - Console.PrintMessage("m: {}\n".format(m)) + Console.PrintMessage(f"m: {m}\n") # it is no fluid but also no solid # -> user set no material reference at all # that now material is known @@ -213,22 +209,14 @@ class DeformationWriter: ) self.write.material(name, "Name", m["Name"]) if density_needed is True: - self.write.material( - name, "Density", - self.write.getDensity(m) - ) - self.write.material( - name, "Youngs Modulus", - self._getYoungsModulus(m) - ) - self.write.material( - name, "Poisson ratio", - float(m["PoissonRatio"]) - ) + self.write.material(name, "Density", self.write.getDensity(m)) + self.write.material(name, "Youngs Modulus", self._getYoungsModulus(m)) + self.write.material(name, "Poisson ratio", float(m["PoissonRatio"])) if tempObj: self.write.material( - name, "Heat expansion Coefficient", - self.write.convert(m["ThermalExpansionCoefficient"], "O^-1") + name, + "Heat expansion Coefficient", + self.write.convert(m["ThermalExpansionCoefficient"], "O^-1"), ) def _getYoungsModulus(self, m): @@ -237,4 +225,5 @@ class DeformationWriter: youngsModulus *= 1e3 return youngsModulus + ## @} diff --git a/src/Mod/Fem/femsolver/elmer/equations/elasticity.py b/src/Mod/Fem/femsolver/elmer/equations/elasticity.py index 6dcedb0a17..f77eccdb6e 100644 --- a/src/Mod/Fem/femsolver/elmer/equations/elasticity.py +++ b/src/Mod/Fem/femsolver/elmer/equations/elasticity.py @@ -39,13 +39,12 @@ EIGEN_SYSTEM_SELECT = [ "Smallest Real Part", "Largest Real Part", "Smallest Imag Part", - "Largest Imag Part" + "Largest Imag Part", ] def create(doc, name="Elasticity"): - return femutils.createObject( - doc, name, Proxy, ViewProxy) + return femutils.createObject(doc, name, Proxy, ViewProxy) class Proxy(linear.Proxy, equationbase.ElasticityProxy): @@ -53,52 +52,37 @@ class Proxy(linear.Proxy, equationbase.ElasticityProxy): Type = "Fem::EquationElmerElasticity" def __init__(self, obj): - super(Proxy, self).__init__(obj) + super().__init__(obj) obj.addProperty( - "App::PropertyBool", - "CalculatePangle", - "Elasticity", - "Compute principal stress angles" + "App::PropertyBool", "CalculatePangle", "Elasticity", "Compute principal stress angles" ) obj.addProperty( "App::PropertyBool", "CalculatePrincipal", "Elasticity", - "Compute principal stress components" + "Compute principal stress components", ) obj.addProperty( - "App::PropertyBool", - "CalculateStrains", - "Elasticity", - "Compute the strain tensor" + "App::PropertyBool", "CalculateStrains", "Elasticity", "Compute the strain tensor" ) obj.addProperty( "App::PropertyBool", "CalculateStresses", "Elasticity", - "Compute stress tensor and vanMises" + "Compute stress tensor and vanMises", ) obj.addProperty( - "App::PropertyBool", - "ConstantBulkSystem", - "Elasticity", - "See Elmer manual for info" + "App::PropertyBool", "ConstantBulkSystem", "Elasticity", "See Elmer manual for info" ) obj.addProperty( "App::PropertyBool", "DisplaceMesh", "Elasticity", - ( - "If mesh is deformed by displacement field.\n" - "Set to False for 'Eigen Analysis'." - ) + ("If mesh is deformed by displacement field.\nSet to False for 'Eigen Analysis'."), ) obj.addProperty( - "App::PropertyBool", - "EigenAnalysis", - "Eigen Values", - "If true, modal analysis" + "App::PropertyBool", "EigenAnalysis", "Eigen Values", "If true, modal analysis" ) obj.addProperty( "App::PropertyBool", @@ -107,13 +91,13 @@ class Proxy(linear.Proxy, equationbase.ElasticityProxy): ( "Should be true if eigen system is complex\n" "Must be false for a damped eigen value analysis." - ) + ), ) obj.addProperty( "App::PropertyBool", "EigenSystemComputeResiduals", "Eigen Values", - "Computes residuals of eigen value system" + "Computes residuals of eigen value system", ) obj.addProperty( "App::PropertyBool", @@ -122,19 +106,19 @@ class Proxy(linear.Proxy, equationbase.ElasticityProxy): ( "Set a damped eigen analysis. Can only be\n" "used if 'Linear Solver Type' is 'Iterative'." - ) + ), ) obj.addProperty( "App::PropertyIntegerConstraint", "EigenSystemMaxIterations", "Eigen Values", - "Max iterations for iterative eigensystem solver" + "Max iterations for iterative eigensystem solver", ) obj.addProperty( "App::PropertyEnumeration", "EigenSystemSelect", "Eigen Values", - "Which eigenvalues are computed" + "Which eigenvalues are computed", ) obj.addProperty( "App::PropertyFloat", @@ -143,25 +127,22 @@ class Proxy(linear.Proxy, equationbase.ElasticityProxy): ( "Convergence tolerance for iterative eigensystem solve\n" "Default is 100 times the 'Linear Tolerance'" - ) + ), ) obj.addProperty( "App::PropertyInteger", "EigenSystemValues", "Eigen Values", - "Number of lowest eigen modes" + "Number of lowest eigen modes", ) obj.addProperty( "App::PropertyBool", "FixDisplacement", "Elasticity", - "If displacements or forces are set,\nthereby model lumping is used" + "If displacements or forces are set,\nthereby model lumping is used", ) obj.addProperty( - "App::PropertyBool", - "GeometricStiffness", - "Elasticity", - "Consider geometric stiffness" + "App::PropertyBool", "GeometricStiffness", "Elasticity", "Consider geometric stiffness" ) obj.addProperty( "App::PropertyBool", @@ -170,25 +151,20 @@ class Proxy(linear.Proxy, equationbase.ElasticityProxy): ( "Computation of incompressible material in connection\n" "with viscoelastic Maxwell material and a custom 'Variable'" - ) + ), ) obj.addProperty( "App::PropertyBool", "MaxwellMaterial", "Elasticity", - "Compute viscoelastic material model" - ) - obj.addProperty( - "App::PropertyBool", - "ModelLumping", - "Elasticity", - "Use model lumping" + "Compute viscoelastic material model", ) + obj.addProperty("App::PropertyBool", "ModelLumping", "Elasticity", "Use model lumping") obj.addProperty( "App::PropertyFile", "ModelLumpingFilename", "Elasticity", - "File to save results from model lumping to" + "File to save results from model lumping to", ) obj.addProperty( "App::PropertyBool", @@ -197,13 +173,10 @@ class Proxy(linear.Proxy, equationbase.ElasticityProxy): ( "If true, 'Eigen Analysis' is stability analysis.\n" "Otherwise modal analysis is performed." - ) + ), ) obj.addProperty( - "App::PropertyBool", - "UpdateTransientSystem", - "Elasticity", - "See Elmer manual for info" + "App::PropertyBool", "UpdateTransientSystem", "Elasticity", "See Elmer manual for info" ) obj.addProperty( "App::PropertyString", @@ -212,7 +185,7 @@ class Proxy(linear.Proxy, equationbase.ElasticityProxy): ( "Only change this if 'Incompressible' is set to true\n" "according to the Elmer manual." - ) + ), ) obj.addProperty( @@ -222,7 +195,7 @@ class Proxy(linear.Proxy, equationbase.ElasticityProxy): ( "Computes solution according to plane\nstress situation.\n" "Applies only for 2D geometry." - ) + ), ) obj.EigenSystemValues = 5 @@ -243,8 +216,8 @@ class Proxy(linear.Proxy, equationbase.ElasticityProxy): obj.EigenSystemSelect = "Smallest Magnitude" # according to Elmer manual default is 100 times the Linear Tolerance # since this is a small value we must set an expression, see linear.py for background - for (prop, expr) in obj.ExpressionEngine: - if (prop == "LinearTolerance"): + for prop, expr in obj.ExpressionEngine: + if prop == "LinearTolerance": obj.setExpression("EigenSystemTolerance", str(100 * obj.evalExpression(expr))) obj.Variable = "Displacement" @@ -252,4 +225,5 @@ class Proxy(linear.Proxy, equationbase.ElasticityProxy): class ViewProxy(linear.ViewProxy, equationbase.ElasticityViewProxy): pass + ## @} diff --git a/src/Mod/Fem/femsolver/elmer/equations/elasticity_writer.py b/src/Mod/Fem/femsolver/elmer/equations/elasticity_writer.py index 4424e903e7..7dff410e77 100644 --- a/src/Mod/Fem/femsolver/elmer/equations/elasticity_writer.py +++ b/src/Mod/Fem/femsolver/elmer/equations/elasticity_writer.py @@ -63,8 +63,7 @@ class ElasticityWriter: s["Displace mesh"] = equation.DisplaceMesh s["Eigen Analysis"] = equation.EigenAnalysis if equation.EigenAnalysis is True: - s["Eigen System Convergence Tolerance"] = \ - equation.EigenSystemTolerance + s["Eigen System Convergence Tolerance"] = equation.EigenSystemTolerance s["Eigen System Complex"] = equation.EigenSystemComplex if equation.EigenSystemComputeResiduals is True: s["Eigen System Compute Residuals"] = equation.EigenSystemComputeResiduals @@ -110,7 +109,7 @@ class ElasticityWriter: ( "Only change this if 'Incompressible' is set to true\n" "according to the Elmer manual." - ) + ), ) equation.Variable = "Displacement" if hasattr(equation, "Bubbles"): @@ -118,10 +117,7 @@ class ElasticityWriter: equation.removeProperty("Bubbles") if not hasattr(equation, "ConstantBulkSystem"): equation.addProperty( - "App::PropertyBool", - "ConstantBulkSystem", - "Elasticity", - "See Elmer manual for info" + "App::PropertyBool", "ConstantBulkSystem", "Elasticity", "See Elmer manual for info" ) if not hasattr(equation, "DisplaceMesh"): equation.addProperty( @@ -131,7 +127,7 @@ class ElasticityWriter: ( "If mesh is deformed by displacement field.\n" "Set to False for 'Eigen Analysis'." - ) + ), ) # DisplaceMesh is true except if DoFrequencyAnalysis is true equation.DisplaceMesh = True @@ -142,10 +138,7 @@ class ElasticityWriter: # DoFrequencyAnalysis was renamed to EigenAnalysis # to follow the Elmer manual equation.addProperty( - "App::PropertyBool", - "EigenAnalysis", - "Eigen Values", - "If true, modal analysis" + "App::PropertyBool", "EigenAnalysis", "Eigen Values", "If true, modal analysis" ) if hasattr(equation, "DoFrequencyAnalysis"): equation.EigenAnalysis = equation.DoFrequencyAnalysis @@ -158,7 +151,7 @@ class ElasticityWriter: ( "Should be true if eigen system is complex\n" "Must be false for a damped eigen value analysis." - ) + ), ) equation.EigenSystemComplex = True if not hasattr(equation, "EigenSystemComputeResiduals"): @@ -166,7 +159,7 @@ class ElasticityWriter: "App::PropertyBool", "EigenSystemComputeResiduals", "Eigen Values", - "Computes residuals of eigen value system" + "Computes residuals of eigen value system", ) if not hasattr(equation, "EigenSystemDamped"): equation.addProperty( @@ -176,14 +169,14 @@ class ElasticityWriter: ( "Set a damped eigen analysis. Can only be\n" "used if 'Linear Solver Type' is 'Iterative'." - ) + ), ) if not hasattr(equation, "EigenSystemMaxIterations"): equation.addProperty( "App::PropertyIntegerConstraint", "EigenSystemMaxIterations", "Eigen Values", - "Max iterations for iterative eigensystem solver" + "Max iterations for iterative eigensystem solver", ) equation.EigenSystemMaxIterations = (300, 1, int(1e8), 1) if not hasattr(equation, "EigenSystemSelect"): @@ -191,7 +184,7 @@ class ElasticityWriter: "App::PropertyEnumeration", "EigenSystemSelect", "Eigen Values", - "Which eigenvalues are computed" + "Which eigenvalues are computed", ) equation.EigenSystemSelect = elasticity.EIGEN_SYSTEM_SELECT equation.EigenSystemSelect = "Smallest Magnitude" @@ -203,7 +196,7 @@ class ElasticityWriter: ( "Convergence tolerance for iterative eigensystem solve\n" "Default is 100 times the 'Linear Tolerance'" - ) + ), ) equation.setExpression("EigenSystemTolerance", str(100 * equation.LinearTolerance)) if not hasattr(equation, "EigenSystemValues"): @@ -213,7 +206,7 @@ class ElasticityWriter: "App::PropertyInteger", "EigenSystemValues", "Eigen Values", - "Number of lowest eigen modes" + "Number of lowest eigen modes", ) if hasattr(equation, "EigenmodesCount"): equation.EigenSystemValues = equation.EigenmodesCount @@ -223,14 +216,14 @@ class ElasticityWriter: "App::PropertyBool", "FixDisplacement", "Elasticity", - "If displacements or forces are set,\nthereby model lumping is used" + "If displacements or forces are set,\nthereby model lumping is used", ) if not hasattr(equation, "GeometricStiffness"): equation.addProperty( "App::PropertyBool", "GeometricStiffness", "Elasticity", - "Consider geometric stiffness" + "Consider geometric stiffness", ) if not hasattr(equation, "Incompressible"): equation.addProperty( @@ -240,28 +233,25 @@ class ElasticityWriter: ( "Computation of incompressible material in connection\n" "with viscoelastic Maxwell material and a custom 'Variable'" - ) + ), ) if not hasattr(equation, "MaxwellMaterial"): equation.addProperty( "App::PropertyBool", "MaxwellMaterial", "Elasticity", - "Compute viscoelastic material model" + "Compute viscoelastic material model", ) if not hasattr(equation, "ModelLumping"): equation.addProperty( - "App::PropertyBool", - "ModelLumping", - "Elasticity", - "Use model lumping" + "App::PropertyBool", "ModelLumping", "Elasticity", "Use model lumping" ) if not hasattr(equation, "ModelLumpingFilename"): equation.addProperty( "App::PropertyFile", "ModelLumpingFilename", "Elasticity", - "File to save results from model lumping to" + "File to save results from model lumping to", ) if not hasattr(equation, "PlaneStress"): equation.addProperty( @@ -271,7 +261,7 @@ class ElasticityWriter: ( "Computes solution according to plane\nstress situation.\n" "Applies only for 2D geometry." - ) + ), ) if not hasattr(equation, "StabilityAnalysis"): equation.addProperty( @@ -281,14 +271,14 @@ class ElasticityWriter: ( "If true, 'Eigen Analysis' is stability analysis.\n" "Otherwise modal analysis is performed." - ) + ), ) if not hasattr(equation, "UpdateTransientSystem"): equation.addProperty( "App::PropertyBool", "UpdateTransientSystem", "Elasticity", - "See Elmer manual for info" + "See Elmer manual for info", ) def handleElasticityConstants(self): @@ -367,7 +357,7 @@ class ElasticityWriter: gravity = self.write.convert(obj.GravityAcceleration.toStr(), "L/T^2") if self.write.getBodyMaterial(name) is None: raise general_writer.WriteError( - "The body {} is not referenced in any material.\n\n".format(name) + f"The body {name} is not referenced in any material.\n\n" ) m = self.write.getBodyMaterial(name).Material @@ -409,17 +399,13 @@ class ElasticityWriter: # get the material data for all bodies for obj in self.write.getMember("App::MaterialObject"): m = obj.Material - refs = ( - obj.References[0][1] - if obj.References - else self.write.getAllBodies() - ) + refs = obj.References[0][1] if obj.References else self.write.getAllBodies() for name in (n for n in refs if n in bodies): # don't evaluate fluid material if self.write.isBodyMaterialFluid(name): break if "YoungsModulus" not in m: - Console.PrintMessage("m: {}\n".format(m)) + Console.PrintMessage(f"m: {m}\n") # it is no fluid but also no solid # -> user set no material reference at all # that now material is known @@ -429,22 +415,14 @@ class ElasticityWriter: ) self.write.material(name, "Name", m["Name"]) if density_needed is True: - self.write.material( - name, "Density", - self.write.getDensity(m) - ) - self.write.material( - name, "Youngs Modulus", - self._getYoungsModulus(m) - ) - self.write.material( - name, "Poisson ratio", - float(m["PoissonRatio"]) - ) + self.write.material(name, "Density", self.write.getDensity(m)) + self.write.material(name, "Youngs Modulus", self._getYoungsModulus(m)) + self.write.material(name, "Poisson ratio", float(m["PoissonRatio"])) if tempObj: self.write.material( - name, "Heat expansion Coefficient", - self.write.convert(m["ThermalExpansionCoefficient"], "O^-1") + name, + "Heat expansion Coefficient", + self.write.convert(m["ThermalExpansionCoefficient"], "O^-1"), ) def _getYoungsModulus(self, m): @@ -453,4 +431,5 @@ class ElasticityWriter: youngsModulus *= 1e3 return youngsModulus + ## @} diff --git a/src/Mod/Fem/femsolver/elmer/equations/electricforce.py b/src/Mod/Fem/femsolver/elmer/equations/electricforce.py index f663b367b7..da2cd30b77 100644 --- a/src/Mod/Fem/femsolver/elmer/equations/electricforce.py +++ b/src/Mod/Fem/femsolver/elmer/equations/electricforce.py @@ -36,8 +36,7 @@ SOLVER_EXEC_METHODS = ["After Timestep", "Always"] def create(doc, name="Electricforce"): - return femutils.createObject( - doc, name, Proxy, ViewProxy) + return femutils.createObject(doc, name, Proxy, ViewProxy) class Proxy(linear.Proxy, equationbase.ElectricforceProxy): @@ -45,7 +44,7 @@ class Proxy(linear.Proxy, equationbase.ElectricforceProxy): Type = "Fem::EquationElmerElectricforce" def __init__(self, obj): - super(Proxy, self).__init__(obj) + super().__init__(obj) obj.addProperty( "App::PropertyEnumeration", @@ -54,7 +53,7 @@ class Proxy(linear.Proxy, equationbase.ElectricforceProxy): ( "That solver is only executed after solution converged\n" "To execute always, change to 'Always'" - ) + ), ) obj.ExecSolver = SOLVER_EXEC_METHODS @@ -68,4 +67,5 @@ class Proxy(linear.Proxy, equationbase.ElectricforceProxy): class ViewProxy(linear.ViewProxy, equationbase.ElectricforceViewProxy): pass + ## @} diff --git a/src/Mod/Fem/femsolver/elmer/equations/electricforce_writer.py b/src/Mod/Fem/femsolver/elmer/equations/electricforce_writer.py index b82cdffa70..a3d6fe666d 100644 --- a/src/Mod/Fem/femsolver/elmer/equations/electricforce_writer.py +++ b/src/Mod/Fem/femsolver/elmer/equations/electricforce_writer.py @@ -60,9 +60,10 @@ class EFwriter: ( "That solver is only executed after solution converged\n" "To execute always, change to 'Always'" - ) + ), ) equation.ExecSolver = electricforce.SOLVER_EXEC_METHODS equation.ExecSolver = "After Timestep" + ## @} diff --git a/src/Mod/Fem/femsolver/elmer/equations/electrostatic.py b/src/Mod/Fem/femsolver/elmer/equations/electrostatic.py index fcf581b5b5..053d217820 100644 --- a/src/Mod/Fem/femsolver/elmer/equations/electrostatic.py +++ b/src/Mod/Fem/femsolver/elmer/equations/electrostatic.py @@ -35,8 +35,7 @@ from . import linear def create(doc, name="Electrostatic"): - return femutils.createObject( - doc, name, Proxy, ViewProxy) + return femutils.createObject(doc, name, Proxy, ViewProxy) class Proxy(linear.Proxy, equationbase.ElectrostaticProxy): @@ -44,38 +43,13 @@ class Proxy(linear.Proxy, equationbase.ElectrostaticProxy): Type = "Fem::EquationElmerElectrostatic" def __init__(self, obj): - super(Proxy, self).__init__(obj) + super().__init__(obj) - obj.addProperty( - "App::PropertyBool", - "CalculateCapacitanceMatrix", - "Electrostatic", - "" - ) - obj.addProperty( - "App::PropertyBool", - "CalculateElectricEnergy", - "Electrostatic", - "" - ) - obj.addProperty( - "App::PropertyBool", - "CalculateElectricField", - "Electrostatic", - "" - ) - obj.addProperty( - "App::PropertyBool", - "CalculateElectricFlux", - "Electrostatic", - "" - ) - obj.addProperty( - "App::PropertyBool", - "CalculateSurfaceCharge", - "Electrostatic", - "" - ) + obj.addProperty("App::PropertyBool", "CalculateCapacitanceMatrix", "Electrostatic", "") + obj.addProperty("App::PropertyBool", "CalculateElectricEnergy", "Electrostatic", "") + obj.addProperty("App::PropertyBool", "CalculateElectricField", "Electrostatic", "") + obj.addProperty("App::PropertyBool", "CalculateElectricFlux", "Electrostatic", "") + obj.addProperty("App::PropertyBool", "CalculateSurfaceCharge", "Electrostatic", "") """ obj.addProperty( "App::PropertyInteger", @@ -91,13 +65,13 @@ class Proxy(linear.Proxy, equationbase.ElectrostaticProxy): ( "File where capacitance matrix is being saved\n" "Only used if 'CalculateCapacitanceMatrix' is true" - ) + ), ) obj.addProperty( "App::PropertyBool", "ConstantWeights", "Electrostatic", - "Use constant weighting for results" + "Use constant weighting for results", ) obj.addProperty( "App::PropertyFloat", @@ -106,7 +80,7 @@ class Proxy(linear.Proxy, equationbase.ElectrostaticProxy): ( "Potential difference in Volt for which capacitance is\n" "calculated if 'CalculateCapacitanceMatrix' is false" - ) + ), ) obj.CapacitanceMatrixFilename = "cmatrix.dat" @@ -117,4 +91,5 @@ class Proxy(linear.Proxy, equationbase.ElectrostaticProxy): class ViewProxy(linear.ViewProxy, equationbase.ElectrostaticViewProxy): pass + ## @} diff --git a/src/Mod/Fem/femsolver/elmer/equations/electrostatic_writer.py b/src/Mod/Fem/femsolver/elmer/equations/electrostatic_writer.py index c09732f390..5014df97ff 100644 --- a/src/Mod/Fem/femsolver/elmer/equations/electrostatic_writer.py +++ b/src/Mod/Fem/femsolver/elmer/equations/electrostatic_writer.py @@ -63,10 +63,7 @@ class ESwriter: s["Constant Weights"] = equation.ConstantWeights s["Exec Solver"] = "Always" s["Optimize Bandwidth"] = True - if ( - equation.CalculateCapacitanceMatrix is False - and (equation.PotentialDifference != 0.0) - ): + if equation.CalculateCapacitanceMatrix is False and (equation.PotentialDifference != 0.0): s["Potential Difference"] = equation.PotentialDifference s["Stabilize"] = equation.Stabilize return s @@ -81,7 +78,7 @@ class ESwriter: ( "File where capacitance matrix is being saved\n" "Only used if 'CalculateCapacitanceMatrix' is true" - ) + ), ) equation.CapacitanceMatrixFilename = "cmatrix.dat" if not hasattr(equation, "ConstantWeights"): @@ -89,7 +86,7 @@ class ESwriter: "App::PropertyBool", "ConstantWeights", "Electrostatic", - "Use constant weighting for results" + "Use constant weighting for results", ) if not hasattr(equation, "PotentialDifference"): equation.addProperty( @@ -99,14 +96,13 @@ class ESwriter: ( "Potential difference in Volt for which capacitance is\n" "calculated if 'CalculateCapacitanceMatrix' is false" - ) + ), ) equation.PotentialDifference = 0.0 def handleElectrostaticConstants(self): permittivity = self.write.convert( - self.write.constsdef["PermittivityOfVacuum"], - "T^4*I^2/(L^3*M)" + self.write.constsdef["PermittivityOfVacuum"], "T^4*I^2/(L^3*M)" ) permittivity = round(permittivity, 20) # to get rid of numerical artifacts self.write.constant("Permittivity Of Vacuum", permittivity) @@ -114,16 +110,12 @@ class ESwriter: def handleElectrostaticMaterial(self, bodies): for obj in self.write.getMember("App::MaterialObject"): m = obj.Material - refs = ( - obj.References[0][1] - if obj.References - else self.write.getAllBodies()) + refs = obj.References[0][1] if obj.References else self.write.getAllBodies() for name in (n for n in refs if n in bodies): self.write.material(name, "Name", m["Name"]) if "RelativePermittivity" in m: self.write.material( - name, "Relative Permittivity", - float(m["RelativePermittivity"]) + name, "Relative Permittivity", float(m["RelativePermittivity"]) ) def handleElectrostaticBndConditions(self): @@ -143,7 +135,7 @@ class ESwriter: "App::PropertyElectricPotential", "Potential", "Parameter", - "Electric Potential" + "Electric Potential", ) # scale to match SI units obj.Potential = savePotential * 1e6 @@ -160,4 +152,5 @@ class ESwriter: self.write.boundary(name, "Capacitance Body", obj.CapacitanceBody) self.write.handled(obj) + ## @} diff --git a/src/Mod/Fem/femsolver/elmer/equations/equation.py b/src/Mod/Fem/femsolver/elmer/equations/equation.py index 8f6042b2ab..97f8b544d3 100644 --- a/src/Mod/Fem/femsolver/elmer/equations/equation.py +++ b/src/Mod/Fem/femsolver/elmer/equations/equation.py @@ -40,7 +40,7 @@ if App.GuiUp: class Proxy(equationbase.BaseProxy): def __init__(self, obj): - super(Proxy, self).__init__(obj) + super().__init__(obj) obj.addProperty( "App::PropertyInteger", "Priority", @@ -49,7 +49,7 @@ class Proxy(equationbase.BaseProxy): "Number of your choice\n" "The equation with highest number\n" "will be solved first." - ) + ), ) @@ -72,14 +72,13 @@ class ViewProxy(equationbase.BaseViewProxy): return None -class _TaskPanel(object): +class _TaskPanel: def __init__(self, obj): self._obj = obj self._refWidget = selection_widgets.SolidSelector() self._refWidget.setReferences(obj.References) - propWidget = obj.ViewObject.Proxy.getTaskWidget( - obj.ViewObject) + propWidget = obj.ViewObject.Proxy.getTaskWidget(obj.ViewObject) if propWidget is None: self.form = self._refWidget else: diff --git a/src/Mod/Fem/femsolver/elmer/equations/flow.py b/src/Mod/Fem/femsolver/elmer/equations/flow.py index 88ad6a84e7..f401a3a83a 100644 --- a/src/Mod/Fem/femsolver/elmer/equations/flow.py +++ b/src/Mod/Fem/femsolver/elmer/equations/flow.py @@ -38,8 +38,7 @@ FLOW_MODEL = ["Full", "No convection", "Stokes"] def create(doc, name="Flow"): - return femutils.createObject( - doc, name, Proxy, ViewProxy) + return femutils.createObject(doc, name, Proxy, ViewProxy) class Proxy(nonlinear.Proxy, equationbase.FlowProxy): @@ -47,7 +46,7 @@ class Proxy(nonlinear.Proxy, equationbase.FlowProxy): Type = "Fem::EquationElmerFlow" def __init__(self, obj): - super(Proxy, self).__init__(obj) + super().__init__(obj) obj.addProperty( "App::PropertyBool", @@ -56,14 +55,9 @@ class Proxy(nonlinear.Proxy, equationbase.FlowProxy): ( "Set to true for incompressible flow for more stable\n" "discretization when Reynolds number increases" - ) - ) - obj.addProperty( - "App::PropertyEnumeration", - "FlowModel", - "Flow", - "Flow model to be used" + ), ) + obj.addProperty("App::PropertyEnumeration", "FlowModel", "Flow", "Flow model to be used") obj.addProperty( "App::PropertyBool", "GradpDiscretization", @@ -71,20 +65,14 @@ class Proxy(nonlinear.Proxy, equationbase.FlowProxy): ( "If true pressure Dirichlet boundary conditions can be used.\n" "Also mass flux is available as a natural boundary condition." - ) + ), ) obj.addProperty( - "App::PropertyString", - "Variable", - "Flow", - "Only for a 2D model change the '3' to '2'" + "App::PropertyString", "Variable", "Flow", "Only for a 2D model change the '3' to '2'" ) obj.addProperty( - "App::PropertyEnumeration", - "Convection", - "Equation", - "Type of convection to be used" + "App::PropertyEnumeration", "Convection", "Equation", "Type of convection to be used" ) obj.addProperty( "App::PropertyBool", @@ -93,7 +81,7 @@ class Proxy(nonlinear.Proxy, equationbase.FlowProxy): ( "Magnetic induction equation will be solved\n" "along with the Navier-Stokes equations" - ) + ), ) obj.FlowModel = FLOW_MODEL obj.FlowModel = "Full" @@ -106,4 +94,5 @@ class Proxy(nonlinear.Proxy, equationbase.FlowProxy): class ViewProxy(nonlinear.ViewProxy, equationbase.FlowViewProxy): pass + ## @} diff --git a/src/Mod/Fem/femsolver/elmer/equations/flow_writer.py b/src/Mod/Fem/femsolver/elmer/equations/flow_writer.py index c19451bb4b..05df2f44d4 100644 --- a/src/Mod/Fem/femsolver/elmer/equations/flow_writer.py +++ b/src/Mod/Fem/femsolver/elmer/equations/flow_writer.py @@ -72,7 +72,7 @@ class Flowwriter: "App::PropertyEnumeration", "Convection", "Equation", - "Type of convection to be used" + "Type of convection to be used", ) equation.Convection = flow.CONVECTION_TYPE equation.Convection = "Computed" @@ -84,14 +84,11 @@ class Flowwriter: ( "Set to true for incompressible flow for more stable\n" "discretization when Reynolds number increases" - ) + ), ) if not hasattr(equation, "FlowModel"): equation.addProperty( - "App::PropertyEnumeration", - "FlowModel", - "Flow", - "Flow model to be used" + "App::PropertyEnumeration", "FlowModel", "Flow", "Flow model to be used" ) equation.FlowModel = flow.FLOW_MODEL equation.FlowModel = "Full" @@ -103,7 +100,7 @@ class Flowwriter: ( "If true pressure Dirichlet boundary conditions can be used.\n" "Also mass flux is available as a natural boundary condition." - ) + ), ) if not hasattr(equation, "MagneticInduction"): equation.addProperty( @@ -113,14 +110,14 @@ class Flowwriter: ( "Magnetic induction equation will be solved\n" "along with the Navier-Stokes equations" - ) + ), ) if not hasattr(equation, "Variable"): equation.addProperty( "App::PropertyString", "Variable", "Flow", - "Only for a 2D model change the '3' to '2'" + "Only for a 2D model change the '3' to '2'", ) equation.Variable = "Flow Solution[Velocity:3 Pressure:1]" @@ -132,10 +129,7 @@ class Flowwriter: self.write.material(name, "Reference Temperature", refTemp) for obj in self.write.getMember("App::MaterialObject"): m = obj.Material - refs = ( - obj.References[0][1] - if obj.References - else self.write.getAllBodies()) + refs = obj.References[0][1] if obj.References else self.write.getAllBodies() for name in (n for n in refs if n in bodies): self.write.material(name, "Name", m["Name"]) if "Density" in m: @@ -161,9 +155,7 @@ class Flowwriter: if "SpecificHeatRatio" in m: self.write.material(name, "Specific Heat Ratio", float(m["SpecificHeatRatio"])) if "CompressibilityModel" in m: - self.write.material( - name, "Compressibility Model", - m["CompressibilityModel"]) + self.write.material(name, "Compressibility Model", m["CompressibilityModel"]) def _outputInitialPressure(self, obj, name): # initial pressure only makes sense for fluid material @@ -276,4 +268,5 @@ class Flowwriter: if equation.MagneticInduction is True: self.write.equation(b, "Magnetic Induction", equation.MagneticInduction) + ## @} diff --git a/src/Mod/Fem/femsolver/elmer/equations/flux.py b/src/Mod/Fem/femsolver/elmer/equations/flux.py index b8bca88afd..e2d897d2c0 100644 --- a/src/Mod/Fem/femsolver/elmer/equations/flux.py +++ b/src/Mod/Fem/femsolver/elmer/equations/flux.py @@ -39,8 +39,7 @@ VARIABLES = ["Potential", "Temperature"] def create(doc, name="Flux"): - return femutils.createObject( - doc, name, Proxy, ViewProxy) + return femutils.createObject(doc, name, Proxy, ViewProxy) class Proxy(linear.Proxy, equationbase.FluxProxy): @@ -48,7 +47,7 @@ class Proxy(linear.Proxy, equationbase.FluxProxy): Type = "Fem::EquationElmerFlux" def __init__(self, obj): - super(Proxy, self).__init__(obj) + super().__init__(obj) obj.addProperty( "App::PropertyBool", @@ -57,43 +56,29 @@ class Proxy(linear.Proxy, equationbase.FluxProxy): ( "Enforces continuity within the same material\n" "in the 'Discontinuous Galerkin' discretization" - ) + ), ) + obj.addProperty("App::PropertyBool", "CalculateFlux", "Flux", "Computes flux vector") obj.addProperty( - "App::PropertyBool", - "CalculateFlux", - "Flux", - "Computes flux vector" - ) - obj.addProperty( - "App::PropertyBool", - "CalculateFluxAbs", - "Flux", - "Computes absolute of flux vector" + "App::PropertyBool", "CalculateFluxAbs", "Flux", "Computes absolute of flux vector" ) obj.addProperty( "App::PropertyBool", "CalculateFluxMagnitude", "Flux", - "Computes magnitude of flux vector field" + "Computes magnitude of flux vector field", ) obj.addProperty( - "App::PropertyBool", - "CalculateGrad", - "Flux", - "Select calculation of gradient" + "App::PropertyBool", "CalculateGrad", "Flux", "Select calculation of gradient" ) obj.addProperty( - "App::PropertyBool", - "CalculateGradAbs", - "Flux", - "Computes absolute of gradient field" + "App::PropertyBool", "CalculateGradAbs", "Flux", "Computes absolute of gradient field" ) obj.addProperty( "App::PropertyBool", "CalculateGradMagnitude", "Flux", - "Computes magnitude of gradient field" + "Computes magnitude of gradient field", ) obj.addProperty( "App::PropertyBool", @@ -102,7 +87,7 @@ class Proxy(linear.Proxy, equationbase.FluxProxy): ( "Enable if standard Galerkin approximation leads to\n" "unphysical results when there are discontinuities" - ) + ), ) obj.addProperty( "App::PropertyBool", @@ -111,19 +96,16 @@ class Proxy(linear.Proxy, equationbase.FluxProxy): ( "If true, negative values of computed magnitude fields\n" "are a posteriori set to zero." - ) + ), ) obj.addProperty( "App::PropertyEnumeration", "FluxCoefficient", "Flux", - "Proportionality coefficient\nto compute the flux" + "Proportionality coefficient\nto compute the flux", ) obj.addProperty( - "App::PropertyEnumeration", - "FluxVariable", - "Flux", - "Variable name for flux calculation" + "App::PropertyEnumeration", "FluxVariable", "Flux", "Variable name for flux calculation" ) obj.CalculateFlux = True @@ -141,4 +123,5 @@ class Proxy(linear.Proxy, equationbase.FluxProxy): class ViewProxy(linear.ViewProxy, equationbase.FluxViewProxy): pass + ## @} diff --git a/src/Mod/Fem/femsolver/elmer/equations/flux_writer.py b/src/Mod/Fem/femsolver/elmer/equations/flux_writer.py index f898a68a8e..f860ecfbd6 100644 --- a/src/Mod/Fem/femsolver/elmer/equations/flux_writer.py +++ b/src/Mod/Fem/femsolver/elmer/equations/flux_writer.py @@ -78,38 +78,35 @@ class Fluxwriter: ( "Enforces continuity within the same material\n" "in the 'Discontinuous Galerkin' discretization" - ) + ), ) if hasattr(equation, "Bubbles"): # Bubbles was removed because it is unused by Elmer for the flux solver equation.removeProperty("Bubbles") if not hasattr(equation, "CalculateFluxAbs"): equation.addProperty( - "App::PropertyBool", - "CalculateFluxAbs", - "Flux", - "Computes absolute of flux vector" + "App::PropertyBool", "CalculateFluxAbs", "Flux", "Computes absolute of flux vector" ) if not hasattr(equation, "CalculateFluxMagnitude"): equation.addProperty( "App::PropertyBool", "CalculateFluxMagnitude", "Flux", - "Computes magnitude of flux vector field" + "Computes magnitude of flux vector field", ) if not hasattr(equation, "CalculateGradAbs"): equation.addProperty( "App::PropertyBool", "CalculateGradAbs", "Flux", - "Computes absolute of gradient field" + "Computes absolute of gradient field", ) if not hasattr(equation, "CalculateGradMagnitude"): equation.addProperty( "App::PropertyBool", "CalculateGradMagnitude", "Flux", - "Computes magnitude of gradient field" + "Computes magnitude of gradient field", ) if not hasattr(equation, "DiscontinuousGalerkin"): equation.addProperty( @@ -119,7 +116,7 @@ class Fluxwriter: ( "Enable if standard Galerkin approximation leads to\n" "unphysical results when there are discontinuities" - ) + ), ) if not hasattr(equation, "EnforcePositiveMagnitude"): equation.addProperty( @@ -129,7 +126,7 @@ class Fluxwriter: ( "If true, negative values of computed magnitude fields\n" "are a posteriori set to zero." - ) + ), ) tempFluxCoefficient = "" if hasattr(equation, "FluxCoefficient"): @@ -143,7 +140,7 @@ class Fluxwriter: "App::PropertyEnumeration", "FluxCoefficient", "Flux", - "Name of proportionality coefficient\nto compute the flux" + "Name of proportionality coefficient\nto compute the flux", ) equation.FluxCoefficient = flux.COEFFICIENTS if tempFluxCoefficient: @@ -161,9 +158,10 @@ class Fluxwriter: "App::PropertyEnumeration", "FluxVariable", "Flux", - "Variable name for flux calculation" + "Variable name for flux calculation", ) equation.FluxVariable = flux.VARIABLES equation.FluxVariable = tempFluxVariable + ## @} diff --git a/src/Mod/Fem/femsolver/elmer/equations/heat.py b/src/Mod/Fem/femsolver/elmer/equations/heat.py index 55b51fa473..a3717bcafa 100644 --- a/src/Mod/Fem/femsolver/elmer/equations/heat.py +++ b/src/Mod/Fem/femsolver/elmer/equations/heat.py @@ -38,8 +38,7 @@ PHASE_CHANGE_MODEL = ["None", "Spatial 1", "Spatial 2", "Temporal"] def create(doc, name="Heat"): - return femutils.createObject( - doc, name, Proxy, ViewProxy) + return femutils.createObject(doc, name, Proxy, ViewProxy) class Proxy(nonlinear.Proxy, equationbase.HeatProxy): @@ -47,27 +46,16 @@ class Proxy(nonlinear.Proxy, equationbase.HeatProxy): Type = "Fem::EquationElmerHeat" def __init__(self, obj): - super(Proxy, self).__init__(obj) + super().__init__(obj) # according to the Elmer models manual Bubbles is by default True # and Stabilize is False (Stabilize is added in linear.py) + obj.addProperty("App::PropertyBool", "Bubbles", "Heat", "") obj.addProperty( - "App::PropertyBool", - "Bubbles", - "Heat", - "" + "App::PropertyEnumeration", "Convection", "Equation", "Type of convection to be used" ) obj.addProperty( - "App::PropertyEnumeration", - "Convection", - "Equation", - "Type of convection to be used" - ) - obj.addProperty( - "App::PropertyEnumeration", - "PhaseChangeModel", - "Equation", - "Model for phase change" + "App::PropertyEnumeration", "PhaseChangeModel", "Equation", "Model for phase change" ) obj.Bubbles = True @@ -82,4 +70,5 @@ class Proxy(nonlinear.Proxy, equationbase.HeatProxy): class ViewProxy(nonlinear.ViewProxy, equationbase.HeatViewProxy): pass + ## @} diff --git a/src/Mod/Fem/femsolver/elmer/equations/heat_writer.py b/src/Mod/Fem/femsolver/elmer/equations/heat_writer.py index 7fa9231269..7599e16a18 100644 --- a/src/Mod/Fem/femsolver/elmer/equations/heat_writer.py +++ b/src/Mod/Fem/femsolver/elmer/equations/heat_writer.py @@ -63,7 +63,7 @@ class Heatwriter: def handleHeatConstants(self): self.write.constant( "Stefan Boltzmann", - self.write.convert(self.write.constsdef["StefanBoltzmann"], "M/(O^4*T^3)") + self.write.convert(self.write.constsdef["StefanBoltzmann"], "M/(O^4*T^3)"), ) def handleHeatEquation(self, bodies, equation): @@ -80,16 +80,13 @@ class Heatwriter: "App::PropertyEnumeration", "Convection", "Equation", - "Type of convection to be used" + "Type of convection to be used", ) equation.Convection = heat.CONVECTION_TYPE equation.Convection = "None" if not hasattr(equation, "PhaseChangeModel"): equation.addProperty( - "App::PropertyEnumeration", - "PhaseChangeModel", - "Equation", - "Model for phase change" + "App::PropertyEnumeration", "PhaseChangeModel", "Equation", "Model for phase change" ) equation.PhaseChangeModel = heat.PHASE_CHANGE_MODEL equation.PhaseChangeModel = "None" @@ -99,12 +96,10 @@ class Heatwriter: for obj in self.write.getMember("Fem::ConstraintTemperature"): i = i + 1 femobjects = membertools.get_several_member( - self.write.analysis, - "Fem::ConstraintTemperature" + self.write.analysis, "Fem::ConstraintTemperature" ) femobjects[i]["Nodes"] = meshtools.get_femnodes_by_femobj_with_references( - self.write.getSingleMember("Fem::FemMeshObject").FemMesh, - femobjects[i] + self.write.getSingleMember("Fem::FemMeshObject").FemMesh, femobjects[i] ) NumberOfNodes = len(femobjects[i]["Nodes"]) if obj.References: @@ -150,7 +145,9 @@ class Heatwriter: ref_sub_obj = ref[1][0] density = None for mat in self.write.getMember("App::MaterialObject"): - mat_ref = [*itertools.chain(*[itertools.product([i[0]],i[1]) for i in mat.References])] + mat_ref = [ + *itertools.chain(*[itertools.product([i[0]], i[1]) for i in mat.References]) + ] if (ref_feat, ref_sub_obj) in mat_ref: density = FreeCAD.Units.Quantity(mat.Material["Density"]) break @@ -162,8 +159,12 @@ class Heatwriter: density = FreeCAD.Units.Quantity(mat.Material["Density"]) break volume = ref_feat.getSubObject(ref_sub_obj).Volume - heatSource = (obj.TotalPower / (density*FreeCAD.Units.Quantity(volume, "mm^3"))).getValueAs("W/kg").Value - + heatSource = ( + (obj.TotalPower / (density * FreeCAD.Units.Quantity(volume, "mm^3"))) + .getValueAs("W/kg") + .Value + ) + if heatSource == 0.0: # a zero heat would break Elmer (division by zero) raise general_writer.WriteError("The body heat source must not be zero!") @@ -197,32 +198,30 @@ class Heatwriter: self.write.material(name, "Reference Temperature", refTemp) for obj in self.write.getMember("App::MaterialObject"): m = obj.Material - refs = ( - obj.References[0][1] - if obj.References - else self.write.getAllBodies()) + refs = obj.References[0][1] if obj.References else self.write.getAllBodies() for name in (n for n in refs if n in bodies): if "Density" not in m: raise general_writer.WriteError( "Used material does not specify the necessary 'Density'." ) self.write.material(name, "Name", m["Name"]) - self.write.material( - name, "Density", - self.write.getDensity(m)) + self.write.material(name, "Density", self.write.getDensity(m)) if "ThermalConductivity" not in m: raise general_writer.WriteError( "Used material does not specify the necessary 'Thermal Conductivity'." ) self.write.material( - name, "Heat Conductivity", - self.write.convert(m["ThermalConductivity"], "M*L/(T^3*O)")) + name, + "Heat Conductivity", + self.write.convert(m["ThermalConductivity"], "M*L/(T^3*O)"), + ) if "SpecificHeat" not in m: raise general_writer.WriteError( "Used material does not specify the necessary 'Specific Heat'." ) self.write.material( - name, "Heat Capacity", - self.write.convert(m["SpecificHeat"], "L^2/(T^2*O)")) + name, "Heat Capacity", self.write.convert(m["SpecificHeat"], "L^2/(T^2*O)") + ) + ## @} diff --git a/src/Mod/Fem/femsolver/elmer/equations/linear.py b/src/Mod/Fem/femsolver/elmer/equations/linear.py index fcbbd5bf76..0b55620e40 100644 --- a/src/Mod/Fem/femsolver/elmer/equations/linear.py +++ b/src/Mod/Fem/femsolver/elmer/equations/linear.py @@ -39,75 +39,32 @@ from . import equation LINEAR_SOLVER = ["Direct", "Iterative"] LINEAR_DIRECT = ["Banded", "MUMPS", "Umfpack"] -LINEAR_ITERATIVE = [ - "BiCGStab", - "BiCGStabl", - "CG", - "GCR", - "CGS", - "GMRES", - "Idrs", - "TFQMR" -] -LINEAR_PRECONDITIONING = [ - "None", - "Diagonal", - "ILU0", - "ILU1", - "ILU2", - "ILU3", - "ILU4", - "ILUT" -] +LINEAR_ITERATIVE = ["BiCGStab", "BiCGStabl", "CG", "GCR", "CGS", "GMRES", "Idrs", "TFQMR"] +LINEAR_PRECONDITIONING = ["None", "Diagonal", "ILU0", "ILU1", "ILU2", "ILU3", "ILU4", "ILUT"] class Proxy(equation.Proxy): def __init__(self, obj): - super(Proxy, self).__init__(obj) + super().__init__(obj) obj.addProperty( "App::PropertyIntegerConstraint", "BiCGstablDegree", "Linear System", - "Polynom degree for iterative method 'BiCGstabl'" + "Polynom degree for iterative method 'BiCGstabl'", ) obj.addProperty( "App::PropertyIntegerConstraint", "IdrsParameter", "Linear System", - "Parameter for iterative method 'Idrs'" - ) - obj.addProperty( - "App::PropertyEnumeration", - "LinearDirectMethod", - "Linear System", - "" - ) - obj.addProperty( - "App::PropertyIntegerConstraint", - "LinearIterations", - "Linear System", - "" - ) - obj.addProperty( - "App::PropertyEnumeration", - "LinearIterativeMethod", - "Linear System", - "" - ) - obj.addProperty( - "App::PropertyEnumeration", - "LinearPreconditioning", - "Linear System", - "" - ) - obj.addProperty( - "App::PropertyEnumeration", - "LinearSolverType", - "Linear System", - "" + "Parameter for iterative method 'Idrs'", ) + obj.addProperty("App::PropertyEnumeration", "LinearDirectMethod", "Linear System", "") + obj.addProperty("App::PropertyIntegerConstraint", "LinearIterations", "Linear System", "") + obj.addProperty("App::PropertyEnumeration", "LinearIterativeMethod", "Linear System", "") + obj.addProperty("App::PropertyEnumeration", "LinearPreconditioning", "Linear System", "") + obj.addProperty("App::PropertyEnumeration", "LinearSolverType", "Linear System", "") obj.addProperty( "App::PropertyBool", "LinearSystemSolverDisabled", @@ -116,26 +73,16 @@ class Proxy(equation.Proxy): "Disable the linear system.\n" "Only use for special cases\n" "and consult the Elmer docs." - ) + ), ) obj.addProperty( "App::PropertyFloat", "LinearTolerance", "Linear System", - "Linear preconditioning method" - ) - obj.addProperty( - "App::PropertyBool", - "Stabilize", - "Base", - "" - ) - obj.addProperty( - "App::PropertyFloat", - "SteadyStateTolerance", - "Steady State", - "" + "Linear preconditioning method", ) + obj.addProperty("App::PropertyBool", "Stabilize", "Base", "") + obj.addProperty("App::PropertyFloat", "SteadyStateTolerance", "Steady State", "") obj.BiCGstablDegree = (2, 2, 10, 1) obj.IdrsParameter = (2, 1, 10, 1) @@ -160,4 +107,5 @@ class Proxy(equation.Proxy): class ViewProxy(equation.ViewProxy): pass + ## @} diff --git a/src/Mod/Fem/femsolver/elmer/equations/magnetodynamic.py b/src/Mod/Fem/femsolver/elmer/equations/magnetodynamic.py index 5e2b15f764..47a627213f 100644 --- a/src/Mod/Fem/femsolver/elmer/equations/magnetodynamic.py +++ b/src/Mod/Fem/femsolver/elmer/equations/magnetodynamic.py @@ -34,8 +34,7 @@ from ... import equationbase def create(doc, name="Magnetodynamic"): - return femutils.createObject( - doc, name, Proxy, ViewProxy) + return femutils.createObject(doc, name, Proxy, ViewProxy) class Proxy(nonlinear.Proxy, equationbase.MagnetodynamicProxy): @@ -43,19 +42,19 @@ class Proxy(nonlinear.Proxy, equationbase.MagnetodynamicProxy): Type = "Fem::EquationElmerMagnetodynamic" def __init__(self, obj): - super(Proxy, self).__init__(obj) + super().__init__(obj) obj.addProperty( "App::PropertyBool", "IsHarmonic", "Magnetodynamic", - "If the magnetic source is harmonically driven" + "If the magnetic source is harmonically driven", ) obj.addProperty( "App::PropertyFrequency", "AngularFrequency", "Magnetodynamic", - "Frequency of the driving current" + "Frequency of the driving current", ) obj.addProperty( "App::PropertyBool", @@ -63,129 +62,68 @@ class Proxy(nonlinear.Proxy, equationbase.MagnetodynamicProxy): "Magnetodynamic", "Must be True if basis functions for edge element interpolation\n" "are selected to be members of optimal edge element family\n" - "or if second-order approximation is used." + "or if second-order approximation is used.", ) obj.addProperty( "App::PropertyBool", "QuadraticApproximation", "Magnetodynamic", - "Enables second-order approximation of driving current" + "Enables second-order approximation of driving current", ) obj.addProperty( "App::PropertyBool", "StaticConductivity", "Magnetodynamic", - "See Elmer models manual for info" + "See Elmer models manual for info", ) obj.addProperty( "App::PropertyBool", "FixInputCurrentDensity", "Magnetodynamic", - "Ensures divergence-freeness of current density" + "Ensures divergence-freeness of current density", ) obj.addProperty( "App::PropertyBool", "AutomatedSourceProjectionBCs", "Magnetodynamic", - "See Elmer models manual for info" + "See Elmer models manual for info", ) obj.addProperty( "App::PropertyBool", "UseLagrangeGauge", "Magnetodynamic", - "See Elmer models manual for info" + "See Elmer models manual for info", ) obj.addProperty( "App::PropertyFloat", "LagrangeGaugePenalizationCoefficient", "Magnetodynamic", - "See Elmer models manual for info" + "See Elmer models manual for info", ) obj.addProperty( "App::PropertyBool", "UseTreeGauge", "Magnetodynamic", - "See Elmer models manual for info\n" - "Will be ignored if 'UsePiolaTransform' is True" - ) - obj.addProperty( - "App::PropertyBool", - "LinearSystemRefactorize", - "Linear System", - "" + "See Elmer models manual for info\nWill be ignored if 'UsePiolaTransform' is True", ) + obj.addProperty("App::PropertyBool", "LinearSystemRefactorize", "Linear System", "") obj.IsHarmonic = False obj.AngularFrequency = 0 obj.Priority = 10 # the post processor options - obj.addProperty( - "App::PropertyBool", - "CalculateCurrentDensity", - "Results", - "" - ) - obj.addProperty( - "App::PropertyBool", - "CalculateElectricField", - "Results", - "" - ) - obj.addProperty( - "App::PropertyBool", - "CalculateElementalFields", - "Results", - "" - ) - obj.addProperty( - "App::PropertyBool", - "CalculateHarmonicLoss", - "Results", - "" - ) - obj.addProperty( - "App::PropertyBool", - "CalculateJouleHeating", - "Results", - "" - ) - obj.addProperty( - "App::PropertyBool", - "CalculateMagneticFieldStrength", - "Results", - "" - ) - obj.addProperty( - "App::PropertyBool", - "CalculateMaxwellStress", - "Results", - "" - ) - obj.addProperty( - "App::PropertyBool", - "CalculateNodalFields", - "Results", - "" - ) - obj.addProperty( - "App::PropertyBool", - "CalculateNodalForces", - "Results", - "" - ) - obj.addProperty( - "App::PropertyBool", - "CalculateNodalHeating", - "Results", - "" - ) - obj.addProperty( - "App::PropertyBool", - "DiscontinuousBodies", - "Results", - "" - ) + obj.addProperty("App::PropertyBool", "CalculateCurrentDensity", "Results", "") + obj.addProperty("App::PropertyBool", "CalculateElectricField", "Results", "") + obj.addProperty("App::PropertyBool", "CalculateElementalFields", "Results", "") + obj.addProperty("App::PropertyBool", "CalculateHarmonicLoss", "Results", "") + obj.addProperty("App::PropertyBool", "CalculateJouleHeating", "Results", "") + obj.addProperty("App::PropertyBool", "CalculateMagneticFieldStrength", "Results", "") + obj.addProperty("App::PropertyBool", "CalculateMaxwellStress", "Results", "") + obj.addProperty("App::PropertyBool", "CalculateNodalFields", "Results", "") + obj.addProperty("App::PropertyBool", "CalculateNodalForces", "Results", "") + obj.addProperty("App::PropertyBool", "CalculateNodalHeating", "Results", "") + obj.addProperty("App::PropertyBool", "DiscontinuousBodies", "Results", "") obj.CalculateCurrentDensity = False obj.CalculateElectricField = False # FIXME: at the moment FreeCAD's post processor cannot display elementary field @@ -204,4 +142,5 @@ class Proxy(nonlinear.Proxy, equationbase.MagnetodynamicProxy): class ViewProxy(nonlinear.ViewProxy, equationbase.MagnetodynamicViewProxy): pass + ## @} diff --git a/src/Mod/Fem/femsolver/elmer/equations/magnetodynamic2D.py b/src/Mod/Fem/femsolver/elmer/equations/magnetodynamic2D.py index 54bced82ed..b12bcb3eaa 100644 --- a/src/Mod/Fem/femsolver/elmer/equations/magnetodynamic2D.py +++ b/src/Mod/Fem/femsolver/elmer/equations/magnetodynamic2D.py @@ -34,8 +34,7 @@ from ... import equationbase def create(doc, name="Magnetodynamic2D"): - return femutils.createObject( - doc, name, Proxy, ViewProxy) + return femutils.createObject(doc, name, Proxy, ViewProxy) class Proxy(nonlinear.Proxy, equationbase.Magnetodynamic2DProxy): @@ -43,85 +42,37 @@ class Proxy(nonlinear.Proxy, equationbase.Magnetodynamic2DProxy): Type = "Fem::EquationElmerMagnetodynamic2D" def __init__(self, obj): - super(Proxy, self).__init__(obj) + super().__init__(obj) obj.addProperty( "App::PropertyBool", "IsHarmonic", "Magnetodynamic2D", - "If the magnetic source is harmonically driven" + "If the magnetic source is harmonically driven", ) obj.addProperty( "App::PropertyFrequency", "AngularFrequency", "Magnetodynamic2D", - "Frequency of the driving current" + "Frequency of the driving current", ) obj.IsHarmonic = False obj.AngularFrequency = 0 obj.Priority = 10 # the post processor options + obj.addProperty("App::PropertyBool", "CalculateCurrentDensity", "Magnetodynamic2D", "") + obj.addProperty("App::PropertyBool", "CalculateElectricField", "Magnetodynamic2D", "") + obj.addProperty("App::PropertyBool", "CalculateElementalFields", "Magnetodynamic2D", "") + obj.addProperty("App::PropertyBool", "CalculateHarmonicLoss", "Magnetodynamic2D", "") + obj.addProperty("App::PropertyBool", "CalculateJouleHeating", "Magnetodynamic2D", "") obj.addProperty( - "App::PropertyBool", - "CalculateCurrentDensity", - "Magnetodynamic2D", - "" - ) - obj.addProperty( - "App::PropertyBool", - "CalculateElectricField", - "Magnetodynamic2D", - "" - ) - obj.addProperty( - "App::PropertyBool", - "CalculateElementalFields", - "Magnetodynamic2D", - "" - ) - obj.addProperty( - "App::PropertyBool", - "CalculateHarmonicLoss", - "Magnetodynamic2D", - "" - ) - obj.addProperty( - "App::PropertyBool", - "CalculateJouleHeating", - "Magnetodynamic2D", - "" - ) - obj.addProperty( - "App::PropertyBool", - "CalculateMagneticFieldStrength", - "Magnetodynamic2D", - "" - ) - obj.addProperty( - "App::PropertyBool", - "CalculateMaxwellStress", - "Magnetodynamic2D", - "" - ) - obj.addProperty( - "App::PropertyBool", - "CalculateNodalFields", - "Magnetodynamic2D", - "" - ) - obj.addProperty( - "App::PropertyBool", - "CalculateNodalForces", - "Magnetodynamic2D", - "" - ) - obj.addProperty( - "App::PropertyBool", - "CalculateNodalHeating", - "Magnetodynamic2D", - "" + "App::PropertyBool", "CalculateMagneticFieldStrength", "Magnetodynamic2D", "" ) + obj.addProperty("App::PropertyBool", "CalculateMaxwellStress", "Magnetodynamic2D", "") + obj.addProperty("App::PropertyBool", "CalculateNodalFields", "Magnetodynamic2D", "") + obj.addProperty("App::PropertyBool", "CalculateNodalForces", "Magnetodynamic2D", "") + obj.addProperty("App::PropertyBool", "CalculateNodalHeating", "Magnetodynamic2D", "") obj.CalculateCurrentDensity = False obj.CalculateElectricField = False # FIXME: at the moment FreeCAD's post processor cannot display elementary field @@ -139,4 +90,5 @@ class Proxy(nonlinear.Proxy, equationbase.Magnetodynamic2DProxy): class ViewProxy(nonlinear.ViewProxy, equationbase.Magnetodynamic2DViewProxy): pass + ## @} diff --git a/src/Mod/Fem/femsolver/elmer/equations/magnetodynamic2D_writer.py b/src/Mod/Fem/femsolver/elmer/equations/magnetodynamic2D_writer.py index 77acad45ca..8444a44325 100644 --- a/src/Mod/Fem/femsolver/elmer/equations/magnetodynamic2D_writer.py +++ b/src/Mod/Fem/femsolver/elmer/equations/magnetodynamic2D_writer.py @@ -92,15 +92,13 @@ class MgDyn2Dwriter: def handleMagnetodynamic2DConstants(self): permeability = self.write.convert( - self.write.constsdef["PermeabilityOfVacuum"], - "M*L/(T^2*I^2)" + self.write.constsdef["PermeabilityOfVacuum"], "M*L/(T^2*I^2)" ) # we round in the following to get rid of numerical artifacts self.write.constant("Permeability Of Vacuum", round(permeability, 20)) permittivity = self.write.convert( - self.write.constsdef["PermittivityOfVacuum"], - "T^4*I^2/(L^3*M)" + self.write.constsdef["PermittivityOfVacuum"], "T^4*I^2/(L^3*M)" ) self.write.constant("Permittivity Of Vacuum", round(permittivity, 20)) @@ -109,22 +107,19 @@ class MgDyn2Dwriter: for name in bodies: if self.write.getBodyMaterial(name) is None: raise general_writer.WriteError( - "The body {} is not referenced in any material.\n\n".format(name) + f"The body {name} is not referenced in any material.\n\n" ) for obj in self.write.getMember("App::MaterialObject"): m = obj.Material - refs = ( - obj.References[0][1] - if obj.References - else self.write.getAllBodies()) + refs = obj.References[0][1] if obj.References else self.write.getAllBodies() for name in (n for n in refs if n in bodies): if "ElectricalConductivity" not in m: - Console.PrintMessage("m: {}\n".format(m)) + Console.PrintMessage(f"m: {m}\n") raise general_writer.WriteError( "The electrical conductivity must be specified for all materials.\n\n" ) if "RelativePermeability" not in m: - Console.PrintMessage("m: {}\n".format(m)) + Console.PrintMessage(f"m: {m}\n") raise general_writer.WriteError( "The relative permeability must be specified for all materials.\n\n" ) @@ -132,15 +127,11 @@ class MgDyn2Dwriter: conductivity = self.write.convert(m["ElectricalConductivity"], "T^3*I^2/(L^3*M)") conductivity = round(conductivity, 10) # to get rid of numerical artifacts self.write.material(name, "Electric Conductivity", conductivity) - self.write.material( - name, "Relative Permeability", - float(m["RelativePermeability"]) - ) + self.write.material(name, "Relative Permeability", float(m["RelativePermeability"])) # permittivity might be necessary for the post processor if "RelativePermittivity" in m: self.write.material( - name, "Relative Permittivity", - float(m["RelativePermittivity"]) + name, "Relative Permittivity", float(m["RelativePermittivity"]) ) def _outputMagnetodynamic2DBodyForce(self, obj, name, equation): @@ -229,12 +220,11 @@ class MgDyn2Dwriter: def handleMagnetodynamic2DEquation(self, bodies, equation): for b in bodies: if equation.IsHarmonic and (equation.AngularFrequency == 0): - raise general_writer.WriteError( - "The angular frequency must not be zero.\n\n" - ) + raise general_writer.WriteError("The angular frequency must not be zero.\n\n") self.write.equation(b, "Name", equation.Name) if equation.IsHarmonic: frequency = float(Units.Quantity(equation.AngularFrequency).Value) self.write.equation(b, "Angular Frequency", round(frequency, 6)) + ## @} diff --git a/src/Mod/Fem/femsolver/elmer/equations/magnetodynamic_writer.py b/src/Mod/Fem/femsolver/elmer/equations/magnetodynamic_writer.py index 7e51f2a5da..c26c9e1699 100644 --- a/src/Mod/Fem/femsolver/elmer/equations/magnetodynamic_writer.py +++ b/src/Mod/Fem/femsolver/elmer/equations/magnetodynamic_writer.py @@ -73,8 +73,9 @@ class MgDynwriter: if equation.UseLagrangeGauge is True: s["Use Lagrange Gauge"] = True if equation.LagrangeGaugePenalizationCoefficient != 0.0: - s["Lagrange Gauge Penalization Coefficient"] = \ + s["Lagrange Gauge Penalization Coefficient"] = ( equation.LagrangeGaugePenalizationCoefficient + ) if equation.UseTreeGauge is True: s["Use Tree Gauge"] = True return s @@ -117,15 +118,13 @@ class MgDynwriter: def handleMagnetodynamicConstants(self): permeability = self.write.convert( - self.write.constsdef["PermeabilityOfVacuum"], - "M*L/(T^2*I^2)" + self.write.constsdef["PermeabilityOfVacuum"], "M*L/(T^2*I^2)" ) # we round in the following to get rid of numerical artifacts self.write.constant("Permeability Of Vacuum", round(permeability, 20)) permittivity = self.write.convert( - self.write.constsdef["PermittivityOfVacuum"], - "T^4*I^2/(L^3*M)" + self.write.constsdef["PermittivityOfVacuum"], "T^4*I^2/(L^3*M)" ) self.write.constant("Permittivity Of Vacuum", round(permittivity, 20)) @@ -134,22 +133,19 @@ class MgDynwriter: for name in bodies: if self.write.getBodyMaterial(name) is None: raise general_writer.WriteError( - "The body {} is not referenced in any material.\n\n".format(name) + f"The body {name} is not referenced in any material.\n\n" ) for obj in self.write.getMember("App::MaterialObject"): m = obj.Material - refs = ( - obj.References[0][1] - if obj.References - else self.write.getAllBodies()) + refs = obj.References[0][1] if obj.References else self.write.getAllBodies() for name in (n for n in refs if n in bodies): if "ElectricalConductivity" not in m: - Console.PrintMessage("m: {}\n".format(m)) + Console.PrintMessage(f"m: {m}\n") raise general_writer.WriteError( "The electrical conductivity must be specified for all materials.\n\n" ) if "RelativePermeability" not in m: - Console.PrintMessage("m: {}\n".format(m)) + Console.PrintMessage(f"m: {m}\n") raise general_writer.WriteError( "The relative permeability must be specified for all materials.\n\n" ) @@ -157,15 +153,11 @@ class MgDynwriter: conductivity = self.write.convert(m["ElectricalConductivity"], "T^3*I^2/(L^3*M)") conductivity = round(conductivity, 10) # to get rid of numerical artifacts self.write.material(name, "Electric Conductivity", conductivity) - self.write.material( - name, "Relative Permeability", - float(m["RelativePermeability"]) - ) + self.write.material(name, "Relative Permeability", float(m["RelativePermeability"])) # permittivity might be necessary for the post processor if "RelativePermittivity" in m: self.write.material( - name, "Relative Permittivity", - float(m["RelativePermittivity"]) + name, "Relative Permittivity", float(m["RelativePermittivity"]) ) def _outputMagnetodynamicBodyForce(self, obj, name, equation): @@ -235,7 +227,7 @@ class MgDynwriter: for obj in currentDensities: if obj.References: firstName = obj.References[0][1][0] - firstName = firstName.rstrip('0123456789') + firstName = firstName.rstrip("0123456789") if firstName == "Solid": for name in obj.References[0][1]: self._outputMagnetodynamicBodyForce(obj, name, equation) @@ -278,7 +270,7 @@ class MgDynwriter: for obj in potentials: if obj.References: firstName = obj.References[0][1][0] - firstName = firstName.rstrip('0123456789') + firstName = firstName.rstrip("0123456789") if firstName == "Solid": for name in obj.References[0][1]: # output only if potentiual is enabled and needed @@ -346,7 +338,7 @@ class MgDynwriter: for obj in currentDensities: if obj.References: firstName = obj.References[0][1][0] - firstName = firstName.rstrip('0123456789') + firstName = firstName.rstrip("0123456789") if firstName == "Face": for name in obj.References[0][1]: self._outputMagnetodynamicBndConditions(obj, name, equation) @@ -363,7 +355,7 @@ class MgDynwriter: for obj in potentials: if obj.References: firstName = obj.References[0][1][0] - firstName = firstName.rstrip('0123456789') + firstName = firstName.rstrip("0123456789") if firstName == "Face": for name in obj.References[0][1]: # output the FreeCAD label as comment @@ -373,4 +365,5 @@ class MgDynwriter: self._outputMagnetodynamicBndConditions(obj, name, equation) self.write.handled(obj) + ## @} diff --git a/src/Mod/Fem/femsolver/elmer/equations/nonlinear.py b/src/Mod/Fem/femsolver/elmer/equations/nonlinear.py index bc7844b206..1bd8cc4291 100644 --- a/src/Mod/Fem/femsolver/elmer/equations/nonlinear.py +++ b/src/Mod/Fem/femsolver/elmer/equations/nonlinear.py @@ -40,32 +40,24 @@ from . import linear class Proxy(linear.Proxy): def __init__(self, obj): - super(Proxy, self).__init__(obj) + super().__init__(obj) obj.addProperty( "App::PropertyIntegerConstraint", "NonlinearIterations", "Nonlinear System", - "Maximum number of iterations" + "Maximum number of iterations", ) obj.addProperty( "App::PropertyIntegerConstraint", "NonlinearNewtonAfterIterations", "Nonlinear System", - "" + "", ) obj.addProperty( - "App::PropertyFloat", - "NonlinearNewtonAfterTolerance", - "Nonlinear System", - "" - ) - obj.addProperty( - "App::PropertyFloat", - "NonlinearTolerance", - "Nonlinear System", - "" + "App::PropertyFloat", "NonlinearNewtonAfterTolerance", "Nonlinear System", "" ) + obj.addProperty("App::PropertyFloat", "NonlinearTolerance", "Nonlinear System", "") obj.addProperty( "App::PropertyFloatConstraint", "RelaxationFactor", @@ -73,7 +65,7 @@ class Proxy(linear.Proxy): ( "Value below 1.0 might be necessary to achieve convergence\n" "Typical values are in the range [0.3, 1.0]" - ) + ), ) obj.NonlinearIterations = (20, 1, int(1e6), 10) @@ -90,4 +82,5 @@ class Proxy(linear.Proxy): class ViewProxy(linear.ViewProxy): pass + ## @} diff --git a/src/Mod/Fem/femsolver/elmer/sifio.py b/src/Mod/Fem/femsolver/elmer/sifio.py index ad65a38ad7..41b2f6e578 100644 --- a/src/Mod/Fem/femsolver/elmer/sifio.py +++ b/src/Mod/Fem/femsolver/elmer/sifio.py @@ -78,10 +78,10 @@ _TYPE_STRING = "String" _TYPE_FILE = "File" _TYPE_VARIABLE = "Variable" -WARN = "\"Warn\"" -IGNORE = "\"Ignore\"" -ABORT = "\"Abort\"" -SILENT = "\"Silent\"" +WARN = '"Warn"' +IGNORE = '"Ignore"' +ABORT = '"Abort"' +SILENT = '"Silent"' def createSection(name): @@ -104,7 +104,7 @@ def isValid(section): return section.name in _VALID_SECTIONS -class Builder(object): +class Builder: _ACTIVE_SOLVERS = "Active Solvers" @@ -191,7 +191,7 @@ class Builder(object): return iter(allSections) -class Sif(object): +class Sif: _CHECK_KEYWORDS = "Check Keywords" _HEADER = "Header" @@ -238,7 +238,7 @@ class Sif(object): stream.write('"%s"' % value) -class Section(object): +class Section: def __init__(self, name): self.name = name @@ -274,7 +274,7 @@ class FileAttr(str): pass -class _Writer(object): +class _Writer: def __init__(self, idManager, sections, stream): self._idMgr = idManager @@ -282,8 +282,7 @@ class _Writer(object): self._stream = stream def write(self): - sortedSections = sorted( - self._sections, key=lambda s: s.priority, reverse=True) + sortedSections = sorted(self._sections, key=lambda s: s.priority, reverse=True) for s in sortedSections: self._writeSection(s) self._stream.write(_NEWLINE) @@ -332,10 +331,7 @@ class _Writer(object): return next(it) def _isCollection(self, data): - return ( - not isinstance(data, str) - and isinstance(data, collections.abc.Iterable) - ) + return not isinstance(data, str) and isinstance(data, collections.abc.Iterable) def _checkScalar(self, dataType): if issubclass(dataType, int): @@ -359,7 +355,7 @@ class _Writer(object): self._stream.write(_WHITESPACE) # check if we have a variable string if attrType is _TYPE_STRING: - if data.startswith('Variable'): + if data.startswith("Variable"): attrType = _TYPE_VARIABLE if attrType is not _TYPE_VARIABLE: self._stream.write(attrType) @@ -367,7 +363,7 @@ class _Writer(object): output = self._preprocess(data, type(data)) # in case of a variable the output must be without the quatoation marks if attrType is _TYPE_VARIABLE: - output = output.lstrip('\"') + output = output.lstrip('"') # we cannot use rstrip because there are two subsequent " at the end output = output[:-1] self._stream.write(output) @@ -382,7 +378,7 @@ class _Writer(object): self._stream.write(_WHITESPACE) # check if we have a variable string if attrType is _TYPE_STRING: - if data.startswith('Variable'): + if data.startswith("Variable"): attrType = _TYPE_VARIABLE if attrType is not _TYPE_VARIABLE: self._stream.write(attrType) @@ -391,7 +387,7 @@ class _Writer(object): output = self._preprocess(val, type(val)) # in case of a variable the output must be without the quatoation marks if attrType is _TYPE_VARIABLE: - output = output.lstrip('\"') + output = output.lstrip('"') # we cannot use rstrip because there are two subsequent " at the end output = output[:-1] self._stream.write(output) @@ -442,7 +438,7 @@ class _Writer(object): return self._getSifDataType(dataType) -class _IdManager(object): +class _IdManager: def __init__(self, firstId=1): self._pool = dict() @@ -460,4 +456,5 @@ class _IdManager(object): self.setId(section) return self._ids[section] + ## @} diff --git a/src/Mod/Fem/femsolver/elmer/solver.py b/src/Mod/Fem/femsolver/elmer/solver.py index 9cbc85a61c..9b4602a0f4 100644 --- a/src/Mod/Fem/femsolver/elmer/solver.py +++ b/src/Mod/Fem/femsolver/elmer/solver.py @@ -50,16 +50,22 @@ from femtools import femutils if FreeCAD.GuiUp: import FemGui -COORDINATE_SYSTEM = ["Cartesian", "Cartesian 1D", "Cartesian 2D", "Cartesian 3D", - "Polar 2D", "Polar 3D", - "Cylindric", "Cylindric Symmetric", - "Axi Symmetric"] +COORDINATE_SYSTEM = [ + "Cartesian", + "Cartesian 1D", + "Cartesian 2D", + "Cartesian 3D", + "Polar 2D", + "Polar 3D", + "Cylindric", + "Cylindric Symmetric", + "Axi Symmetric", +] SIMULATION_TYPE = ["Scanning", "Steady State", "Transient"] def create(doc, name="ElmerSolver"): - return femutils.createObject( - doc, name, Proxy, ViewProxy) + return femutils.createObject(doc, name, Proxy, ViewProxy) class Proxy(solverbase.Proxy): @@ -80,14 +86,9 @@ class Proxy(solverbase.Proxy): } def __init__(self, obj): - super(Proxy, self).__init__(obj) + super().__init__(obj) - obj.addProperty( - "App::PropertyEnumeration", - "CoordinateSystem", - "Coordinate System", - "" - ) + obj.addProperty("App::PropertyEnumeration", "CoordinateSystem", "Coordinate System", "") obj.CoordinateSystem = COORDINATE_SYSTEM obj.CoordinateSystem = "Cartesian" @@ -95,7 +96,7 @@ class Proxy(solverbase.Proxy): "App::PropertyIntegerConstraint", "BDFOrder", "Timestepping", - "Order of time stepping method 'BDF'" + "Order of time stepping method 'BDF'", ) # according to the Elmer manual recommended is order 2 # possible ranage is 1 - 5 @@ -105,7 +106,7 @@ class Proxy(solverbase.Proxy): "App::PropertyIntegerList", "OutputIntervals", "Timestepping", - "After how many time steps a result file is output" + "After how many time steps a result file is output", ) obj.OutputIntervals = [1] @@ -113,10 +114,7 @@ class Proxy(solverbase.Proxy): "App::PropertyIntegerList", "TimestepIntervals", "Timestepping", - ( - "List of times if 'Simulation Type'\n" - "is either 'Scanning' or 'Transient'" - ) + ("List of times if 'Simulation Type'\nis either 'Scanning' or 'Transient'"), ) obj.addProperty( "App::PropertyFloatList", @@ -125,19 +123,14 @@ class Proxy(solverbase.Proxy): ( "List of time steps sizes if 'Simulation Type'\n" "is either 'Scanning' or 'Transient'" - ) + ), ) # there is no universal default, it all depends on the analysis, however # we have to set something and set 10 seconds in steps of 0.1s obj.TimestepIntervals = [100] obj.TimestepSizes = [0.1] - obj.addProperty( - "App::PropertyEnumeration", - "SimulationType", - "Type", - "" - ) + obj.addProperty("App::PropertyEnumeration", "SimulationType", "Type", "") obj.SimulationType = SIMULATION_TYPE obj.SimulationType = "Steady State" @@ -145,7 +138,7 @@ class Proxy(solverbase.Proxy): "App::PropertyInteger", "SteadyStateMaxIterations", "Type", - "Maximal steady state iterations" + "Maximal steady state iterations", ) obj.SteadyStateMaxIterations = 1 @@ -153,42 +146,26 @@ class Proxy(solverbase.Proxy): "App::PropertyInteger", "SteadyStateMinIterations", "Type", - "Minimal steady state iterations" + "Minimal steady state iterations", ) obj.SteadyStateMinIterations = 0 - obj.addProperty( - "App::PropertyLink", - "ElmerResult", - "Base", - "", - 4 | 8 - ) + obj.addProperty("App::PropertyLink", "ElmerResult", "Base", "", 4 | 8) - obj.addProperty( - "App::PropertyLinkList", - "ElmerTimeResults", - "Base", - "", - 4 | 8 - ) + obj.addProperty("App::PropertyLinkList", "ElmerTimeResults", "Base", "", 4 | 8) - obj.addProperty( - "App::PropertyLink", - "ElmerOutput", - "Base", - "", - 4 | 8 - ) + obj.addProperty("App::PropertyLink", "ElmerOutput", "Base", "", 4 | 8) def createMachine(self, obj, directory, testmode=False): return run.Machine( - solver=obj, directory=directory, + solver=obj, + directory=directory, check=tasks.Check(), prepare=tasks.Prepare(), solve=tasks.Solve(), results=tasks.Results(), - testmode=testmode) + testmode=testmode, + ) def createEquation(self, doc, eqId): return self._EQUATIONS[eqId].create(doc) @@ -201,7 +178,7 @@ class Proxy(solverbase.Proxy): def edit(self, directory): pattern = os.path.join(directory, "case.sif") - FreeCAD.Console.PrintMessage("{}\n".format(pattern)) + FreeCAD.Console.PrintMessage(f"{pattern}\n") f = glob.glob(pattern)[0] FemGui.open(f) @@ -212,4 +189,5 @@ class ViewProxy(solverbase.ViewProxy): def getIcon(self): return ":/icons/FEM_SolverElmer.svg" + ## @} diff --git a/src/Mod/Fem/femsolver/elmer/tasks.py b/src/Mod/Fem/femsolver/elmer/tasks.py index 1c5b544862..97db591ab0 100644 --- a/src/Mod/Fem/femsolver/elmer/tasks.py +++ b/src/Mod/Fem/femsolver/elmer/tasks.py @@ -47,7 +47,7 @@ class Check(run.Check): def run(self): self.pushStatus("Checking analysis...\n") - if (self.check_mesh_exists()): + if self.check_mesh_exists(): self.checkMeshType() self.check_material_exists() self.checkEquations() @@ -55,9 +55,7 @@ class Check(run.Check): def checkMeshType(self): mesh = membertools.get_single_member(self.analysis, "Fem::FemMeshObject") if not femutils.is_of_type(mesh, "Fem::FemMeshGmsh"): - self.report.error( - "Unsupported type of mesh. " - "Mesh must be created with gmsh.") + self.report.error("Unsupported type of mesh. Mesh must be created with gmsh.") self.fail() return False return True @@ -65,9 +63,7 @@ class Check(run.Check): def checkEquations(self): equations = self.solver.Group if not equations: - self.report.error( - "Solver has no equations. " - "Add at least one equation.") + self.report.error("Solver has no equations. Add at least one equation.") self.fail() @@ -77,14 +73,13 @@ class Prepare(run.Prepare): # TODO print working dir to report console self.pushStatus("Preparing input files...\n") num_cores = settings.get_cores("ElmerGrid") - self.pushStatus("Number of CPU cores to be used for the solver run: {}\n" - .format(num_cores)) + self.pushStatus(f"Number of CPU cores to be used for the solver run: {num_cores}\n") if self.testmode: # test mode: neither gmsh, nor elmergrid nor elmersolver binaries needed - FreeCAD.Console.PrintMessage("Machine testmode: {}\n".format(self.testmode)) + FreeCAD.Console.PrintMessage(f"Machine testmode: {self.testmode}\n") w = writer.Writer(self.solver, self.directory, True) else: - FreeCAD.Console.PrintLog("Machine testmode: {}\n".format(self.testmode)) + FreeCAD.Console.PrintLog(f"Machine testmode: {self.testmode}\n") w = writer.Writer(self.solver, self.directory) try: w.write_solver_input() @@ -93,7 +88,7 @@ class Prepare(run.Prepare): except writer.WriteError as e: self.report.error(str(e)) self.fail() - except IOError: + except OSError: self.report.error("Can't access working directory.") self.fail() @@ -124,11 +119,10 @@ class Solve(run.Solve): solvpath = os.path.split(binary)[0] if os.path.isdir(solvpath): os.environ["ELMER_HOME"] = solvpath - os.environ["LD_LIBRARY_PATH"] = "$LD_LIBRARY_PATH:{}/modules".format(solvpath) + os.environ["LD_LIBRARY_PATH"] = f"$LD_LIBRARY_PATH:{solvpath}/modules" # different call depending if with multithreading or not num_cores = settings.get_cores("ElmerSolver") - self.pushStatus("Number of CPU cores to be used for the solver run: {}\n" - .format(num_cores)) + self.pushStatus(f"Number of CPU cores to be used for the solver run: {num_cores}\n") args = [] if num_cores > 1: if system() != "Windows": @@ -143,14 +137,11 @@ class Solve(run.Solve): cwd=self.directory, stdout=subprocess.PIPE, stderr=subprocess.PIPE, - startupinfo=femutils.startProgramInfo("hide") + startupinfo=femutils.startProgramInfo("hide"), ) else: self._process = subprocess.Popen( - args, - cwd=self.directory, - stdout=subprocess.PIPE, - stderr=subprocess.PIPE + args, cwd=self.directory, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) self.signalAbort.add(self._process.terminate) output = self._observeSolver(self._process) @@ -172,7 +163,8 @@ class Solve(run.Solve): def _createOutput(self): self.solver.ElmerOutput = self.analysis.Document.addObject( - "App::TextDocument", self.solver.Name + "Output") + "App::TextDocument", self.solver.Name + "Output" + ) self.solver.ElmerOutput.Label = self.solver.Label + "Output" # App::TextDocument has no Attribute ReadOnly # TODO check if the attribute has been removed from App::TextDocument @@ -194,11 +186,7 @@ class Solve(run.Solve): FrequencyList = [] for line in OutputList: LineList = line.split(" ") - if ( - len(LineList) > 1 - and LineList[0] == "EigenSolve:" - and LineList[1] == "Computed" - ): + if len(LineList) > 1 and LineList[0] == "EigenSolve:" and LineList[1] == "Computed": # we found a result and take now the next LineList[2] lines modeCount = int(LineList[2]) modeNumber = modeCount @@ -219,9 +207,7 @@ class Solve(run.Solve): # now we can perform the calculation eigenFreq = cmath.sqrt(eigenFreq) / (2 * cmath.pi) # create an output line - FrequencyList.append( - "Mode {}: {} Hz".format(modeNumber - modeCount + 1, eigenFreq.real) - ) + FrequencyList.append(f"Mode {modeNumber - modeCount + 1}: {eigenFreq.real} Hz") modeCount = modeCount - 1 if modeNumber > 0: # push the results and append to output @@ -274,7 +260,8 @@ class Results(run.Results): def _createResults(self): self.solver.ElmerResult = self.analysis.Document.addObject( - "Fem::FemPostPipeline", self.solver.Name + "Result") + "Fem::FemPostPipeline", self.solver.Name + "Result" + ) self.solver.ElmerResult.Label = self.solver.ElmerResult.Name self.solver.ElmerResult.ViewObject.SelectionStyle = "BoundBox" self.analysis.addObject(self.solver.ElmerResult) @@ -290,7 +277,7 @@ class Results(run.Results): self.pushStatus("\nNo result file was created.\n") self.fail() return - pvdFile = open(pvdFilePath, "r") + pvdFile = open(pvdFilePath) # read all lines pvdContent = pvdFile.readlines() # skip header and footer line and evaluate all lines @@ -299,7 +286,7 @@ class Results(run.Results): # so .split("\"") gives as 2nd the time and as 7th the filename for i in range(0, len(pvdContent) - 2): # get time - lineArray = pvdContent[i + 1].split("\"") + lineArray = pvdContent[i + 1].split('"') time = float(lineArray[1]) filename = os.path.join(self.directory, lineArray[7]) if os.path.isfile(filename): @@ -317,7 +304,7 @@ class Results(run.Results): # but not the shape and bar coloring self.solver.ElmerTimeResults[i].ViewObject.updateColorBars() else: - self.pushStatus("\nResult file for time {} is missing.\n".format(time)) + self.pushStatus(f"\nResult file for time {time} is missing.\n") self.fail() return self.solver.Document.recompute() @@ -328,9 +315,7 @@ class Results(run.Results): # FreeCAD would replaces dots in object names with underscores, thus do the same newName = self.solver.Name + "_" + str(time).replace(".", "_") + "_" + "Result" if counter > len(self.solver.ElmerTimeResults): - pipeline = self.analysis.Document.addObject( - "Fem::FemPostPipeline", newName - ) + pipeline = self.analysis.Document.addObject("Fem::FemPostPipeline", newName) # App::PropertyLinkList does not support append # thus we have to use a temporary list to append tmplist = self.solver.ElmerTimeResults @@ -343,9 +328,7 @@ class Results(run.Results): # store current list before removing object since object removal will automatically # remove entry from self.solver.ElmerTimeResults tmplist = self.solver.ElmerTimeResults - self.analysis.Document.removeObject( - self.solver.ElmerTimeResults[counter - 1].Name - ) + self.analysis.Document.removeObject(self.solver.ElmerTimeResults[counter - 1].Name) tmplist[counter - 1] = self.analysis.Document.addObject( "Fem::FemPostPipeline", newName ) @@ -354,10 +337,7 @@ class Results(run.Results): def _finishTimeResults(self, time, counter): # we purposely use the decimal dot in the label - self.solver.ElmerTimeResults[counter].Label = ( - "{}_{}_Result" - .format(self.solver.Name, time) - ) + self.solver.ElmerTimeResults[counter].Label = f"{self.solver.Name}_{time}_Result" self.solver.ElmerTimeResults[counter].ViewObject.OnTopWhenSelected = True self.analysis.addObject(self.solver.ElmerTimeResults[counter]) # to assure the user sees something, set the default to Surface @@ -389,4 +369,5 @@ class Results(run.Results): self.fail() return postPath + ## @} diff --git a/src/Mod/Fem/femsolver/elmer/writer.py b/src/Mod/Fem/femsolver/elmer/writer.py index 0ba6c9fc21..fcf7b75c8f 100644 --- a/src/Mod/Fem/femsolver/elmer/writer.py +++ b/src/Mod/Fem/femsolver/elmer/writer.py @@ -63,25 +63,30 @@ _STARTINFO_NAME = "ELMERSOLVER_STARTINFO" _SIF_NAME = "case.sif" _ELMERGRID_IFORMAT = "8" _ELMERGRID_OFORMAT = "2" -_COORDS_NON_MAGNETO_2D = ["Polar 2D", "Polar 3D", "Cartesian 3D", - "Cylindric", "Cylindric Symmetric"] +_COORDS_NON_MAGNETO_2D = [ + "Polar 2D", + "Polar 3D", + "Cartesian 3D", + "Cylindric", + "Cylindric Symmetric", +] def _getAllSubObjects(obj): s = ["Solid" + str(i + 1) for i in range(len(obj.Shape.Solids))] - s.extend(("Face" + str(i + 1) for i in range(len(obj.Shape.Faces)))) - s.extend(("Edge" + str(i + 1) for i in range(len(obj.Shape.Edges)))) - s.extend(("Vertex" + str(i + 1) for i in range(len(obj.Shape.Vertexes)))) + s.extend("Face" + str(i + 1) for i in range(len(obj.Shape.Faces))) + s.extend("Edge" + str(i + 1) for i in range(len(obj.Shape.Edges))) + s.extend("Vertex" + str(i + 1) for i in range(len(obj.Shape.Vertexes))) return s -class Writer(object): +class Writer: def __init__(self, solver, directory, testmode=False): self.analysis = solver.getParentGroup() self.solver = solver self.directory = directory - Console.PrintMessage("Write elmer input files to: {}\n".format(self.directory)) + Console.PrintMessage(f"Write elmer input files to: {self.directory}\n") self.testmode = testmode self._usedVarNames = set() self._builder = sifio.Builder() @@ -184,8 +189,9 @@ class Writer(object): Console.PrintMessage( "Unit schema: {} not supported by Elmer writer. " "The FreeCAD standard unit schema mm/kg/s is used. " - "Elmer sif-file writing is done in Standard FreeCAD units.\n" - .format(Units.listSchemas(self.unit_schema)) + "Elmer sif-file writing is done in Standard FreeCAD units.\n".format( + Units.listSchemas(self.unit_schema) + ) ) def getFromUi(self, value, unit, outputDim): @@ -216,8 +222,7 @@ class Writer(object): self._exportToUnv(groups, mesh, unvPath) if self.testmode: Console.PrintMessage( - "Solver Elmer testmode, ElmerGrid will not be used. " - "It might not be installed.\n" + "Solver Elmer testmode, ElmerGrid will not be used. It might not be installed.\n" ) else: binary = settings.get_binary("ElmerGrid") @@ -226,29 +231,23 @@ class Writer(object): raise WriteError("Could not find ElmerGrid binary.") # for multithreading we first need a normal mesh creation run # then a second to split the mesh into the number of used cores - argsBasic = [binary, - _ELMERGRID_IFORMAT, - _ELMERGRID_OFORMAT, - unvPath] + argsBasic = [binary, _ELMERGRID_IFORMAT, _ELMERGRID_OFORMAT, unvPath] args = argsBasic args.extend(["-out", self.directory]) if system() == "Windows": subprocess.call( - args, - stdout=subprocess.DEVNULL, - startupinfo=femutils.startProgramInfo("hide") + args, stdout=subprocess.DEVNULL, startupinfo=femutils.startProgramInfo("hide") ) else: subprocess.call(args, stdout=subprocess.DEVNULL) if num_cores > 1: args = argsBasic - args.extend(["-partdual", "-metiskway", str(num_cores), - "-out", self.directory]) + args.extend(["-partdual", "-metiskway", str(num_cores), "-out", self.directory]) if system() == "Windows": subprocess.call( args, stdout=subprocess.DEVNULL, - startupinfo=femutils.startProgramInfo("hide") + startupinfo=femutils.startProgramInfo("hide"), ) else: subprocess.call(args, stdout=subprocess.DEVNULL) @@ -281,10 +280,10 @@ class Writer(object): tools.write_geo() if self.testmode: Console.PrintMessage( - "Solver Elmer testmode, Gmsh will not be used. " - "It might not be installed.\n" + "Solver Elmer testmode, Gmsh will not be used. It might not be installed.\n" ) import shutil + shutil.copyfile(geoPath, os.path.join(self.directory, "group_mesh.geo")) else: tools.get_gmsh_command() @@ -307,14 +306,13 @@ class Writer(object): permittivity = float(objs[0].VacuumPermittivity.getValueAs("F/m")) # since the base unit of FC is in mm, we must scale it to get plain SI permittivity = permittivity * 1e-9 - Console.PrintLog("Overwriting vacuum permittivity with: {}\n".format(permittivity)) + Console.PrintLog(f"Overwriting vacuum permittivity with: {permittivity}\n") self.constsdef["PermittivityOfVacuum"] = "{} {}".format(permittivity, "F/m") self.handled(objs[0]) elif len(objs) > 1: Console.PrintError( "More than one permittivity constant overwriting objects ({} objs). " - "The permittivity constant overwriting is ignored.\n" - .format(len(objs)) + "The permittivity constant overwriting is ignored.\n".format(len(objs)) ) def _handleSimulation(self): @@ -336,18 +334,9 @@ class Writer(object): self._simulation("Coordinate Scaling", 0.001) self._simulation("Simulation Type", self.solver.SimulationType) if self.solver.SimulationType == "Steady State": - self._simulation( - "Steady State Max Iterations", - self.solver.SteadyStateMaxIterations - ) - self._simulation( - "Steady State Min Iterations", - self.solver.SteadyStateMinIterations - ) - if ( - self.solver.SimulationType == "Scanning" - or self.solver.SimulationType == "Transient" - ): + self._simulation("Steady State Max Iterations", self.solver.SteadyStateMaxIterations) + self._simulation("Steady State Min Iterations", self.solver.SteadyStateMinIterations) + if self.solver.SimulationType == "Scanning" or self.solver.SimulationType == "Transient": self._simulation("BDF Order", self.solver.BDFOrder) self._simulation("Output Intervals", self.solver.OutputIntervals) self._simulation("Timestep Intervals", self.solver.TimestepIntervals) @@ -359,10 +348,7 @@ class Writer(object): # updates older simulations if not hasattr(self.solver, "CoordinateSystem"): solver.addProperty( - "App::PropertyEnumeration", - "CoordinateSystem", - "Coordinate System", - "" + "App::PropertyEnumeration", "CoordinateSystem", "Coordinate System", "" ) solver.CoordinateSystem = solverClass.COORDINATE_SYSTEM solver.CoordinateSystem = "Cartesian" @@ -371,32 +357,21 @@ class Writer(object): "App::PropertyIntegerConstraint", "BDFOrder", "Timestepping", - "Order of time stepping method 'BDF'" + "Order of time stepping method 'BDF'", ) solver.BDFOrder = (2, 1, 5, 1) if not hasattr(self.solver, "ElmerTimeResults"): - solver.addProperty( - "App::PropertyLinkList", - "ElmerTimeResults", - "Base", - "", - 4 | 8 - ) + solver.addProperty("App::PropertyLinkList", "ElmerTimeResults", "Base", "", 4 | 8) if not hasattr(self.solver, "OutputIntervals"): solver.addProperty( "App::PropertyIntegerList", "OutputIntervals", "Timestepping", - "After how many time steps a result file is output" + "After how many time steps a result file is output", ) solver.OutputIntervals = [1] if not hasattr(self.solver, "SimulationType"): - solver.addProperty( - "App::PropertyEnumeration", - "SimulationType", - "Type", - "" - ) + solver.addProperty("App::PropertyEnumeration", "SimulationType", "Type", "") solver.SimulationType = solverClass.SIMULATION_TYPE solver.SimulationType = "Steady State" if not hasattr(self.solver, "TimestepIntervals"): @@ -407,7 +382,7 @@ class Writer(object): ( "List of maximum optimization rounds if 'Simulation Type'\n" "is either 'Scanning' or 'Transient'" - ) + ), ) solver.TimestepIntervals = [100] if not hasattr(self.solver, "TimestepSizes"): @@ -418,7 +393,7 @@ class Writer(object): ( "List of time steps of optimization if 'Simulation Type'\n" "is either 'Scanning' or 'Transient'" - ) + ), ) solver.TimestepSizes = [0.1] @@ -622,8 +597,9 @@ class Writer(object): raise WriteError( "The coordinate setting '{}'\n is not " "supported by the equation 'Magnetodynamic2D'.\n\n" - "Possible is:\n'Cartesian 2D' or 'Axi Symmetric'" - .format(self.solver.CoordinateSystem) + "Possible is:\n'Cartesian 2D' or 'Axi Symmetric'".format( + self.solver.CoordinateSystem + ) ) solverSection = MgDyn2D.getMagnetodynamic2DSolver(equation) @@ -661,14 +637,14 @@ class Writer(object): "Disable the linear system.\n" "Only use for special cases\n" "and consult the Elmer docs." - ) + ), ) if not hasattr(equation, "IdrsParameter"): equation.addProperty( "App::PropertyIntegerConstraint", "IdrsParameter", "Linear System", - "Parameter for iterative method 'Idrs'" + "Parameter for iterative method 'Idrs'", ) equation.IdrsParameter = (2, 1, 10, 1) @@ -682,25 +658,17 @@ class Writer(object): if equation.LinearSystemSolverDisabled is True: s["Linear System Solver Disabled"] = equation.LinearSystemSolverDisabled if equation.LinearSolverType == "Direct": - s["Linear System Direct Method"] = \ - equation.LinearDirectMethod + s["Linear System Direct Method"] = equation.LinearDirectMethod elif equation.LinearSolverType == "Iterative": - s["Linear System Iterative Method"] = \ - equation.LinearIterativeMethod + s["Linear System Iterative Method"] = equation.LinearIterativeMethod if equation.LinearIterativeMethod == "BiCGStabl": - s["BiCGstabl polynomial degree"] = \ - equation.BiCGstablDegree + s["BiCGstabl polynomial degree"] = equation.BiCGstablDegree if equation.LinearIterativeMethod == "Idrs": - s["Idrs Parameter"] = \ - equation.IdrsParameter - s["Linear System Max Iterations"] = \ - equation.LinearIterations - s["Linear System Convergence Tolerance"] = \ - equation.LinearTolerance - s["Linear System Preconditioning"] = \ - equation.LinearPreconditioning - s["Steady State Convergence Tolerance"] = \ - equation.SteadyStateTolerance + s["Idrs Parameter"] = equation.IdrsParameter + s["Linear System Max Iterations"] = equation.LinearIterations + s["Linear System Convergence Tolerance"] = equation.LinearTolerance + s["Linear System Preconditioning"] = equation.LinearPreconditioning + s["Steady State Convergence Tolerance"] = equation.SteadyStateTolerance s["Linear System Abort Not Converged"] = False s["Linear System Residual Output"] = 1 s["Linear System Precondition Recompute"] = 1 @@ -711,8 +679,7 @@ class Writer(object): equation.setExpression("NonlinearTolerance", str(equation.NonlinearTolerance)) if self._hasExpression(equation) != equation.NonlinearNewtonAfterTolerance: equation.setExpression( - "NonlinearNewtonAfterTolerance", - str(equation.NonlinearNewtonAfterTolerance) + "NonlinearNewtonAfterTolerance", str(equation.NonlinearNewtonAfterTolerance) ) def createNonlinearSolver(self, equation): @@ -721,16 +688,11 @@ class Writer(object): # write the linear solver s = self.createLinearSolver(equation) # write the nonlinear solver - s["Nonlinear System Max Iterations"] = \ - equation.NonlinearIterations - s["Nonlinear System Convergence Tolerance"] = \ - equation.NonlinearTolerance - s["Nonlinear System Relaxation Factor"] = \ - equation.RelaxationFactor - s["Nonlinear System Newton After Iterations"] = \ - equation.NonlinearNewtonAfterIterations - s["Nonlinear System Newton After Tolerance"] = \ - equation.NonlinearNewtonAfterTolerance + s["Nonlinear System Max Iterations"] = equation.NonlinearIterations + s["Nonlinear System Convergence Tolerance"] = equation.NonlinearTolerance + s["Nonlinear System Relaxation Factor"] = equation.RelaxationFactor + s["Nonlinear System Newton After Iterations"] = equation.NonlinearNewtonAfterIterations + s["Nonlinear System Newton After Tolerance"] = equation.NonlinearNewtonAfterTolerance return s # ------------------------------------------------------------------------------------------- @@ -777,7 +739,7 @@ class Writer(object): return density def _hasExpression(self, equation): - for (obj, exp) in equation.ExpressionEngine: + for obj, exp in equation.ExpressionEngine: if obj == equation: return exp return None @@ -824,10 +786,7 @@ class Writer(object): # To get it back in the original size we let Elmer scale it back s["Coordinate Scaling Revert"] = True s["Equation"] = "ResultOutput" - if ( - self.solver.SimulationType == "Scanning" - or self.solver.SimulationType == "Transient" - ): + if self.solver.SimulationType == "Scanning" or self.solver.SimulationType == "Transient": # we must execute the post solver every time we output a result # therefore we must use the same as self.solver.OutputIntervals s["Exec Intervals"] = self.solver.OutputIntervals @@ -892,4 +851,5 @@ class Writer(object): class WriteError(Exception): pass + ## @} diff --git a/src/Mod/Fem/femsolver/equationbase.py b/src/Mod/Fem/femsolver/equationbase.py index d8a843fa01..478a904708 100644 --- a/src/Mod/Fem/femsolver/equationbase.py +++ b/src/Mod/Fem/femsolver/equationbase.py @@ -34,21 +34,19 @@ if FreeCAD.GuiUp: from pivy import coin -class BaseProxy(object): +class BaseProxy: BaseType = "App::FeaturePython" def __init__(self, obj): obj.Proxy = self - obj.addProperty( - "App::PropertyLinkSubList", "References", - "Base", "") + obj.addProperty("App::PropertyLinkSubList", "References", "Base", "") def execute(self, obj): return True -class BaseViewProxy(object): +class BaseViewProxy: def __init__(self, vobj): vobj.Proxy = self diff --git a/src/Mod/Fem/femsolver/fenics/fenics_tools.py b/src/Mod/Fem/femsolver/fenics/fenics_tools.py index 58ba15e369..13b09e7488 100644 --- a/src/Mod/Fem/femsolver/fenics/fenics_tools.py +++ b/src/Mod/Fem/femsolver/fenics/fenics_tools.py @@ -38,11 +38,12 @@ except ImportError: raise Exception("No Fenics modules found, please install them.\n") -class XDMFReader(object): +class XDMFReader: """ Reads XDMF file and provides unified interface for returning cell functions or facet functions. """ + def __init__(self, xdmffilename): """ Sets filename and sets mesh instance to None. @@ -69,12 +70,7 @@ class XDMFReader(object): xdmffile.close() def readCellExpression( - self, - group_value_dict, - value_type="scalar", - overlap=lambda x: x[0], - *args, - **kwargs + self, group_value_dict, value_type="scalar", overlap=lambda x: x[0], *args, **kwargs ): """ Reads cell expression and returns it. @@ -82,28 +78,19 @@ class XDMFReader(object): value_type_dictionary = { "scalar": ScalarCellExpressionFromXDMF, "vector2d": Vector2DCellExpressionFromXDMF, - "vector3d": Vector3DCellExpressionFromXDMF} + "vector3d": Vector3DCellExpressionFromXDMF, + } self.readMesh() xdmffile = fenics.XDMFFile(self.xdmffilename) cf = value_type_dictionary[value_type.lower()]( - group_value_dict, - overlap=overlap, - *args, **kwargs + group_value_dict, overlap=overlap, *args, **kwargs ) cf.init() - for (key, value) in cf.group_value_dict.items(): - cf.markers[key] = fenics.MeshFunction( - "size_t", - self.mesh, - self.mesh.topology().dim() - ) + for key, value in cf.group_value_dict.items(): + cf.markers[key] = fenics.MeshFunction("size_t", self.mesh, self.mesh.topology().dim()) xdmffile.read(cf.markers[key], key) - cf.dx[key] = fenics.Measure( - "dx", - domain=self.mesh, - subdomain_data=cf.markers[key] - ) + cf.dx[key] = fenics.Measure("dx", domain=self.mesh, subdomain_data=cf.markers[key]) xdmffile.close() return cf @@ -115,34 +102,30 @@ class XDMFReader(object): xdmffile = fenics.XDMFFile(self.xdmffilename) ff = FacetFunctionFromXDMF(group_value_dict, *args, **kwargs) ff.init() - for (key, value) in ff.group_value_dict.items(): + for key, value in ff.group_value_dict.items(): ff.markers[key] = fenics.MeshFunction( - "size_t", - self.mesh, - self.mesh.topology().dim() - 1 + "size_t", self.mesh, self.mesh.topology().dim() - 1 ) xdmffile.read(ff.markers[key], key) ff.marked[key] = value.get("marked", 1) - ff.ds[key] = fenics.Measure( - "ds", - domain=self.mesh, - subdomain_data=ff.markers[key] - ) + ff.ds[key] = fenics.Measure("ds", domain=self.mesh, subdomain_data=ff.markers[key]) ff.bcs[key] = value xdmffile.close() return ff -class CellExpressionFromXDMF(object): +class CellExpressionFromXDMF: """ Creates cell function expression from XDMF file. """ + def __init__( - self, group_value_dict, - default=lambda x: 0., + self, + group_value_dict, + default=lambda x: 0.0, check_marked=(lambda x: x == 1), overlap=lambda x: x[0], - **kwargs + **kwargs, ): self.init() self.group_value_dict = group_value_dict @@ -160,7 +143,8 @@ class CellExpressionFromXDMF(object): def eval_cell_backend(self, values, x, cell): values_list = [ - func(x) for (key, func) in self.group_value_dict.items() + func(x) + for (key, func) in self.group_value_dict.items() if self.check_marked(self.markers[key][cell.index]) ] return_value = self.overlap(values_list) @@ -183,16 +167,13 @@ class ScalarCellExpressionFromXDMF(fenics.Expression, CellExpressionFromXDMF): def __init__( self, group_value_dict, - default=lambda x: 0., + default=lambda x: 0.0, check_marked=(lambda x: x == 1), overlap=lambda x: x[0], - **kwargs + **kwargs, ): CellExpressionFromXDMF.__init__( - self, group_value_dict, - default=default, - check_marked=check_marked, - overlap=overlap + self, group_value_dict, default=default, check_marked=check_marked, overlap=overlap ) def eval_cell(self, values, x, cell): @@ -209,13 +190,11 @@ class Vector3DCellExpressionFromXDMF(fenics.Expression, CellExpressionFromXDMF): group_value_dict, default=lambda x: np.zeros((3,)), check_marked=(lambda x: x == 1), - overlap=lambda x: x[0], **kwargs + overlap=lambda x: x[0], + **kwargs, ): CellExpressionFromXDMF.__init__( - self, group_value_dict, - default=default, - check_marked=check_marked, - overlap=overlap + self, group_value_dict, default=default, check_marked=check_marked, overlap=overlap ) def eval_cell(self, values, x, cell): @@ -233,14 +212,10 @@ class Vector2DCellExpressionFromXDMF(fenics.Expression, CellExpressionFromXDMF): default=lambda x: np.zeros((2,)), check_marked=(lambda x: x == 1), overlap=lambda x: x[0], - **kwargs + **kwargs, ): CellExpressionFromXDMF.__init__( - self, - group_value_dict, - default=default, - check_marked=check_marked, - overlap=overlap + self, group_value_dict, default=default, check_marked=check_marked, overlap=overlap ) def eval_cell(self, values, x, cell): @@ -250,10 +225,11 @@ class Vector2DCellExpressionFromXDMF(fenics.Expression, CellExpressionFromXDMF): return (2,) -class FacetFunctionFromXDMF(object): +class FacetFunctionFromXDMF: """ Creates facet function from XDMF file. """ + def __init__(self, group_value_dict, *args, **kwargs): self.group_value_dict = group_value_dict self.init() @@ -266,18 +242,21 @@ class FacetFunctionFromXDMF(object): def getDirichletBCs(self, vectorspace, *args, **kwargs): dbcs = [] - for (dict_key, dict_value) in self.bcs.items(): + for dict_key, dict_value in self.bcs.items(): if dict_value["type"] == "Dirichlet": bc = fenics.DirichletBC( vectorspace, dict_value["value"], self.markers[dict_key], dict_value.get("marked", 1), - *args, **kwargs + *args, + **kwargs, ) dbcs.append(bc) return dbcs + # TODO: write some functions to return integrals for Neumann and Robin # boundary conditions for the general case (i.e. vector, tensor) + ## @} diff --git a/src/Mod/Fem/femsolver/mystran/add_con_fixed.py b/src/Mod/Fem/femsolver/mystran/add_con_fixed.py index 0b9c94da97..c705316e5d 100644 --- a/src/Mod/Fem/femsolver/mystran/add_con_fixed.py +++ b/src/Mod/Fem/femsolver/mystran/add_con_fixed.py @@ -41,22 +41,19 @@ def add_con_fixed(f, model, mystran_writer): spc_ids.append(conid) fixed_obj = femobj["Object"] # print(fixed_obj.Name) - fixed_code += "# {}\n".format(fixed_obj.Name) + fixed_code += f"# {fixed_obj.Name}\n" # node set fixed_code += "nodes_{} = {}\n".format(fixed_obj.Name, femobj["Nodes"]) # all nodes in one line may be to long ... FIXME - fixed_code += ( - "model.add_spc1(conid={}, components={}, nodes=nodes_{})\n\n" - .format(conid, "123456", fixed_obj.Name) + fixed_code += "model.add_spc1(conid={}, components={}, nodes=nodes_{})\n\n".format( + conid, "123456", fixed_obj.Name ) # spcadd card spcadd_code = "# spcadd card, Single-Point Constraint Set Combination from SPC or SPC1 cards\n" - spcadd_code += ( - "model.add_spcadd(conid=1, sets={})\n\n".format(spc_ids) - ) + spcadd_code += f"model.add_spcadd(conid=1, sets={spc_ids})\n\n" - pynas_code = "{}\n{}".format(fixed_code, spcadd_code) + pynas_code = f"{fixed_code}\n{spcadd_code}" # print(pynas_code) # write the pyNastran code diff --git a/src/Mod/Fem/femsolver/mystran/add_con_force.py b/src/Mod/Fem/femsolver/mystran/add_con_force.py index 20299cb99b..02a57ee498 100644 --- a/src/Mod/Fem/femsolver/mystran/add_con_force.py +++ b/src/Mod/Fem/femsolver/mystran/add_con_force.py @@ -44,28 +44,26 @@ def add_con_force(f, model, mystran_writer): force_obj = femobj["Object"] # print(force_obj.Name) - force_code += "# {}\n".format(force_obj.Name) + force_code += f"# {force_obj.Name}\n" dirvec = femobj["Object"].DirectionVector print(femobj["NodeLoadTable"]) for ref_shape in femobj["NodeLoadTable"]: - force_code += "# {}\n".format(ref_shape[0]) + force_code += f"# {ref_shape[0]}\n" for n in sorted(ref_shape[1]): # the loads in ref_shape[1][n] are without unit node_load = ref_shape[1][n] - force_code += ( - "model.add_force(sid={}, node={}, mag={}, xyz=({}, {}, {}))\n" - .format(sid, n, node_load, dirvec.x, dirvec.y, dirvec.z) + force_code += "model.add_force(sid={}, node={}, mag={}, xyz=({}, {}, {}))\n".format( + sid, n, node_load, dirvec.x, dirvec.y, dirvec.z ) force_code += "\n" # generate calce factors lists # load card, static load combinations - load_code = ( - "model.add_load(sid=1, scale=1.0, scale_factors={}, load_ids={})\n\n\n" - .format(scale_factors, load_ids) + load_code = "model.add_load(sid=1, scale=1.0, scale_factors={}, load_ids={})\n\n\n".format( + scale_factors, load_ids ) - pynas_code = "{}\n{}".format(force_code, load_code) + pynas_code = f"{force_code}\n{load_code}" # print(pynas_code) # write the pyNastran code diff --git a/src/Mod/Fem/femsolver/mystran/add_femelement_geometry.py b/src/Mod/Fem/femsolver/mystran/add_femelement_geometry.py index 7a21110aeb..654192a64a 100644 --- a/src/Mod/Fem/femsolver/mystran/add_femelement_geometry.py +++ b/src/Mod/Fem/femsolver/mystran/add_femelement_geometry.py @@ -40,13 +40,9 @@ def add_femelement_geometry(f, model, mystran_writer): width = beamsec_obj.RectWidth.getValueAs("mm").Value pynas_code = "# pbarl card, properties of a simple beam element (CBAR entry)\n" pynas_code += "# defined by cross-sectional dimensions\n" - pynas_code += ( - "dim = [{}, {}]\n" - .format(width, height) - ) - pynas_code += ( - "model.add_pbarl(pid=1, mid=1, Type={}, dim=dim, nsm=0.0)\n" - .format('"BAR"') + pynas_code += f"dim = [{width}, {height}]\n" + pynas_code += "model.add_pbarl(pid=1, mid=1, Type={}, dim=dim, nsm=0.0)\n".format( + '"BAR"' ) pynas_code += "# pbarl.validate()\n\n\n" else: @@ -56,9 +52,8 @@ def add_femelement_geometry(f, model, mystran_writer): shellth_obj = mystran_writer.member.geos_shellthickness[0]["Object"] thickness = shellth_obj.Thickness.getValueAs("mm").Value pynas_code = "# pshell card, thin shell element properties\n" - pynas_code += ( - "model.add_pshell(pid=1, mid1=1, t={}, mid2=1, mid3=1)\n\n\n" - .format(thickness) + pynas_code += "model.add_pshell(pid=1, mid1=1, t={}, mid2=1, mid3=1)\n\n\n".format( + thickness ) else: pynas_code = "# psolid card, defines solid element\n" diff --git a/src/Mod/Fem/femsolver/mystran/add_femelement_material.py b/src/Mod/Fem/femsolver/mystran/add_femelement_material.py index b384a565ba..84c05a7096 100644 --- a/src/Mod/Fem/femsolver/mystran/add_femelement_material.py +++ b/src/Mod/Fem/femsolver/mystran/add_femelement_material.py @@ -41,10 +41,7 @@ def add_femelement_material(f, model, mystran_writer): YM_in_MPa = YM.getValueAs("MPa").Value PR = float(mat_obj.Material["PoissonRatio"]) pynas_code = "# mat1 card, material properties for linear isotropic material\n" - pynas_code += ( - "mat = model.add_mat1(mid=1, E={:.1f}, G=None, nu={})\n\n\n" - .format(YM_in_MPa, PR) - ) + pynas_code += f"mat = model.add_mat1(mid=1, E={YM_in_MPa:.1f}, G=None, nu={PR})\n\n\n" # write the pyNastran code f.write(pynas_code) diff --git a/src/Mod/Fem/femsolver/mystran/add_mesh.py b/src/Mod/Fem/femsolver/mystran/add_mesh.py index 05a1cf361b..aa3b21f2f7 100644 --- a/src/Mod/Fem/femsolver/mystran/add_mesh.py +++ b/src/Mod/Fem/femsolver/mystran/add_mesh.py @@ -38,19 +38,14 @@ def add_mesh(f, model, mystran_writer): if not mystran_writer.femnodes_mesh: mystran_writer.femnodes_mesh = mystran_writer.femmesh.Nodes if not mystran_writer.femelement_table: - mystran_writer.femelement_table = meshtools.get_femelement_table( - mystran_writer.femmesh - ) + mystran_writer.femelement_table = meshtools.get_femelement_table(mystran_writer.femmesh) mesh_eletype = exportNastranMesh.get_export_element_type( - mystran_writer.femmesh, - mystran_writer.femelement_table + mystran_writer.femmesh, mystran_writer.femelement_table ) # get the pynas code mesh_pynas_code = exportNastranMesh.get_pynastran_mesh( - mystran_writer.femnodes_mesh, - mystran_writer.femelement_table, - mesh_eletype + mystran_writer.femnodes_mesh, mystran_writer.femelement_table, mesh_eletype ) # print(mesh_pynas_code) diff --git a/src/Mod/Fem/femsolver/mystran/solver.py b/src/Mod/Fem/femsolver/mystran/solver.py index 8f2739daee..c7fa364e97 100644 --- a/src/Mod/Fem/femsolver/mystran/solver.py +++ b/src/Mod/Fem/femsolver/mystran/solver.py @@ -45,18 +45,16 @@ ANALYSIS_TYPES = ["static"] def create(doc, name="SolverMystran"): - return femutils.createObject( - doc, name, Proxy, ViewProxy) + return femutils.createObject(doc, name, Proxy, ViewProxy) class Proxy(solverbase.Proxy): - """The Fem::FemSolver's Proxy python type, add solver specific properties - """ + """The Fem::FemSolver's Proxy python type, add solver specific properties""" Type = "Fem::SolverMystran" def __init__(self, obj): - super(Proxy, self).__init__(obj) + super().__init__(obj) obj.Proxy = self # mystran_prefs = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Fem/Mystran") @@ -67,19 +65,21 @@ class Proxy(solverbase.Proxy): def createMachine(self, obj, directory, testmode=False): return run.Machine( - solver=obj, directory=directory, + solver=obj, + directory=directory, check=tasks.Check(), prepare=tasks.Prepare(), solve=tasks.Solve(), results=tasks.Results(), - testmode=testmode) + testmode=testmode, + ) def editSupported(self): return True def edit(self, directory): pattern = os.path.join(directory, "*.bdf") # TODO Mystran file ending - FreeCAD.Console.PrintMessage("{}\n".format(pattern)) + FreeCAD.Console.PrintMessage(f"{pattern}\n") f = glob.glob(pattern)[0] FemGui.open(f) # see comment in oofem solver file @@ -93,4 +93,5 @@ class ViewProxy(solverbase.ViewProxy): def getIcon(self): return ":/icons/FEM_SolverMystran.svg" + ## @} diff --git a/src/Mod/Fem/femsolver/mystran/tasks.py b/src/Mod/Fem/femsolver/mystran/tasks.py index 1ef663ccf6..6298728e34 100644 --- a/src/Mod/Fem/femsolver/mystran/tasks.py +++ b/src/Mod/Fem/femsolver/mystran/tasks.py @@ -37,6 +37,7 @@ import FreeCAD try: import hfcMystranNeuIn + result_reading = True except Exception: FreeCAD.Console.PrintWarning("Module to read results not found.\n") @@ -120,7 +121,7 @@ class Solve(run.Solve): args=[binary, infile], # pass empty param fails! [binary, "", infile] cwd=self.directory, stdout=subprocess.PIPE, - stderr=subprocess.PIPE + stderr=subprocess.PIPE, ) self.signalAbort.add(self._process.terminate) self._process.communicate() @@ -132,8 +133,7 @@ class Solve(run.Solve): class Results(run.Results): def run(self): - prefs = FreeCAD.ParamGet( - "User parameter:BaseApp/Preferences/Mod/Fem/General") + prefs = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Fem/General") if not prefs.GetBool("KeepResultsOnReRun", False): self.purge_results() if result_reading is True: @@ -160,10 +160,8 @@ class Results(run.Results): break else: # TODO: use solver framework status message system - FreeCAD.Console.PrintError( - "FEM: No results found at {}!\n" - .format(neu_result_file) - ) + FreeCAD.Console.PrintError(f"FEM: No results found at {neu_result_file}!\n") self.fail() + ## @} diff --git a/src/Mod/Fem/femsolver/mystran/writer.py b/src/Mod/Fem/femsolver/mystran/writer.py index f8b242605b..4b819ef5fa 100644 --- a/src/Mod/Fem/femsolver/mystran/writer.py +++ b/src/Mod/Fem/femsolver/mystran/writer.py @@ -52,22 +52,10 @@ from .. import writerbase class FemInputWriterMystran(writerbase.FemInputWriter): def __init__( - self, - analysis_obj, - solver_obj, - mesh_obj, - member, - dir_name=None, - mat_geo_sets=None + self, analysis_obj, solver_obj, mesh_obj, member, dir_name=None, mat_geo_sets=None ): writerbase.FemInputWriter.__init__( - self, - analysis_obj, - solver_obj, - mesh_obj, - member, - dir_name, - mat_geo_sets + self, analysis_obj, solver_obj, mesh_obj, member, dir_name, mat_geo_sets ) # basename (only for implementation purpose later delete this code # the mesh should never be None for Calculix solver @@ -78,17 +66,14 @@ class FemInputWriterMystran(writerbase.FemInputWriter): self.basename = "Mesh" self.solverinput_file = join(self.dir_name, self.basename + ".bdf") self.pynasinput_file = join(self.dir_name, self.basename + ".py") - FreeCAD.Console.PrintLog( - "FemInputWriterMystran --> self.dir_name --> {}\n" - .format(self.dir_name) + FreeCAD.Console.PrintLog(f"FemInputWriterMystran --> self.dir_name --> {self.dir_name}\n") + FreeCAD.Console.PrintMessage( + "FemInputWriterMystra --> self.solverinput_file --> {}\n".format( + self.solverinput_file + ) ) FreeCAD.Console.PrintMessage( - "FemInputWriterMystra --> self.solverinput_file --> {}\n" - .format(self.solverinput_file) - ) - FreeCAD.Console.PrintMessage( - "FemInputWriterMystra --> self.pynasf_name --> {}\n" - .format(self.pynasinput_file) + f"FemInputWriterMystra --> self.pynasf_name --> {self.pynasinput_file}\n" ) def write_solver_input(self): @@ -112,8 +97,9 @@ class FemInputWriterMystran(writerbase.FemInputWriter): model = add_solver_control.add_solver_control(pynasf, model, self) pynasf.write( - "\n\nmodel.write_bdf('{}', enddata=True)\n" - .format(join(self.dir_name, self.basename + "_pyNas.bdf")) + "\n\nmodel.write_bdf('{}', enddata=True)\n".format( + join(self.dir_name, self.basename + "_pyNas.bdf") + ) ) pynasf.close() @@ -121,9 +107,8 @@ class FemInputWriterMystran(writerbase.FemInputWriter): # print(model.get_bdf_stats()) model.write_bdf(self.solverinput_file, enddata=True) - writing_time_string = ( - "Writing time input file: {} seconds" - .format(round((time.process_time() - timestart), 2)) + writing_time_string = "Writing time input file: {} seconds".format( + round((time.process_time() - timestart), 2) ) FreeCAD.Console.PrintMessage(writing_time_string + " \n\n") diff --git a/src/Mod/Fem/femsolver/report.py b/src/Mod/Fem/femsolver/report.py index ce0d5100a8..1a6d90f4ed 100644 --- a/src/Mod/Fem/femsolver/report.py +++ b/src/Mod/Fem/femsolver/report.py @@ -46,10 +46,10 @@ def display(report, title=None, text=None): def displayGui(report, title=None, text=None): import FreeCADGui as Gui from . import reportdialog + if not report.isEmpty(): mw = Gui.getMainWindow() - dialog = reportdialog.ReportDialog( - report, title, text, mw) + dialog = reportdialog.ReportDialog(report, title, text, mw) dialog.exec_() @@ -62,7 +62,7 @@ def displayLog(report): App.Console.PrintError("%s\n" % e) -class Report(object): +class Report: def __init__(self): self.infos = [] @@ -95,4 +95,5 @@ class Report(object): def error(self, msg): self.errors.append(msg) + ## @} diff --git a/src/Mod/Fem/femsolver/reportdialog.py b/src/Mod/Fem/femsolver/reportdialog.py index 0315867540..3e1b807258 100644 --- a/src/Mod/Fem/femsolver/reportdialog.py +++ b/src/Mod/Fem/femsolver/reportdialog.py @@ -42,7 +42,7 @@ INFO_COLOR = "Logging" class ReportDialog(QtGui.QDialog): def __init__(self, report, title="Report", text=None, parent=None): - super(ReportDialog, self).__init__(parent) + super().__init__(parent) msgDetails = QtGui.QTextEdit() msgDetails.setReadOnly(True) msgDetails.setHtml(self._getText(report)) @@ -73,8 +73,7 @@ class ReportDialog(QtGui.QDialog): return text def _getColoredLine(self, text, outputwin_color_type): - return '{}'.format( - getOutputWinColor(outputwin_color_type), text - ) + return f'{text}' + ## @} diff --git a/src/Mod/Fem/femsolver/run.py b/src/Mod/Fem/femsolver/run.py index 432f428e76..1678f52ced 100644 --- a/src/Mod/Fem/femsolver/run.py +++ b/src/Mod/Fem/femsolver/run.py @@ -40,6 +40,7 @@ import os import os.path import shutil import tempfile + # import threading # not used ATM import FreeCAD as App @@ -69,7 +70,7 @@ _dirTypes = {} def run_fem_solver(solver, working_dir=None): - """ Execute *solver* of the solver framework. + """Execute *solver* of the solver framework. Uses :meth:`getMachine ` to obtain a :class:`Machine` instance of the solver. It than executes the Machine with @@ -101,6 +102,7 @@ def run_fem_solver(solver, working_dir=None): if solver.Proxy.Type == "Fem::SolverCcxTools": from femtools.ccxtools import CcxTools as ccx + App.Console.PrintMessage("Run of CalxuliX ccx tools solver started.\n") fea = ccx(solver) fea.reset_mesh_purge_results_checked() @@ -117,7 +119,7 @@ def run_fem_solver(solver, working_dir=None): fea.ccx_run() fea.load_results() else: - App.Console.PrintError("Houston, we have a problem...!\n{}\n".format(message)) + App.Console.PrintError(f"Houston, we have a problem...!\n{message}\n") App.Console.PrintMessage("Run of CalxuliX ccx tools solver finished.\n") else: # App.Console.PrintMessage("Frame work solver!\n") @@ -130,14 +132,12 @@ def run_fem_solver(solver, working_dir=None): error_message = ( "Please save the file before executing the solver. " "This must be done because the location of the working " - "directory is set to \"Beside *.FCStd File\"." + 'directory is set to "Beside *.FCStd File".' ) App.Console.PrintError(error_message + "\n") if App.GuiUp: QtGui.QMessageBox.critical( - FreeCADGui.getMainWindow(), - "Can't start Solver", - error_message + FreeCADGui.getMainWindow(), "Can't start Solver", error_message ) return except DirectoryDoesNotExistError: @@ -145,9 +145,7 @@ def run_fem_solver(solver, working_dir=None): App.Console.PrintError(error_message + "\n") if App.GuiUp: QtGui.QMessageBox.critical( - FreeCADGui.getMainWindow(), - "Can't start Solver", - error_message + FreeCADGui.getMainWindow(), "Can't start Solver", error_message ) return if not machine.running: @@ -158,6 +156,7 @@ def run_fem_solver(solver, working_dir=None): if machine.failed is True: App.Console.PrintError("Machine failed to run.\n") from .report import displayLog + displayLog(machine.report) if App.GuiUp: error_message = ( @@ -165,11 +164,12 @@ def run_fem_solver(solver, working_dir=None): "of the following errors are resolved." ) from .report import display + display(machine.report, "Run Report", error_message) def getMachine(solver, path=None): - """ Get or create :class:`Machine` using caching mechanism. + """Get or create :class:`Machine` using caching mechanism. :param solver: A document object which must be a framework compliant solver. This means @@ -257,14 +257,12 @@ def _getBesideBase(solver): error_message = ( "Please save the file before executing the solver. " "This must be done because the location of the working " - "directory is set to \"Beside *.FCStd File\"." + 'directory is set to "Beside *.FCStd File".' ) App.Console.PrintError(error_message + "\n") if App.GuiUp: QtGui.QMessageBox.critical( - FreeCADGui.getMainWindow(), - "Can't start Solver", - error_message + FreeCADGui.getMainWindow(), "Can't start Solver", error_message ) raise MustSaveError() # TODO may be do not abort but use a temporary directory @@ -273,8 +271,7 @@ def _getBesideBase(solver): def _getCustomDir(solver): base = _getCustomBase(solver) - specificPath = os.path.join( - base, solver.Document.Name, solver.Label) + specificPath = os.path.join(base, solver.Document.Name, solver.Label) specificPath = _getUniquePath(specificPath) if not os.path.isdir(specificPath): os.makedirs(specificPath) @@ -288,9 +285,7 @@ def _getCustomBase(solver): App.Console.PrintError(error_message + "\n") if App.GuiUp: QtGui.QMessageBox.critical( - FreeCADGui.getMainWindow(), - "Can't start Solver", - error_message + FreeCADGui.getMainWindow(), "Can't start Solver", error_message ) raise DirectoryDoesNotExistError("Invalid path") return path @@ -309,7 +304,7 @@ def _getUniquePath(path): class BaseTask(task.Thread): def __init__(self): - super(BaseTask, self).__init__() + super().__init__() self.solver = None self.directory = None self.testmode = None @@ -321,10 +316,8 @@ class BaseTask(task.Thread): class Machine(BaseTask): - def __init__( - self, solver, directory, check, - prepare, solve, results, testmode): - super(Machine, self).__init__() + def __init__(self, solver, directory, check, prepare, solve, results, testmode): + super().__init__() self.solver = solver self.directory = directory self.signalState = set() @@ -346,11 +339,7 @@ class Machine(BaseTask): self._confTasks() self._isReset = False self._pendingState = self.state - while ( - not self.aborted - and not self.failed - and self._pendingState <= self.target - ): + while not self.aborted and not self.failed and self._pendingState <= self.target: task = self._getTask(self._pendingState) self._runTask(task) self.report.extend(task.report) @@ -363,21 +352,14 @@ class Machine(BaseTask): self._applyPending() def reset(self, newState=CHECK): - state = (self.state - if self._pendingState is None - else self._pendingState) + state = self.state if self._pendingState is None else self._pendingState if newState < state: self._isReset = True self._state = newState signal.notify(self.signalState) def _confTasks(self): - tasks = [ - self.check, - self.prepare, - self.solve, - self.results - ] + tasks = [self.check, self.prepare, self.solve, self.results] for t in tasks: t.solver = self.solver t.directory = self.directory @@ -397,6 +379,7 @@ class Machine(BaseTask): def killer(): task.abort() + self.signalAbort.add(killer) task.signalStatus.add(statusProxy) task.start() @@ -428,10 +411,7 @@ class Check(BaseTask): self.fail() return False elif len(meshes) > 1: - self.report.error( - "Too many meshes. " - "More than one mesh is not supported." - ) + self.report.error("Too many meshes. More than one mesh is not supported.") self.fail() return False return True @@ -439,10 +419,7 @@ class Check(BaseTask): def check_material_exists(self): objs = self.get_several_member("App::MaterialObjectPython") if len(objs) == 0: - self.report.error( - "Missing a material object. " - "At least one material is required." - ) + self.report.error("Missing a material object. At least one material is required.") self.fail() return False return True @@ -507,10 +484,7 @@ class Check(BaseTask): if femutils.is_of_type(m, *sc): supported = True if not supported: - self.report.warning( - "Ignored unsupported constraint: {}" - .format(m.Label) - ) + self.report.warning(f"Ignored unsupported constraint: {m.Label}") return True @@ -538,7 +512,7 @@ class Results(BaseTask): pass -class _DocObserver(object): +class _DocObserver: _instance = None _WHITELIST = [ @@ -546,11 +520,7 @@ class _DocObserver(object): "App::MaterialObject", "Fem::FemMeshObject", ] - _BLACKLIST_PROPS = [ - "Label", - "ElmerOutput", - "ElmerResult" - ] + _BLACKLIST_PROPS = ["Label", "ElmerOutput", "ElmerResult"] def __init__(self): self._saved = {} diff --git a/src/Mod/Fem/femsolver/settings.py b/src/Mod/Fem/femsolver/settings.py index 028c338575..57d9319a33 100644 --- a/src/Mod/Fem/femsolver/settings.py +++ b/src/Mod/Fem/femsolver/settings.py @@ -51,7 +51,7 @@ import FreeCAD class DirSetting: - """ Enum of possible directory setting values. + """Enum of possible directory setting values. Strings used to indicate the solver directory setting set in FreeCADs setting system. Returned by :func:`get_dir_setting` for that purpose. There @@ -71,6 +71,7 @@ class DirSetting: Use directory set below. Create own subdirectory for every solver. Name directory after the solver label prefixed with the document name. """ + TEMPORARY = "temporary" BESIDE = "beside" CUSTOM = "custom" @@ -82,7 +83,7 @@ _GENERAL_PARAM = _PARAM_PATH + "General" def get_binary(name, silent=False): - """ Find binary of solver *name* honoring user settings. + """Find binary of solver *name* honoring user settings. Return the specific path set by the user in FreeCADs settings/parameter system if set or the default binary name if no specific path is set. If no @@ -101,14 +102,13 @@ def get_binary(name, silent=False): if not silent: FreeCAD.Console.PrintError( "Settings solver name: {} not found in " - "solver settings modules _SOLVER_PARAM dirctionary.\n" - .format(name) + "solver settings modules _SOLVER_PARAM dirctionary.\n".format(name) ) return None def get_cores(name): - """ Read number of CPU cores for solver *name* honoring user settings. + """Read number of CPU cores for solver *name* honoring user settings. Returns number of CPU cores to be used for the solver run @@ -120,14 +120,13 @@ def get_cores(name): else: FreeCAD.Console.PrintError( "Settings solver name: {} not found in " - "solver settings modules _SOLVER_PARAM dirctionary.\n" - .format(name) + "solver settings modules _SOLVER_PARAM dirctionary.\n".format(name) ) return None def get_write_comments(name): - """ Check whether "write_comments" is set for solver. + """Check whether "write_comments" is set for solver. Returns ``True`` if the "write_comments" setting/parameter is set for the solver with the id *name*. Returns ``False`` otherwise. If the solver is @@ -140,20 +139,19 @@ def get_write_comments(name): else: FreeCAD.Console.PrintError( "Settings solver name: {} not found in " - "solver settings modules _SOLVER_PARAM dirctionary.\n" - .format(name) + "solver settings modules _SOLVER_PARAM dirctionary.\n".format(name) ) return None def get_custom_dir(): - """ Get value for :term:`General/CustomDirectoryPath` parameter. """ + """Get value for :term:`General/CustomDirectoryPath` parameter.""" param_group = FreeCAD.ParamGet(_GENERAL_PARAM) return param_group.GetString("CustomDirectoryPath") def get_dir_setting(): - """ Return directory setting set by the user. + """Return directory setting set by the user. Return one of the three possible values of the :class:`DirSetting` enum depending on the setting set in FreeCAD parameter system. Result dependes @@ -169,8 +167,7 @@ def get_dir_setting(): def get_default_solver(): - """ Return default solver name. - """ + """Return default solver name.""" solver_map = {0: "None"} if get_binary("Calculix", True): solver_map[1] = "CalculiXCcxTools" @@ -184,8 +181,8 @@ def get_default_solver(): return solver_map[param_group.GetInt("DefaultSolver", 0)] -class _SolverDlg(object): - """ Internal query logic for solver specific settings. +class _SolverDlg: + """Internal query logic for solver specific settings. Each instance queries settings for one specific solver (e.g. Elmer) common among all solvers. To clarify: There are a few settings that are useful @@ -233,26 +230,26 @@ class _SolverDlg(object): # without any additional user input # see ccxttols, it works for Windows and Linux there binary = self.default - FreeCAD.Console.PrintLog("Solver binary path default: {} \n".format(binary)) + FreeCAD.Console.PrintLog(f"Solver binary path default: {binary} \n") # check if use_default is set to True # if True the standard binary path will be overwritten with a user binary path if self.param_group.GetBool(self.use_default, True) is False: binary = self.param_group.GetString(self.custom_path) - FreeCAD.Console.PrintLog("Solver binary path user setting: {} \n".format(binary)) + FreeCAD.Console.PrintLog(f"Solver binary path user setting: {binary} \n") # get the whole binary path name for the given command or binary path and return it # None is returned if the binary has not been found # The user does not know what exactly has going wrong. from shutil import which as find_bin + the_found_binary = find_bin(binary) if (the_found_binary is None) and (not silent): FreeCAD.Console.PrintError( - "The binary has not been found. Full binary search path: {}\n" - .format(binary) + f"The binary has not been found. Full binary search path: {binary}\n" ) else: - FreeCAD.Console.PrintLog("Found solver binary path: {}\n".format(the_found_binary)) + FreeCAD.Console.PrintLog(f"Found solver binary path: {the_found_binary}\n") return the_found_binary def get_cores(self): @@ -268,25 +265,30 @@ _SOLVER_PARAM = { default="ccx", param_path=_PARAM_PATH + "Ccx", use_default="UseStandardCcxLocation", - custom_path="ccxBinaryPath"), + custom_path="ccxBinaryPath", + ), "ElmerSolver": _SolverDlg( default="ElmerSolver", param_path=_PARAM_PATH + "Elmer", use_default="UseStandardElmerLocation", - custom_path="elmerBinaryPath"), + custom_path="elmerBinaryPath", + ), "ElmerGrid": _SolverDlg( default="ElmerGrid", param_path=_PARAM_PATH + "Elmer", use_default="UseStandardGridLocation", - custom_path="gridBinaryPath"), + custom_path="gridBinaryPath", + ), "Mystran": _SolverDlg( default="mystran", param_path=_PARAM_PATH + "Mystran", use_default="UseStandardMystranLocation", - custom_path="mystranBinaryPath"), + custom_path="mystranBinaryPath", + ), "Z88": _SolverDlg( default="z88r", param_path=_PARAM_PATH + "Z88", use_default="UseStandardZ88Location", - custom_path="z88BinaryPath"), + custom_path="z88BinaryPath", + ), } diff --git a/src/Mod/Fem/femsolver/signal.py b/src/Mod/Fem/femsolver/signal.py index 2552c1cab8..991f65c6d6 100644 --- a/src/Mod/Fem/femsolver/signal.py +++ b/src/Mod/Fem/femsolver/signal.py @@ -33,4 +33,5 @@ def notify(signal, *args): for slot in signal: slot(*args) + ## @} diff --git a/src/Mod/Fem/femsolver/solver_taskpanel.py b/src/Mod/Fem/femsolver/solver_taskpanel.py index 5d3817bef8..be6968636e 100644 --- a/src/Mod/Fem/femsolver/solver_taskpanel.py +++ b/src/Mod/Fem/femsolver/solver_taskpanel.py @@ -39,10 +39,7 @@ import femsolver.run _UPDATE_INTERVAL = 50 _REPORT_TITLE = "Run Report" -_REPORT_ERR = ( - "Failed to run. Please try again after all " - "of the following errors are resolved." -) +_REPORT_ERR = "Failed to run. Please try again after all of the following errors are resolved." class ControlTaskPanel(QtCore.QObject): @@ -56,7 +53,7 @@ class ControlTaskPanel(QtCore.QObject): machineStateChanged = QtCore.Signal(float) def __init__(self, machine): - super(ControlTaskPanel, self).__init__() + super().__init__() self.form = ControlWidget() self._machine = None @@ -89,14 +86,12 @@ class ControlTaskPanel(QtCore.QObject): self.machineStatusChanged.connect(self.form.appendStatus) self.machineStatusCleared.connect(self.form.clearStatus) self.machineTimeChanged.connect(self.form.setTime) - self.machineStateChanged.connect( - lambda: self.form.updateState(self.machine)) + self.machineStateChanged.connect(lambda: self.form.updateState(self.machine)) self.machineChanged.connect(self._updateTimer) # Set initial machine. Signal updates the widget. self.machineChanged.connect(self.updateWidget) - self.form.destroyed.connect( - lambda: self.machineChanged.disconnect(self.updateWidget)) + self.form.destroyed.connect(lambda: self.machineChanged.disconnect(self.updateWidget)) self.machine = machine @@ -125,8 +120,7 @@ class ControlTaskPanel(QtCore.QObject): @QtCore.Slot() def edit(self): self.machine.reset(femsolver.run.SOLVE) - self.machine.solver.Proxy.edit( - self.machine.directory) + self.machine.solver.Proxy.edit(self.machine.directory) @QtCore.Slot() def abort(self): @@ -142,8 +136,7 @@ class ControlTaskPanel(QtCore.QObject): @QtCore.Slot() def updateMachine(self): if self.form.directory() != self.machine.directory: - self.machine = femsolver.run.getMachine( - self.machine.solver, self.form.directory()) + self.machine = femsolver.run.getMachine(self.machine.solver, self.form.directory()) @QtCore.Slot() def _updateTimer(self): @@ -207,7 +200,7 @@ class ControlWidget(QtGui.QWidget): directoryChanged = QtCore.Signal() def __init__(self, parent=None): - super(ControlWidget, self).__init__(parent) + super().__init__(parent) self._setupUi() self._inputFileName = "" @@ -339,8 +332,8 @@ class ControlWidget(QtGui.QWidget): self._directoryGrp.setDisabled(False) self._writeBtt.setDisabled(False) self._editBtt.setDisabled( - not machine.solver.Proxy.editSupported() - or machine.state <= femsolver.run.PREPARE + not machine.solver.Proxy.editSupported() or machine.state <= femsolver.run.PREPARE ) + ## @} diff --git a/src/Mod/Fem/femsolver/solverbase.py b/src/Mod/Fem/femsolver/solverbase.py index 1623d5a745..2b84222966 100644 --- a/src/Mod/Fem/femsolver/solverbase.py +++ b/src/Mod/Fem/femsolver/solverbase.py @@ -42,7 +42,7 @@ if App.GuiUp: from . import solver_taskpanel -class Proxy(object): +class Proxy: BaseType = "Fem::FemSolverObjectPython" @@ -60,8 +60,7 @@ class Proxy(object): raise NotImplementedError() def addEquation(self, obj, eqId): - obj.addObject(self.createEquation( - obj.Document, eqId)) + obj.addObject(self.createEquation(obj.Document, eqId)) def editSupported(self): return False @@ -73,7 +72,7 @@ class Proxy(object): return True -class ViewProxy(object): +class ViewProxy: """Proxy for FemSolverElmers View Provider.""" def __init__(self, vobj): @@ -87,23 +86,15 @@ class ViewProxy(object): error_message = ( "Please save the file before opening the task panel. " "This must be done because the location of the working " - "directory is set to \"Beside *.FCStd File\"." + 'directory is set to "Beside *.FCStd File".' ) App.Console.PrintError(error_message + "\n") - QtGui.QMessageBox.critical( - Gui.getMainWindow(), - "Can't open Task Panel", - error_message - ) + QtGui.QMessageBox.critical(Gui.getMainWindow(), "Can't open Task Panel", error_message) return False except DirectoryDoesNotExistError: error_message = "Selected working directory doesn't exist." App.Console.PrintError(error_message + "\n") - QtGui.QMessageBox.critical( - Gui.getMainWindow(), - "Can't open Task Panel", - error_message - ) + QtGui.QMessageBox.critical(Gui.getMainWindow(), "Can't open Task Panel", error_message) return False task = solver_taskpanel.ControlTaskPanel(machine) Gui.Control.showDialog(task) @@ -121,4 +112,5 @@ class ViewProxy(object): def attach(self, vobj): pass + ## @} diff --git a/src/Mod/Fem/femsolver/task.py b/src/Mod/Fem/femsolver/task.py index d1829bf2ef..3343c28324 100644 --- a/src/Mod/Fem/femsolver/task.py +++ b/src/Mod/Fem/femsolver/task.py @@ -36,7 +36,7 @@ from . import report from . import signal -class Task(object): +class Task: def __init__(self): self.report = None @@ -57,15 +57,13 @@ class Task(object): def stopping(): self.stopTime = time.time() self.running = False + self.signalStopping.add(stopping) @property def time(self): if self.startTime is not None: - endTime = ( - self.stopTime - if self.stopTime is not None - else time.time()) + endTime = self.stopTime if self.stopTime is not None else time.time() return endTime - self.startTime return None @@ -124,13 +122,12 @@ class Task(object): class Thread(Task): def __init__(self): - super(Thread, self).__init__() + super().__init__() self._thread = None def start(self): - super(Thread, self).start() - self._thread = threading.Thread( - target=self.protector) + super().start() + self._thread = threading.Thread(target=self.protector) self._thread.daemon = True self._thread.start() self._attachObserver() @@ -144,8 +141,10 @@ class Thread(Task): self._thread.join() signal.notify(self.signalStopping) signal.notify(self.signalStopped) + thread = threading.Thread(target=waitForStop) thread.daemon = True thread.start() + ## @} diff --git a/src/Mod/Fem/femsolver/writerbase.py b/src/Mod/Fem/femsolver/writerbase.py index e440877d94..f480b1f78c 100644 --- a/src/Mod/Fem/femsolver/writerbase.py +++ b/src/Mod/Fem/femsolver/writerbase.py @@ -36,15 +36,9 @@ import FreeCAD from femmesh import meshsetsgetter -class FemInputWriter(): +class FemInputWriter: def __init__( - self, - analysis_obj, - solver_obj, - mesh_obj, - member, - dir_name=None, - mat_geo_sets=None + self, analysis_obj, solver_obj, mesh_obj, member, dir_name=None, mat_geo_sets=None ): # class attributes from parameter values self.analysis = analysis_obj @@ -73,10 +67,10 @@ class FemInputWriter(): make_tmp_dir = True if make_tmp_dir is True: from tempfile import mkdtemp + dir_name = mkdtemp(prefix="fcfem_") FreeCAD.Console.PrintWarning( - "The working directory '{}' was created and will be used." - .format(dir_name) + f"The working directory '{dir_name}' was created and will be used." ) self.dir_name = dir_name @@ -147,12 +141,7 @@ class FemInputWriter(): # ******************************************************************************************** # generic writer for constraints mesh sets and constraints property data # write constraint node sets, constraint face sets, constraint element sets - def write_constraints_meshsets( - self, - f, - femobjs, - con_module - ): + def write_constraints_meshsets(self, f, femobjs, con_module): if not femobjs: return @@ -166,7 +155,7 @@ class FemInputWriter(): for femobj in femobjs: # femobj --> dict, FreeCAD document object is femobj["Object"] the_obj = femobj["Object"] - the_file.write("** {}\n".format(the_obj.Label)) + the_file.write(f"** {the_obj.Label}\n") con_module.write_meshdata_constraint(the_file, femobj, the_obj, self) if write_after != "": the_file.write(write_after) @@ -180,8 +169,8 @@ class FemInputWriter(): f.write("** {}\n".format(write_name.replace("_", " "))) if self.split_inpfile is True: - file_name_split = "{}_{}.inp".format(self.mesh_name, write_name) - f.write("*INCLUDE,INPUT={}\n".format(file_name_split)) + file_name_split = f"{self.mesh_name}_{write_name}.inp" + f.write(f"*INCLUDE,INPUT={file_name_split}\n") inpfile_split = open(join(self.dir_name, file_name_split), "w") constraint_sets_loop_writing(inpfile_split, femobjs, write_before, write_after) inpfile_split.close() @@ -189,12 +178,7 @@ class FemInputWriter(): constraint_sets_loop_writing(f, femobjs, write_before, write_after) # write constraint property data - def write_constraints_propdata( - self, - f, - femobjs, - con_module - ): + def write_constraints_propdata(self, f, femobjs, con_module): if not femobjs: return @@ -208,13 +192,13 @@ class FemInputWriter(): # write constraint to file f.write("\n{}\n".format(59 * "*")) - f.write("** {}\n".format(con_module.get_constraint_title())) + f.write(f"** {con_module.get_constraint_title()}\n") if write_before != "": f.write(write_before) for femobj in femobjs: # femobj --> dict, FreeCAD document object is femobj["Object"] the_obj = femobj["Object"] - f.write("** {}\n".format(the_obj.Label)) + f.write(f"** {the_obj.Label}\n") con_module.write_constraint(f, femobj, the_obj, self) if write_after != "": f.write(write_after) diff --git a/src/Mod/Fem/femsolver/z88/solver.py b/src/Mod/Fem/femsolver/z88/solver.py index 1b4235857a..0129b35ee6 100644 --- a/src/Mod/Fem/femsolver/z88/solver.py +++ b/src/Mod/Fem/femsolver/z88/solver.py @@ -45,18 +45,16 @@ ANALYSIS_TYPES = ["static"] def create(doc, name="SolverZ88"): - return femutils.createObject( - doc, name, Proxy, ViewProxy) + return femutils.createObject(doc, name, Proxy, ViewProxy) class Proxy(solverbase.Proxy): - """The Fem::FemSolver's Proxy python type, add solver specific properties - """ + """The Fem::FemSolver's Proxy python type, add solver specific properties""" Type = "Fem::SolverZ88" def __init__(self, obj): - super(Proxy, self).__init__(obj) + super().__init__(obj) obj.Proxy = self # z88_prefs = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Fem/Z88") @@ -67,39 +65,41 @@ class Proxy(solverbase.Proxy): def createMachine(self, obj, directory, testmode=False): return run.Machine( - solver=obj, directory=directory, + solver=obj, + directory=directory, check=tasks.Check(), prepare=tasks.Prepare(), solve=tasks.Solve(), results=tasks.Results(), - testmode=testmode) + testmode=testmode, + ) def editSupported(self): return True def edit(self, directory): pattern = os.path.join(directory, "z88i1.txt") - FreeCAD.Console.PrintMessage("{}\n".format(pattern)) + FreeCAD.Console.PrintMessage(f"{pattern}\n") f = glob.glob(pattern)[0] FemGui.open(f) pattern = os.path.join(directory, "z88i2.txt") - FreeCAD.Console.PrintMessage("{}\n".format(pattern)) + FreeCAD.Console.PrintMessage(f"{pattern}\n") f = glob.glob(pattern)[0] FemGui.open(f) pattern = os.path.join(directory, "z88i5.txt") - FreeCAD.Console.PrintMessage("{}\n".format(pattern)) + FreeCAD.Console.PrintMessage(f"{pattern}\n") f = glob.glob(pattern)[0] FemGui.open(f) pattern = os.path.join(directory, "z88man.txt") - FreeCAD.Console.PrintMessage("{}\n".format(pattern)) + FreeCAD.Console.PrintMessage(f"{pattern}\n") f = glob.glob(pattern)[0] FemGui.open(f) pattern = os.path.join(directory, "z88mat.txt") - FreeCAD.Console.PrintMessage("{}\n".format(pattern)) + FreeCAD.Console.PrintMessage(f"{pattern}\n") f = glob.glob(pattern)[0] FemGui.open(f) pattern = os.path.join(directory, "z88elp.txt") - FreeCAD.Console.PrintMessage("{}\n".format(pattern)) + FreeCAD.Console.PrintMessage(f"{pattern}\n") f = glob.glob(pattern)[0] FemGui.open(f) @@ -112,4 +112,5 @@ class ViewProxy(solverbase.ViewProxy): def getIcon(self): return ":/icons/FEM_SolverZ88.svg" + ## @} diff --git a/src/Mod/Fem/femsolver/z88/tasks.py b/src/Mod/Fem/femsolver/z88/tasks.py index 38b0a09d0e..0deeb254ab 100644 --- a/src/Mod/Fem/femsolver/z88/tasks.py +++ b/src/Mod/Fem/femsolver/z88/tasks.py @@ -76,11 +76,7 @@ class Prepare(run.Prepare): # write solver input w = writer.FemInputWriterZ88( - self.analysis, - self.solver, - mesh_obj, - meshdatagetter.member, - self.directory + self.analysis, self.solver, mesh_obj, meshdatagetter.member, self.directory ) path = w.write_solver_input() # report to user if task succeeded @@ -111,7 +107,7 @@ class Solve(run.Solve): prefs = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Fem/Z88") solver_index = prefs.GetInt("Solver", 0) solver_name = SOLVER_TYPES[solver_index] - self.pushStatus("Used solver: {}\n".format(solver_name)) + self.pushStatus(f"Used solver: {solver_name}\n") # run solver test mode # AFAIK: z88r needs to be run twice @@ -136,14 +132,14 @@ class Solve(run.Solve): cwd=self.directory, stdout=subprocess.PIPE, stderr=subprocess.PIPE, - startupinfo=femutils.startProgramInfo(state) + startupinfo=femutils.startProgramInfo(state), ) else: self._process = subprocess.Popen( [binary, command, "-" + solver_name], cwd=self.directory, stdout=subprocess.PIPE, - stderr=subprocess.PIPE + stderr=subprocess.PIPE, ) self.signalAbort.add(self._process.terminate) self._process.communicate() @@ -155,8 +151,7 @@ class Solve(run.Solve): class Results(run.Results): def run(self): - prefs = FreeCAD.ParamGet( - "User parameter:BaseApp/Preferences/Mod/Fem/General") + prefs = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Fem/General") if not prefs.GetBool("KeepResultsOnReRun", False): self.purge_results() self.load_results() @@ -173,18 +168,14 @@ class Results(run.Results): def load_results(self): self.pushStatus("Import new results...\n") # displacements from z88o2 file - disp_result_file = os.path.join( - self.directory, "z88o2.txt") + disp_result_file = os.path.join(self.directory, "z88o2.txt") if os.path.isfile(disp_result_file): result_name_prefix = "Z88_" + self.solver.AnalysisType + "_" - importZ88O2Results.import_z88_disp( - disp_result_file, self.analysis, result_name_prefix) + importZ88O2Results.import_z88_disp(disp_result_file, self.analysis, result_name_prefix) else: # TODO: use solver framework status message system - FreeCAD.Console.PrintError( - "FEM: No results found at {}!\n" - .format(disp_result_file) - ) + FreeCAD.Console.PrintError(f"FEM: No results found at {disp_result_file}!\n") self.fail() + ## @} diff --git a/src/Mod/Fem/femsolver/z88/writer.py b/src/Mod/Fem/femsolver/z88/writer.py index 3bb63eb22f..92bf583bcb 100644 --- a/src/Mod/Fem/femsolver/z88/writer.py +++ b/src/Mod/Fem/femsolver/z88/writer.py @@ -39,21 +39,9 @@ from femmesh import meshtools class FemInputWriterZ88(writerbase.FemInputWriter): - def __init__( - self, - analysis_obj, - solver_obj, - mesh_obj, - member, - dir_name=None - ): + def __init__(self, analysis_obj, solver_obj, mesh_obj, member, dir_name=None): writerbase.FemInputWriter.__init__( - self, - analysis_obj, - solver_obj, - mesh_obj, - member, - dir_name + self, analysis_obj, solver_obj, mesh_obj, member, dir_name ) self.file_name = join(self.dir_name, "z88") @@ -63,18 +51,11 @@ class FemInputWriterZ88(writerbase.FemInputWriter): timestart = time.process_time() FreeCAD.Console.PrintMessage("\n") # because of time print in separate line FreeCAD.Console.PrintMessage("Z88 solver input writing...\n") - FreeCAD.Console.PrintLog( - "FemInputWriterZ88 --> self.dir_name --> {}\n" - .format(self.dir_name) - ) + FreeCAD.Console.PrintLog(f"FemInputWriterZ88 --> self.dir_name --> {self.dir_name}\n") FreeCAD.Console.PrintMessage( - "FemInputWriterZ88 --> self.file_name --> {}\n" - .format(self.file_name) - ) - FreeCAD.Console.PrintMessage( - "Write z88 input files to: {}\n" - .format(self.dir_name) + f"FemInputWriterZ88 --> self.file_name --> {self.file_name}\n" ) + FreeCAD.Console.PrintMessage(f"Write z88 input files to: {self.dir_name}\n") control = self.set_z88_elparam() if control is False: return None @@ -86,12 +67,10 @@ class FemInputWriterZ88(writerbase.FemInputWriter): self.write_z88_integration_properties() self.write_z88_memory_parameter() self.write_z88_solver_parameter() - writing_time_string = ( - "Writing time input file: {} seconds" - .format(round((time.process_time() - timestart), 2)) + writing_time_string = "Writing time input file: {} seconds".format( + round((time.process_time() - timestart), 2) ) - FreeCAD.Console.PrintMessage( - "{}\n\n".format(writing_time_string)) + FreeCAD.Console.PrintMessage(f"{writing_time_string}\n\n") return self.dir_name # ******************************************************************************************** @@ -107,14 +86,14 @@ class FemInputWriterZ88(writerbase.FemInputWriter): param = {4: z8804, 24: z8824, 23: z8823, 17: z8817, 16: z8816, 1: z8801, 10: z8810} # TODO: test elements 17, 16, 10, INTORD etc self.z88_element_type = importZ88Mesh.get_z88_element_type( - self.femmesh, - self.femelement_table + self.femmesh, self.femelement_table ) if self.z88_element_type in param: self.z88_elparam = param[self.z88_element_type] else: FreeCAD.Console.PrintError( - "Element type not supported by Z88. Can not write Z88 solver input.\n") + "Element type not supported by Z88. Can not write Z88 solver input.\n" + ) return False FreeCAD.Console.PrintMessage(self.z88_elparam) FreeCAD.Console.PrintMessage("\n") @@ -130,10 +109,7 @@ class FemInputWriterZ88(writerbase.FemInputWriter): mesh_file_path = self.file_name + "i1.txt" f = open(mesh_file_path, "w") importZ88Mesh.write_z88_mesh_to_file( - self.femnodes_mesh, - self.femelement_table, - self.z88_element_type, - f + self.femnodes_mesh, self.femelement_table, self.z88_element_type, f ) f.close() @@ -145,9 +121,9 @@ class FemInputWriterZ88(writerbase.FemInputWriter): # write nodes to constraints_data (different from writing to file in ccxInpWriter for femobj in self.member.cons_fixed: for n in femobj["Nodes"]: - constraints_data.append((n, "{} 1 2 0\n".format(n))) - constraints_data.append((n, "{} 2 2 0\n".format(n))) - constraints_data.append((n, "{} 3 2 0\n".format(n))) + constraints_data.append((n, f"{n} 1 2 0\n")) + constraints_data.append((n, f"{n} 2 2 0\n")) + constraints_data.append((n, f"{n} 3 2 0\n")) # forces constraints # write node loads to constraints_data @@ -159,15 +135,15 @@ class FemInputWriterZ88(writerbase.FemInputWriter): for n in sorted(ref_shape[1]): # the loads in ref_shape[1][n] are without unit node_load = ref_shape[1][n] - if (direction_vec.x != 0.0): + if direction_vec.x != 0.0: v1 = direction_vec.x * node_load - constraints_data.append((n, "{} 1 1 {}\n".format(n, v1))) - if (direction_vec.y != 0.0): + constraints_data.append((n, f"{n} 1 1 {v1}\n")) + if direction_vec.y != 0.0: v2 = direction_vec.y * node_load - constraints_data.append((n, "{} 2 1 {}\n".format(n, v2))) - if (direction_vec.z != 0.0): + constraints_data.append((n, f"{n} 2 1 {v2}\n")) + if direction_vec.z != 0.0: v3 = direction_vec.z * node_load - constraints_data.append((n, "{} 3 1 {}\n".format(n, v3))) + constraints_data.append((n, f"{n} 3 1 {v3}\n")) # write constraints_data to file constraints_file_path = self.file_name + "i2.txt" @@ -193,7 +169,7 @@ class FemInputWriterZ88(writerbase.FemInputWriter): materials_file_path = self.file_name + "mat.txt" fms = open(materials_file_path, "w") fms.write("1\n") - fms.write("1 {} {}".format(self.element_count, material_data_file_name)) + fms.write(f"1 {self.element_count} {material_data_file_name}") fms.write("\n") fms.close() material_data_file_path = join(self.dir_name, material_data_file_name) @@ -201,7 +177,7 @@ class FemInputWriterZ88(writerbase.FemInputWriter): YM = FreeCAD.Units.Quantity(mat_obj.Material["YoungsModulus"]) YM_in_MPa = YM.getValueAs("MPa") PR = float(mat_obj.Material["PoissonRatio"]) - fmd.write("{0} {1:.3f}".format(YM_in_MPa, PR)) + fmd.write(f"{YM_in_MPa} {PR:.3f}") fmd.write("\n") fmd.close() @@ -219,35 +195,24 @@ class FemInputWriterZ88(writerbase.FemInputWriter): elif beam_obj.SectionType == "Circular": diameter = beam_obj.CircDiameter.getValueAs("mm").Value from math import pi + area = 0.25 * pi * diameter * diameter else: FreeCAD.Console.PrintError( "Cross section type {} not supported, " - "cross section area will be 0 in solver input.\n" - .format(beam_obj.SectionType) + "cross section area will be 0 in solver input.\n".format(beam_obj.SectionType) ) # TODO make the check in prechecks and delete it here # no extensive errorhandling in writer # this way the solver will fail and an exception is raised somehow - elements_data.append( - "1 {} {} 0 0 0 0 0 0 " - .format(self.element_count, area) - ) - FreeCAD.Console.PrintWarning( - "Be aware, only trusses are supported for edge meshes!\n" - ) + elements_data.append(f"1 {self.element_count} {area} 0 0 0 0 0 0 ") + FreeCAD.Console.PrintWarning("Be aware, only trusses are supported for edge meshes!\n") elif meshtools.is_face_femmesh(self.femmesh): thick_obj = self.member.geos_shellthickness[0]["Object"] thickness = thick_obj.Thickness.getValueAs("mm").Value - elements_data.append( - "1 {} {} 0 0 0 0 0 0 " - .format(self.element_count, thickness) - ) + elements_data.append(f"1 {self.element_count} {thickness} 0 0 0 0 0 0 ") elif meshtools.is_solid_femmesh(self.femmesh): - elements_data.append( - "1 {} 0 0 0 0 0 0 0" - .format(self.element_count) - ) + elements_data.append(f"1 {self.element_count} 0 0 0 0 0 0 0") else: FreeCAD.Console.PrintError("Error!\n") f = open(element_properties_file_path, "w") @@ -260,14 +225,14 @@ class FemInputWriterZ88(writerbase.FemInputWriter): # ******************************************************************************************** def write_z88_integration_properties(self): integration_data = [] - integration_data.append("1 {} {} {}".format( - self.element_count, - self.z88_elparam["INTORD"], - self.z88_elparam["INTOS"] - )) + integration_data.append( + "1 {} {} {}".format( + self.element_count, self.z88_elparam["INTORD"], self.z88_elparam["INTOS"] + ) + ) integration_properties_file_path = self.file_name + "int.txt" f = open(integration_properties_file_path, "w") - f.write("{}\n".format(len(integration_data))) + f.write(f"{len(integration_data)}\n") for i in integration_data: f.write(i) f.write("\n") @@ -297,9 +262,9 @@ class FemInputWriterZ88(writerbase.FemInputWriter): output = "" for line in template_array: if line.find("MAXGS") > -1: - line = " MAXGS {}".format(MaxGS) + line = f" MAXGS {MaxGS}" if line.find("MAXKOI") > -1: - line = " MAXKOI {}".format(MaxKOI) + line = f" MAXKOI {MaxKOI}" output += line + "\n" solver_parameter_file_path = self.file_name + ".dyn" diff --git a/src/Mod/Fem/femtaskpanels/task_constraint_bodyheatsource.py b/src/Mod/Fem/femtaskpanels/task_constraint_bodyheatsource.py index b740b7ebd7..cd4634e8f9 100644 --- a/src/Mod/Fem/femtaskpanels/task_constraint_bodyheatsource.py +++ b/src/Mod/Fem/femtaskpanels/task_constraint_bodyheatsource.py @@ -40,42 +40,39 @@ from femtools import femutils from femtools import membertools -class _TaskPanel(object): +class _TaskPanel: def __init__(self, obj): self.obj = obj self.parameter_widget = FreeCADGui.PySideUic.loadUi( - FreeCAD.getHomePath() + "Mod/Fem/Resources/ui/BodyHeatSource.ui") + FreeCAD.getHomePath() + "Mod/Fem/Resources/ui/BodyHeatSource.ui" + ) self.init_parameter_widget() QtCore.QObject.connect( self.parameter_widget.qsb_dissipation_rate, QtCore.SIGNAL("valueChanged(Base::Quantity)"), - self.dissipation_rate_changed + self.dissipation_rate_changed, ) QtCore.QObject.connect( self.parameter_widget.qsb_total_power, QtCore.SIGNAL("valueChanged(Base::Quantity)"), - self.total_power_changed + self.total_power_changed, ) QtCore.QObject.connect( self.parameter_widget.cb_mode, QtCore.SIGNAL("currentIndexChanged(int)"), - self.mode_changed + self.mode_changed, ) - # geometry selection widget # start with Solid in list! self.selection_widget = selection_widgets.GeometryElementsSelection( - obj.References, - ["Solid", "Face"], - True, - False + obj.References, ["Solid", "Face"], True, False ) # form made from param and selection widget @@ -127,16 +124,17 @@ class _TaskPanel(object): else: self._part.ViewObject.hide() - def init_parameter_widget(self): self.dissipation_rate = self.obj.DissipationRate self.total_power = self.obj.TotalPower - FreeCADGui.ExpressionBinding(self.parameter_widget.qsb_dissipation_rate)\ - .bind(self.obj, "DissipationRate") + FreeCADGui.ExpressionBinding(self.parameter_widget.qsb_dissipation_rate).bind( + self.obj, "DissipationRate" + ) self.parameter_widget.qsb_dissipation_rate.setProperty("value", self.dissipation_rate) - FreeCADGui.ExpressionBinding(self.parameter_widget.qsb_total_power)\ - .bind(self.obj, "TotalPower") + FreeCADGui.ExpressionBinding(self.parameter_widget.qsb_total_power).bind( + self.obj, "TotalPower" + ) self.parameter_widget.qsb_total_power.setProperty("value", self.total_power) self.mode = self.obj.Mode diff --git a/src/Mod/Fem/femtaskpanels/task_constraint_centrif.py b/src/Mod/Fem/femtaskpanels/task_constraint_centrif.py index 31833351a8..30dfe6b8fc 100644 --- a/src/Mod/Fem/femtaskpanels/task_constraint_centrif.py +++ b/src/Mod/Fem/femtaskpanels/task_constraint_centrif.py @@ -54,24 +54,18 @@ class _TaskPanel: QtCore.QObject.connect( self.parameterWidget.if_rotation_frequency, QtCore.SIGNAL("valueChanged(Base::Quantity)"), - self.rotation_frequency_changed + self.rotation_frequency_changed, ) self.init_parameter_widget() # axis of rotation selection widget self.AxisSelectionWidget = selection_widgets.GeometryElementsSelection( - obj.RotationAxis, - ["Edge"], - False, - False + obj.RotationAxis, ["Edge"], False, False ) # loaded body selection widget self.BodySelectionWidget = selection_widgets.GeometryElementsSelection( - obj.References, - ["Solid"], - False, - False + obj.References, ["Solid"], False, False ) # form made from param and selection widget @@ -81,16 +75,16 @@ class _TaskPanel: # check values RotationAxis items = len(self.AxisSelectionWidget.references) FreeCAD.Console.PrintMessage( - "Task panel: found axis references: {}\n{}\n" - .format(items, self.AxisSelectionWidget.references) + "Task panel: found axis references: {}\n{}\n".format( + items, self.AxisSelectionWidget.references + ) ) if items != 1: msgBox = QtGui.QMessageBox() msgBox.setIcon(QtGui.QMessageBox.Question) msgBox.setText( - "Constraint Centrif requires exactly one line\n\nfound references: {}" - .format(items) + f"Constraint Centrif requires exactly one line\n\nfound references: {items}" ) msgBox.setWindowTitle("FreeCAD FEM Constraint Centrif - Axis selection") retryButton = msgBox.addButton(QtGui.QMessageBox.Retry) @@ -105,8 +99,9 @@ class _TaskPanel: # check values BodyReference items = len(self.BodySelectionWidget.references) FreeCAD.Console.PrintMessage( - "Task panel: found body references: {}\n{}\n" - .format(items, self.BodySelectionWidget.references) + "Task panel: found body references: {}\n{}\n".format( + items, self.BodySelectionWidget.references + ) ) # if no solid is added as reference all volume elements are used diff --git a/src/Mod/Fem/femtaskpanels/task_constraint_currentdensity.py b/src/Mod/Fem/femtaskpanels/task_constraint_currentdensity.py index 8faeee420d..46632d0fad 100644 --- a/src/Mod/Fem/femtaskpanels/task_constraint_currentdensity.py +++ b/src/Mod/Fem/femtaskpanels/task_constraint_currentdensity.py @@ -38,22 +38,20 @@ from femtools import femutils from femtools import membertools -class _TaskPanel(object): +class _TaskPanel: def __init__(self, obj): self._obj = obj self._paramWidget = FreeCADGui.PySideUic.loadUi( - FreeCAD.getHomePath() + "Mod/Fem/Resources/ui/CurrentDensity.ui") + FreeCAD.getHomePath() + "Mod/Fem/Resources/ui/CurrentDensity.ui" + ) self._initParamWidget() # geometry selection widget # start with Solid in list! self._selectionWidget = selection_widgets.GeometryElementsSelection( - obj.References, - ["Solid", "Face"], - True, - False + obj.References, ["Solid", "Face"], True, False ) # form made from param and selection widget @@ -104,86 +102,80 @@ class _TaskPanel(object): self._part.ViewObject.hide() def _initParamWidget(self): - self._paramWidget.realXQSB.setProperty( - 'value', self._obj.CurrentDensity_re_1) - FreeCADGui.ExpressionBinding( - self._paramWidget.realXQSB).bind(self._obj, "CurrentDensity_re_1") - self._paramWidget.realYQSB.setProperty( - 'value', self._obj.CurrentDensity_re_2) - FreeCADGui.ExpressionBinding( - self._paramWidget.realYQSB).bind(self._obj, "CurrentDensity_re_2") - self._paramWidget.realZQSB.setProperty( - 'value', self._obj.CurrentDensity_re_3) - FreeCADGui.ExpressionBinding( - self._paramWidget.realZQSB).bind(self._obj, "CurrentDensity_re_3") - self._paramWidget.imagXQSB.setProperty( - 'value', self._obj.CurrentDensity_im_1) - FreeCADGui.ExpressionBinding( - self._paramWidget.imagXQSB).bind(self._obj, "CurrentDensity_im_1") - self._paramWidget.imagYQSB.setProperty( - 'value', self._obj.CurrentDensity_im_2) - FreeCADGui.ExpressionBinding( - self._paramWidget.imagYQSB).bind(self._obj, "CurrentDensity_im_2") - self._paramWidget.imagZQSB.setProperty( - 'value', self._obj.CurrentDensity_im_3) - FreeCADGui.ExpressionBinding( - self._paramWidget.imagZQSB).bind(self._obj, "CurrentDensity_im_3") + self._paramWidget.realXQSB.setProperty("value", self._obj.CurrentDensity_re_1) + FreeCADGui.ExpressionBinding(self._paramWidget.realXQSB).bind( + self._obj, "CurrentDensity_re_1" + ) + self._paramWidget.realYQSB.setProperty("value", self._obj.CurrentDensity_re_2) + FreeCADGui.ExpressionBinding(self._paramWidget.realYQSB).bind( + self._obj, "CurrentDensity_re_2" + ) + self._paramWidget.realZQSB.setProperty("value", self._obj.CurrentDensity_re_3) + FreeCADGui.ExpressionBinding(self._paramWidget.realZQSB).bind( + self._obj, "CurrentDensity_re_3" + ) + self._paramWidget.imagXQSB.setProperty("value", self._obj.CurrentDensity_im_1) + FreeCADGui.ExpressionBinding(self._paramWidget.imagXQSB).bind( + self._obj, "CurrentDensity_im_1" + ) + self._paramWidget.imagYQSB.setProperty("value", self._obj.CurrentDensity_im_2) + FreeCADGui.ExpressionBinding(self._paramWidget.imagYQSB).bind( + self._obj, "CurrentDensity_im_2" + ) + self._paramWidget.imagZQSB.setProperty("value", self._obj.CurrentDensity_im_3) + FreeCADGui.ExpressionBinding(self._paramWidget.imagZQSB).bind( + self._obj, "CurrentDensity_im_3" + ) - self._paramWidget.reXunspecBox.setChecked( - self._obj.CurrentDensity_re_1_Disabled) - self._paramWidget.reYunspecBox.setChecked( - self._obj.CurrentDensity_re_2_Disabled) - self._paramWidget.reZunspecBox.setChecked( - self._obj.CurrentDensity_re_3_Disabled) - self._paramWidget.imXunspecBox.setChecked( - self._obj.CurrentDensity_im_1_Disabled) - self._paramWidget.imYunspecBox.setChecked( - self._obj.CurrentDensity_im_2_Disabled) - self._paramWidget.imZunspecBox.setChecked( - self._obj.CurrentDensity_im_3_Disabled) + self._paramWidget.reXunspecBox.setChecked(self._obj.CurrentDensity_re_1_Disabled) + self._paramWidget.reYunspecBox.setChecked(self._obj.CurrentDensity_re_2_Disabled) + self._paramWidget.reZunspecBox.setChecked(self._obj.CurrentDensity_re_3_Disabled) + self._paramWidget.imXunspecBox.setChecked(self._obj.CurrentDensity_im_1_Disabled) + self._paramWidget.imYunspecBox.setChecked(self._obj.CurrentDensity_im_2_Disabled) + self._paramWidget.imZunspecBox.setChecked(self._obj.CurrentDensity_im_3_Disabled) def _applyCurrentDensityChanges(self, enabledBox, currentDensityQSB): enabled = enabledBox.isChecked() currentdensity = None try: - currentdensity = currentDensityQSB.property('value') + currentdensity = currentDensityQSB.property("value") except ValueError: FreeCAD.Console.PrintMessage( "Wrong input. Not recognised input: '{}' " "Current density has not been set.\n".format(currentDensityQSB.text()) ) - currentdensity = '0.0 A/m^2' + currentdensity = "0.0 A/m^2" return enabled, currentdensity def _applyWidgetChanges(self): # apply the current densities and their enabled state - self._obj.CurrentDensity_re_1_Disabled, self._obj.CurrentDensity_re_1 = \ + self._obj.CurrentDensity_re_1_Disabled, self._obj.CurrentDensity_re_1 = ( self._applyCurrentDensityChanges( - self._paramWidget.reXunspecBox, - self._paramWidget.realXQSB + self._paramWidget.reXunspecBox, self._paramWidget.realXQSB ) - self._obj.CurrentDensity_re_2_Disabled, self._obj.CurrentDensity_re_2 = \ + ) + self._obj.CurrentDensity_re_2_Disabled, self._obj.CurrentDensity_re_2 = ( self._applyCurrentDensityChanges( - self._paramWidget.reYunspecBox, - self._paramWidget.realYQSB + self._paramWidget.reYunspecBox, self._paramWidget.realYQSB ) - self._obj.CurrentDensity_re_3_Disabled, self._obj.CurrentDensity_re_3 = \ + ) + self._obj.CurrentDensity_re_3_Disabled, self._obj.CurrentDensity_re_3 = ( self._applyCurrentDensityChanges( - self._paramWidget.reZunspecBox, - self._paramWidget.realZQSB + self._paramWidget.reZunspecBox, self._paramWidget.realZQSB ) - self._obj.CurrentDensity_im_1_Disabled, self._obj.CurrentDensity_im_1 = \ + ) + self._obj.CurrentDensity_im_1_Disabled, self._obj.CurrentDensity_im_1 = ( self._applyCurrentDensityChanges( - self._paramWidget.imXunspecBox, - self._paramWidget.imagXQSB + self._paramWidget.imXunspecBox, self._paramWidget.imagXQSB ) - self._obj.CurrentDensity_im_2_Disabled, self._obj.CurrentDensity_im_2 = \ + ) + self._obj.CurrentDensity_im_2_Disabled, self._obj.CurrentDensity_im_2 = ( self._applyCurrentDensityChanges( - self._paramWidget.imYunspecBox, - self._paramWidget.imagYQSB + self._paramWidget.imYunspecBox, self._paramWidget.imagYQSB ) - self._obj.CurrentDensity_im_3_Disabled, self._obj.CurrentDensity_im_3 = \ + ) + self._obj.CurrentDensity_im_3_Disabled, self._obj.CurrentDensity_im_3 = ( self._applyCurrentDensityChanges( - self._paramWidget.imZunspecBox, - self._paramWidget.imagZQSB + self._paramWidget.imZunspecBox, self._paramWidget.imagZQSB ) + ) diff --git a/src/Mod/Fem/femtaskpanels/task_constraint_electrostaticpotential.py b/src/Mod/Fem/femtaskpanels/task_constraint_electrostaticpotential.py index 7ff248653f..0b9e73e108 100644 --- a/src/Mod/Fem/femtaskpanels/task_constraint_electrostaticpotential.py +++ b/src/Mod/Fem/femtaskpanels/task_constraint_electrostaticpotential.py @@ -41,22 +41,20 @@ from femtools import femutils from femtools import membertools -class _TaskPanel(object): +class _TaskPanel: def __init__(self, obj): self._obj = obj self._paramWidget = FreeCADGui.PySideUic.loadUi( - FreeCAD.getHomePath() + "Mod/Fem/Resources/ui/ElectrostaticPotential.ui") + FreeCAD.getHomePath() + "Mod/Fem/Resources/ui/ElectrostaticPotential.ui" + ) self._initParamWidget() # geometry selection widget # start with Solid in list! self._selectionWidget = selection_widgets.GeometryElementsSelection( - obj.References, - ["Solid", "Face", "Edge", "Vertex"], - True, - False + obj.References, ["Solid", "Face", "Edge", "Vertex"], True, False ) # form made from param and selection widget @@ -87,7 +85,7 @@ class _TaskPanel(object): QtCore.QObject.connect( self._paramWidget.vectorFieldBox, QtCore.SIGNAL("toggled(bool)"), - self._vectorField_visibility + self._vectorField_visibility, ) def _vectorField_visibility(self, visible): @@ -128,134 +126,88 @@ class _TaskPanel(object): self._part.ViewObject.hide() def _initParamWidget(self): - self._paramWidget.potentialQSB.setProperty( - 'value', self._obj.Potential) - FreeCADGui.ExpressionBinding( - self._paramWidget.potentialQSB).bind(self._obj, "Potential") - self._paramWidget.potentialBox.setChecked( - not self._obj.PotentialEnabled) + self._paramWidget.potentialQSB.setProperty("value", self._obj.Potential) + FreeCADGui.ExpressionBinding(self._paramWidget.potentialQSB).bind(self._obj, "Potential") + self._paramWidget.potentialBox.setChecked(not self._obj.PotentialEnabled) # the vector potentials # realScalarQSB always the same value as potentialQSB - self._paramWidget.realScalarQSB.setProperty( - 'value', self._obj.Potential) - FreeCADGui.ExpressionBinding( - self._paramWidget.realScalarQSB).bind(self._obj, "Potential") - self._paramWidget.realXQSB.setProperty( - 'value', self._obj.AV_re_1) - FreeCADGui.ExpressionBinding( - self._paramWidget.realXQSB).bind(self._obj, "AV_re_1") - self._paramWidget.realYQSB.setProperty( - 'value', self._obj.AV_re_2) - FreeCADGui.ExpressionBinding( - self._paramWidget.realYQSB).bind(self._obj, "AV_re_2") - self._paramWidget.realZQSB.setProperty( - 'value', self._obj.AV_re_3) - FreeCADGui.ExpressionBinding( - self._paramWidget.realZQSB).bind(self._obj, "AV_re_3") - self._paramWidget.imagScalarQSB.setProperty( - 'value', self._obj.AV_im) - FreeCADGui.ExpressionBinding( - self._paramWidget.imagScalarQSB).bind(self._obj, "AV_im") - self._paramWidget.imagXQSB.setProperty( - 'value', self._obj.AV_im_1) - FreeCADGui.ExpressionBinding( - self._paramWidget.imagXQSB).bind(self._obj, "AV_im_1") - self._paramWidget.imagYQSB.setProperty( - 'value', self._obj.AV_im_2) - FreeCADGui.ExpressionBinding( - self._paramWidget.imagYQSB).bind(self._obj, "AV_im_2") - self._paramWidget.imagZQSB.setProperty( - 'value', self._obj.AV_im_3) - FreeCADGui.ExpressionBinding( - self._paramWidget.imagZQSB).bind(self._obj, "AV_im_3") + self._paramWidget.realScalarQSB.setProperty("value", self._obj.Potential) + FreeCADGui.ExpressionBinding(self._paramWidget.realScalarQSB).bind(self._obj, "Potential") + self._paramWidget.realXQSB.setProperty("value", self._obj.AV_re_1) + FreeCADGui.ExpressionBinding(self._paramWidget.realXQSB).bind(self._obj, "AV_re_1") + self._paramWidget.realYQSB.setProperty("value", self._obj.AV_re_2) + FreeCADGui.ExpressionBinding(self._paramWidget.realYQSB).bind(self._obj, "AV_re_2") + self._paramWidget.realZQSB.setProperty("value", self._obj.AV_re_3) + FreeCADGui.ExpressionBinding(self._paramWidget.realZQSB).bind(self._obj, "AV_re_3") + self._paramWidget.imagScalarQSB.setProperty("value", self._obj.AV_im) + FreeCADGui.ExpressionBinding(self._paramWidget.imagScalarQSB).bind(self._obj, "AV_im") + self._paramWidget.imagXQSB.setProperty("value", self._obj.AV_im_1) + FreeCADGui.ExpressionBinding(self._paramWidget.imagXQSB).bind(self._obj, "AV_im_1") + self._paramWidget.imagYQSB.setProperty("value", self._obj.AV_im_2) + FreeCADGui.ExpressionBinding(self._paramWidget.imagYQSB).bind(self._obj, "AV_im_2") + self._paramWidget.imagZQSB.setProperty("value", self._obj.AV_im_3) + FreeCADGui.ExpressionBinding(self._paramWidget.imagZQSB).bind(self._obj, "AV_im_3") - self._paramWidget.reXunspecBox.setChecked( - self._obj.AV_re_1_Disabled) - self._paramWidget.reYunspecBox.setChecked( - self._obj.AV_re_2_Disabled) - self._paramWidget.reZunspecBox.setChecked( - self._obj.AV_re_3_Disabled) - self._paramWidget.imScalarunspecBox.setChecked( - self._obj.AV_im_Disabled) - self._paramWidget.imXunspecBox.setChecked( - self._obj.AV_im_1_Disabled) - self._paramWidget.imYunspecBox.setChecked( - self._obj.AV_im_2_Disabled) - self._paramWidget.imZunspecBox.setChecked( - self._obj.AV_im_3_Disabled) + self._paramWidget.reXunspecBox.setChecked(self._obj.AV_re_1_Disabled) + self._paramWidget.reYunspecBox.setChecked(self._obj.AV_re_2_Disabled) + self._paramWidget.reZunspecBox.setChecked(self._obj.AV_re_3_Disabled) + self._paramWidget.imScalarunspecBox.setChecked(self._obj.AV_im_Disabled) + self._paramWidget.imXunspecBox.setChecked(self._obj.AV_im_1_Disabled) + self._paramWidget.imYunspecBox.setChecked(self._obj.AV_im_2_Disabled) + self._paramWidget.imZunspecBox.setChecked(self._obj.AV_im_3_Disabled) - self._paramWidget.potentialConstantBox.setChecked( - self._obj.PotentialConstant) + self._paramWidget.potentialConstantBox.setChecked(self._obj.PotentialConstant) - self._paramWidget.electricInfinityBox.setChecked( - self._obj.ElectricInfinity) + self._paramWidget.electricInfinityBox.setChecked(self._obj.ElectricInfinity) - self._paramWidget.electricForcecalculationBox.setChecked( - self._obj.ElectricForcecalculation) + self._paramWidget.electricForcecalculationBox.setChecked(self._obj.ElectricForcecalculation) - self._paramWidget.capacitanceBodyBox.setChecked( - not self._obj.CapacitanceBodyEnabled) - self._paramWidget.capacitanceBody_spinBox.setValue( - self._obj.CapacitanceBody) + self._paramWidget.capacitanceBodyBox.setChecked(not self._obj.CapacitanceBodyEnabled) + self._paramWidget.capacitanceBody_spinBox.setValue(self._obj.CapacitanceBody) self._paramWidget.capacitanceBody_spinBox.setEnabled( - not self._paramWidget.capacitanceBodyBox.isChecked()) + not self._paramWidget.capacitanceBodyBox.isChecked() + ) def _applyPotentialChanges(self, enabledBox, potentialQSB): enabled = enabledBox.isChecked() potential = None try: - potential = potentialQSB.property('value') + potential = potentialQSB.property("value") except ValueError: FreeCAD.Console.PrintMessage( "Wrong input. Not recognised input: '{}' " "Potential has not been set.\n".format(potentialQSB.text()) ) - potential = '0.0 mm^2*kg/(s^3*A)' + potential = "0.0 mm^2*kg/(s^3*A)" return enabled, potential def _applyWidgetChanges(self): # apply the voltages and their enabled state - self._obj.PotentialEnabled, self._obj.Potential = \ - self._applyPotentialChanges( - self._paramWidget.potentialBox, - self._paramWidget.potentialQSB - ) - self._obj.AV_re_1_Disabled, self._obj.AV_re_1 = \ - self._applyPotentialChanges( - self._paramWidget.reXunspecBox, - self._paramWidget.realXQSB - ) - self._obj.AV_re_2_Disabled, self._obj.AV_re_2 = \ - self._applyPotentialChanges( - self._paramWidget.reYunspecBox, - self._paramWidget.realYQSB - ) - self._obj.AV_re_3_Disabled, self._obj.AV_re_3 = \ - self._applyPotentialChanges( - self._paramWidget.reZunspecBox, - self._paramWidget.realZQSB - ) - self._obj.AV_im_Disabled, self._obj.AV_im = \ - self._applyPotentialChanges( - self._paramWidget.imScalarunspecBox, - self._paramWidget.imagScalarQSB - ) - self._obj.AV_im_1_Disabled, self._obj.AV_im_1 = \ - self._applyPotentialChanges( - self._paramWidget.imXunspecBox, - self._paramWidget.imagXQSB - ) - self._obj.AV_im_2_Disabled, self._obj.AV_im_2 = \ - self._applyPotentialChanges( - self._paramWidget.imYunspecBox, - self._paramWidget.imagYQSB - ) - self._obj.AV_im_3_Disabled, self._obj.AV_im_3 = \ - self._applyPotentialChanges( - self._paramWidget.imZunspecBox, - self._paramWidget.imagZQSB - ) + self._obj.PotentialEnabled, self._obj.Potential = self._applyPotentialChanges( + self._paramWidget.potentialBox, self._paramWidget.potentialQSB + ) + self._obj.AV_re_1_Disabled, self._obj.AV_re_1 = self._applyPotentialChanges( + self._paramWidget.reXunspecBox, self._paramWidget.realXQSB + ) + self._obj.AV_re_2_Disabled, self._obj.AV_re_2 = self._applyPotentialChanges( + self._paramWidget.reYunspecBox, self._paramWidget.realYQSB + ) + self._obj.AV_re_3_Disabled, self._obj.AV_re_3 = self._applyPotentialChanges( + self._paramWidget.reZunspecBox, self._paramWidget.realZQSB + ) + self._obj.AV_im_Disabled, self._obj.AV_im = self._applyPotentialChanges( + self._paramWidget.imScalarunspecBox, self._paramWidget.imagScalarQSB + ) + self._obj.AV_im_1_Disabled, self._obj.AV_im_1 = self._applyPotentialChanges( + self._paramWidget.imXunspecBox, self._paramWidget.imagXQSB + ) + self._obj.AV_im_2_Disabled, self._obj.AV_im_2 = self._applyPotentialChanges( + self._paramWidget.imYunspecBox, self._paramWidget.imagYQSB + ) + self._obj.AV_im_3_Disabled, self._obj.AV_im_3 = self._applyPotentialChanges( + self._paramWidget.imZunspecBox, self._paramWidget.imagZQSB + ) # because this is an enable the others are disabled, reverse self._obj.PotentialEnabled = not self._obj.PotentialEnabled @@ -266,8 +218,7 @@ class _TaskPanel(object): calc_is_checked = self._paramWidget.electricForcecalculationBox.isChecked() self._obj.ElectricForcecalculation = calc_is_checked # two lines because max line length - self._obj.CapacitanceBodyEnabled = \ - not self._paramWidget.capacitanceBodyBox.isChecked() + self._obj.CapacitanceBodyEnabled = not self._paramWidget.capacitanceBodyBox.isChecked() if self._obj.CapacitanceBodyEnabled: self._paramWidget.capacitanceBody_spinBox.setEnabled(True) self._obj.CapacitanceBody = self._paramWidget.capacitanceBody_spinBox.value() diff --git a/src/Mod/Fem/femtaskpanels/task_constraint_flowvelocity.py b/src/Mod/Fem/femtaskpanels/task_constraint_flowvelocity.py index 4e0a634a5e..6c8538fba9 100644 --- a/src/Mod/Fem/femtaskpanels/task_constraint_flowvelocity.py +++ b/src/Mod/Fem/femtaskpanels/task_constraint_flowvelocity.py @@ -40,7 +40,7 @@ from femtools import femutils from femtools import membertools -class _TaskPanel(object): +class _TaskPanel: def __init__(self, obj): self._obj = obj @@ -52,10 +52,7 @@ class _TaskPanel(object): # geometry selection widget # start with Solid in list! self._selectionWidget = selection_widgets.GeometryElementsSelection( - obj.References, - ["Solid", "Face", "Edge", "Vertex"], - True, - False + obj.References, ["Solid", "Face", "Edge", "Vertex"], True, False ) # form made from param and selection widget @@ -73,36 +70,24 @@ class _TaskPanel(object): # connect unspecified option QtCore.QObject.connect( - self._paramWidget.velocityXBox, - QtCore.SIGNAL("toggled(bool)"), - self._velocityXEnable + self._paramWidget.velocityXBox, QtCore.SIGNAL("toggled(bool)"), self._velocityXEnable ) QtCore.QObject.connect( - self._paramWidget.velocityYBox, - QtCore.SIGNAL("toggled(bool)"), - self._velocityYEnable + self._paramWidget.velocityYBox, QtCore.SIGNAL("toggled(bool)"), self._velocityYEnable ) QtCore.QObject.connect( - self._paramWidget.velocityZBox, - QtCore.SIGNAL("toggled(bool)"), - self._velocityZEnable + self._paramWidget.velocityZBox, QtCore.SIGNAL("toggled(bool)"), self._velocityZEnable ) # connect formula option QtCore.QObject.connect( - self._paramWidget.formulaXCB, - QtCore.SIGNAL("toggled(bool)"), - self._formulaXEnable + self._paramWidget.formulaXCB, QtCore.SIGNAL("toggled(bool)"), self._formulaXEnable ) QtCore.QObject.connect( - self._paramWidget.formulaYCB, - QtCore.SIGNAL("toggled(bool)"), - self._formulaYEnable + self._paramWidget.formulaYCB, QtCore.SIGNAL("toggled(bool)"), self._formulaYEnable ) QtCore.QObject.connect( - self._paramWidget.formulaZCB, - QtCore.SIGNAL("toggled(bool)"), - self._formulaZEnable + self._paramWidget.formulaZCB, QtCore.SIGNAL("toggled(bool)"), self._formulaZEnable ) self._initParamWidget() @@ -197,79 +182,60 @@ class _TaskPanel(object): def _initParamWidget(self): unit = "m/s" - self._paramWidget.velocityX.setProperty('unit', unit) - self._paramWidget.velocityY.setProperty('unit', unit) - self._paramWidget.velocityZ.setProperty('unit', unit) + self._paramWidget.velocityX.setProperty("unit", unit) + self._paramWidget.velocityY.setProperty("unit", unit) + self._paramWidget.velocityZ.setProperty("unit", unit) - self._paramWidget.velocityX.setProperty( - 'value', self._obj.VelocityX) - FreeCADGui.ExpressionBinding( - self._paramWidget.velocityX).bind(self._obj, "VelocityX") - self._paramWidget.velocityXBox.setChecked( - self._obj.VelocityXUnspecified) + self._paramWidget.velocityX.setProperty("value", self._obj.VelocityX) + FreeCADGui.ExpressionBinding(self._paramWidget.velocityX).bind(self._obj, "VelocityX") + self._paramWidget.velocityXBox.setChecked(self._obj.VelocityXUnspecified) self._paramWidget.formulaX.setText(self._obj.VelocityXFormula) - self._paramWidget.formulaXCB.setChecked( - self._obj.VelocityXHasFormula) + self._paramWidget.formulaXCB.setChecked(self._obj.VelocityXHasFormula) - self._paramWidget.velocityY.setProperty( - 'value', self._obj.VelocityY) - FreeCADGui.ExpressionBinding( - self._paramWidget.velocityY).bind(self._obj, "VelocityY") - self._paramWidget.velocityYBox.setChecked( - self._obj.VelocityYUnspecified) + self._paramWidget.velocityY.setProperty("value", self._obj.VelocityY) + FreeCADGui.ExpressionBinding(self._paramWidget.velocityY).bind(self._obj, "VelocityY") + self._paramWidget.velocityYBox.setChecked(self._obj.VelocityYUnspecified) self._paramWidget.formulaY.setText(self._obj.VelocityYFormula) - self._paramWidget.formulaYCB.setChecked( - self._obj.VelocityYHasFormula) + self._paramWidget.formulaYCB.setChecked(self._obj.VelocityYHasFormula) - self._paramWidget.velocityZ.setProperty( - 'value', self._obj.VelocityZ) - FreeCADGui.ExpressionBinding( - self._paramWidget.velocityZ).bind(self._obj, "VelocityZ") - self._paramWidget.velocityZBox.setChecked( - self._obj.VelocityZUnspecified) + self._paramWidget.velocityZ.setProperty("value", self._obj.VelocityZ) + FreeCADGui.ExpressionBinding(self._paramWidget.velocityZ).bind(self._obj, "VelocityZ") + self._paramWidget.velocityZBox.setChecked(self._obj.VelocityZUnspecified) self._paramWidget.formulaZ.setText(self._obj.VelocityZFormula) - self._paramWidget.formulaZCB.setChecked( - self._obj.VelocityZHasFormula) + self._paramWidget.formulaZCB.setChecked(self._obj.VelocityZHasFormula) - self._paramWidget.normalBox.setChecked( - self._obj.NormalToBoundary) + self._paramWidget.normalBox.setChecked(self._obj.NormalToBoundary) def _applyVelocityChanges(self, enabledBox, velocityQSB): enabled = enabledBox.isChecked() velocity = None try: - velocity = velocityQSB.property('value') + velocity = velocityQSB.property("value") except ValueError: FreeCAD.Console.PrintMessage( "Wrong input. Not recognised input: '{}' " "Velocity has not been set.\n".format(velocityQSB.text()) ) - velocity = '0.0 m/s' + velocity = "0.0 m/s" return enabled, velocity def _applyWidgetChanges(self): # apply the velocities and their enabled state - self._obj.VelocityXUnspecified, self._obj.VelocityX = \ - self._applyVelocityChanges( - self._paramWidget.velocityXBox, - self._paramWidget.velocityX - ) + self._obj.VelocityXUnspecified, self._obj.VelocityX = self._applyVelocityChanges( + self._paramWidget.velocityXBox, self._paramWidget.velocityX + ) self._obj.VelocityXHasFormula = self._paramWidget.formulaXCB.isChecked() self._obj.VelocityXFormula = self._paramWidget.formulaX.text() - self._obj.VelocityYUnspecified, self._obj.VelocityY = \ - self._applyVelocityChanges( - self._paramWidget.velocityYBox, - self._paramWidget.velocityY - ) + self._obj.VelocityYUnspecified, self._obj.VelocityY = self._applyVelocityChanges( + self._paramWidget.velocityYBox, self._paramWidget.velocityY + ) self._obj.VelocityYHasFormula = self._paramWidget.formulaYCB.isChecked() self._obj.VelocityYFormula = self._paramWidget.formulaY.text() - self._obj.VelocityZUnspecified, self._obj.VelocityZ = \ - self._applyVelocityChanges( - self._paramWidget.velocityZBox, - self._paramWidget.velocityZ - ) + self._obj.VelocityZUnspecified, self._obj.VelocityZ = self._applyVelocityChanges( + self._paramWidget.velocityZBox, self._paramWidget.velocityZ + ) self._obj.VelocityZHasFormula = self._paramWidget.formulaZCB.isChecked() self._obj.VelocityZFormula = self._paramWidget.formulaZ.text() diff --git a/src/Mod/Fem/femtaskpanels/task_constraint_initialflowvelocity.py b/src/Mod/Fem/femtaskpanels/task_constraint_initialflowvelocity.py index 6516c70823..42b6fe7704 100644 --- a/src/Mod/Fem/femtaskpanels/task_constraint_initialflowvelocity.py +++ b/src/Mod/Fem/femtaskpanels/task_constraint_initialflowvelocity.py @@ -40,21 +40,19 @@ from femtools import femutils from femtools import membertools -class _TaskPanel(object): +class _TaskPanel: def __init__(self, obj): self._obj = obj self._paramWidget = FreeCADGui.PySideUic.loadUi( - FreeCAD.getHomePath() + "Mod/Fem/Resources/ui/InitialFlowVelocity.ui") + FreeCAD.getHomePath() + "Mod/Fem/Resources/ui/InitialFlowVelocity.ui" + ) # geometry selection widget # start with Solid in list! self._selectionWidget = selection_widgets.GeometryElementsSelection( - obj.References, - ["Solid", "Face"], - True, - False + obj.References, ["Solid", "Face"], True, False ) # form made from param and selection widget @@ -72,36 +70,24 @@ class _TaskPanel(object): # connect unspecified option QtCore.QObject.connect( - self._paramWidget.velocityXBox, - QtCore.SIGNAL("toggled(bool)"), - self._velocityXEnable + self._paramWidget.velocityXBox, QtCore.SIGNAL("toggled(bool)"), self._velocityXEnable ) QtCore.QObject.connect( - self._paramWidget.velocityYBox, - QtCore.SIGNAL("toggled(bool)"), - self._velocityYEnable + self._paramWidget.velocityYBox, QtCore.SIGNAL("toggled(bool)"), self._velocityYEnable ) QtCore.QObject.connect( - self._paramWidget.velocityZBox, - QtCore.SIGNAL("toggled(bool)"), - self._velocityZEnable + self._paramWidget.velocityZBox, QtCore.SIGNAL("toggled(bool)"), self._velocityZEnable ) # connect formula option QtCore.QObject.connect( - self._paramWidget.formulaXCB, - QtCore.SIGNAL("toggled(bool)"), - self._formulaXEnable + self._paramWidget.formulaXCB, QtCore.SIGNAL("toggled(bool)"), self._formulaXEnable ) QtCore.QObject.connect( - self._paramWidget.formulaYCB, - QtCore.SIGNAL("toggled(bool)"), - self._formulaYEnable + self._paramWidget.formulaYCB, QtCore.SIGNAL("toggled(bool)"), self._formulaYEnable ) QtCore.QObject.connect( - self._paramWidget.formulaZCB, - QtCore.SIGNAL("toggled(bool)"), - self._formulaZEnable + self._paramWidget.formulaZCB, QtCore.SIGNAL("toggled(bool)"), self._formulaZEnable ) self._initParamWidget() @@ -196,75 +182,57 @@ class _TaskPanel(object): def _initParamWidget(self): unit = "m/s" - self._paramWidget.velocityX.setProperty('unit', unit) - self._paramWidget.velocityY.setProperty('unit', unit) - self._paramWidget.velocityZ.setProperty('unit', unit) + self._paramWidget.velocityX.setProperty("unit", unit) + self._paramWidget.velocityY.setProperty("unit", unit) + self._paramWidget.velocityZ.setProperty("unit", unit) - self._paramWidget.velocityX.setProperty( - 'value', self._obj.VelocityX) - FreeCADGui.ExpressionBinding( - self._paramWidget.velocityX).bind(self._obj, "VelocityX") - self._paramWidget.velocityXBox.setChecked( - self._obj.VelocityXUnspecified) + self._paramWidget.velocityX.setProperty("value", self._obj.VelocityX) + FreeCADGui.ExpressionBinding(self._paramWidget.velocityX).bind(self._obj, "VelocityX") + self._paramWidget.velocityXBox.setChecked(self._obj.VelocityXUnspecified) self._paramWidget.formulaX.setText(self._obj.VelocityXFormula) - self._paramWidget.formulaXCB.setChecked( - self._obj.VelocityXHasFormula) + self._paramWidget.formulaXCB.setChecked(self._obj.VelocityXHasFormula) - self._paramWidget.velocityY.setProperty( - 'value', self._obj.VelocityY) - FreeCADGui.ExpressionBinding( - self._paramWidget.velocityY).bind(self._obj, "VelocityY") - self._paramWidget.velocityYBox.setChecked( - self._obj.VelocityYUnspecified) + self._paramWidget.velocityY.setProperty("value", self._obj.VelocityY) + FreeCADGui.ExpressionBinding(self._paramWidget.velocityY).bind(self._obj, "VelocityY") + self._paramWidget.velocityYBox.setChecked(self._obj.VelocityYUnspecified) self._paramWidget.formulaY.setText(self._obj.VelocityYFormula) - self._paramWidget.formulaYCB.setChecked( - self._obj.VelocityYHasFormula) + self._paramWidget.formulaYCB.setChecked(self._obj.VelocityYHasFormula) - self._paramWidget.velocityZ.setProperty( - 'value', self._obj.VelocityZ) - FreeCADGui.ExpressionBinding( - self._paramWidget.velocityZ).bind(self._obj, "VelocityZ") - self._paramWidget.velocityZBox.setChecked( - self._obj.VelocityZUnspecified) + self._paramWidget.velocityZ.setProperty("value", self._obj.VelocityZ) + FreeCADGui.ExpressionBinding(self._paramWidget.velocityZ).bind(self._obj, "VelocityZ") + self._paramWidget.velocityZBox.setChecked(self._obj.VelocityZUnspecified) self._paramWidget.formulaZ.setText(self._obj.VelocityZFormula) - self._paramWidget.formulaZCB.setChecked( - self._obj.VelocityZHasFormula) + self._paramWidget.formulaZCB.setChecked(self._obj.VelocityZHasFormula) def _applyVelocityChanges(self, enabledBox, velocityQSB): enabled = enabledBox.isChecked() velocity = None try: - velocity = velocityQSB.property('value') + velocity = velocityQSB.property("value") except ValueError: FreeCAD.Console.PrintMessage( "Wrong input. Not recognised input: '{}' " "Velocity has not been set.\n".format(velocityQSB.text()) ) - velocity = '0.0 m/s' + velocity = "0.0 m/s" return enabled, velocity def _applyWidgetChanges(self): # apply the velocities and their enabled state - self._obj.VelocityXUnspecified, self._obj.VelocityX = \ - self._applyVelocityChanges( - self._paramWidget.velocityXBox, - self._paramWidget.velocityX - ) + self._obj.VelocityXUnspecified, self._obj.VelocityX = self._applyVelocityChanges( + self._paramWidget.velocityXBox, self._paramWidget.velocityX + ) self._obj.VelocityXHasFormula = self._paramWidget.formulaXCB.isChecked() self._obj.VelocityXFormula = self._paramWidget.formulaX.text() - self._obj.VelocityYUnspecified, self._obj.VelocityY = \ - self._applyVelocityChanges( - self._paramWidget.velocityYBox, - self._paramWidget.velocityY - ) + self._obj.VelocityYUnspecified, self._obj.VelocityY = self._applyVelocityChanges( + self._paramWidget.velocityYBox, self._paramWidget.velocityY + ) self._obj.VelocityYHasFormula = self._paramWidget.formulaYCB.isChecked() self._obj.VelocityYFormula = self._paramWidget.formulaY.text() - self._obj.VelocityZUnspecified, self._obj.VelocityZ = \ - self._applyVelocityChanges( - self._paramWidget.velocityZBox, - self._paramWidget.velocityZ - ) + self._obj.VelocityZUnspecified, self._obj.VelocityZ = self._applyVelocityChanges( + self._paramWidget.velocityZBox, self._paramWidget.velocityZ + ) self._obj.VelocityZHasFormula = self._paramWidget.formulaZCB.isChecked() self._obj.VelocityZFormula = self._paramWidget.formulaZ.text() diff --git a/src/Mod/Fem/femtaskpanels/task_constraint_initialpressure.py b/src/Mod/Fem/femtaskpanels/task_constraint_initialpressure.py index be32559a3e..9ed9e1bec9 100644 --- a/src/Mod/Fem/femtaskpanels/task_constraint_initialpressure.py +++ b/src/Mod/Fem/femtaskpanels/task_constraint_initialpressure.py @@ -37,22 +37,20 @@ from femtools import femutils from femtools import membertools -class _TaskPanel(object): +class _TaskPanel: def __init__(self, obj): self._obj = obj self._paramWidget = FreeCADGui.PySideUic.loadUi( - FreeCAD.getHomePath() + "Mod/Fem/Resources/ui/InitialPressure.ui") + FreeCAD.getHomePath() + "Mod/Fem/Resources/ui/InitialPressure.ui" + ) self._initParamWidget() # geometry selection widget # start with Solid in list! self._selectionWidget = selection_widgets.GeometryElementsSelection( - obj.References, - ["Solid", "Face"], - True, - False + obj.References, ["Solid", "Face"], True, False ) # form made from param and selection widget @@ -103,20 +101,17 @@ class _TaskPanel(object): self._part.ViewObject.hide() def _initParamWidget(self): - self._paramWidget.pressureQSB.setProperty( - 'value', self._obj.Pressure) - FreeCADGui.ExpressionBinding( - self._paramWidget.pressureQSB).bind(self._obj, "Pressure") + self._paramWidget.pressureQSB.setProperty("value", self._obj.Pressure) + FreeCADGui.ExpressionBinding(self._paramWidget.pressureQSB).bind(self._obj, "Pressure") def _applyWidgetChanges(self): pressure = None try: - pressure = self._paramWidget.pressureQSB.property('value') + pressure = self._paramWidget.pressureQSB.property("value") except ValueError: FreeCAD.Console.PrintMessage( "Wrong input. Not recognised input: '{}' " - "Pressure has not been set.\n" - .format(self._paramWidget.pressureQSB.text()) + "Pressure has not been set.\n".format(self._paramWidget.pressureQSB.text()) ) if pressure is not None: self._obj.Pressure = pressure diff --git a/src/Mod/Fem/femtaskpanels/task_constraint_magnetization.py b/src/Mod/Fem/femtaskpanels/task_constraint_magnetization.py index f666a662ad..05c4c56ec1 100644 --- a/src/Mod/Fem/femtaskpanels/task_constraint_magnetization.py +++ b/src/Mod/Fem/femtaskpanels/task_constraint_magnetization.py @@ -38,22 +38,20 @@ from femtools import femutils from femtools import membertools -class _TaskPanel(object): +class _TaskPanel: def __init__(self, obj): self._obj = obj self._paramWidget = FreeCADGui.PySideUic.loadUi( - FreeCAD.getHomePath() + "Mod/Fem/Resources/ui/Magnetization.ui") + FreeCAD.getHomePath() + "Mod/Fem/Resources/ui/Magnetization.ui" + ) self._initParamWidget() # geometry selection widget # magnetization is always a body force for 3D, therefore only allow solid self._selectionWidget = selection_widgets.GeometryElementsSelection( - obj.References, - ["Solid", "Face"], - True, - False + obj.References, ["Solid", "Face"], True, False ) # form made from param and selection widget @@ -104,86 +102,80 @@ class _TaskPanel(object): self._part.ViewObject.hide() def _initParamWidget(self): - self._paramWidget.realXQSB.setProperty( - 'value', self._obj.Magnetization_re_1) - FreeCADGui.ExpressionBinding( - self._paramWidget.realXQSB).bind(self._obj, "Magnetization_re_1") - self._paramWidget.realYQSB.setProperty( - 'value', self._obj.Magnetization_re_2) - FreeCADGui.ExpressionBinding( - self._paramWidget.realYQSB).bind(self._obj, "Magnetization_re_2") - self._paramWidget.realZQSB.setProperty( - 'value', self._obj.Magnetization_re_3) - FreeCADGui.ExpressionBinding( - self._paramWidget.realZQSB).bind(self._obj, "Magnetization_re_3") - self._paramWidget.imagXQSB.setProperty( - 'value', self._obj.Magnetization_im_1) - FreeCADGui.ExpressionBinding( - self._paramWidget.imagXQSB).bind(self._obj, "Magnetization_im_1") - self._paramWidget.imagYQSB.setProperty( - 'value', self._obj.Magnetization_im_2) - FreeCADGui.ExpressionBinding( - self._paramWidget.imagYQSB).bind(self._obj, "Magnetization_im_2") - self._paramWidget.imagZQSB.setProperty( - 'value', self._obj.Magnetization_im_3) - FreeCADGui.ExpressionBinding( - self._paramWidget.imagZQSB).bind(self._obj, "Magnetization_im_3") + self._paramWidget.realXQSB.setProperty("value", self._obj.Magnetization_re_1) + FreeCADGui.ExpressionBinding(self._paramWidget.realXQSB).bind( + self._obj, "Magnetization_re_1" + ) + self._paramWidget.realYQSB.setProperty("value", self._obj.Magnetization_re_2) + FreeCADGui.ExpressionBinding(self._paramWidget.realYQSB).bind( + self._obj, "Magnetization_re_2" + ) + self._paramWidget.realZQSB.setProperty("value", self._obj.Magnetization_re_3) + FreeCADGui.ExpressionBinding(self._paramWidget.realZQSB).bind( + self._obj, "Magnetization_re_3" + ) + self._paramWidget.imagXQSB.setProperty("value", self._obj.Magnetization_im_1) + FreeCADGui.ExpressionBinding(self._paramWidget.imagXQSB).bind( + self._obj, "Magnetization_im_1" + ) + self._paramWidget.imagYQSB.setProperty("value", self._obj.Magnetization_im_2) + FreeCADGui.ExpressionBinding(self._paramWidget.imagYQSB).bind( + self._obj, "Magnetization_im_2" + ) + self._paramWidget.imagZQSB.setProperty("value", self._obj.Magnetization_im_3) + FreeCADGui.ExpressionBinding(self._paramWidget.imagZQSB).bind( + self._obj, "Magnetization_im_3" + ) - self._paramWidget.reXunspecBox.setChecked( - self._obj.Magnetization_re_1_Disabled) - self._paramWidget.reYunspecBox.setChecked( - self._obj.Magnetization_re_2_Disabled) - self._paramWidget.reZunspecBox.setChecked( - self._obj.Magnetization_re_3_Disabled) - self._paramWidget.imXunspecBox.setChecked( - self._obj.Magnetization_im_1_Disabled) - self._paramWidget.imYunspecBox.setChecked( - self._obj.Magnetization_im_2_Disabled) - self._paramWidget.imZunspecBox.setChecked( - self._obj.Magnetization_im_3_Disabled) + self._paramWidget.reXunspecBox.setChecked(self._obj.Magnetization_re_1_Disabled) + self._paramWidget.reYunspecBox.setChecked(self._obj.Magnetization_re_2_Disabled) + self._paramWidget.reZunspecBox.setChecked(self._obj.Magnetization_re_3_Disabled) + self._paramWidget.imXunspecBox.setChecked(self._obj.Magnetization_im_1_Disabled) + self._paramWidget.imYunspecBox.setChecked(self._obj.Magnetization_im_2_Disabled) + self._paramWidget.imZunspecBox.setChecked(self._obj.Magnetization_im_3_Disabled) def _applyMagnetizationChanges(self, enabledBox, magnetizationQSB): enabled = enabledBox.isChecked() magnetization = None try: - magnetization = magnetizationQSB.property('value') + magnetization = magnetizationQSB.property("value") except ValueError: FreeCAD.Console.PrintMessage( "Wrong input. Not recognised input: '{}' " "Magnetization has not been set.\n".format(magnetizationQSB.text()) ) - magnetization = '0.0 A/m' + magnetization = "0.0 A/m" return enabled, magnetization def _applyWidgetChanges(self): # apply the magnetizations and their enabled state - self._obj.Magnetization_re_1_Disabled, self._obj.Magnetization_re_1 = \ + self._obj.Magnetization_re_1_Disabled, self._obj.Magnetization_re_1 = ( self._applyMagnetizationChanges( - self._paramWidget.reXunspecBox, - self._paramWidget.realXQSB + self._paramWidget.reXunspecBox, self._paramWidget.realXQSB ) - self._obj.Magnetization_re_2_Disabled, self._obj.Magnetization_re_2 = \ + ) + self._obj.Magnetization_re_2_Disabled, self._obj.Magnetization_re_2 = ( self._applyMagnetizationChanges( - self._paramWidget.reYunspecBox, - self._paramWidget.realYQSB + self._paramWidget.reYunspecBox, self._paramWidget.realYQSB ) - self._obj.Magnetization_re_3_Disabled, self._obj.Magnetization_re_3 = \ + ) + self._obj.Magnetization_re_3_Disabled, self._obj.Magnetization_re_3 = ( self._applyMagnetizationChanges( - self._paramWidget.reZunspecBox, - self._paramWidget.realZQSB + self._paramWidget.reZunspecBox, self._paramWidget.realZQSB ) - self._obj.Magnetization_im_1_Disabled, self._obj.Magnetization_im_1 = \ + ) + self._obj.Magnetization_im_1_Disabled, self._obj.Magnetization_im_1 = ( self._applyMagnetizationChanges( - self._paramWidget.imXunspecBox, - self._paramWidget.imagXQSB + self._paramWidget.imXunspecBox, self._paramWidget.imagXQSB ) - self._obj.Magnetization_im_2_Disabled, self._obj.Magnetization_im_2 = \ + ) + self._obj.Magnetization_im_2_Disabled, self._obj.Magnetization_im_2 = ( self._applyMagnetizationChanges( - self._paramWidget.imYunspecBox, - self._paramWidget.imagYQSB + self._paramWidget.imYunspecBox, self._paramWidget.imagYQSB ) - self._obj.Magnetization_im_3_Disabled, self._obj.Magnetization_im_3 = \ + ) + self._obj.Magnetization_im_3_Disabled, self._obj.Magnetization_im_3 = ( self._applyMagnetizationChanges( - self._paramWidget.imZunspecBox, - self._paramWidget.imagZQSB + self._paramWidget.imZunspecBox, self._paramWidget.imagZQSB ) + ) diff --git a/src/Mod/Fem/femtaskpanels/task_constraint_sectionprint.py b/src/Mod/Fem/femtaskpanels/task_constraint_sectionprint.py index df285630de..2b4f292bde 100644 --- a/src/Mod/Fem/femtaskpanels/task_constraint_sectionprint.py +++ b/src/Mod/Fem/femtaskpanels/task_constraint_sectionprint.py @@ -58,15 +58,12 @@ class _TaskPanel: QtCore.QObject.connect( self.parameterWidget.cb_variable, QtCore.SIGNAL("currentIndexChanged(int)"), - self.variable_changed + self.variable_changed, ) # geometry selection widget self.selectionWidget = selection_widgets.GeometryElementsSelection( - obj.References, - ["Face"], - False, - False + obj.References, ["Face"], False, False ) # form made from param and selection widget @@ -80,8 +77,9 @@ class _TaskPanel: msgBox = QtGui.QMessageBox() msgBox.setIcon(QtGui.QMessageBox.Question) msgBox.setText( - "Constraint SectionPrint requires exactly one face\n\nfound references: {}" - .format(items) + "Constraint SectionPrint requires exactly one face\n\nfound references: {}".format( + items + ) ) msgBox.setWindowTitle("FreeCAD FEM Constraint SectionPrint") retryButton = msgBox.addButton(QtGui.QMessageBox.Retry) diff --git a/src/Mod/Fem/femtaskpanels/task_constraint_tie.py b/src/Mod/Fem/femtaskpanels/task_constraint_tie.py index 4cab0dfa68..cbcade3946 100644 --- a/src/Mod/Fem/femtaskpanels/task_constraint_tie.py +++ b/src/Mod/Fem/femtaskpanels/task_constraint_tie.py @@ -54,21 +54,16 @@ class _TaskPanel: QtCore.QObject.connect( self.parameterWidget.spb_tolerance, QtCore.SIGNAL("valueChanged(Base::Quantity)"), - self.tolerance_changed + self.tolerance_changed, ) QtCore.QObject.connect( - self.parameterWidget.ckb_adjust, - QtCore.SIGNAL("toggled(bool)"), - self.adjust_changed + self.parameterWidget.ckb_adjust, QtCore.SIGNAL("toggled(bool)"), self.adjust_changed ) self.init_parameter_widget() # geometry selection widget self.selectionWidget = selection_widgets.GeometryElementsSelection( - obj.References, - ["Face"], - False, - False + obj.References, ["Face"], False, False ) # form made from param and selection widget @@ -78,16 +73,14 @@ class _TaskPanel: # check values items = len(self.selectionWidget.references) FreeCAD.Console.PrintMessage( - "Task panel: found references: {}\n{}\n" - .format(items, self.selectionWidget.references) + f"Task panel: found references: {items}\n{self.selectionWidget.references}\n" ) if items != 2: msgBox = QtGui.QMessageBox() msgBox.setIcon(QtGui.QMessageBox.Question) msgBox.setText( - "Constraint Tie requires exactly two faces\n\nfound references: {}" - .format(items) + f"Constraint Tie requires exactly two faces\n\nfound references: {items}" ) msgBox.setWindowTitle("FreeCAD FEM Constraint Tie") retryButton = msgBox.addButton(QtGui.QMessageBox.Retry) @@ -117,8 +110,7 @@ class _TaskPanel: def init_parameter_widget(self): self.tolerance = self.obj.Tolerance self.adjust = self.obj.Adjust - FreeCADGui.ExpressionBinding(self.parameterWidget.spb_tolerance)\ - .bind(self.obj, "Tolerance") + FreeCADGui.ExpressionBinding(self.parameterWidget.spb_tolerance).bind(self.obj, "Tolerance") self.parameterWidget.spb_tolerance.setProperty("value", self.tolerance) self.parameterWidget.ckb_adjust.setChecked(self.adjust) diff --git a/src/Mod/Fem/femtaskpanels/task_element_fluid1D.py b/src/Mod/Fem/femtaskpanels/task_element_fluid1D.py index 4a60ae1d50..3147398b71 100644 --- a/src/Mod/Fem/femtaskpanels/task_element_fluid1D.py +++ b/src/Mod/Fem/femtaskpanels/task_element_fluid1D.py @@ -58,162 +58,162 @@ class _TaskPanel: QtCore.QObject.connect( self.parameterWidget.cb_section_type, QtCore.SIGNAL("activated(int)"), - self.sectiontype_changed + self.sectiontype_changed, ) QtCore.QObject.connect( self.parameterWidget.cb_liquid_section_type, QtCore.SIGNAL("activated(int)"), - self.liquidsectiontype_changed + self.liquidsectiontype_changed, ) QtCore.QObject.connect( self.parameterWidget.if_manning_area, QtCore.SIGNAL("valueChanged(Base::Quantity)"), - self.manning_area_changed + self.manning_area_changed, ) QtCore.QObject.connect( self.parameterWidget.if_manning_radius, QtCore.SIGNAL("valueChanged(Base::Quantity)"), - self.manning_radius_changed + self.manning_radius_changed, ) QtCore.QObject.connect( self.parameterWidget.sb_manning_coefficient, QtCore.SIGNAL("valueChanged(double)"), - self.manning_coefficient_changed + self.manning_coefficient_changed, ) QtCore.QObject.connect( self.parameterWidget.if_enlarge_area1, QtCore.SIGNAL("valueChanged(Base::Quantity)"), - self.enlarge_area1_changed + self.enlarge_area1_changed, ) QtCore.QObject.connect( self.parameterWidget.if_enlarge_area2, QtCore.SIGNAL("valueChanged(Base::Quantity)"), - self.enlarge_area2_changed + self.enlarge_area2_changed, ) QtCore.QObject.connect( self.parameterWidget.if_contract_area1, QtCore.SIGNAL("valueChanged(Base::Quantity)"), - self.contract_area1_changed + self.contract_area1_changed, ) QtCore.QObject.connect( self.parameterWidget.if_contract_area2, QtCore.SIGNAL("valueChanged(Base::Quantity)"), - self.contract_area2_changed + self.contract_area2_changed, ) QtCore.QObject.connect( self.parameterWidget.if_inletpressure, QtCore.SIGNAL("valueChanged(Base::Quantity)"), - self.inlet_pressure_changed + self.inlet_pressure_changed, ) QtCore.QObject.connect( self.parameterWidget.if_outletpressure, QtCore.SIGNAL("valueChanged(Base::Quantity)"), - self.outlet_pressure_changed + self.outlet_pressure_changed, ) QtCore.QObject.connect( self.parameterWidget.if_inletflowrate, QtCore.SIGNAL("valueChanged(Base::Quantity)"), - self.inlet_flowrate_changed + self.inlet_flowrate_changed, ) QtCore.QObject.connect( self.parameterWidget.if_outletflowrate, QtCore.SIGNAL("valueChanged(Base::Quantity)"), - self.outlet_flowrate_changed + self.outlet_flowrate_changed, ) QtCore.QObject.connect( self.parameterWidget.gb_inletpressure, QtCore.SIGNAL("clicked(bool)"), - self.inlet_pressure_active + self.inlet_pressure_active, ) QtCore.QObject.connect( self.parameterWidget.gb_outletpressure, QtCore.SIGNAL("clicked(bool)"), - self.outlet_pressure_active + self.outlet_pressure_active, ) QtCore.QObject.connect( self.parameterWidget.gb_inletflowrate, QtCore.SIGNAL("clicked(bool)"), - self.inlet_flowrate_active + self.inlet_flowrate_active, ) QtCore.QObject.connect( self.parameterWidget.gb_outletflowrate, QtCore.SIGNAL("clicked(bool)"), - self.outlet_flowrate_active + self.outlet_flowrate_active, ) QtCore.QObject.connect( self.parameterWidget.if_entrance_pipe_area, QtCore.SIGNAL("valueChanged(Base::Quantity)"), - self.entrance_pipe_area_changed + self.entrance_pipe_area_changed, ) QtCore.QObject.connect( self.parameterWidget.if_entrance_area, QtCore.SIGNAL("valueChanged(Base::Quantity)"), - self.entrance_area_changed + self.entrance_area_changed, ) QtCore.QObject.connect( self.parameterWidget.if_diaphragm_pipe_area, QtCore.SIGNAL("valueChanged(Base::Quantity)"), - self.diaphragm_pipe_area_changed + self.diaphragm_pipe_area_changed, ) QtCore.QObject.connect( self.parameterWidget.if_diaphragm_area, QtCore.SIGNAL("valueChanged(Base::Quantity)"), - self.diaphragm_area_changed + self.diaphragm_area_changed, ) QtCore.QObject.connect( self.parameterWidget.if_bend_pipe_area, QtCore.SIGNAL("valueChanged(Base::Quantity)"), - self.bend_pipe_area_changed + self.bend_pipe_area_changed, ) QtCore.QObject.connect( self.parameterWidget.sb_bradius_pdiameter, QtCore.SIGNAL("valueChanged(double)"), - self.bradius_pdiameter_changed + self.bradius_pdiameter_changed, ) QtCore.QObject.connect( self.parameterWidget.sb_bend_angle, QtCore.SIGNAL("valueChanged(double)"), - self.bend_angle_changed + self.bend_angle_changed, ) QtCore.QObject.connect( self.parameterWidget.sb_bend_loss_coefficient, QtCore.SIGNAL("valueChanged(double)"), - self.bend_loss_coefficient_changed + self.bend_loss_coefficient_changed, ) QtCore.QObject.connect( self.parameterWidget.if_gatevalve_pipe_area, QtCore.SIGNAL("valueChanged(Base::Quantity)"), - self.gatevalve_pipe_area_changed + self.gatevalve_pipe_area_changed, ) QtCore.QObject.connect( self.parameterWidget.sb_gatevalve_closing_coeff, QtCore.SIGNAL("valueChanged(double)"), - self.gatevalve_closing_coeff_changed + self.gatevalve_closing_coeff_changed, ) QtCore.QObject.connect( self.parameterWidget.if_colebrooke_pipe_area, QtCore.SIGNAL("valueChanged(Base::Quantity)"), - self.colebrooke_pipe_area_changed + self.colebrooke_pipe_area_changed, ) QtCore.QObject.connect( self.parameterWidget.if_colebrooke_radius, QtCore.SIGNAL("valueChanged(Base::Quantity)"), - self.colebrooke_radius_changed + self.colebrooke_radius_changed, ) QtCore.QObject.connect( self.parameterWidget.if_colebrooke_grain_diameter, QtCore.SIGNAL("valueChanged(Base::Quantity)"), - self.colebrooke_grain_diameter_changed + self.colebrooke_grain_diameter_changed, ) QtCore.QObject.connect( self.parameterWidget.sb_colebrooke_form_factor, QtCore.SIGNAL("valueChanged(double)"), - self.colebrooke_form_factor_changed + self.colebrooke_form_factor_changed, ) QtCore.QObject.connect( self.parameterWidget.tw_pump_characteristics, QtCore.SIGNAL("cellChanged(int, int)"), - self.pump_characteristics_changed + self.pump_characteristics_changed, ) # some fluid types deactivated since they are not implemented in ccx writer self.parameterWidget.cb_section_type.addItems( @@ -233,10 +233,7 @@ class _TaskPanel: # geometry selection widget self.selectionWidget = selection_widgets.GeometryElementsSelection( - obj.References, - ["Edge"], - False, - True + obj.References, ["Edge"], False, True ) # form made from param and selection widget @@ -345,11 +342,11 @@ class _TaskPanel: self.parameterWidget.if_enlarge_area2.setText(self.EnlargeArea2.UserString) self.parameterWidget.if_contract_area1.setText(self.ContractArea1.UserString) self.parameterWidget.if_contract_area2.setText(self.ContractArea2.UserString) - self.parameterWidget.if_inletpressure.setText(FreeCAD.Units.Quantity( - 1000 * self.InletPressure, FreeCAD.Units.Pressure).UserString + self.parameterWidget.if_inletpressure.setText( + FreeCAD.Units.Quantity(1000 * self.InletPressure, FreeCAD.Units.Pressure).UserString ) - self.parameterWidget.if_outletpressure.setText(FreeCAD.Units.Quantity( - 1000 * self.OutletPressure, FreeCAD.Units.Pressure).UserString + self.parameterWidget.if_outletpressure.setText( + FreeCAD.Units.Quantity(1000 * self.OutletPressure, FreeCAD.Units.Pressure).UserString ) self.parameterWidget.if_inletflowrate.setText(str(self.InletFlowRate)) self.parameterWidget.if_outletflowrate.setText(str(self.OutletFlowRate)) @@ -395,9 +392,7 @@ class _TaskPanel: self.parameterWidget.cb_liquid_section_type.setCurrentIndex(index) self.parameterWidget.sw_liquid_section_type.setCurrentIndex(index) # parameterWidget returns unicode - self.LiquidSectionType = str( - self.parameterWidget.cb_liquid_section_type.itemText(index) - ) + self.LiquidSectionType = str(self.parameterWidget.cb_liquid_section_type.itemText(index)) def manning_area_changed(self, base_quantity_value): self.ManningArea = base_quantity_value diff --git a/src/Mod/Fem/femtaskpanels/task_element_geometry1D.py b/src/Mod/Fem/femtaskpanels/task_element_geometry1D.py index 5461098e5c..07ff4931bc 100644 --- a/src/Mod/Fem/femtaskpanels/task_element_geometry1D.py +++ b/src/Mod/Fem/femtaskpanels/task_element_geometry1D.py @@ -54,32 +54,32 @@ class _TaskPanel: QtCore.QObject.connect( self.parameterWidget.cb_crosssectiontype, QtCore.SIGNAL("activated(int)"), - self.sectiontype_changed + self.sectiontype_changed, ) QtCore.QObject.connect( self.parameterWidget.if_rec_height, QtCore.SIGNAL("valueChanged(Base::Quantity)"), - self.rec_height_changed + self.rec_height_changed, ) QtCore.QObject.connect( self.parameterWidget.if_rec_width, QtCore.SIGNAL("valueChanged(Base::Quantity)"), - self.rec_width_changed + self.rec_width_changed, ) QtCore.QObject.connect( self.parameterWidget.if_circ_diameter, QtCore.SIGNAL("valueChanged(Base::Quantity)"), - self.circ_diameter_changed + self.circ_diameter_changed, ) QtCore.QObject.connect( self.parameterWidget.if_pipe_diameter, QtCore.SIGNAL("valueChanged(Base::Quantity)"), - self.pipe_diameter_changed + self.pipe_diameter_changed, ) QtCore.QObject.connect( self.parameterWidget.if_pipe_thickness, QtCore.SIGNAL("valueChanged(Base::Quantity)"), - self.pipe_thickness_changed + self.pipe_thickness_changed, ) self.parameterWidget.cb_crosssectiontype.addItems( @@ -90,10 +90,7 @@ class _TaskPanel: # geometry selection widget self.selectionWidget = selection_widgets.GeometryElementsSelection( - obj.References, - ["Edge"], - False, - True + obj.References, ["Edge"], False, True ) # form made from param and selection widget @@ -133,9 +130,7 @@ class _TaskPanel: def updateParameterWidget(self): "fills the widgets" - index_crosssectiontype = self.parameterWidget.cb_crosssectiontype.findText( - self.SectionType - ) + index_crosssectiontype = self.parameterWidget.cb_crosssectiontype.findText(self.SectionType) self.parameterWidget.cb_crosssectiontype.setCurrentIndex(index_crosssectiontype) self.parameterWidget.if_rec_height.setText(self.RectHeight.UserString) self.parameterWidget.if_rec_width.setText(self.RectWidth.UserString) diff --git a/src/Mod/Fem/femtaskpanels/task_element_geometry2D.py b/src/Mod/Fem/femtaskpanels/task_element_geometry2D.py index 4d4365b6b7..ecfe6f8f5e 100644 --- a/src/Mod/Fem/femtaskpanels/task_element_geometry2D.py +++ b/src/Mod/Fem/femtaskpanels/task_element_geometry2D.py @@ -53,16 +53,13 @@ class _TaskPanel: QtCore.QObject.connect( self.parameterWidget.if_thickness, QtCore.SIGNAL("valueChanged(Base::Quantity)"), - self.thickness_changed + self.thickness_changed, ) self.init_parameter_widget() # geometry selection widget self.selectionWidget = selection_widgets.GeometryElementsSelection( - obj.References, - ["Face"], - False, - True + obj.References, ["Face"], False, True ) # form made from param and selection widget diff --git a/src/Mod/Fem/femtaskpanels/task_element_rotation1D.py b/src/Mod/Fem/femtaskpanels/task_element_rotation1D.py index 1bf66d8d50..cabbd91ce8 100644 --- a/src/Mod/Fem/femtaskpanels/task_element_rotation1D.py +++ b/src/Mod/Fem/femtaskpanels/task_element_rotation1D.py @@ -53,17 +53,14 @@ class _TaskPanel: QtCore.QObject.connect( self.parameterWidget.if_rotation, QtCore.SIGNAL("valueChanged(Base::Quantity)"), - self.rotation_changed + self.rotation_changed, ) self.rotation = self.obj.Rotation self.parameterWidget.if_rotation.setText(self.rotation.UserString) # geometry selection widget self.selectionWidget = selection_widgets.GeometryElementsSelection( - obj.References, - ["Edge"], - False, - True + obj.References, ["Edge"], False, True ) # form made from param and selection widget diff --git a/src/Mod/Fem/femtaskpanels/task_material_common.py b/src/Mod/Fem/femtaskpanels/task_material_common.py index b88ceca6cc..85dae5f91d 100644 --- a/src/Mod/Fem/femtaskpanels/task_material_common.py +++ b/src/Mod/Fem/femtaskpanels/task_material_common.py @@ -72,63 +72,59 @@ class _TaskPanel: ) # globals QtCore.QObject.connect( - self.parameterWidget.cb_materials, - QtCore.SIGNAL("activated(int)"), - self.choose_material + self.parameterWidget.cb_materials, QtCore.SIGNAL("activated(int)"), self.choose_material ) QtCore.QObject.connect( self.parameterWidget.chbu_allow_edit, QtCore.SIGNAL("clicked()"), - self.toggleInputFieldsReadOnly + self.toggleInputFieldsReadOnly, ) QtCore.QObject.connect( - self.parameterWidget.pushButton_editMat, - QtCore.SIGNAL("clicked()"), - self.edit_material + 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 + self.density_changed, ) # mechanical properties QtCore.QObject.connect( self.parameterWidget.input_fd_young_modulus, QtCore.SIGNAL("editingFinished()"), - self.ym_changed + self.ym_changed, ) QtCore.QObject.connect( self.parameterWidget.spinBox_poisson_ratio, QtCore.SIGNAL("editingFinished()"), - self.pr_changed + self.pr_changed, ) # thermal properties QtCore.QObject.connect( self.parameterWidget.input_fd_thermal_conductivity, QtCore.SIGNAL("editingFinished()"), - self.tc_changed + self.tc_changed, ) QtCore.QObject.connect( self.parameterWidget.input_fd_expansion_coefficient, QtCore.SIGNAL("editingFinished()"), - self.tec_changed + self.tec_changed, ) QtCore.QObject.connect( self.parameterWidget.input_fd_specific_heat, QtCore.SIGNAL("editingFinished()"), - self.sh_changed + 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 + self.kinematic_viscosity_changed, ) QtCore.QObject.connect( self.parameterWidget.input_fd_vol_expansion_coefficient, QtCore.SIGNAL("editingFinished()"), - self.vtec_changed + self.vtec_changed, ) # init all parameter input files with read only @@ -150,6 +146,7 @@ class _TaskPanel: # get all available materials (fill self.materials, self.cards and self.icons) from materialtools.cardutils import import_materials as getmats + # Note: import_materials(category="Solid", ...), # category default to Solid, but must be given for FluidMaterial to be imported self.materials, self.cards, self.icons = getmats(self.obj.Category) @@ -158,7 +155,7 @@ class _TaskPanel: # 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: {}\n".format(self.card_path)) + FreeCAD.Console.PrintLog(f"card_path: {self.card_path}\n") 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 @@ -169,9 +166,7 @@ class _TaskPanel: 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 + QtGui.QIcon(":/icons/help-browser.svg"), self.card_path, self.card_path ) index = self.parameterWidget.cb_materials.findData(self.card_path) # fill input fields and set the current material in the cb widget @@ -188,10 +183,7 @@ class _TaskPanel: # geometry selection widget self.selectionWidget = selection_widgets.GeometryElementsSelection( - obj.References, - ["Solid", "Face", "Edge"], - False, - True + obj.References, ["Solid", "Face", "Edge"], False, True ) # start with Solid in list! # form made from param and selection widget @@ -210,6 +202,7 @@ class _TaskPanel: if self.selectionWidget.has_equal_references_shape_types(): self.do_not_set_thermal_zeros() from materialtools.cardutils import check_mat_units as checkunits + if checkunits(self.material) is True: self.obj.Material = self.material self.obj.References = self.selectionWidget.references @@ -234,7 +227,7 @@ class _TaskPanel: doc.resetEdit() def do_not_set_thermal_zeros(self): - """ thermal material parameter are set to 0.0 if not available + """thermal material parameter are set to 0.0 if not available this leads to wrong material values and to not finding the card on reopen the task pane, thus do not write thermal parameter, if they are 0.0 @@ -254,8 +247,7 @@ class _TaskPanel: if Units.Quantity(self.material["SpecificHeat"]) == 0.0: self.material.pop("SpecificHeat", None) FreeCAD.Console.PrintMessage( - "Zero SpecificHeat value. " - "This parameter is not saved in the material data.\n" + "Zero SpecificHeat value. This parameter is not saved in the material data.\n" ) def isfloat(self, num): @@ -302,10 +294,7 @@ class _TaskPanel: if index < 0: return self.card_path = self.parameterWidget.cb_materials.itemData(index) # returns whole path - FreeCAD.Console.PrintMessage( - "Material card chosen:\n" - " {}\n".format(self.card_path) - ) + FreeCAD.Console.PrintMessage(f"Material card chosen:\n {self.card_path}\n") self.material = self.materials[self.card_path] self.check_material_keys() self.set_mat_params_in_input_fields(self.material) @@ -330,9 +319,7 @@ class _TaskPanel: self.has_transient_mat = True self.card_path = "_transient_material" self.parameterWidget.cb_materials.addItem( - QtGui.QIcon(":/icons/help-browser.svg"), - self.card_path, - self.card_path + QtGui.QIcon(":/icons/help-browser.svg"), self.card_path, self.card_path ) self.set_transient_material() @@ -340,15 +327,18 @@ class _TaskPanel: def edit_material(self): # opens the material editor to choose a material or edit material params import MaterialEditor + if self.card_path not in self.cards: FreeCAD.Console.PrintLog( "Card path not in cards, material dict will be used to open Material Editor.\n" ) new_material_params = MaterialEditor.editMaterial( - material=self.material, category=self.obj.Category) + material=self.material, category=self.obj.Category + ) else: - new_material_params = MaterialEditor.editMaterial(card_path=self.card_path, - category=self.obj.Category) + new_material_params = MaterialEditor.editMaterial( + card_path=self.card_path, category=self.obj.Category + ) # material editor returns the mat_dict only, not a card_path # if the material editor was canceled a empty dict will be returned # do not change the self.material @@ -356,6 +346,7 @@ class _TaskPanel: if new_material_params: # check material quantity units from materialtools.cardutils import check_mat_units as checkunits + if checkunits(new_material_params) is True: self.material = new_material_params self.card_path = self.get_material_card(self.material) @@ -390,9 +381,7 @@ class _TaskPanel: FreeCAD.Console.PrintError(error_message) QtGui.QMessageBox.critical(None, "Material data not changed", error_message) else: - FreeCAD.Console.PrintLog( - "No changes where made by the material editor.\n" - ) + FreeCAD.Console.PrintLog("No changes where made by the material editor.\n") def toggleInputFieldsReadOnly(self): if self.parameterWidget.chbu_allow_edit.isChecked(): @@ -423,8 +412,7 @@ class _TaskPanel: if "Density" not in str(Units.Unit(self.material["Density"])): FreeCAD.Console.PrintMessage( "Density in material data seems to have no unit " - "or a wrong unit (reset the value): {}\n" - .format(self.material["Name"]) + "or a wrong unit (reset the value): {}\n".format(self.material["Name"]) ) self.material["Density"] = "0 kg/m^3" else: @@ -440,8 +428,7 @@ class _TaskPanel: if "Pressure" not in str(Units.Unit(self.material["YoungsModulus"])): FreeCAD.Console.PrintMessage( "YoungsModulus in material data seems to have no unit " - "or a wrong unit (reset the value): {}\n" - .format(self.material["Name"]) + "or a wrong unit (reset the value): {}\n".format(self.material["Name"]) ) self.material["YoungsModulus"] = "0 MPa" else: @@ -458,8 +445,9 @@ class _TaskPanel: float(self.material["PoissonRatio"]) except ValueError: FreeCAD.Console.PrintMessage( - "PoissonRatio has wrong or no data (reset the value): {}\n" - .format(self.material["PoissonRatio"]) + "PoissonRatio has wrong or no data (reset the value): {}\n".format( + self.material["PoissonRatio"] + ) ) self.material["PoissonRatio"] = "0" else: @@ -475,8 +463,7 @@ class _TaskPanel: if "KinematicViscosity" not in str(Units.Unit(ki_vis)): FreeCAD.Console.PrintMessage( "KinematicViscosity in material data seems to have no unit " - "or a wrong unit (reset the value): {}\n" - .format(self.material["Name"]) + "or a wrong unit (reset the value): {}\n".format(self.material["Name"]) ) self.material["KinematicViscosity"] = "0 m^2/s" else: @@ -490,15 +477,17 @@ class _TaskPanel: if "ThermalExpansionCoefficient" not in str(Units.Unit(vol_ther_ex_co)): FreeCAD.Console.PrintMessage( "ThermalExpansionCoefficient in material data " - "seems to have no unit or a wrong unit (reset the value): {}\n" - .format(self.material["Name"]) + "seems to have no unit or a wrong unit (reset the value): {}\n".format( + self.material["Name"] + ) ) self.material["ThermalExpansionCoefficient"] = "0 1/K" else: if self.material["Name"] != "NoName": FreeCAD.Console.PrintMessage( - "ThermalExpansionCoefficient not found in {}\n" - .format(self.material["Name"]) + "ThermalExpansionCoefficient not found in {}\n".format( + self.material["Name"] + ) ) self.material["ThermalExpansionCoefficient"] = "0 1/K" if "VolumetricThermalExpansionCoefficient" in self.material: @@ -507,8 +496,9 @@ class _TaskPanel: if "ThermalExpansionCoefficient" not in str(Units.Unit(vol_ther_ex_co)): FreeCAD.Console.PrintMessage( "VolumetricThermalExpansionCoefficient in material data " - "seems to have no unit or a wrong unit (reset the value): {}\n" - .format(self.material["Name"]) + "seems to have no unit or a wrong unit (reset the value): {}\n".format( + self.material["Name"] + ) ) self.material["VolumetricThermalExpansionCoefficient"] = "0 1/K" else: @@ -527,18 +517,15 @@ class _TaskPanel: "Problem with the quantity for ThermalConductivity: '{}' Reset value.\n" "May try the following in Python console:\n" "from FreeCAD import Units\n" - "Units.Quantity('{}')\n" - .format( - self.material["ThermalConductivity"], - self.material["ThermalConductivity"] + "Units.Quantity('{}')\n".format( + self.material["ThermalConductivity"], self.material["ThermalConductivity"] ) ) self.material["ThermalConductivity"] = "0 W/m/K" if "ThermalConductivity" not in str(Units.Unit(self.material["ThermalConductivity"])): FreeCAD.Console.PrintMessage( "ThermalConductivity in material data seems to have no unit " - "or a wrong unit (reset the value): {}\n" - .format(self.material["Name"]) + "or a wrong unit (reset the value): {}\n".format(self.material["Name"]) ) self.material["ThermalConductivity"] = "0 W/m/K" else: @@ -552,8 +539,7 @@ class _TaskPanel: if "ThermalExpansionCoefficient" not in str(Units.Unit(the_ex_co)): FreeCAD.Console.PrintMessage( "ThermalExpansionCoefficient in material data seems to have no unit " - "or a wrong unit (reset the value): {}\n" - .format(self.material["Name"]) + "or a wrong unit (reset the value): {}\n".format(self.material["Name"]) ) self.material["ThermalExpansionCoefficient"] = "0 um/m/K" else: @@ -566,8 +552,7 @@ class _TaskPanel: if "SpecificHeat" not in str(Units.Unit(self.material["SpecificHeat"])): FreeCAD.Console.PrintMessage( "SpecificHeat in material data seems to have no unit " - "or a wrong unit (reset the value): {}\n" - .format(self.material["Name"]) + "or a wrong unit (reset the value): {}\n".format(self.material["Name"]) ) self.material["SpecificHeat"] = "0 J/kg/K" else: @@ -618,8 +603,9 @@ class _TaskPanel: def density_changed(self): print( - "String read from density input field: {}" - .format(self.parameterWidget.input_fd_density.text()) + "String read from density input field: {}".format( + self.parameterWidget.input_fd_density.text() + ) ) # FreeCADs standard unit for density is kg/mm^3 for UnitsSchemeInternal self.update_material_property( @@ -688,7 +674,7 @@ class _TaskPanel: ym_new_unit = "MPa" ym = Units.Quantity(matmap["YoungsModulus"]) ym_with_new_unit = ym.getValueAs(ym_new_unit) - q = Units.Quantity("{} {}".format(ym_with_new_unit, ym_new_unit)) + q = Units.Quantity(f"{ym_with_new_unit} {ym_new_unit}") self.parameterWidget.input_fd_young_modulus.setText(q.UserString) if "PoissonRatio" in matmap: self.parameterWidget.spinBox_poisson_ratio.setValue(float(matmap["PoissonRatio"])) @@ -697,7 +683,7 @@ class _TaskPanel: nu_new_unit = "m^2/s" nu = Units.Quantity(matmap["KinematicViscosity"]) nu_with_new_unit = nu.getValueAs(nu_new_unit) - q = Units.Quantity("{} {}".format(nu_with_new_unit, nu_new_unit)) + q = Units.Quantity(f"{nu_with_new_unit} {nu_new_unit}") self.parameterWidget.input_fd_kinematic_viscosity.setText(q.UserString) # For isotropic materials and fluidic material # use the volumetric thermal expansion coefficient @@ -706,7 +692,7 @@ class _TaskPanel: vtec_new_unit = "m^3/m^3/K" vtec = Units.Quantity(matmap["VolumetricThermalExpansionCoefficient"]) vtec_with_new_unit = vtec.getValueAs(vtec_new_unit) - q = Units.Quantity("{} {}".format(vtec_with_new_unit, vtec_new_unit)) + q = Units.Quantity(f"{vtec_with_new_unit} {vtec_new_unit}") self.parameterWidget.input_fd_vol_expansion_coefficient.setText(q.UserString) if "Density" in matmap: density_new_unit = "kg/m^3" @@ -715,26 +701,26 @@ class _TaskPanel: # self.parameterWidget.input_fd_density.setText( # "{} {}".format(density_with_new_unit, density_new_unit) # ) - q = Units.Quantity("{} {}".format(density_with_new_unit, density_new_unit)) + q = Units.Quantity(f"{density_with_new_unit} {density_new_unit}") self.parameterWidget.input_fd_density.setText(q.UserString) # thermal properties if "ThermalConductivity" in matmap: tc_new_unit = "W/m/K" tc = Units.Quantity(matmap["ThermalConductivity"]) tc_with_new_unit = tc.getValueAs(tc_new_unit) - q = Units.Quantity("{} {}".format(tc_with_new_unit, tc_new_unit)) + q = Units.Quantity(f"{tc_with_new_unit} {tc_new_unit}") self.parameterWidget.input_fd_thermal_conductivity.setText(q.UserString) if "ThermalExpansionCoefficient" in matmap: # linear, only for solid tec_new_unit = "um/m/K" tec = Units.Quantity(matmap["ThermalExpansionCoefficient"]) tec_with_new_unit = tec.getValueAs(tec_new_unit) - q = Units.Quantity("{} {}".format(tec_with_new_unit, tec_new_unit)) + q = Units.Quantity(f"{tec_with_new_unit} {tec_new_unit}") self.parameterWidget.input_fd_expansion_coefficient.setText(q.UserString) if "SpecificHeat" in matmap: sh_new_unit = "J/kg/K" sh = Units.Quantity(matmap["SpecificHeat"]) sh_with_new_unit = sh.getValueAs(sh_new_unit) - q = Units.Quantity("{} {}".format(sh_with_new_unit, sh_new_unit)) + q = Units.Quantity(f"{sh_with_new_unit} {sh_new_unit}") self.parameterWidget.input_fd_specific_heat.setText(q.UserString) # fill the combo box with cards ************************************************************** diff --git a/src/Mod/Fem/femtaskpanels/task_material_reinforced.py b/src/Mod/Fem/femtaskpanels/task_material_reinforced.py index f8549bd658..9f3e1af491 100644 --- a/src/Mod/Fem/femtaskpanels/task_material_reinforced.py +++ b/src/Mod/Fem/femtaskpanels/task_material_reinforced.py @@ -79,26 +79,23 @@ class _TaskPanel: QtCore.QObject.connect( self.parameterWidget.cb_materials_m, QtCore.SIGNAL("activated(int)"), - self.choose_material_m + self.choose_material_m, ) QtCore.QObject.connect( - self.parameterWidget.pb_edit_m, - QtCore.SIGNAL("clicked()"), - self.edit_material_m + 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 + self.choose_material_r, ) QtCore.QObject.connect( - self.parameterWidget.pb_edit_r, - QtCore.SIGNAL("clicked()"), - self.edit_material_r + 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() @@ -106,7 +103,7 @@ class _TaskPanel: # 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)) + FreeCAD.Console.PrintLog(f"card_path: {self.card_path_m}\n") 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 @@ -117,9 +114,7 @@ class _TaskPanel: 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 + 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) # fill input fields and set the current material in the cb widget @@ -136,7 +131,7 @@ class _TaskPanel: # 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)) + FreeCAD.Console.PrintLog(f"card_path: {self.card_path_r}\n") 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 @@ -147,9 +142,7 @@ class _TaskPanel: 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 + 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 @@ -170,6 +163,7 @@ class _TaskPanel: # leave task panel *************************************************************************** def accept(self): from materialtools.cardutils import check_mat_units as checkunits + if checkunits(self.material_m) is True and checkunits(self.material_r) is True: self.obj.Material = self.material_m self.obj.Reinforcement = self.material_r @@ -204,7 +198,7 @@ class _TaskPanel: else: print("Matrix material: no Name") for key in mat_dict: - print(" {}: {}".format(key, mat_dict[key])) + print(f" {key}: {mat_dict[key]}") # choose material card *********************************************************************** def get_material_card(self, material): @@ -212,7 +206,7 @@ class _TaskPanel: unmatched_items = set(self.materials[a_mat].items()) ^ set(material.items()) # print(a_mat + " --> unmatched_items = " + str(len(unmatched_items))) if len(unmatched_items) < 4: - FreeCAD.Console.PrintLog("{}\n".format(unmatched_items)) + FreeCAD.Console.PrintLog(f"{unmatched_items}\n") if len(unmatched_items) == 0: return a_mat return "" @@ -223,8 +217,7 @@ class _TaskPanel: # get the whole card path self.card_path_m = self.parameterWidget.cb_materials_m.itemData(index) FreeCAD.Console.PrintMessage( - "choose_material in FEM material task panel:\n" - " {}\n".format(self.card_path_m) + f"choose_material in FEM material task panel:\n {self.card_path_m}\n" ) self.material_m = self.materials[self.card_path_m] self.parameterWidget.cb_materials_m.setCurrentIndex(index) @@ -243,8 +236,7 @@ class _TaskPanel: # get the whole card path self.card_path_r = self.parameterWidget.cb_materials_r.itemData(index) FreeCAD.Console.PrintMessage( - "choose_material in FEM material task panel:\n" - " {}\n".format(self.card_path_r) + f"choose_material in FEM material task panel:\n {self.card_path_r}\n" ) self.material_r = self.materials[self.card_path_r] self.parameterWidget.cb_materials_r.setCurrentIndex(index) @@ -268,9 +260,7 @@ class _TaskPanel: self.has_transient_mat_m = True self.card_path_m = "_Transient_Matrix_Material" self.parameterWidget.cb_materials_m.addItem( - QtGui.QIcon(":/icons/help-browser.svg"), - self.card_path_m, - self.card_path_m + QtGui.QIcon(":/icons/help-browser.svg"), self.card_path_m, self.card_path_m ) self.set_transient_material_m() @@ -284,9 +274,7 @@ class _TaskPanel: self.has_transient_mat_r = True self.card_path_r = "_Transient_Reinforcement_Material" self.parameterWidget.cb_materials_r.addItem( - QtGui.QIcon(":/icons/help-browser.svg"), - self.card_path_r, - self.card_path_r + QtGui.QIcon(":/icons/help-browser.svg"), self.card_path_r, self.card_path_r ) self.set_transient_material_r() @@ -297,6 +285,7 @@ class _TaskPanel: def edit_material_m(self): # opens the material editor to choose a material or edit material params import MaterialEditor + if self.card_path_m not in self.cards: FreeCAD.Console.PrintLog( "Card path not in cards, material dict will be used to open Material Editor.\n" @@ -311,10 +300,11 @@ class _TaskPanel: if new_material_params: # check material quantity units from materialtools.cardutils import check_mat_units as checkunits + if checkunits(new_material_params) is True: self.material_m = new_material_params self.card_path_m = self.get_material_card(self.material_m) - FreeCAD.Console.PrintMessage("card_path: {}\n".format(self.card_path_m)) + FreeCAD.Console.PrintMessage(f"card_path: {self.card_path_m}\n") if not self.card_path_m: FreeCAD.Console.PrintMessage( "Material card chosen by the material editor " @@ -349,6 +339,7 @@ class _TaskPanel: def edit_material_r(self): # opens the material editor to choose a material or edit material params import MaterialEditor + if self.card_path_r not in self.cards: FreeCAD.Console.PrintLog( "Card path not in cards, material dict will be used to open Material Editor.\n" @@ -363,10 +354,11 @@ class _TaskPanel: if new_material_params: # check material quantity units from materialtools.cardutils import check_mat_units as checkunits + if checkunits(new_material_params) is True: self.material_r = new_material_params self.card_path_r = self.get_material_card(self.material_r) - FreeCAD.Console.PrintMessage("card_path: {}\n".format(self.card_path_r)) + FreeCAD.Console.PrintMessage(f"card_path: {self.card_path_r}\n") if not self.card_path_r: FreeCAD.Console.PrintMessage( "Material card chosen by the material editor " diff --git a/src/Mod/Fem/femtaskpanels/task_mesh_boundarylayer.py b/src/Mod/Fem/femtaskpanels/task_mesh_boundarylayer.py index f545d610fc..a88506021a 100644 --- a/src/Mod/Fem/femtaskpanels/task_mesh_boundarylayer.py +++ b/src/Mod/Fem/femtaskpanels/task_mesh_boundarylayer.py @@ -53,28 +53,25 @@ class _TaskPanel: QtCore.QObject.connect( self.parameterWidget.bl_number_of_layers, QtCore.SIGNAL("valueChanged(int)"), - self.bl_number_of_layers_changed + self.bl_number_of_layers_changed, ) QtCore.QObject.connect( self.parameterWidget.bl_min_thickness, QtCore.SIGNAL("valueChanged(Base::Quantity)"), - self.bl_min_thickness_changed + 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.bl_growth_rate_changed, ) self.init_parameter_widget() # geometry selection widget # start with Solid in list! self.selectionWidget = selection_widgets.GeometryElementsSelection( - obj.References, - ["Solid", "Face", "Edge", "Vertex"], - True, - False + obj.References, ["Solid", "Face", "Edge", "Vertex"], True, False ) # form made from param and selection widget diff --git a/src/Mod/Fem/femtaskpanels/task_mesh_gmsh.py b/src/Mod/Fem/femtaskpanels/task_mesh_gmsh.py index 856b8fc7ae..0e0dfbdfb7 100644 --- a/src/Mod/Fem/femtaskpanels/task_mesh_gmsh.py +++ b/src/Mod/Fem/femtaskpanels/task_mesh_gmsh.py @@ -64,50 +64,34 @@ class _TaskPanel: self.console_message_gmsh = "" QtCore.QObject.connect( - self.form.if_max, - QtCore.SIGNAL("valueChanged(Base::Quantity)"), - self.max_changed + self.form.if_max, QtCore.SIGNAL("valueChanged(Base::Quantity)"), self.max_changed ) QtCore.QObject.connect( - self.form.if_min, - QtCore.SIGNAL("valueChanged(Base::Quantity)"), - self.min_changed + self.form.if_min, QtCore.SIGNAL("valueChanged(Base::Quantity)"), self.min_changed ) QtCore.QObject.connect( - self.form.cb_dimension, - QtCore.SIGNAL("activated(int)"), - self.choose_dimension + self.form.cb_dimension, QtCore.SIGNAL("activated(int)"), self.choose_dimension ) QtCore.QObject.connect( - self.form.cb_order, - QtCore.SIGNAL("activated(int)"), - self.choose_order + self.form.cb_order, QtCore.SIGNAL("activated(int)"), self.choose_order ) + QtCore.QObject.connect(self.Timer, QtCore.SIGNAL("timeout()"), self.update_timer_text) QtCore.QObject.connect( - self.Timer, - QtCore.SIGNAL("timeout()"), - self.update_timer_text - ) - QtCore.QObject.connect( - self.form.pb_get_gmsh_version, - QtCore.SIGNAL("clicked()"), - self.get_gmsh_version + self.form.pb_get_gmsh_version, QtCore.SIGNAL("clicked()"), self.get_gmsh_version ) - self.form.cb_dimension.addItems( - mesh_gmsh.MeshGmsh.known_element_dimensions - ) + self.form.cb_dimension.addItems(mesh_gmsh.MeshGmsh.known_element_dimensions) - self.form.cb_order.addItems( - mesh_gmsh.MeshGmsh.known_element_orders - ) + self.form.cb_order.addItems(mesh_gmsh.MeshGmsh.known_element_orders) self.get_mesh_params() self.get_active_analysis() self.update() def getStandardButtons(self): - button_value = QtGui.QDialogButtonBox.Ok | QtGui.QDialogButtonBox.Apply | QtGui.QDialogButtonBox.Cancel + button_value = ( + QtGui.QDialogButtonBox.Ok | QtGui.QDialogButtonBox.Apply | QtGui.QDialogButtonBox.Cancel + ) return button_value # show a OK, a apply and a Cancel button # def reject() is called on Cancel button @@ -158,9 +142,7 @@ class _TaskPanel: ) ) if outputwin_color_type: - if ( - outputwin_color_type == "#00AA00" - ): # Success is not part of output window parameters + if outputwin_color_type == "#00AA00": # Success is not part of output window parameters self.console_message_gmsh += '{}
'.format( outputwin_color_type, message ) @@ -178,7 +160,7 @@ class _TaskPanel: if self.gmsh_runs: FreeCAD.Console.PrintMessage("timer2\n") # FreeCAD.Console.PrintMessage("Time: {0:4.1f}: \n".format(time.time() - self.Start)) - self.form.l_time.setText("Time: {0:4.1f}: ".format(time.time() - self.Start)) + self.form.l_time.setText(f"Time: {time.time() - self.Start:4.1f}: ") def max_changed(self, base_quantity_value): self.clmax = base_quantity_value @@ -200,24 +182,23 @@ class _TaskPanel: def get_gmsh_version(self): from femmesh import gmshtools + version, full_message = gmshtools.GmshTools(self.mesh_obj, self.analysis).get_gmsh_version() if version[0] and version[1] and version[2]: messagebox = QtGui.QMessageBox.information else: messagebox = QtGui.QMessageBox.warning - messagebox( - None, - "Gmsh - Information", - full_message - ) + messagebox(None, "Gmsh - Information", full_message) def run_gmsh(self): from femmesh import gmshtools + gmsh_mesh = gmshtools.GmshTools(self.mesh_obj, self.analysis) QApplication.setOverrideCursor(Qt.WaitCursor) part = self.mesh_obj.Part if ( - self.mesh_obj.MeshRegionList and part.Shape.ShapeType == "Compound" + self.mesh_obj.MeshRegionList + and part.Shape.ShapeType == "Compound" and ( is_of_type(part, "FeatureBooleanFragments") or is_of_type(part, "FeatureSlice") @@ -226,7 +207,7 @@ class _TaskPanel: ): gmsh_mesh.outputCompoundWarning() self.Start = time.time() - self.form.l_time.setText("Time: {0:4.1f}: ".format(time.time() - self.Start)) + self.form.l_time.setText(f"Time: {time.time() - self.Start:4.1f}: ") self.console_message_gmsh = "" self.gmsh_runs = True self.console_log("We are going to start ...") @@ -237,20 +218,17 @@ class _TaskPanel: error = gmsh_mesh.create_mesh() except Exception: error = sys.exc_info()[1] - FreeCAD.Console.PrintError( - "Unexpected error when creating mesh: {}\n" - .format(error) - ) + FreeCAD.Console.PrintError(f"Unexpected error when creating mesh: {error}\n") if error: FreeCAD.Console.PrintWarning("Gmsh had warnings:\n") - FreeCAD.Console.PrintWarning("{}\n".format(error)) + FreeCAD.Console.PrintWarning(f"{error}\n") self.console_log("Gmsh had warnings ...", "Warning") self.console_log(error, "Error") else: FreeCAD.Console.PrintMessage("Clean run of Gmsh\n") self.console_log("Clean run of Gmsh", "#00AA00") self.console_log("Gmsh done!") - self.form.l_time.setText("Time: {0:4.1f}: ".format(time.time() - self.Start)) + self.form.l_time.setText(f"Time: {time.time() - self.Start:4.1f}: ") self.Timer.stop() self.update() QApplication.restoreOverrideCursor() @@ -263,10 +241,7 @@ class _TaskPanel: else: for m in analysis.Group: if m.Name == self.mesh_obj.Name: - FreeCAD.Console.PrintLog( - "Active analysis found: {}\n" - .format(analysis.Name) - ) + FreeCAD.Console.PrintLog(f"Active analysis found: {analysis.Name}\n") self.analysis = analysis # group meshing break else: diff --git a/src/Mod/Fem/femtaskpanels/task_mesh_group.py b/src/Mod/Fem/femtaskpanels/task_mesh_group.py index c369d57e40..c1e2030839 100644 --- a/src/Mod/Fem/femtaskpanels/task_mesh_group.py +++ b/src/Mod/Fem/femtaskpanels/task_mesh_group.py @@ -53,22 +53,19 @@ class _TaskPanel: QtCore.QObject.connect( self.parameterWidget.rb_name, QtCore.SIGNAL("toggled(bool)"), - self.choose_exportidentifier_name + self.choose_exportidentifier_name, ) QtCore.QObject.connect( self.parameterWidget.rb_label, QtCore.SIGNAL("toggled(bool)"), - self.choose_exportidentifier_label + self.choose_exportidentifier_label, ) self.init_parameter_widget() # geometry selection widget # start with Solid in list! self.selectionWidget = selection_widgets.GeometryElementsSelection( - obj.References, - ["Solid", "Face", "Edge", "Vertex"], - True, - False + obj.References, ["Solid", "Face", "Edge", "Vertex"], True, False ) # form made from param and selection widget diff --git a/src/Mod/Fem/femtaskpanels/task_mesh_region.py b/src/Mod/Fem/femtaskpanels/task_mesh_region.py index 553fbbac32..cd72d9a0f8 100644 --- a/src/Mod/Fem/femtaskpanels/task_mesh_region.py +++ b/src/Mod/Fem/femtaskpanels/task_mesh_region.py @@ -53,17 +53,14 @@ class _TaskPanel: QtCore.QObject.connect( self.parameterWidget.if_elelen, QtCore.SIGNAL("valueChanged(Base::Quantity)"), - self.elelen_changed + self.elelen_changed, ) self.init_parameter_widget() # geometry selection widget # start with Solid in list! self.selectionWidget = selection_widgets.GeometryElementsSelection( - obj.References, - ["Solid", "Face", "Edge", "Vertex"], - True, - False + obj.References, ["Solid", "Face", "Edge", "Vertex"], True, False ) # form made from param and selection widget diff --git a/src/Mod/Fem/femtaskpanels/task_result_mechanical.py b/src/Mod/Fem/femtaskpanels/task_result_mechanical.py index f0ec4e9d77..7b93c64232 100644 --- a/src/Mod/Fem/femtaskpanels/task_result_mechanical.py +++ b/src/Mod/Fem/femtaskpanels/task_result_mechanical.py @@ -32,6 +32,7 @@ __url__ = "https://www.freecad.org" try: import matplotlib + matplotlib.use("Qt5Agg") except Exception: print("Failed to set matplotlib backend to Qt5Agg") @@ -71,113 +72,92 @@ class _TaskPanel: 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 - ) + 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 + 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 + self.abs_displacement_selected, ) QtCore.QObject.connect( self.result_widget.rb_x_displacement, QtCore.SIGNAL("toggled(bool)"), - self.x_displacement_selected + self.x_displacement_selected, ) QtCore.QObject.connect( self.result_widget.rb_y_displacement, QtCore.SIGNAL("toggled(bool)"), - self.y_displacement_selected + self.y_displacement_selected, ) QtCore.QObject.connect( self.result_widget.rb_z_displacement, QtCore.SIGNAL("toggled(bool)"), - self.z_displacement_selected + self.z_displacement_selected, ) QtCore.QObject.connect( self.result_widget.rb_temperature, QtCore.SIGNAL("toggled(bool)"), - self.temperature_selected + self.temperature_selected, ) QtCore.QObject.connect( - self.result_widget.rb_vm_stress, - QtCore.SIGNAL("toggled(bool)"), - self.vm_stress_selected + 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 + 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 + 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 + self.max_shear_selected, ) QtCore.QObject.connect( self.result_widget.rb_massflowrate, QtCore.SIGNAL("toggled(bool)"), - self.massflowrate_selected + self.massflowrate_selected, ) QtCore.QObject.connect( self.result_widget.rb_networkpressure, QtCore.SIGNAL("toggled(bool)"), - self.networkpressure_selected + self.networkpressure_selected, ) QtCore.QObject.connect( - self.result_widget.rb_peeq, - QtCore.SIGNAL("toggled(bool)"), - self.peeq_selected + self.result_widget.rb_peeq, QtCore.SIGNAL("toggled(bool)"), self.peeq_selected ) # stats - self.result_widget.show_histogram.clicked.connect( - self.show_histogram_clicked - ) + 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 + self.show_displacement, ) QtCore.QObject.connect( self.result_widget.hsb_displacement_factor, QtCore.SIGNAL("valueChanged(int)"), - self.hsb_disp_factor_changed + self.hsb_disp_factor_changed, ) - self.result_widget.sb_displacement_factor.valueChanged.connect( - self.sb_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 - ) + 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.result_widget.calculate, QtCore.SIGNAL("clicked()"), self.calculate ) self.update() @@ -187,7 +167,7 @@ class _TaskPanel: 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_max.setValue(10.0 * scale_factor) self.result_widget.sb_displacement_factor.setValue(scale_factor) def restore_result_dialog(self): @@ -259,10 +239,10 @@ class _TaskPanel: FreeCAD.FEM_dialog = { "results_type": "None", "show_disp": False, - "disp_factor": 0., - "disp_factor_max": 100. + "disp_factor": 0.0, + "disp_factor_max": 100.0, } - self.result_widget.sb_displacement_factor_max.setValue(100.) # init non standard values + self.result_widget.sb_displacement_factor_max.setValue(100.0) # init non standard values def getStandardButtons(self): return QtGui.QDialogButtonBox.Close @@ -290,7 +270,7 @@ class _TaskPanel: "Uabs", self.result_obj.DisplacementLengths, "mm", - translate("FEM", "Displacement Magnitude") + translate("FEM", "Displacement Magnitude"), ) else: self.result_widget.rb_none.setChecked(True) @@ -298,45 +278,24 @@ class _TaskPanel: def x_displacement_selected(self, state): if len(self.result_obj.DisplacementVectors) > 0: - res_disp_u1 = self.get_scalar_disp_list( - self.result_obj.DisplacementVectors, 0 - ) - self.result_selected( - "U1", - res_disp_u1, - "mm", - translate("FEM", "Displacement X") - ) + res_disp_u1 = self.get_scalar_disp_list(self.result_obj.DisplacementVectors, 0) + self.result_selected("U1", res_disp_u1, "mm", translate("FEM", "Displacement X")) else: self.result_widget.rb_none.setChecked(True) self.none_selected(True) def y_displacement_selected(self, state): if len(self.result_obj.DisplacementVectors) > 0: - res_disp_u2 = self.get_scalar_disp_list( - self.result_obj.DisplacementVectors, 1 - ) - self.result_selected( - "U2", - res_disp_u2, - "mm", - translate("FEM", "Displacement Y") - ) + res_disp_u2 = self.get_scalar_disp_list(self.result_obj.DisplacementVectors, 1) + self.result_selected("U2", res_disp_u2, "mm", translate("FEM", "Displacement Y")) else: self.result_widget.rb_none.setChecked(True) self.none_selected(True) def z_displacement_selected(self, state): if len(self.result_obj.DisplacementVectors) > 0: - res_disp_u3 = self.get_scalar_disp_list( - self.result_obj.DisplacementVectors, 2 - ) - self.result_selected( - "U3", - res_disp_u3, - "mm", - translate("FEM", "Displacement Z") - ) + res_disp_u3 = self.get_scalar_disp_list(self.result_obj.DisplacementVectors, 2) + self.result_selected("U3", res_disp_u3, "mm", translate("FEM", "Displacement Z")) else: self.result_widget.rb_none.setChecked(True) self.none_selected(True) @@ -344,10 +303,7 @@ class _TaskPanel: def vm_stress_selected(self, state): if len(self.result_obj.vonMises) > 0: self.result_selected( - "Sabs", - self.result_obj.vonMises, - "MPa", - translate("FEM", "von Mises Stress") + "Sabs", self.result_obj.vonMises, "MPa", translate("FEM", "von Mises Stress") ) else: self.result_widget.rb_none.setChecked(True) @@ -356,10 +312,7 @@ class _TaskPanel: def max_shear_selected(self, state): if len(self.result_obj.MaxShear) > 0: self.result_selected( - "MaxShear", - self.result_obj.MaxShear, - "MPa", - translate("FEM", "Max Shear Stress") + "MaxShear", self.result_obj.MaxShear, "MPa", translate("FEM", "Max Shear Stress") ) else: self.result_widget.rb_none.setChecked(True) @@ -371,7 +324,7 @@ class _TaskPanel: "MaxPrin", self.result_obj.PrincipalMax, "MPa", - translate("FEM", "Max Principal Stress") + translate("FEM", "Max Principal Stress"), ) else: self.result_widget.rb_none.setChecked(True) @@ -380,10 +333,7 @@ class _TaskPanel: def temperature_selected(self, state): if len(self.result_obj.Temperature) > 0: self.result_selected( - "Temp", - self.result_obj.Temperature, - "K", - translate("FEM", "Temperature") + "Temp", self.result_obj.Temperature, "K", translate("FEM", "Temperature") ) else: self.result_widget.rb_none.setChecked(True) @@ -392,10 +342,7 @@ class _TaskPanel: def massflowrate_selected(self, state): if len(self.result_obj.MassFlowRate) > 0: self.result_selected( - "MFlow", - self.result_obj.MassFlowRate, - "kg/s", - translate("FEM", "Mass Flow Rate") + "MFlow", self.result_obj.MassFlowRate, "kg/s", translate("FEM", "Mass Flow Rate") ) else: self.result_widget.rb_none.setChecked(True) @@ -407,7 +354,7 @@ class _TaskPanel: "NPress", self.result_obj.NetworkPressure, "MPa", - translate("FEM", "Network Pressure") + translate("FEM", "Network Pressure"), ) else: self.result_widget.rb_none.setChecked(True) @@ -419,7 +366,7 @@ class _TaskPanel: "MinPrin", self.result_obj.PrincipalMin, "MPa", - translate("FEM", "Min Principal Stress") + translate("FEM", "Min Principal Stress"), ) else: self.result_widget.rb_none.setChecked(True) @@ -428,10 +375,7 @@ class _TaskPanel: def peeq_selected(self, state): if len(self.result_obj.Peeq) > 0: self.result_selected( - "Peeq", - self.result_obj.Peeq, - "", - translate("FEM", "Equivalent Plastic Strain") + "Peeq", self.result_obj.Peeq, "", translate("FEM", "Equivalent Plastic Strain") ) else: self.result_widget.rb_none.setChecked(True) @@ -452,7 +396,7 @@ class _TaskPanel: QtGui.QMessageBox.information( None, self.result_obj.Label + " - " + translate("FEM", "Information"), - translate("FEM", "No histogram available.\nPlease select a result type first.") + translate("FEM", "No histogram available.\nPlease select a result type first."), ) def user_defined_text(self, equation): @@ -523,19 +467,52 @@ class _TaskPanel: from ply import lex from ply import yacc import femtools.tokrules as tokrules + identifiers = [ - "x", "y", "z", "T", "vM", "Peeq", "P1", "P2", "P3", - "sxx", "syy", "szz", "sxy", "sxz", "syz", - "exx", "eyy", "ezz", "exy", "exz", "eyz", - "MS", "MF", "NP", "rx", "ry", "rz", "mc", - "s1x", "s1y", "s1z", "s2x", "s2y", "s2z", "s3x", "s3y", "s3z" + "x", + "y", + "z", + "T", + "vM", + "Peeq", + "P1", + "P2", + "P3", + "sxx", + "syy", + "szz", + "sxy", + "sxz", + "syz", + "exx", + "eyy", + "ezz", + "exy", + "exz", + "eyz", + "MS", + "MF", + "NP", + "rx", + "ry", + "rz", + "mc", + "s1x", + "s1y", + "s1z", + "s2x", + "s2y", + "s2z", + "s3x", + "s3y", + "s3z", ] tokrules.names = {} for i in identifiers: tokrules.names[i] = locals()[i] lexer = lex.lex(module=tokrules) - yacc.parse(input="UserDefinedFormula={0}".format(userdefined_eq), lexer=lexer) + yacc.parse(input=f"UserDefinedFormula={userdefined_eq}", lexer=lexer) UserDefinedFormula = tokrules.names["UserDefinedFormula"].tolist() tokrules.names = {} # UserDefinedFormula = eval(userdefined_eq).tolist() @@ -580,18 +557,15 @@ class _TaskPanel: def update_colors_stats(self, res_values, res_unit, minm, maxm): QApplication.setOverrideCursor(Qt.WaitCursor) if self.suitable_results: - self.mesh_obj.ViewObject.setNodeColorByScalars( - self.result_obj.NodeNumbers, - res_values - ) + self.mesh_obj.ViewObject.setNodeColorByScalars(self.result_obj.NodeNumbers, res_values) self.set_result_stats(res_unit, minm, maxm) QtGui.QApplication.restoreOverrideCursor() def set_result_stats(self, unit, minm, maxm): self.result_widget.le_min.setProperty("unit", unit) - self.result_widget.le_min.setProperty("rawText", "{:.6} {}".format(minm, unit)) + self.result_widget.le_min.setProperty("rawText", f"{minm:.6} {unit}") self.result_widget.le_max.setProperty("unit", unit) - self.result_widget.le_max.setProperty("rawText", "{:.6} {}".format(maxm, unit)) + self.result_widget.le_max.setProperty("rawText", f"{maxm:.6} {unit}") def update_displacement(self, factor=None): if factor is None: @@ -610,15 +584,14 @@ class _TaskPanel: FreeCAD.FEM_dialog["result_obj"] = self.result_obj if self.suitable_results: self.mesh_obj.ViewObject.setNodeDisplacementByVectors( - self.result_obj.NodeNumbers, - self.result_obj.DisplacementVectors + self.result_obj.NodeNumbers, self.result_obj.DisplacementVectors ) self.update_displacement() QtGui.QApplication.restoreOverrideCursor() def hsb_disp_factor_changed(self, value): self.result_widget.sb_displacement_factor.setValue( - value / 100. * self.result_widget.sb_displacement_factor_max.value() + value / 100.0 * self.result_widget.sb_displacement_factor_max.value() ) self.update_displacement() @@ -626,11 +599,11 @@ class _TaskPanel: FreeCAD.FEM_dialog["disp_factor_max"] = value if value < self.result_widget.sb_displacement_factor.value(): self.result_widget.sb_displacement_factor.setValue(value) - if value == 0.: + if value == 0.0: self.result_widget.hsb_displacement_factor.setValue(0) else: self.result_widget.hsb_displacement_factor.setValue( - round(self.result_widget.sb_displacement_factor.value() / value * 100.) + round(self.result_widget.sb_displacement_factor.value() / value * 100.0) ) def sb_disp_factor_changed(self, value): @@ -639,15 +612,15 @@ class _TaskPanel: self.result_widget.sb_displacement_factor.setValue( self.result_widget.sb_displacement_factor_max.value() ) - if self.result_widget.sb_displacement_factor_max.value() == 0.: - self.result_widget.hsb_displacement_factor.setValue(0.) + if self.result_widget.sb_displacement_factor_max.value() == 0.0: + self.result_widget.hsb_displacement_factor.setValue(0.0) else: self.result_widget.hsb_displacement_factor.setValue( - round(value / self.result_widget.sb_displacement_factor_max.value() * 100.) + round(value / self.result_widget.sb_displacement_factor_max.value() * 100.0) ) def disable_empty_result_buttons(self): - """ disable radio buttons if result does not exists in result object""" + """disable radio buttons if result does not exists in result object""" """assignments DisplacementLengths --> rb_abs_displacement DisplacementVectors --> rb_x_displacement, rb_y_displacement, rb_z_displacement @@ -688,19 +661,12 @@ class _TaskPanel: self.disable_empty_result_buttons() if self.mesh_obj.FemMesh.NodeCount == 0: the_error_messagetext = ( - "FEM: there are no nodes in result mesh, " - "there will be nothing to show." - ) - error_message = ( - translate("FEM", the_error_messagetext) + "\n" + "FEM: there are no nodes in result mesh, there will be nothing to show." ) + error_message = translate("FEM", the_error_messagetext) + "\n" FreeCAD.Console.PrintError(error_message) - QtGui.QMessageBox.critical( - None, - translate("FEM", "Empty result mesh"), - error_message - ) - elif (self.mesh_obj.FemMesh.NodeCount == len(self.result_obj.NodeNumbers)): + QtGui.QMessageBox.critical(None, translate("FEM", "Empty result mesh"), error_message) + elif self.mesh_obj.FemMesh.NodeCount == len(self.result_obj.NodeNumbers): self.suitable_results = True hide_parts_constraints() else: @@ -709,26 +675,19 @@ class _TaskPanel: "FEM: Graphical bending stress output " "for beam or shell FEM Meshes not yet supported." ) - error_message = ( - translate("FEM", the_error_messagetext) + "\n" - ) + error_message = translate("FEM", the_error_messagetext) + "\n" FreeCAD.Console.PrintError(error_message) QtGui.QMessageBox.critical( - None, - translate("FEM", "No result object"), - error_message + None, translate("FEM", "No result object"), error_message ) else: the_error_messagetext = ( - "FEM: Result node numbers are " - "not equal to FEM Mesh NodeCount." + "FEM: Result node numbers are not equal to FEM Mesh NodeCount." ) error_message = translate("FEM", the_error_messagetext) + "\n" FreeCAD.Console.PrintError(error_message) QtGui.QMessageBox.critical( - None, - translate("FEM", "No result object"), - error_message + None, translate("FEM", "No result object"), error_message ) def reset_mesh_color(self): @@ -752,6 +711,7 @@ class _TaskPanel: # helper def hide_parts_constraints(): from FemGui import getActiveAnalysis + fem_prefs = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Fem/General") hide_constraints = fem_prefs.GetBool("HideConstraint", False) if hide_constraints: diff --git a/src/Mod/Fem/femtaskpanels/task_solver_ccxtools.py b/src/Mod/Fem/femtaskpanels/task_solver_ccxtools.py index c2c93edab0..fcbd24b49c 100644 --- a/src/Mod/Fem/femtaskpanels/task_solver_ccxtools.py +++ b/src/Mod/Fem/femtaskpanels/task_solver_ccxtools.py @@ -60,6 +60,7 @@ class _TaskPanel: ) from femtools.ccxtools import CcxTools as ccx + # we do not need to pass the analysis, it will be found on fea init # TODO: if there is not analysis object in document init of fea # will fail with an exception and task panel will not open @@ -85,82 +86,54 @@ class _TaskPanel: # Connect Signals and Slots QtCore.QObject.connect( - self.form.tb_choose_working_dir, - QtCore.SIGNAL("clicked()"), - self.choose_working_dir + 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 + 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 + self.form.pb_edit_inp, QtCore.SIGNAL("clicked()"), self.editCalculixInputFile ) # connect stopCalculix before runCalculix # see https://github.com/FreeCAD/FreeCAD/issues/12448 + QtCore.QObject.connect(self.form.pb_run_ccx, QtCore.SIGNAL("clicked()"), self.stopCalculix) + QtCore.QObject.connect(self.form.pb_run_ccx, QtCore.SIGNAL("clicked()"), self.runCalculix) QtCore.QObject.connect( - self.form.pb_run_ccx, - QtCore.SIGNAL("clicked()"), - self.stopCalculix - ) - 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 + 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 + self.select_frequency_analysis, ) QtCore.QObject.connect( self.form.rb_thermomech_analysis, QtCore.SIGNAL("clicked()"), - self.select_thermomech_analysis + self.select_thermomech_analysis, ) QtCore.QObject.connect( - self.form.rb_check_mesh, - QtCore.SIGNAL("clicked()"), - self.select_check_mesh + self.form.rb_check_mesh, QtCore.SIGNAL("clicked()"), self.select_check_mesh ) QtCore.QObject.connect( self.form.rb_buckling_analysis, QtCore.SIGNAL("clicked()"), - self.select_buckling_analysis - ) - QtCore.QObject.connect( - self.Calculix, - QtCore.SIGNAL("started()"), - self.calculixStarted + self.select_buckling_analysis, ) + QtCore.QObject.connect(self.Calculix, QtCore.SIGNAL("started()"), self.calculixStarted) QtCore.QObject.connect( self.Calculix, QtCore.SIGNAL("stateChanged(QProcess::ProcessState)"), - self.calculixStateChanged + self.calculixStateChanged, ) QtCore.QObject.connect( - self.Calculix, - QtCore.SIGNAL("error(QProcess::ProcessError)"), - self.calculixError + self.Calculix, QtCore.SIGNAL("error(QProcess::ProcessError)"), self.calculixError ) QtCore.QObject.connect( self.Calculix, QtCore.SIGNAL("finished(int, QProcess::ExitStatus)"), - self.calculixFinished - ) - QtCore.QObject.connect( - self.Timer, - QtCore.SIGNAL("timeout()"), - self.UpdateText + self.calculixFinished, ) + QtCore.QObject.connect(self.Timer, QtCore.SIGNAL("timeout()"), self.UpdateText) self.update() @@ -194,9 +167,7 @@ class _TaskPanel: ) ) if outputwin_color_type: - if ( - outputwin_color_type == "#00AA00" - ): # Success is not part of output window parameters + if outputwin_color_type == "#00AA00": # Success is not part of output window parameters self.fem_console_message += '{}
'.format( outputwin_color_type, message ) @@ -241,12 +212,12 @@ class _TaskPanel: return True def UpdateText(self): - if(self.Calculix.state() == QtCore.QProcess.ProcessState.Running): - self.form.l_time.setText("Time: {0:4.1f}: ".format(time.time() - self.Start)) + if self.Calculix.state() == QtCore.QProcess.ProcessState.Running: + self.form.l_time.setText(f"Time: {time.time() - self.Start:4.1f}: ") def calculixError(self, error=""): - print("Error() {}".format(error)) - self.femConsoleMessage("CalculiX execute error: {}".format(error), "Error") + print(f"Error() {error}") + self.femConsoleMessage(f"CalculiX execute error: {error}", "Error") def calculixNoError(self): print("CalculiX done without error!") @@ -256,7 +227,7 @@ class _TaskPanel: def calculixStarted(self): # print("calculixStarted()") - FreeCAD.Console.PrintLog("calculix state: {}\n".format(self.Calculix.state())) + FreeCAD.Console.PrintLog(f"calculix state: {self.Calculix.state()}\n") self.form.pb_run_ccx.setText("Stop CalculiX") def calculixStateChanged(self, newState): @@ -271,7 +242,7 @@ class _TaskPanel: def calculixFinished(self, exitCode, exitStatus): # print("calculixFinished(), exit code: {}".format(exitCode)) - FreeCAD.Console.PrintLog("calculix state: {}\n".format(self.Calculix.state())) + FreeCAD.Console.PrintLog(f"calculix state: {self.Calculix.state()}\n") # Restore previous cwd QtCore.QDir.setCurrent(self.cwd) @@ -289,7 +260,7 @@ class _TaskPanel: self.calculixError() self.femConsoleMessage("Loading result sets...") - self.form.l_time.setText("Time: {0:4.1f}: ".format(time.time() - self.Start)) + self.form.l_time.setText(f"Time: {time.time() - self.Start:4.1f}: ") self.fea.reset_mesh_purge_results_checked() self.fea.inp_file_name = self.fea.inp_file_name @@ -304,8 +275,9 @@ class _TaskPanel: "The used CalculiX version {}.{} creates broken output files. " "The result file will not be read by FreeCAD FEM. " "You still can try to read it stand alone with FreeCAD, but it is " - "strongly recommended to upgrade CalculiX to a newer version.\n" - .format(majorVersion, minorVersion) + "strongly recommended to upgrade CalculiX to a newer version.\n".format( + majorVersion, minorVersion + ) ) QtGui.QMessageBox.warning(None, "Upgrade CalculiX", message) raise @@ -317,7 +289,7 @@ class _TaskPanel: FreeCAD.Console.PrintError("loading results failed\n") QApplication.restoreOverrideCursor() - self.form.l_time.setText("Time: {0:4.1f}: ".format(time.time() - self.Start)) + self.form.l_time.setText(f"Time: {time.time() - self.Start:4.1f}: ") # restore mesh object visibility CCX_mesh = self.fea.analysis.Document.getObject("ResultMesh") @@ -325,15 +297,16 @@ class _TaskPanel: CCX_mesh.ViewObject.Visibility = self.CCX_mesh_visibility def choose_working_dir(self): - wd = QtGui.QFileDialog.getExistingDirectory(None, "Choose CalculiX working directory", - self.fea.working_dir) + wd = QtGui.QFileDialog.getExistingDirectory( + None, "Choose CalculiX working directory", self.fea.working_dir + ) if os.path.isdir(wd): self.fea.setup_working_dir(wd) self.form.le_working_dir.setText(self.fea.working_dir) def write_input_file_handler(self): self.Start = time.time() - self.form.l_time.setText("Time: {0:4.1f}: ".format(time.time() - self.Start)) + self.form.l_time.setText(f"Time: {time.time() - self.Start:4.1f}: ") QApplication.restoreOverrideCursor() if self.check_prerequisites_helper(): QApplication.setOverrideCursor(Qt.WaitCursor) @@ -345,12 +318,12 @@ class _TaskPanel: else: self.femConsoleMessage("Write .inp file failed!", "Error") QApplication.restoreOverrideCursor() - self.form.l_time.setText("Time: {0:4.1f}: ".format(time.time() - self.Start)) + self.form.l_time.setText(f"Time: {time.time() - self.Start:4.1f}: ") def check_prerequisites_helper(self): self.Start = time.time() self.femConsoleMessage("Check dependencies...") - self.form.l_time.setText("Time: {0:4.1f}: ".format(time.time() - self.Start)) + self.form.l_time.setText(f"Time: {time.time() - self.Start:4.1f}: ") self.fea.update_objects() message = self.fea.check_prerequisites() @@ -366,7 +339,7 @@ class _TaskPanel: self.ext_editor_process.start(ext_editor_path, [filename]) def editCalculixInputFile(self): - print("editCalculixInputFile {}".format(self.fea.inp_file_name)) + print(f"editCalculixInputFile {self.fea.inp_file_name}") ccx_prefs = FreeCAD.ParamGet(self.PREFS_PATH) if ccx_prefs.GetBool("UseInternalEditor", True): FemGui.open(self.fea.inp_file_name) @@ -385,21 +358,21 @@ class _TaskPanel: if self.Calculix.state() == QtCore.QProcess.ProcessState.NotRunning: if self.fea.ccx_binary_present is False: self.femConsoleMessage( - "CalculiX can not be started. Missing or incorrect CalculiX binary: {}" - .format(self.fea.ccx_binary) + "CalculiX can not be started. Missing or incorrect CalculiX binary: {}".format( + self.fea.ccx_binary + ) ) # TODO deactivate the run button return # print("runCalculix") self.Start = time.time() - self.femConsoleMessage("CalculiX binary: {}".format(self.fea.ccx_binary)) - self.femConsoleMessage("CalculiX input file: {}".format(self.fea.inp_file_name)) + self.femConsoleMessage(f"CalculiX binary: {self.fea.ccx_binary}") + self.femConsoleMessage(f"CalculiX input file: {self.fea.inp_file_name}") self.femConsoleMessage("Run CalculiX...") FreeCAD.Console.PrintMessage( - "run CalculiX at: {} with: {}\n" - .format(self.fea.ccx_binary, self.fea.inp_file_name) + f"run CalculiX at: {self.fea.ccx_binary} with: {self.fea.inp_file_name}\n" ) # change cwd because ccx may crash if directory has no write permission # there is also a limit of the length of file names so jump to the document directory diff --git a/src/Mod/Fem/femtest/app/support_utils.py b/src/Mod/Fem/femtest/app/support_utils.py index a7ed551e35..10ff3b3433 100644 --- a/src/Mod/Fem/femtest/app/support_utils.py +++ b/src/Mod/Fem/femtest/app/support_utils.py @@ -37,15 +37,13 @@ import FreeCAD from os.path import join -def get_fem_test_home_dir( -): +def get_fem_test_home_dir(): return join(FreeCAD.getHomePath(), "Mod", "Fem", "femtest", "data") -def get_fem_test_tmp_dir( - dirname=None -): +def get_fem_test_tmp_dir(dirname=None): from uuid import uuid4 + _unique_id = str(uuid4())[-12:] # print(_unique_id) if dirname is None: @@ -54,23 +52,18 @@ def get_fem_test_tmp_dir( temp_dir = join(tempfile.gettempdir(), "FEM_unittests", dirname + "_" + _unique_id) if not os.path.exists(temp_dir): os.makedirs(temp_dir) - return(temp_dir) + return temp_dir -def get_unit_test_tmp_dir( - temp_dir, - unittestdir -): +def get_unit_test_tmp_dir(temp_dir, unittestdir): testdir = join(temp_dir, unittestdir) if not os.path.exists(testdir): os.makedirs(testdir) return testdir -def fcc_print( - message -): - FreeCAD.Console.PrintMessage("{} \n".format(message)) +def fcc_print(message): + FreeCAD.Console.PrintMessage(f"{message} \n") def get_namefromdef(strdel="", stradd=""): @@ -78,16 +71,14 @@ def get_namefromdef(strdel="", stradd=""): return (sys._getframe(1).f_code.co_name).replace(strdel, stradd) -def get_defmake_count( - fem_vtk_post=True -): +def get_defmake_count(fem_vtk_post=True): """ 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 = join(FreeCAD.getHomePath(), "Mod", "Fem", "ObjectsFem.py") - modfile = open(name_modfile, "r") + modfile = open(name_modfile) lines_modefile = modfile.readlines() modfile.close() lines_defmake = [li for li in lines_modefile if li.startswith("def make")] @@ -102,11 +93,10 @@ def get_defmake_count( return len(lines_defmake) -def get_fem_test_defs( -): +def get_fem_test_defs(): test_path = join(FreeCAD.getHomePath(), "Mod", "Fem", "femtest", "app") - print("Modules, classes, methods taken from: {}".format(test_path)) + print(f"Modules, classes, methods taken from: {test_path}") collected_test_module_paths = [] for tfile in sorted(os.listdir(test_path)): @@ -118,11 +108,11 @@ def get_fem_test_defs( 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) + module_path = f"femtest.app.{module_name}" if module_path not in collected_test_modules: collected_test_modules.append(module_path) class_name = "" - tfile = open(f, "r") + tfile = open(f) for ln in tfile: ln = ln.lstrip() ln = ln.rstrip() @@ -130,7 +120,7 @@ def get_fem_test_defs( ln = ln.lstrip("class ") ln = ln.split("(")[0] class_name = ln - class_path = "femtest.app.{}.{}".format(module_name, class_name) + class_path = f"femtest.app.{module_name}.{class_name}" if class_path not in collected_test_classes: collected_test_classes.append(class_path) if ln.startswith("def test"): @@ -138,7 +128,7 @@ def get_fem_test_defs( ln = ln.split("(")[0] if ln == "test_00print": continue - method_path = "femtest.app.{}.{}.{}".format(module_name, class_name, ln) + method_path = f"femtest.app.{module_name}.{class_name}.{ln}" collected_test_methods.append(method_path) tfile.close() @@ -161,17 +151,17 @@ def get_fem_test_defs( 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(f"make -j 4 && ./bin/FreeCADCmd -t {m}\n") 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(f"make -j 4 && ./bin/FreeCADCmd -t {m}\n") 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(f"make -j 4 && ./bin/FreeCADCmd -t {m}\n") cf.write("\n") cf.write("\n") cf.write("# methods in FreeCAD\n") @@ -180,11 +170,10 @@ def get_fem_test_defs( "\nimport unittest\n" "unittest.TextTestRunner().run(unittest.TestLoader().loadTestsFromName(\n" " '{}'\n" - "))\n" - .format(m) + "))\n".format(m) ) cf.close() - print("The file was saved in:{}".format(file_path)) + print(f"The file was saved in:{file_path}") def try_converting_to_float(line: str) -> Union[None, List[float]]: @@ -267,28 +256,38 @@ def parse_diff(diff_lines: Iterator[str]) -> List[str]: bad_lines.extend(changes_block) return bad_lines -def compare_inp_files( - file_name1, - file_name2 -): - file1 = open(file_name1, "r") + +def compare_inp_files(file_name1, file_name2): + file1 = open(file_name1) f1 = file1.readlines() file1.close() # l.startswith("17671.0,1") is a temporary workaround # for python3 problem with 1DFlow input # TODO as soon as the 1DFlow result reading is fixed # this should be triggered in the 1DFlow unit test - lf1 = [li for li in f1 if not ( - li.startswith("** written ") or li.startswith("** file ") or li.startswith("17671.0,1") - )] + lf1 = [ + li + for li in f1 + if not ( + li.startswith("** written ") + or li.startswith("** file ") + or li.startswith("17671.0,1") + ) + ] lf1 = force_unix_line_ends(lf1) - file2 = open(file_name2, "r") + file2 = open(file_name2) f2 = file2.readlines() file2.close() # TODO see comment on file1 - lf2 = [li for li in f2 if not ( - li.startswith("** written ") or li.startswith("** file ") or li.startswith("17671.0,1") - )] + lf2 = [ + li + for li in f2 + if not ( + li.startswith("** written ") + or li.startswith("** file ") + or li.startswith("17671.0,1") + ) + ] lf2 = force_unix_line_ends(lf2) import difflib @@ -299,11 +298,8 @@ def compare_inp_files( return f"Comparing {file_name1} to {file_name2} failed!\n{''.join(bad_lines)}" -def compare_files( - file_name1, - file_name2 -): - file1 = open(file_name1, "r") +def compare_files(file_name1, file_name2): + file1 = open(file_name1) f1 = file1.readlines() file1.close() @@ -312,39 +308,43 @@ def compare_files( # workaround to compare geos of elmer test and temporary file path # (not only names change, path changes with operating system) - lf1 = [li for li in f1 if not ( - li.startswith('Merge "') - or li.startswith('Save "') - or li.startswith("// ") - or li.startswith("General.NumThreads") - )] + lf1 = [ + li + for li in f1 + if not ( + li.startswith('Merge "') + or li.startswith('Save "') + or li.startswith("// ") + or li.startswith("General.NumThreads") + ) + ] lf1 = force_unix_line_ends(lf1) - file2 = open(file_name2, "r") + file2 = open(file_name2) f2 = file2.readlines() file2.close() - lf2 = [li for li in f2 if not ( - li.startswith('Merge "') - or li.startswith('Save "') - or li.startswith("// ") - or li.startswith("General.NumThreads") - )] + lf2 = [ + li + for li in f2 + if not ( + li.startswith('Merge "') + or li.startswith('Save "') + or li.startswith("// ") + or li.startswith("General.NumThreads") + ) + ] lf2 = force_unix_line_ends(lf2) import difflib + diff = difflib.unified_diff(lf1, lf2, n=0) result = "" for li in diff: result += li if result: - result = "Comparing {} to {} failed!\n".format(file_name1, file_name2) + result + result = f"Comparing {file_name1} to {file_name2} failed!\n" + result return result -def compare_stats( - fea, - stat_file, - res_obj_name, - loc_stat_types=None -): +def compare_stats(fea, stat_file, res_obj_name, loc_stat_types=None): import femresult.resulttools as resulttools # get the stat types which should be compared @@ -361,7 +361,7 @@ def compare_stats( "Peeq", "Temp", "MFlow", - "NPress" + "NPress", ] if not loc_stat_types: loc_stat_types = stat_types @@ -374,16 +374,13 @@ def compare_stats( stats = [] for s in loc_stat_types: statval = resulttools.get_stats(obj, s) - stats.append( - "{}: ({:.10f}, {:.10f})\n" - .format(s, statval[0], statval[1]) - ) + stats.append(f"{s}: ({statval[0]:.10f}, {statval[1]:.10f})\n") else: - fcc_print("Result object not found. Name: {}".format(res_obj_name)) + fcc_print(f"Result object not found. Name: {res_obj_name}") return True # get stats to compare with, the expected ones - sf = open(stat_file, "r") + sf = open(stat_file) sf_content = [] for li in sf.readlines(): for st in loc_stat_types: @@ -396,20 +393,18 @@ def compare_stats( # compare stats if stats != sf_content: - fcc_print("Stats read from {}.frd file".format(fea.base_name)) + fcc_print(f"Stats read from {fea.base_name}.frd file") fcc_print("!=") - fcc_print("Expected stats from {}".format(stat_file)) + fcc_print(f"Expected stats from {stat_file}") for i in range(len(stats)): if stats[i] != sf_content[i]: - fcc_print("{} != {}".format(stats[i].rstrip(), sf_content[i].rstrip())) + fcc_print(f"{stats[i].rstrip()} != {sf_content[i].rstrip()}") return True return False -def force_unix_line_ends( - line_list -): +def force_unix_line_ends(line_list): new_line_list = [] for ln in line_list: if ln.endswith("\r\n"): @@ -418,9 +413,7 @@ def force_unix_line_ends( return new_line_list -def collect_python_modules( - femsubdir=None -): +def collect_python_modules(femsubdir=None): if not femsubdir: pydir = join(FreeCAD.ConfigGet("AppHomePath"), "Mod", "Fem") else: @@ -430,20 +423,17 @@ def collect_python_modules( for pyfile in sorted(os.listdir(pydir)): if pyfile.endswith(".py") and not pyfile.startswith("Init"): if not femsubdir: - collected_modules.append( - os.path.splitext(os.path.basename(pyfile))[0] - ) + collected_modules.append(os.path.splitext(os.path.basename(pyfile))[0]) else: collected_modules.append( - femsubdir.replace("/", ".") + "." + os.path.splitext( - os.path.basename(pyfile) - )[0] + femsubdir.replace("/", ".") + + "." + + os.path.splitext(os.path.basename(pyfile))[0] ) return collected_modules -def all_test_files( -): +def all_test_files(): # open all files cube_frequency() cube_static() @@ -454,61 +444,38 @@ def all_test_files( # run the specific test case of the file # open the file in FreeCAD GUI and return the doc identifier -def cube_frequency( -): +def cube_frequency(): testname = "femtest.testccxtools.TestCcxTools.test_3_freq_analysis" unittest.TextTestRunner().run(unittest.TestLoader().loadTestsFromName(testname)) - doc = FreeCAD.open(join( - get_fem_test_tmp_dir(), - "FEM_ccx_frequency", - "cube_frequency.FCStd") - ) + doc = FreeCAD.open(join(get_fem_test_tmp_dir(), "FEM_ccx_frequency", "cube_frequency.FCStd")) return doc -def cube_static( -): +def cube_static(): testname = "femtest.testccxtools.TestCcxTools.test_1_static_analysis" unittest.TextTestRunner().run(unittest.TestLoader().loadTestsFromName(testname)) - doc = FreeCAD.open( - join(get_fem_test_tmp_dir(), - "FEM_ccx_static", - "cube_static.FCStd") - ) + doc = FreeCAD.open(join(get_fem_test_tmp_dir(), "FEM_ccx_static", "cube_static.FCStd")) return doc -def Flow1D_thermomech( -): +def Flow1D_thermomech(): testname = "femtest.testccxtools.TestCcxTools.test_5_Flow1D_thermomech_analysis" unittest.TextTestRunner().run(unittest.TestLoader().loadTestsFromName(testname)) - doc = FreeCAD.open(join( - get_fem_test_tmp_dir(), - "FEM_ccx_Flow1D_thermomech", - "Flow1D_thermomech.FCStd") + doc = FreeCAD.open( + join(get_fem_test_tmp_dir(), "FEM_ccx_Flow1D_thermomech", "Flow1D_thermomech.FCStd") ) return doc -def multimat( -): +def multimat(): testname = "femtest.testccxtools.TestCcxTools.test_2_static_multiple_material" unittest.TextTestRunner().run(unittest.TestLoader().loadTestsFromName(testname)) - doc = FreeCAD.open(join( - get_fem_test_tmp_dir(), - "FEM_ccx_multimat", - "multimat.FCStd") - ) + doc = FreeCAD.open(join(get_fem_test_tmp_dir(), "FEM_ccx_multimat", "multimat.FCStd")) return doc -def spine_thermomech( -): +def spine_thermomech(): testname = "femtest.testccxtools.TestCcxTools.test_4_thermomech_analysis" unittest.TextTestRunner().run(unittest.TestLoader().loadTestsFromName(testname)) - doc = FreeCAD.open(join( - get_fem_test_tmp_dir(), - "FEM_ccx_thermomech", - "spine_thermomech.FCStd") - ) + doc = FreeCAD.open(join(get_fem_test_tmp_dir(), "FEM_ccx_thermomech", "spine_thermomech.FCStd")) return doc diff --git a/src/Mod/Fem/femtest/app/test_ccxtools.py b/src/Mod/Fem/femtest/app/test_ccxtools.py index 1e8d9a61cd..43b15c00d9 100644 --- a/src/Mod/Fem/femtest/app/test_ccxtools.py +++ b/src/Mod/Fem/femtest/app/test_ccxtools.py @@ -68,9 +68,7 @@ class TestCcxTools(unittest.TestCase): # this test just prints a line with stars fcc_print( - "\n{0}\n{1} run FEM TestCcxTools tests {2}\n{0}".format( - 100 * "*", 10 * "*", 62 * "*" - ) + "\n{0}\n{1} run FEM TestCcxTools tests {2}\n{0}".format(100 * "*", 10 * "*", 62 * "*") ) # ******************************************************************************************** @@ -345,11 +343,7 @@ class TestCcxTools(unittest.TestCase): analysis_dir=None, test_end=False, ): - fcc_print( - "\n--------------- " - "Start of FEM ccxtools {} test" - "---------------".format(base_name) - ) + fcc_print(f"\n--------------- Start of FEM ccxtools {base_name} test---------------") if analysis_dir is None: analysis_dir = testtools.get_fem_test_tmp_dir(self.pre_dir_name + base_name) @@ -358,44 +352,40 @@ class TestCcxTools(unittest.TestCase): fea = ccxtools.FemToolsCcx(analysis, solver_object, test_mode=True) fea.update_objects() - fcc_print("Setting up working directory {}".format(analysis_dir)) + fcc_print(f"Setting up working directory {analysis_dir}") fea.setup_working_dir(analysis_dir) self.assertTrue( True if fea.working_dir == analysis_dir else False, - "Setting working directory {} failed".format(analysis_dir), + f"Setting working directory {analysis_dir} failed", ) - fcc_print("Checking FEM inp file prerequisites for {} ...".format(base_name)) + fcc_print(f"Checking FEM inp file prerequisites for {base_name} ...") error = fea.check_prerequisites() self.assertFalse( error, - "ccxtools check_prerequisites returned error message: {}".format(error), + f"ccxtools check_prerequisites returned error message: {error}", ) inpfile_given = join(self.test_file_dir, (base_name + ".inp")) inpfile_totest = join(analysis_dir, (self.mesh_name + ".inp")) fcc_print("Checking FEM inp file write...") - fcc_print("Writing {} for {}".format(inpfile_totest, base_name)) + fcc_print(f"Writing {inpfile_totest} for {base_name}") error = fea.write_inp_file() self.assertFalse(error, "Writing failed") - fcc_print("Comparing {} to {}".format(inpfile_given, inpfile_totest)) + fcc_print(f"Comparing {inpfile_given} to {inpfile_totest}") ret = testtools.compare_inp_files(inpfile_given, inpfile_totest) - self.assertFalse(ret, "ccxtools write_inp_file test failed.\n{}".format(ret)) + self.assertFalse(ret, f"ccxtools write_inp_file test failed.\n{ret}") if test_end is True: # do not save and print End of tests return fea save_fc_file = join(analysis_dir, base_name + ".FCStd") - fcc_print("Save FreeCAD file for {} to {}...".format(base_name, save_fc_file)) + fcc_print(f"Save FreeCAD file for {base_name} to {save_fc_file}...") self.document.saveAs(save_fc_file) - fcc_print( - "\n--------------- " "End of FEM ccxtools {}" "---------------".format( - base_name - ) - ) + fcc_print(f"\n--------------- End of FEM ccxtools {base_name}---------------") # ******************************************************************************************** def result_reading_test( @@ -415,40 +405,40 @@ class TestCcxTools(unittest.TestCase): fea.setup_working_dir(self.test_file_dir) self.assertTrue( True if fea.working_dir == self.test_file_dir else False, - "Setting working directory {} failed".format(self.test_file_dir), + f"Setting working directory {self.test_file_dir} failed", ) - fcc_print("Setting base name to read test {}.frd file...".format(base_name)) + fcc_print(f"Setting base name to read test {base_name}.frd file...") fea.set_base_name(base_name) self.assertTrue( True if fea.base_name == base_name else False, - "Setting base name to {} failed".format(base_name), + f"Setting base name to {base_name} failed", ) - fcc_print("Setting inp file name to read test {}.frd file...".format(base_name)) + fcc_print(f"Setting inp file name to read test {base_name}.frd file...") fea.set_inp_file_name() self.assertTrue( True if fea.inp_file_name == inpfile_given else False, - "Setting inp file name to {} failed".format(inpfile_given), + f"Setting inp file name to {inpfile_given} failed", ) - fcc_print("Checking FEM frd file read from {}...".format(base_name)) + fcc_print(f"Checking FEM frd file read from {base_name}...") fea.load_results() self.assertTrue( fea.results_present, - "Cannot read results from {}.frd frd file".format(fea.base_name), + f"Cannot read results from {fea.base_name}.frd frd file", ) - fcc_print("Reading stats from result object for {}...".format(base_name)) + fcc_print(f"Reading stats from result object for {base_name}...") expected_values = join(self.test_file_dir, base_name + "_expected_values") ret = testtools.compare_stats(fea, expected_values, res_obj_name) self.assertFalse(ret, "Invalid results read from .frd file") save_fc_file = join(analysis_dir, base_name + ".FCStd") - fcc_print("Save FreeCAD file for {} to {}...".format(base_name, save_fc_file)) + fcc_print(f"Save FreeCAD file for {base_name} to {save_fc_file}...") self.document.saveAs(save_fc_file) - fcc_print("--------------- End of {} -------------------".format(base_name)) + fcc_print(f"--------------- End of {base_name} -------------------") # ************************************************************************************************ @@ -498,12 +488,8 @@ def create_test_results(): res_obj_static = doc_static_cube.getObject("CCX_Results") for s in stat_types: statval = resulttools.get_stats(res_obj_static, s) - stats_static.append( - "{0}: ({1:.14g}, {2:.14g}, )\n".format(s, statval[0], statval[1]) - ) - static_expected_values_file = join( - static_analysis_dir, "cube_static_expected_values" - ) + stats_static.append(f"{s}: ({statval[0]:.14g}, {statval[1]:.14g}, )\n") + static_expected_values_file = join(static_analysis_dir, "cube_static_expected_values") f = open(static_expected_values_file, "w") for s in stats_static: f.write(s) @@ -523,9 +509,7 @@ def create_test_results(): unittest.TestLoader().loadTestsFromName(test_class + ".test_freq_analysis") ) frequency_analysis_dir = join(temp_dir, "FEM_ccx_frequency") - doc_frequency_cube = FreeCAD.open( - join(frequency_analysis_dir, "cube_frequency.FCStd") - ) + doc_frequency_cube = FreeCAD.open(join(frequency_analysis_dir, "cube_frequency.FCStd")) FemGui.setActiveAnalysis(doc_frequency_cube.Analysis) fea = ccxtools.FemToolsCcx() fea.update_objects() @@ -539,12 +523,8 @@ def create_test_results(): res_obj_freq = doc_frequency_cube.getObject("CCX_Mode7_Results") for s in stat_types: statval = resulttools.get_stats(res_obj_freq, s) - stats_frequency.append( - "{0}: ({1:.14g}, {2:.14g})\n".format(s, statval[0], statval[1]) - ) - frequency_expected_values_file = join( - frequency_analysis_dir, "cube_frequency_expected_values" - ) + stats_frequency.append(f"{s}: ({statval[0]:.14g}, {statval[1]:.14g})\n") + frequency_expected_values_file = join(frequency_analysis_dir, "cube_frequency_expected_values") f = open(frequency_expected_values_file, "w") for s in stats_frequency: f.write(s) diff --git a/src/Mod/Fem/femtest/app/test_common.py b/src/Mod/Fem/femtest/app/test_common.py index 0e6250b841..d791149671 100644 --- a/src/Mod/Fem/femtest/app/test_common.py +++ b/src/Mod/Fem/femtest/app/test_common.py @@ -38,38 +38,28 @@ class TestFemCommon(unittest.TestCase): fcc_print("import TestFemCommon") # ******************************************************************************************** - def setUp( - self - ): + def setUp(self): # setUp is executed before every test # new document self.document = FreeCAD.newDocument(self.__class__.__name__) # ******************************************************************************************** - def tearDown( - self - ): + def tearDown(self): # tearDown is executed after every test FreeCAD.closeDocument(self.document.Name) # ******************************************************************************************** - def test_00print( - self - ): + def test_00print(self): # since method name starts with 00 this will be run first # this test just prints a line with stars - fcc_print("\n{0}\n{1} run FEM TestFemCommon tests {2}\n{0}".format( - 100 * "*", - 10 * "*", - 61 * "*" - )) + fcc_print( + "\n{0}\n{1} run FEM TestFemCommon tests {2}\n{0}".format(100 * "*", 10 * "*", 61 * "*") + ) # ******************************************************************************************** - def test_adding_refshaps( - self - ): + def test_adding_refshaps(self): doc = self.document slab = doc.addObject("Part::Plane", "Face") slab.Length = 500.00 @@ -85,15 +75,14 @@ class TestFemCommon(unittest.TestCase): doc.recompute() expected_reflist = [(slab, ("Edge1", "Edge2", "Edge3", "Edge4"))] assert_err_message = ( - "Adding reference shapes did not result in expected list {} != {}" - .format(cf.References, expected_reflist) + "Adding reference shapes did not result in expected list {} != {}".format( + cf.References, expected_reflist + ) ) self.assertEqual(cf.References, expected_reflist, assert_err_message) # ******************************************************************************************** - def test_pyimport_all_FEM_modules( - self - ): + def test_pyimport_all_FEM_modules(self): # we're going to try to import all python modules from FreeCAD FEM pymodules = [] @@ -130,12 +119,12 @@ class TestFemCommon(unittest.TestCase): ) and not FreeCAD.GuiUp: continue - fcc_print("Try importing {0} ...".format(mod)) + fcc_print(f"Try importing {mod} ...") try: - im = __import__("{0}".format(mod)) + im = __import__(f"{mod}") except ImportError: im = False if not im: # to get an error message what was going wrong - __import__("{0}".format(mod)) - self.assertTrue(im, "Problem importing {0}".format(mod)) + __import__(f"{mod}") + self.assertTrue(im, f"Problem importing {mod}") diff --git a/src/Mod/Fem/femtest/app/test_femimport.py b/src/Mod/Fem/femtest/app/test_femimport.py index e767dbdfeb..7c3771766f 100644 --- a/src/Mod/Fem/femtest/app/test_femimport.py +++ b/src/Mod/Fem/femtest/app/test_femimport.py @@ -39,42 +39,36 @@ class TestFemImport(unittest.TestCase): # no is document needed to test import Fem and import FemGui # thus neither setUp nor tearDown methods are needed - def test_00print( - self - ): - fcc_print("\n{0}\n{1} run FEM TestFemImport tests {2}\n{0}".format( - 100 * "*", - 10 * "*", - 61 * "*" - )) + def test_00print(self): + fcc_print( + "\n{0}\n{1} run FEM TestFemImport tests {2}\n{0}".format(100 * "*", 10 * "*", 61 * "*") + ) # ******************************************************************************************** - def test_import_fem( - self - ): + def test_import_fem(self): mod = "Fem" - fcc_print("\n Try importing {0} ...".format(mod)) + fcc_print(f"\n Try importing {mod} ...") try: - im = __import__("{0}".format(mod)) + im = __import__(f"{mod}") except ImportError: im = False if not im: # to get an error message what was going wrong - __import__("{0}".format(mod)) - self.assertTrue(im, "Problem importing {0}".format(mod)) + __import__(f"{mod}") + self.assertTrue(im, f"Problem importing {mod}") if FreeCAD.GuiUp: mod = "FemGui" - fcc_print(" Try importing {0} ...".format(mod)) + fcc_print(f" Try importing {mod} ...") try: - im = __import__("{0}".format(mod)) + im = __import__(f"{mod}") except ImportError: im = False if not im: # to get an error message what was going wrong - __import__("{0}".format(mod)) - self.assertTrue(im, "Problem importing {0}".format(mod)) + __import__(f"{mod}") + self.assertTrue(im, f"Problem importing {mod}") # ************************************************************************************************ @@ -84,37 +78,29 @@ class TestObjectExistance(unittest.TestCase): fcc_print("import TestObjectExistance") # ******************************************************************************************** - def setUp( - self - ): + def setUp(self): # setUp is executed before every test # new document self.document = FreeCAD.newDocument(self.__class__.__name__) # ******************************************************************************************** - def tearDown( - self - ): + def tearDown(self): # tearDown is executed after every test FreeCAD.closeDocument(self.document.Name) # ******************************************************************************************** - def test_00print( - self - ): + def test_00print(self): # since method name starts with 00 this will be run first # this test just prints a line with stars - fcc_print("\n{0}\n{1} run FEM TestObjectExistance tests {2}\n{0}".format( - 100 * "*", - 10 * "*", - 55 * "*" - )) + fcc_print( + "\n{0}\n{1} run FEM TestObjectExistance tests {2}\n{0}".format( + 100 * "*", 10 * "*", 55 * "*" + ) + ) # ******************************************************************************************** - def test_objects_existance( - self - ): + def test_objects_existance(self): expected_obj_types = [ "Fem::Constraint", @@ -193,12 +179,6 @@ class TestObjectExistance(unittest.TestCase): obj_types = sorted(obj_types) # test - self.assertEqual( - expected_len, - len(obj_types) - ) + self.assertEqual(expected_len, len(obj_types)) - self.assertEqual( - expected_obj_types, - obj_types - ) + self.assertEqual(expected_obj_types, obj_types) diff --git a/src/Mod/Fem/femtest/app/test_material.py b/src/Mod/Fem/femtest/app/test_material.py index 6c0d8c38d6..e9a0262755 100644 --- a/src/Mod/Fem/femtest/app/test_material.py +++ b/src/Mod/Fem/femtest/app/test_material.py @@ -37,54 +37,45 @@ class TestMaterialUnits(unittest.TestCase): fcc_print("import TestMaterialUnits") # ******************************************************************************************** - def setUp( - self - ): + def setUp(self): # setUp is executed before every test # new document self.document = FreeCAD.newDocument(self.__class__.__name__) # ******************************************************************************************** - def tearDown( - self - ): + def tearDown(self): # tearDown is executed after every test FreeCAD.closeDocument(self.document.Name) # ******************************************************************************************** - def test_00print( - self - ): + def test_00print(self): # since method name starts with 00 this will be run first # this test just prints a line with stars - fcc_print("\n{0}\n{1} run FEM TestMaterialUnits tests {2}\n{0}".format( - 100 * "*", - 10 * "*", - 57 * "*" - )) + fcc_print( + "\n{0}\n{1} run FEM TestMaterialUnits tests {2}\n{0}".format( + 100 * "*", 10 * "*", 57 * "*" + ) + ) # ******************************************************************************************** - def test_known_quantity_units( - self - ): + def test_known_quantity_units(self): from materialtools.cardutils import get_known_material_quantity_parameter as knownquant + known_quantity_parameter = knownquant() from materialtools.cardutils import check_parm_unit as checkparamunit + for param in known_quantity_parameter: - fcc_print("{}".format(param)) + fcc_print(f"{param}") self.assertTrue( checkparamunit(param), "Unit of quantity material parameter {} " - "is unknown to the FreeCAD unit system." - .format(param) + "is unknown to the FreeCAD unit system.".format(param), ) # ******************************************************************************************** - def test_material_card_quantities( - self - ): + def test_material_card_quantities(self): # test the value and unit of known quantity parameter # from solid build in material cards # keep in mind only if FreeCAD is installed all materials are copied @@ -92,28 +83,29 @@ class TestMaterialUnits(unittest.TestCase): # get build in materials builtin_solid_mat_dir = join( - FreeCAD.getResourceDir(), - "Mod", - "Material", - "StandardMaterial" + FreeCAD.getResourceDir(), "Mod", "Material", "StandardMaterial" ) - fcc_print("{}".format(builtin_solid_mat_dir)) + fcc_print(f"{builtin_solid_mat_dir}") from materialtools.cardutils import add_cards_from_a_dir as addmats + materials, cards, icons = addmats({}, {}, {}, builtin_solid_mat_dir, "") # get known material quantity parameter from materialtools.cardutils import get_known_material_quantity_parameter as knownquant + known_quantities = knownquant() # check param, value pairs from materialtools.cardutils import check_value_unit as checkvalueunit + for mat in materials: - fcc_print("{}".format(mat)) + fcc_print(f"{mat}") for param, value in materials[mat].items(): if param in known_quantities: # fcc_print(" {} --> {}".format(param, value)) self.assertTrue( checkvalueunit(param, value), - "Unit of quantity {} from material parameter {} is wrong." - .format(value, param) + "Unit of quantity {} from material parameter {} is wrong.".format( + value, param + ), ) diff --git a/src/Mod/Fem/femtest/app/test_mesh.py b/src/Mod/Fem/femtest/app/test_mesh.py index a7d0681c9a..1faa59147a 100644 --- a/src/Mod/Fem/femtest/app/test_mesh.py +++ b/src/Mod/Fem/femtest/app/test_mesh.py @@ -39,38 +39,28 @@ class TestMeshCommon(unittest.TestCase): fcc_print("import TestMeshCommon") # ******************************************************************************************** - def setUp( - self - ): + def setUp(self): # setUp is executed before every test # new document self.document = FreeCAD.newDocument(self.__class__.__name__) # ******************************************************************************************** - def tearDown( - self - ): + def tearDown(self): # tearDown is executed after every test FreeCAD.closeDocument(self.document.Name) # ******************************************************************************************** - def test_00print( - self - ): + def test_00print(self): # since method name starts with 00 this will be run first # this test just prints a line with stars - fcc_print("\n{0}\n{1} run FEM TestMeshCommon tests {2}\n{0}".format( - 100 * "*", - 10 * "*", - 60 * "*" - )) + fcc_print( + "\n{0}\n{1} run FEM TestMeshCommon tests {2}\n{0}".format(100 * "*", 10 * "*", 60 * "*") + ) # ******************************************************************************************** - def test_mesh_seg2_python( - self - ): + def test_mesh_seg2_python(self): seg2 = Fem.FemMesh() seg2.addNode(0, 0, 0, 1) seg2.addNode(2, 0, 0, 2) @@ -78,40 +68,32 @@ class TestMeshCommon(unittest.TestCase): seg2.addEdge([1, 2]) seg2.addEdge([2, 3], 2) - node_data = [ - seg2.NodeCount, - seg2.Nodes - ] + node_data = [seg2.NodeCount, seg2.Nodes] edge_data = [ seg2.EdgeCount, seg2.Edges[0], seg2.getElementNodes(seg2.Edges[0]), seg2.Edges[1], - seg2.getElementNodes(seg2.Edges[1]) + seg2.getElementNodes(seg2.Edges[1]), ] expected_nodes = [ 3, { 1: FreeCAD.Vector(0.0, 0.0, 0.0), 2: FreeCAD.Vector(2.0, 0.0, 0.0), - 3: FreeCAD.Vector(4.0, 0.0, 0.0) - } + 3: FreeCAD.Vector(4.0, 0.0, 0.0), + }, ] expected_edges = [2, 1, (1, 2), 2, (2, 3)] self.assertEqual( - node_data, - expected_nodes, - "Nodes of Python created seg2 element are unexpected" + node_data, expected_nodes, "Nodes of Python created seg2 element are unexpected" ) self.assertEqual( - edge_data, expected_edges, - "Edges of Python created seg2 element are unexpected" + edge_data, expected_edges, "Edges of Python created seg2 element are unexpected" ) # ******************************************************************************************** - def test_mesh_seg3_python( - self - ): + def test_mesh_seg3_python(self): seg3 = Fem.FemMesh() seg3.addNode(0, 0, 0, 1) seg3.addNode(1, 0, 0, 2) @@ -127,33 +109,28 @@ class TestMeshCommon(unittest.TestCase): seg3.Edges[0], seg3.getElementNodes(seg3.Edges[0]), seg3.Edges[1], - seg3.getElementNodes(seg3.Edges[1]) + seg3.getElementNodes(seg3.Edges[1]), ] expected_nodes = [ - 5, { + 5, + { 1: FreeCAD.Vector(0.0, 0.0, 0.0), 2: FreeCAD.Vector(1.0, 0.0, 0.0), 3: FreeCAD.Vector(2.0, 0.0, 0.0), 4: FreeCAD.Vector(3.0, 0.0, 0.0), - 5: FreeCAD.Vector(4.0, 0.0, 0.0) - } + 5: FreeCAD.Vector(4.0, 0.0, 0.0), + }, ] expected_edges = [2, 1, (1, 3, 2), 2, (3, 5, 4)] self.assertEqual( - node_data, - expected_nodes, - "Nodes of Python created seg3 element are unexpected" + node_data, expected_nodes, "Nodes of Python created seg3 element are unexpected" ) self.assertEqual( - edge_data, - expected_edges, - "Edges of Python created seg3 element are unexpected" + edge_data, expected_edges, "Edges of Python created seg3 element are unexpected" ) # ******************************************************************************************** - def test_unv_save_load( - self - ): + def test_unv_save_load(self): tetra10 = Fem.FemMesh() tetra10.addNode(6, 12, 18, 1) tetra10.addNode(0, 0, 18, 2) @@ -176,13 +153,11 @@ class TestMeshCommon(unittest.TestCase): self.assertEqual( newmesh.getElementNodes(1), expected, - "Nodes order of quadratic volume element is unexpected" + "Nodes order of quadratic volume element is unexpected", ) # ******************************************************************************************** - def test_writeAbaqus_precision( - self - ): + def test_writeAbaqus_precision(self): # https://forum.freecad.org/viewtopic.php?f=18&t=22759#p176669 # ccx reads only F20.0 (i. e. Fortran floating point field 20 chars wide) # thus precision is set to 13 in writeAbaqus @@ -193,14 +168,14 @@ class TestMeshCommon(unittest.TestCase): -5000000000000000000.1, -1.123456789123456e-14, -0.1234567890123456789e-101, - 2 + 2, ) seg2.addEdge([1, 2]) inp_file = join(testtools.get_fem_test_tmp_dir("mesh_common_inp_preci"), "seg2_mesh.inp") seg2.writeABAQUS(inp_file, 1, False) - read_file = open(inp_file, "r") + read_file = open(inp_file) read_node_line = "line was not found" for ln in read_file: ln = ln.strip() @@ -214,10 +189,7 @@ class TestMeshCommon(unittest.TestCase): expected = [expected_lin, expected_win] self.assertTrue( True if read_node_line in expected else False, - "Problem in test_writeAbaqus_precision, \n{0}\n{1}".format( - read_node_line, - expected - ) + f"Problem in test_writeAbaqus_precision, \n{read_node_line}\n{expected}", ) @@ -227,9 +199,7 @@ class TestMeshEleTetra10(unittest.TestCase): fcc_print("import TestMeshEleTetra10") # ******************************************************************************************** - def setUp( - self - ): + def setUp(self): # setUp is executed before every test # new document @@ -238,11 +208,7 @@ class TestMeshEleTetra10(unittest.TestCase): # more inits self.elem = "tetra10" - self.base_testfile = join( - testtools.get_fem_test_home_dir(), - "mesh", - (self.elem + "_mesh.") - ) + self.base_testfile = join(testtools.get_fem_test_home_dir(), "mesh", (self.elem + "_mesh.")) # 10 node tetrahedron --> tetra10 femmesh = Fem.FemMesh() @@ -271,12 +237,12 @@ class TestMeshEleTetra10(unittest.TestCase): 8: FreeCAD.Vector(6.0, 9.0, 9.0), 9: FreeCAD.Vector(3.0, 3.0, 9.0), 10: FreeCAD.Vector(9.0, 3.0, 9.0), - } + }, } self.expected_elem = { "volcount": 1, "tetcount": 1, - "volumes": [1, (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)] + "volumes": [1, (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)], } """ fcc_print("\n") @@ -286,34 +252,27 @@ class TestMeshEleTetra10(unittest.TestCase): """ # ******************************************************************************************** - def tearDown( - self - ): + def tearDown(self): # tearDown is executed after every test FreeCAD.closeDocument(self.document.Name) # ******************************************************************************************** - def test_00print( - self - ): + def test_00print(self): # since method name starts with 00 this will be run first # this test just prints a line with stars - fcc_print("\n{0}\n{1} run FEM TestMeshEleTetra10 tests {2}\n{0}".format( - 100 * "*", - 10 * "*", - 56 * "*" - )) + fcc_print( + "\n{0}\n{1} run FEM TestMeshEleTetra10 tests {2}\n{0}".format( + 100 * "*", 10 * "*", 56 * "*" + ) + ) # ******************************************************************************************** - def get_file_paths( - self, - file_extension - ): + def get_file_paths(self, file_extension): testfile = self.base_testfile + file_extension outfile = join( testtools.get_fem_test_tmp_dir("mesh_elements_" + self.elem + "_" + file_extension), - self.elem + "_mesh." + file_extension + self.elem + "_mesh." + file_extension, ) # fcc_print("\n") @@ -322,18 +281,15 @@ class TestMeshEleTetra10(unittest.TestCase): return (outfile, testfile) # ******************************************************************************************** - def compare_mesh_files( - self, - femmesh_testfile, - femmesh_outfile, - filetyp - ): + def compare_mesh_files(self, femmesh_testfile, femmesh_outfile, filetyp): # """ - fcc_print([ - femmesh_testfile.Volumes[0], - femmesh_testfile.getElementNodes(femmesh_outfile.Volumes[0]) - ]) + fcc_print( + [ + femmesh_testfile.Volumes[0], + femmesh_testfile.getElementNodes(femmesh_outfile.Volumes[0]), + ] + ) # """ # test reading the test mesh @@ -341,85 +297,74 @@ class TestMeshEleTetra10(unittest.TestCase): femmesh_testfile.Nodes, self.expected_nodes["nodes"], "Test reading {} mesh to {} file failed. Nodes are different.\n".format( - self.elem, - filetyp - ) + self.elem, filetyp + ), ) self.assertEqual( [ femmesh_testfile.Volumes[0], - femmesh_testfile.getElementNodes(femmesh_outfile.Volumes[0]) + femmesh_testfile.getElementNodes(femmesh_outfile.Volumes[0]), ], self.expected_elem["volumes"], "Test reading {} mesh to {} file failed. Volumes are different.\n".format( - self.elem, - filetyp - ) + self.elem, filetyp + ), ) # test reading the written mesh self.assertEqual( femmesh_outfile.Nodes, self.expected_nodes["nodes"], "Test reading {} mesh to {} file failed. Nodes are different.\n".format( - self.elem, - filetyp - ) + self.elem, filetyp + ), ) self.assertEqual( [ femmesh_outfile.Volumes[0], - femmesh_outfile.getElementNodes(femmesh_outfile.Volumes[0]) + femmesh_outfile.getElementNodes(femmesh_outfile.Volumes[0]), ], self.expected_elem["volumes"], "Test reading {} mesh to {} file failed. Volumes are different.\n".format( - self.elem, - filetyp - ) + self.elem, filetyp + ), ) # test if both are equal self.assertEqual( femmesh_outfile.Nodes, femmesh_testfile.Nodes, "Test reading {} mesh to {} file failed. Nodes are different.\n".format( - self.elem, - filetyp - ) + self.elem, filetyp + ), ) self.assertEqual( femmesh_outfile.Volumes, femmesh_testfile.Volumes, "Test reading {} mesh to {} file failed. Volumes are different.\n".format( - self.elem, - filetyp - ) + self.elem, filetyp + ), ) # ******************************************************************************************** - def test_tetra10_create( - self - ): + def test_tetra10_create(self): # tetra10 element: creating by Python - node_data = { - "count": self.femmesh.NodeCount, - "nodes": self.femmesh.Nodes - } + node_data = {"count": self.femmesh.NodeCount, "nodes": self.femmesh.Nodes} elem_data = { "volcount": self.femmesh.VolumeCount, "tetcount": self.femmesh.TetraCount, "volumes": [ self.femmesh.Volumes[0], - self.femmesh.getElementNodes(self.femmesh.Volumes[0]) - ] + self.femmesh.getElementNodes(self.femmesh.Volumes[0]), + ], } self.assertEqual( node_data, self.expected_nodes, - "Nodes of Python created " + self.elem + "mesh element are unexpected" + "Nodes of Python created " + self.elem + "mesh element are unexpected", ) self.assertEqual( elem_data, self.expected_elem, - "Elements of Python created " + self.elem + "mesh element are unexpected" + "Elements of Python created " + self.elem + "mesh element are unexpected", ) """ obj = doc.addObject("Fem::FemMeshObject" , elem) @@ -429,9 +374,7 @@ class TestMeshEleTetra10(unittest.TestCase): """ # ******************************************************************************************** - def test_tetra10_inp( - self - ): + def test_tetra10_inp(self): # tetra10 element: reading from and writing to inp mesh file format file_extension = "inp" @@ -441,16 +384,10 @@ class TestMeshEleTetra10(unittest.TestCase): femmesh_outfile = Fem.read(outfile) # read the mesh from written mesh femmesh_testfile = Fem.read(testfile) # read the mesh from test mesh - self.compare_mesh_files( - femmesh_testfile, - femmesh_outfile, - file_extension - ) + self.compare_mesh_files(femmesh_testfile, femmesh_outfile, file_extension) # ******************************************************************************************** - def test_tetra10_unv( - self - ): + def test_tetra10_unv(self): # tetra10 element: reading from and writing to unv mesh file format file_extension = "unv" @@ -460,16 +397,10 @@ class TestMeshEleTetra10(unittest.TestCase): femmesh_outfile = Fem.read(outfile) # read the mesh from written mesh femmesh_testfile = Fem.read(testfile) # read the mesh from test mesh - self.compare_mesh_files( - femmesh_testfile, - femmesh_outfile, - file_extension - ) + self.compare_mesh_files(femmesh_testfile, femmesh_outfile, file_extension) # ******************************************************************************************** - def test_tetra10_vkt( - self - ): + def test_tetra10_vkt(self): # tetra10 element: reading from and writing to unv mesh file format file_extension = "vtk" @@ -480,18 +411,12 @@ class TestMeshEleTetra10(unittest.TestCase): femmesh_outfile = Fem.read(outfile) # read the mesh from written mesh femmesh_testfile = Fem.read(testfile) # read the mesh from test mesh - self.compare_mesh_files( - femmesh_testfile, - femmesh_outfile, - file_extension - ) + self.compare_mesh_files(femmesh_testfile, femmesh_outfile, file_extension) else: fcc_print("FEM_VTK post processing is disabled.") # ******************************************************************************************** - def test_tetra10_yml( - self - ): + def test_tetra10_yml(self): # tetra10 element: reading from and writing to yaml/json mesh file format file_extension = "yml" @@ -503,21 +428,17 @@ class TestMeshEleTetra10(unittest.TestCase): # femmesh_outfile = Fem.read(testfile) # read the mesh from test mesh # directly use Python methods to read and write files from feminout.importYamlJsonMesh import write + write(outfile, self.femmesh) from feminout.importYamlJsonMesh import read + femmesh_testfile = read(outfile) femmesh_outfile = read(testfile) - self.compare_mesh_files( - femmesh_testfile, - femmesh_outfile, - file_extension - ) + self.compare_mesh_files(femmesh_testfile, femmesh_outfile, file_extension) # ******************************************************************************************** - def test_tetra10_z88( - self - ): + def test_tetra10_z88(self): # tetra10 element: reading from and writing to z88 mesh file format file_extension = "z88" @@ -527,11 +448,7 @@ class TestMeshEleTetra10(unittest.TestCase): femmesh_testfile = Fem.read(outfile) # read the mesh from written mesh femmesh_outfile = Fem.read(testfile) # read the mesh from test mesh - self.compare_mesh_files( - femmesh_testfile, - femmesh_outfile, - file_extension - ) + self.compare_mesh_files(femmesh_testfile, femmesh_outfile, file_extension) # ************************************************************************************************ @@ -541,33 +458,25 @@ class TestMeshGroups(unittest.TestCase): fcc_print("import TestMeshGroups") # ******************************************************************************************** - def setUp( - self - ): + def setUp(self): # setUp is executed before every test # new document self.document = FreeCAD.newDocument(self.__class__.__name__) # ******************************************************************************************** - def tearDown( - self - ): + def tearDown(self): # tearDown is executed after every test FreeCAD.closeDocument(self.document.Name) # ******************************************************************************************** - def test_00print( - self - ): + def test_00print(self): # since method name starts with 00 this will be run first # this test just prints a line with stars - fcc_print("\n{0}\n{1} run FEM TestMeshGroups tests {2}\n{0}".format( - 100 * "*", - 10 * "*", - 57 * "*" - )) + fcc_print( + "\n{0}\n{1} run FEM TestMeshGroups tests {2}\n{0}".format(100 * "*", 10 * "*", 57 * "*") + ) # ******************************************************************************************** def test_add_groups(self): @@ -598,20 +507,14 @@ class TestMeshGroups(unittest.TestCase): "MyEdgeGroup", "MyVolumeGroup", "My0DElementGroup", - "MyBallGroup" - ] - expected_dict["types"] = [ - "Node", - "Edge", - "Volume", - "0DElement", - "Ball" + "MyBallGroup", ] + expected_dict["types"] = ["Node", "Edge", "Volume", "0DElement", "Ball"] expected_dict["count"] = fm.GroupCount + 5 result_dict = {} mygrpids = [] - for (name, typ) in zip(expected_dict["names"], expected_dict["types"]): + for name, typ in zip(expected_dict["names"], expected_dict["types"]): mygrpids.append(fm.addGroup(name, typ)) expected_dict["ids"] = sorted(tuple(mygrpids)) @@ -621,8 +524,7 @@ class TestMeshGroups(unittest.TestCase): result_dict["count"] = fm.GroupCount result_dict["ids"] = sorted(fm.Groups) - result_dict["types"] = list([fm.getGroupElementType(g) - for g in fm.Groups]) + result_dict["types"] = list([fm.getGroupElementType(g) for g in fm.Groups]) result_dict["names"] = list([fm.getGroupName(g) for g in fm.Groups]) # fcc_print("result dict") @@ -631,7 +533,7 @@ class TestMeshGroups(unittest.TestCase): self.assertEqual( expected_dict, result_dict, - msg="expected: {0}\n\nresult: {1}\n\n differ".format(expected_dict, result_dict) + msg=f"expected: {expected_dict}\n\nresult: {result_dict}\n\n differ", ) def test_delete_groups(self): @@ -663,9 +565,10 @@ class TestMeshGroups(unittest.TestCase): old_group_count, new_group_count, msg=( - "GroupCount before and after adding and deleting groups differ: {0} != {1}" - .format(old_group_count, new_group_count) - ) + "GroupCount before and after adding and deleting groups differ: {} != {}".format( + old_group_count, new_group_count + ) + ), ) def test_add_group_elements(self): @@ -699,7 +602,8 @@ class TestMeshGroups(unittest.TestCase): elements_to_be_added, elements_returned, msg=( - "elements to be added {0} and elements returned {1} differ". - format(elements_to_be_added, elements_returned) - ) + "elements to be added {} and elements returned {} differ".format( + elements_to_be_added, elements_returned + ) + ), ) diff --git a/src/Mod/Fem/femtest/app/test_object.py b/src/Mod/Fem/femtest/app/test_object.py index dc5d64d62c..e972e2fa50 100644 --- a/src/Mod/Fem/femtest/app/test_object.py +++ b/src/Mod/Fem/femtest/app/test_object.py @@ -40,38 +40,30 @@ class TestObjectCreate(unittest.TestCase): fcc_print("import TestObjectCreate") # ******************************************************************************************** - def setUp( - self - ): + def setUp(self): # setUp is executed before every test # new document self.document = FreeCAD.newDocument(self.__class__.__name__) # ******************************************************************************************** - def tearDown( - self - ): + def tearDown(self): # tearDown is executed after every test FreeCAD.closeDocument(self.document.Name) # ******************************************************************************************** - def test_00print( - self - ): + def test_00print(self): # since method name starts with 00 this will be run first # this test just prints a line with stars - fcc_print("\n{0}\n{1} run FEM TestObjectCreate tests {2}\n{0}".format( - 100 * "*", - 10 * "*", - 58 * "*" - )) + fcc_print( + "\n{0}\n{1} run FEM TestObjectCreate tests {2}\n{0}".format( + 100 * "*", 10 * "*", 58 * "*" + ) + ) # ******************************************************************************************** - def test_femobjects_make( - self - ): + def test_femobjects_make(self): doc = create_all_fem_objects_doc(self.document) # count the def make in ObjectsFem module @@ -94,20 +86,17 @@ class TestObjectCreate(unittest.TestCase): self.assertEqual(len(doc.Analysis.Group), count_defmake - 19) self.assertEqual(len(doc.Objects), count_defmake) - fcc_print("doc objects count: {}, method: {}".format( - len(doc.Objects), - sys._getframe().f_code.co_name) + fcc_print( + "doc objects count: {}, method: {}".format( + len(doc.Objects), sys._getframe().f_code.co_name + ) ) # save the file save_fc_file = join( - testtools.get_fem_test_tmp_dir("objects_create_all"), - "all_objects.FCStd" - ) - fcc_print( - "Save FreeCAD all objects file to {} ..." - .format(save_fc_file) + testtools.get_fem_test_tmp_dir("objects_create_all"), "all_objects.FCStd" ) + fcc_print(f"Save FreeCAD all objects file to {save_fc_file} ...") self.document.saveAs(save_fc_file) @@ -117,538 +106,375 @@ class TestObjectType(unittest.TestCase): fcc_print("import TestObjectType") # ******************************************************************************************** - def setUp( - self - ): + def setUp(self): # setUp is executed before every test # new document self.document = FreeCAD.newDocument(self.__class__.__name__) # ******************************************************************************************** - def tearDown( - self - ): + def tearDown(self): # tearDown is executed after every test FreeCAD.closeDocument(self.document.Name) # ******************************************************************************************** - def test_00print( - self - ): + def test_00print(self): # since method name starts with 00 this will be run first # this test just prints a line with stars - fcc_print("\n{0}\n{1} run FEM TestObjectType tests {2}\n{0}".format( - 100 * "*", - 10 * "*", - 60 * "*" - )) + fcc_print( + "\n{0}\n{1} run FEM TestObjectType tests {2}\n{0}".format(100 * "*", 10 * "*", 60 * "*") + ) # ******************************************************************************************** - def test_femobjects_type( - self - ): + def test_femobjects_type(self): doc = self.document create_all_fem_objects_doc from femtools.femutils import type_of_obj - self.assertEqual( - "Fem::FemAnalysis", - type_of_obj(ObjectsFem.makeAnalysis(doc)) - ) + + self.assertEqual("Fem::FemAnalysis", type_of_obj(ObjectsFem.makeAnalysis(doc))) self.assertEqual( "Fem::ConstantVacuumPermittivity", - type_of_obj(ObjectsFem.makeConstantVacuumPermittivity(doc)) + type_of_obj(ObjectsFem.makeConstantVacuumPermittivity(doc)), ) self.assertEqual( - "Fem::ConstraintBearing", - type_of_obj(ObjectsFem.makeConstraintBearing(doc)) + "Fem::ConstraintBearing", type_of_obj(ObjectsFem.makeConstraintBearing(doc)) ) self.assertEqual( "Fem::ConstraintBodyHeatSource", - type_of_obj(ObjectsFem.makeConstraintBodyHeatSource(doc)) + type_of_obj(ObjectsFem.makeConstraintBodyHeatSource(doc)), ) self.assertEqual( - "Fem::ConstraintContact", - type_of_obj(ObjectsFem.makeConstraintContact(doc)) + "Fem::ConstraintContact", type_of_obj(ObjectsFem.makeConstraintContact(doc)) ) self.assertEqual( "Fem::ConstraintCurrentDensity", - type_of_obj(ObjectsFem.makeConstraintCurrentDensity(doc)) + type_of_obj(ObjectsFem.makeConstraintCurrentDensity(doc)), ) self.assertEqual( - "Fem::ConstraintDisplacement", - type_of_obj(ObjectsFem.makeConstraintDisplacement(doc)) + "Fem::ConstraintDisplacement", type_of_obj(ObjectsFem.makeConstraintDisplacement(doc)) ) self.assertEqual( "Fem::ConstraintElectrostaticPotential", - type_of_obj(ObjectsFem.makeConstraintElectrostaticPotential(doc)) + type_of_obj(ObjectsFem.makeConstraintElectrostaticPotential(doc)), + ) + self.assertEqual("Fem::ConstraintFixed", type_of_obj(ObjectsFem.makeConstraintFixed(doc))) + self.assertEqual( + "Fem::ConstraintRigidBody", type_of_obj(ObjectsFem.makeConstraintRigidBody(doc)) ) self.assertEqual( - "Fem::ConstraintFixed", - type_of_obj(ObjectsFem.makeConstraintFixed(doc)) + "Fem::ConstraintFlowVelocity", type_of_obj(ObjectsFem.makeConstraintFlowVelocity(doc)) ) self.assertEqual( - "Fem::ConstraintRigidBody", - type_of_obj(ObjectsFem.makeConstraintRigidBody(doc)) + "Fem::ConstraintFluidBoundary", type_of_obj(ObjectsFem.makeConstraintFluidBoundary(doc)) ) + self.assertEqual("Fem::ConstraintSpring", type_of_obj(ObjectsFem.makeConstraintSpring(doc))) + self.assertEqual("Fem::ConstraintForce", type_of_obj(ObjectsFem.makeConstraintForce(doc))) + self.assertEqual("Fem::ConstraintGear", type_of_obj(ObjectsFem.makeConstraintGear(doc))) self.assertEqual( - "Fem::ConstraintFlowVelocity", - type_of_obj(ObjectsFem.makeConstraintFlowVelocity(doc)) - ) - self.assertEqual( - "Fem::ConstraintFluidBoundary", - type_of_obj(ObjectsFem.makeConstraintFluidBoundary(doc)) - ) - self.assertEqual( - "Fem::ConstraintSpring", - type_of_obj(ObjectsFem.makeConstraintSpring(doc)) - ) - self.assertEqual( - "Fem::ConstraintForce", - type_of_obj(ObjectsFem.makeConstraintForce(doc)) - ) - self.assertEqual( - "Fem::ConstraintGear", - type_of_obj(ObjectsFem.makeConstraintGear(doc)) - ) - self.assertEqual( - "Fem::ConstraintHeatflux", - type_of_obj(ObjectsFem.makeConstraintHeatflux(doc)) + "Fem::ConstraintHeatflux", type_of_obj(ObjectsFem.makeConstraintHeatflux(doc)) ) self.assertEqual( "Fem::ConstraintInitialFlowVelocity", - type_of_obj(ObjectsFem.makeConstraintInitialFlowVelocity(doc)) + type_of_obj(ObjectsFem.makeConstraintInitialFlowVelocity(doc)), ) self.assertEqual( "Fem::ConstraintInitialPressure", - type_of_obj(ObjectsFem.makeConstraintInitialPressure(doc)) + type_of_obj(ObjectsFem.makeConstraintInitialPressure(doc)), ) self.assertEqual( "Fem::ConstraintInitialTemperature", - type_of_obj(ObjectsFem.makeConstraintInitialTemperature(doc)) + type_of_obj(ObjectsFem.makeConstraintInitialTemperature(doc)), ) self.assertEqual( - "Fem::ConstraintMagnetization", - type_of_obj(ObjectsFem.makeConstraintMagnetization(doc)) + "Fem::ConstraintMagnetization", type_of_obj(ObjectsFem.makeConstraintMagnetization(doc)) ) self.assertEqual( - "Fem::ConstraintPlaneRotation", - type_of_obj(ObjectsFem.makeConstraintPlaneRotation(doc)) + "Fem::ConstraintPlaneRotation", type_of_obj(ObjectsFem.makeConstraintPlaneRotation(doc)) ) self.assertEqual( - "Fem::ConstraintPressure", - type_of_obj(ObjectsFem.makeConstraintPressure(doc)) + "Fem::ConstraintPressure", type_of_obj(ObjectsFem.makeConstraintPressure(doc)) + ) + self.assertEqual("Fem::ConstraintPulley", type_of_obj(ObjectsFem.makeConstraintPulley(doc))) + self.assertEqual( + "Fem::ConstraintSectionPrint", type_of_obj(ObjectsFem.makeConstraintSectionPrint(doc)) ) self.assertEqual( - "Fem::ConstraintPulley", - type_of_obj(ObjectsFem.makeConstraintPulley(doc)) + "Fem::ConstraintSelfWeight", type_of_obj(ObjectsFem.makeConstraintSelfWeight(doc)) ) self.assertEqual( - "Fem::ConstraintSectionPrint", - type_of_obj(ObjectsFem.makeConstraintSectionPrint(doc)) + "Fem::ConstraintCentrif", type_of_obj(ObjectsFem.makeConstraintCentrif(doc)) ) self.assertEqual( - "Fem::ConstraintSelfWeight", - type_of_obj(ObjectsFem.makeConstraintSelfWeight(doc)) + "Fem::ConstraintTemperature", type_of_obj(ObjectsFem.makeConstraintTemperature(doc)) + ) + self.assertEqual("Fem::ConstraintTie", type_of_obj(ObjectsFem.makeConstraintTie(doc))) + self.assertEqual( + "Fem::ConstraintTransform", type_of_obj(ObjectsFem.makeConstraintTransform(doc)) + ) + self.assertEqual("Fem::ElementFluid1D", type_of_obj(ObjectsFem.makeElementFluid1D(doc))) + self.assertEqual( + "Fem::ElementGeometry1D", type_of_obj(ObjectsFem.makeElementGeometry1D(doc)) ) self.assertEqual( - "Fem::ConstraintCentrif", - type_of_obj(ObjectsFem.makeConstraintCentrif(doc)) + "Fem::ElementGeometry2D", type_of_obj(ObjectsFem.makeElementGeometry2D(doc)) ) self.assertEqual( - "Fem::ConstraintTemperature", - type_of_obj(ObjectsFem.makeConstraintTemperature(doc)) - ) - self.assertEqual( - "Fem::ConstraintTie", - type_of_obj(ObjectsFem.makeConstraintTie(doc)) - ) - self.assertEqual( - "Fem::ConstraintTransform", - type_of_obj(ObjectsFem.makeConstraintTransform(doc)) - ) - self.assertEqual( - "Fem::ElementFluid1D", - type_of_obj(ObjectsFem.makeElementFluid1D(doc)) - ) - self.assertEqual( - "Fem::ElementGeometry1D", - type_of_obj(ObjectsFem.makeElementGeometry1D(doc)) - ) - self.assertEqual( - "Fem::ElementGeometry2D", - type_of_obj(ObjectsFem.makeElementGeometry2D(doc)) - ) - self.assertEqual( - "Fem::ElementRotation1D", - type_of_obj(ObjectsFem.makeElementRotation1D(doc)) + "Fem::ElementRotation1D", type_of_obj(ObjectsFem.makeElementRotation1D(doc)) ) materialsolid = ObjectsFem.makeMaterialSolid(doc) - self.assertEqual( - "Fem::MaterialCommon", - type_of_obj(ObjectsFem.makeMaterialFluid(doc)) - ) - self.assertEqual( - "Fem::MaterialCommon", - type_of_obj(materialsolid)) + self.assertEqual("Fem::MaterialCommon", type_of_obj(ObjectsFem.makeMaterialFluid(doc))) + self.assertEqual("Fem::MaterialCommon", type_of_obj(materialsolid)) self.assertEqual( "Fem::MaterialMechanicalNonlinear", - type_of_obj(ObjectsFem.makeMaterialMechanicalNonlinear(doc, materialsolid)) + type_of_obj(ObjectsFem.makeMaterialMechanicalNonlinear(doc, materialsolid)), ) self.assertEqual( - "Fem::MaterialReinforced", - type_of_obj(ObjectsFem.makeMaterialReinforced(doc)) + "Fem::MaterialReinforced", type_of_obj(ObjectsFem.makeMaterialReinforced(doc)) ) mesh = ObjectsFem.makeMeshGmsh(doc) + self.assertEqual("Fem::FemMeshGmsh", type_of_obj(mesh)) self.assertEqual( - "Fem::FemMeshGmsh", - type_of_obj(mesh)) - self.assertEqual( - "Fem::MeshBoundaryLayer", - type_of_obj(ObjectsFem.makeMeshBoundaryLayer(doc, mesh)) + "Fem::MeshBoundaryLayer", type_of_obj(ObjectsFem.makeMeshBoundaryLayer(doc, mesh)) ) + self.assertEqual("Fem::MeshGroup", type_of_obj(ObjectsFem.makeMeshGroup(doc, mesh))) + self.assertEqual("Fem::MeshRegion", type_of_obj(ObjectsFem.makeMeshRegion(doc, mesh))) self.assertEqual( - "Fem::MeshGroup", - type_of_obj(ObjectsFem.makeMeshGroup(doc, mesh)) - ) - self.assertEqual( - "Fem::MeshRegion", - type_of_obj(ObjectsFem.makeMeshRegion(doc, mesh)) - ) - self.assertEqual( - "Fem::FemMeshShapeNetgenObject", - type_of_obj(ObjectsFem.makeMeshNetgen(doc)) - ) - self.assertEqual( - "Fem::MeshResult", - type_of_obj(ObjectsFem.makeMeshResult(doc)) - ) - self.assertEqual( - "Fem::ResultMechanical", - type_of_obj(ObjectsFem.makeResultMechanical(doc)) + "Fem::FemMeshShapeNetgenObject", type_of_obj(ObjectsFem.makeMeshNetgen(doc)) ) + self.assertEqual("Fem::MeshResult", type_of_obj(ObjectsFem.makeMeshResult(doc))) + self.assertEqual("Fem::ResultMechanical", type_of_obj(ObjectsFem.makeResultMechanical(doc))) solverelmer = ObjectsFem.makeSolverElmer(doc) self.assertEqual( - "Fem::SolverCcxTools", - type_of_obj(ObjectsFem.makeSolverCalculiXCcxTools(doc)) - ) - self.assertEqual( - "Fem::SolverCalculix", - type_of_obj(ObjectsFem.makeSolverCalculix(doc)) - ) - self.assertEqual( - "Fem::SolverElmer", - type_of_obj(solverelmer) - ) - self.assertEqual( - "Fem::SolverMystran", - type_of_obj(ObjectsFem.makeSolverMystran(doc)) - ) - self.assertEqual( - "Fem::SolverZ88", - type_of_obj(ObjectsFem.makeSolverZ88(doc)) + "Fem::SolverCcxTools", type_of_obj(ObjectsFem.makeSolverCalculiXCcxTools(doc)) ) + self.assertEqual("Fem::SolverCalculix", type_of_obj(ObjectsFem.makeSolverCalculix(doc))) + self.assertEqual("Fem::SolverElmer", type_of_obj(solverelmer)) + self.assertEqual("Fem::SolverMystran", type_of_obj(ObjectsFem.makeSolverMystran(doc))) + self.assertEqual("Fem::SolverZ88", type_of_obj(ObjectsFem.makeSolverZ88(doc))) self.assertEqual( "Fem::EquationElmerDeformation", - type_of_obj(ObjectsFem.makeEquationDeformation(doc, solverelmer)) + type_of_obj(ObjectsFem.makeEquationDeformation(doc, solverelmer)), ) self.assertEqual( "Fem::EquationElmerElasticity", - type_of_obj(ObjectsFem.makeEquationElasticity(doc, solverelmer)) + type_of_obj(ObjectsFem.makeEquationElasticity(doc, solverelmer)), ) self.assertEqual( "Fem::EquationElmerElectricforce", - type_of_obj(ObjectsFem.makeEquationElectricforce(doc, solverelmer)) + type_of_obj(ObjectsFem.makeEquationElectricforce(doc, solverelmer)), ) self.assertEqual( "Fem::EquationElmerElectrostatic", - type_of_obj(ObjectsFem.makeEquationElectrostatic(doc, solverelmer)) + type_of_obj(ObjectsFem.makeEquationElectrostatic(doc, solverelmer)), ) self.assertEqual( - "Fem::EquationElmerFlow", - type_of_obj(ObjectsFem.makeEquationFlow(doc, solverelmer)) + "Fem::EquationElmerFlow", type_of_obj(ObjectsFem.makeEquationFlow(doc, solverelmer)) ) self.assertEqual( - "Fem::EquationElmerFlux", - type_of_obj(ObjectsFem.makeEquationFlux(doc, solverelmer)) + "Fem::EquationElmerFlux", type_of_obj(ObjectsFem.makeEquationFlux(doc, solverelmer)) ) self.assertEqual( - "Fem::EquationElmerHeat", - type_of_obj(ObjectsFem.makeEquationHeat(doc, solverelmer)) + "Fem::EquationElmerHeat", type_of_obj(ObjectsFem.makeEquationHeat(doc, solverelmer)) ) self.assertEqual( "Fem::EquationElmerMagnetodynamic2D", - type_of_obj(ObjectsFem.makeEquationMagnetodynamic2D(doc, solverelmer)) + type_of_obj(ObjectsFem.makeEquationMagnetodynamic2D(doc, solverelmer)), ) self.assertEqual( "Fem::EquationElmerMagnetodynamic", - type_of_obj(ObjectsFem.makeEquationMagnetodynamic(doc, solverelmer)) + type_of_obj(ObjectsFem.makeEquationMagnetodynamic(doc, solverelmer)), ) - fcc_print("doc objects count: {}, method: {}".format( - len(doc.Objects), - sys._getframe().f_code.co_name) + fcc_print( + "doc objects count: {}, method: {}".format( + len(doc.Objects), sys._getframe().f_code.co_name + ) ) # TODO: vtk post objs, thus 5 obj less than test_femobjects_make self.assertEqual(len(doc.Objects), testtools.get_defmake_count(False)) # TODO: use different type for material fluid and material solid # ******************************************************************************************** - def test_femobjects_isoftype( - self - ): + def test_femobjects_isoftype(self): doc = self.document from femtools.femutils import is_of_type - self.assertTrue(is_of_type( - ObjectsFem.makeAnalysis(doc), - "Fem::FemAnalysis" - )) - self.assertTrue(is_of_type( - ObjectsFem.makeConstantVacuumPermittivity(doc), - "Fem::ConstantVacuumPermittivity" - )) - self.assertTrue(is_of_type( - ObjectsFem.makeConstraintBearing(doc), - "Fem::ConstraintBearing" - )) - self.assertTrue(is_of_type( - ObjectsFem.makeConstraintBodyHeatSource(doc), - "Fem::ConstraintBodyHeatSource" - )) - self.assertTrue(is_of_type( - ObjectsFem.makeConstraintContact(doc), - "Fem::ConstraintContact" - )) - self.assertTrue(is_of_type( - ObjectsFem.makeConstraintCurrentDensity(doc), - "Fem::ConstraintCurrentDensity" - )) - self.assertTrue(is_of_type( - ObjectsFem.makeConstraintDisplacement(doc), - "Fem::ConstraintDisplacement" - )) - self.assertTrue(is_of_type( - ObjectsFem.makeConstraintElectrostaticPotential(doc), - "Fem::ConstraintElectrostaticPotential" - )) - self.assertTrue(is_of_type( - ObjectsFem.makeConstraintFixed(doc), - "Fem::ConstraintFixed" - )) - self.assertTrue(is_of_type( - ObjectsFem.makeConstraintRigidBody(doc), - "Fem::ConstraintRigidBody" - )) - self.assertTrue(is_of_type( - ObjectsFem.makeConstraintFlowVelocity(doc), - "Fem::ConstraintFlowVelocity" - )) - self.assertTrue(is_of_type( - ObjectsFem.makeConstraintFluidBoundary(doc), - "Fem::ConstraintFluidBoundary" - )) - self.assertTrue(is_of_type( - ObjectsFem.makeConstraintMagnetization(doc), - "Fem::ConstraintMagnetization" - )) - self.assertTrue(is_of_type( - ObjectsFem.makeConstraintSpring(doc), - "Fem::ConstraintSpring" - )) - self.assertTrue(is_of_type( - ObjectsFem.makeConstraintForce(doc), - "Fem::ConstraintForce" - )) - self.assertTrue(is_of_type( - ObjectsFem.makeConstraintGear(doc), - "Fem::ConstraintGear" - )) - self.assertTrue(is_of_type( - ObjectsFem.makeConstraintHeatflux(doc), - "Fem::ConstraintHeatflux" - )) - self.assertTrue(is_of_type( - ObjectsFem.makeConstraintInitialFlowVelocity(doc), - "Fem::ConstraintInitialFlowVelocity" - )) - self.assertTrue(is_of_type( - ObjectsFem.makeConstraintInitialPressure(doc), - "Fem::ConstraintInitialPressure" - )) - self.assertTrue(is_of_type( - ObjectsFem.makeConstraintInitialTemperature(doc), - "Fem::ConstraintInitialTemperature" - )) - self.assertTrue(is_of_type( - ObjectsFem.makeConstraintPlaneRotation(doc), - "Fem::ConstraintPlaneRotation" - )) - self.assertTrue(is_of_type( - ObjectsFem.makeConstraintPressure(doc), - "Fem::ConstraintPressure" - )) - self.assertTrue(is_of_type( - ObjectsFem.makeConstraintPulley(doc), - "Fem::ConstraintPulley" - )) - self.assertTrue(is_of_type( - ObjectsFem.makeConstraintSectionPrint(doc), - "Fem::ConstraintSectionPrint" - )) - self.assertTrue(is_of_type( - ObjectsFem.makeConstraintSelfWeight(doc), - "Fem::ConstraintSelfWeight" - )) - self.assertTrue(is_of_type( - ObjectsFem.makeConstraintCentrif(doc), - "Fem::ConstraintCentrif" - )) - self.assertTrue(is_of_type( - ObjectsFem.makeConstraintTemperature(doc), - "Fem::ConstraintTemperature" - )) - self.assertTrue(is_of_type( - ObjectsFem.makeConstraintTie(doc), - "Fem::ConstraintTie" - )) - self.assertTrue(is_of_type( - ObjectsFem.makeConstraintTransform(doc), - "Fem::ConstraintTransform" - )) - self.assertTrue(is_of_type( - ObjectsFem.makeElementFluid1D(doc), - "Fem::ElementFluid1D" - )) - self.assertTrue(is_of_type( - ObjectsFem.makeElementGeometry1D(doc), - "Fem::ElementGeometry1D" - )) - self.assertTrue(is_of_type( - ObjectsFem.makeElementGeometry2D(doc), - "Fem::ElementGeometry2D" - )) - self.assertTrue(is_of_type( - ObjectsFem.makeElementRotation1D(doc), - "Fem::ElementRotation1D" - )) - materialsolid = ObjectsFem.makeMaterialSolid(doc) - self.assertTrue(is_of_type( - ObjectsFem.makeMaterialFluid(doc), - "Fem::MaterialCommon" - )) - self.assertTrue(is_of_type( - materialsolid, - "Fem::MaterialCommon" - )) - self.assertTrue(is_of_type( - ObjectsFem.makeMaterialMechanicalNonlinear(doc, materialsolid), - "Fem::MaterialMechanicalNonlinear" - )) - self.assertTrue(is_of_type( - ObjectsFem.makeMaterialReinforced(doc), - "Fem::MaterialReinforced" - )) - mesh = ObjectsFem.makeMeshGmsh(doc) - self.assertTrue(is_of_type( - mesh, - "Fem::FemMeshGmsh" - )) - self.assertTrue(is_of_type( - ObjectsFem.makeMeshBoundaryLayer(doc, mesh), - "Fem::MeshBoundaryLayer" - )) - self.assertTrue(is_of_type( - ObjectsFem.makeMeshGroup(doc, mesh), - "Fem::MeshGroup" - )) - self.assertTrue(is_of_type( - ObjectsFem.makeMeshRegion(doc, mesh), - "Fem::MeshRegion" - )) - self.assertTrue(is_of_type( - ObjectsFem.makeMeshNetgen(doc), - "Fem::FemMeshShapeNetgenObject" - )) - self.assertTrue(is_of_type( - ObjectsFem.makeMeshResult(doc), - "Fem::MeshResult" - )) - self.assertTrue(is_of_type( - ObjectsFem.makeResultMechanical(doc), - "Fem::ResultMechanical" - )) - solverelmer = ObjectsFem.makeSolverElmer(doc) - self.assertTrue(is_of_type( - ObjectsFem.makeSolverCalculiXCcxTools(doc), - "Fem::SolverCcxTools" - )) - self.assertTrue(is_of_type( - ObjectsFem.makeSolverCalculix(doc), - "Fem::SolverCalculix" - )) - self.assertTrue(is_of_type( - solverelmer, - "Fem::SolverElmer" - )) - self.assertTrue(is_of_type( - ObjectsFem.makeSolverMystran(doc), - "Fem::SolverMystran" - )) - self.assertTrue(is_of_type( - ObjectsFem.makeSolverZ88(doc), - "Fem::SolverZ88" - )) - self.assertTrue(is_of_type( - ObjectsFem.makeEquationDeformation(doc, solverelmer), - "Fem::EquationElmerDeformation" - )) - self.assertTrue(is_of_type( - ObjectsFem.makeEquationElasticity(doc, solverelmer), - "Fem::EquationElmerElasticity" - )) - self.assertTrue(is_of_type( - ObjectsFem.makeEquationElectricforce(doc, solverelmer), - "Fem::EquationElmerElectricforce" - )) - self.assertTrue(is_of_type( - ObjectsFem.makeEquationElectrostatic(doc, solverelmer), - "Fem::EquationElmerElectrostatic" - )) - self.assertTrue(is_of_type( - ObjectsFem.makeEquationFlow(doc, solverelmer), - "Fem::EquationElmerFlow" - )) - self.assertTrue(is_of_type( - ObjectsFem.makeEquationFlux(doc, solverelmer), - "Fem::EquationElmerFlux" - )) - self.assertTrue(is_of_type( - ObjectsFem.makeEquationHeat(doc, solverelmer), - "Fem::EquationElmerHeat" - )) - self.assertTrue(is_of_type( - ObjectsFem.makeEquationMagnetodynamic2D(doc, solverelmer), - "Fem::EquationElmerMagnetodynamic2D" - )) - self.assertTrue(is_of_type( - ObjectsFem.makeEquationMagnetodynamic(doc, solverelmer), - "Fem::EquationElmerMagnetodynamic" - )) - fcc_print("doc objects count: {}, method: {}".format( - len(doc.Objects), - sys._getframe().f_code.co_name) + self.assertTrue(is_of_type(ObjectsFem.makeAnalysis(doc), "Fem::FemAnalysis")) + self.assertTrue( + is_of_type( + ObjectsFem.makeConstantVacuumPermittivity(doc), "Fem::ConstantVacuumPermittivity" + ) + ) + self.assertTrue(is_of_type(ObjectsFem.makeConstraintBearing(doc), "Fem::ConstraintBearing")) + self.assertTrue( + is_of_type( + ObjectsFem.makeConstraintBodyHeatSource(doc), "Fem::ConstraintBodyHeatSource" + ) + ) + self.assertTrue(is_of_type(ObjectsFem.makeConstraintContact(doc), "Fem::ConstraintContact")) + self.assertTrue( + is_of_type( + ObjectsFem.makeConstraintCurrentDensity(doc), "Fem::ConstraintCurrentDensity" + ) + ) + self.assertTrue( + is_of_type(ObjectsFem.makeConstraintDisplacement(doc), "Fem::ConstraintDisplacement") + ) + self.assertTrue( + is_of_type( + ObjectsFem.makeConstraintElectrostaticPotential(doc), + "Fem::ConstraintElectrostaticPotential", + ) + ) + self.assertTrue(is_of_type(ObjectsFem.makeConstraintFixed(doc), "Fem::ConstraintFixed")) + self.assertTrue( + is_of_type(ObjectsFem.makeConstraintRigidBody(doc), "Fem::ConstraintRigidBody") + ) + self.assertTrue( + is_of_type(ObjectsFem.makeConstraintFlowVelocity(doc), "Fem::ConstraintFlowVelocity") + ) + self.assertTrue( + is_of_type(ObjectsFem.makeConstraintFluidBoundary(doc), "Fem::ConstraintFluidBoundary") + ) + self.assertTrue( + is_of_type(ObjectsFem.makeConstraintMagnetization(doc), "Fem::ConstraintMagnetization") + ) + self.assertTrue(is_of_type(ObjectsFem.makeConstraintSpring(doc), "Fem::ConstraintSpring")) + self.assertTrue(is_of_type(ObjectsFem.makeConstraintForce(doc), "Fem::ConstraintForce")) + self.assertTrue(is_of_type(ObjectsFem.makeConstraintGear(doc), "Fem::ConstraintGear")) + self.assertTrue( + is_of_type(ObjectsFem.makeConstraintHeatflux(doc), "Fem::ConstraintHeatflux") + ) + self.assertTrue( + is_of_type( + ObjectsFem.makeConstraintInitialFlowVelocity(doc), + "Fem::ConstraintInitialFlowVelocity", + ) + ) + self.assertTrue( + is_of_type( + ObjectsFem.makeConstraintInitialPressure(doc), "Fem::ConstraintInitialPressure" + ) + ) + self.assertTrue( + is_of_type( + ObjectsFem.makeConstraintInitialTemperature(doc), + "Fem::ConstraintInitialTemperature", + ) + ) + self.assertTrue( + is_of_type(ObjectsFem.makeConstraintPlaneRotation(doc), "Fem::ConstraintPlaneRotation") + ) + self.assertTrue( + is_of_type(ObjectsFem.makeConstraintPressure(doc), "Fem::ConstraintPressure") + ) + self.assertTrue(is_of_type(ObjectsFem.makeConstraintPulley(doc), "Fem::ConstraintPulley")) + self.assertTrue( + is_of_type(ObjectsFem.makeConstraintSectionPrint(doc), "Fem::ConstraintSectionPrint") + ) + self.assertTrue( + is_of_type(ObjectsFem.makeConstraintSelfWeight(doc), "Fem::ConstraintSelfWeight") + ) + self.assertTrue(is_of_type(ObjectsFem.makeConstraintCentrif(doc), "Fem::ConstraintCentrif")) + self.assertTrue( + is_of_type(ObjectsFem.makeConstraintTemperature(doc), "Fem::ConstraintTemperature") + ) + self.assertTrue(is_of_type(ObjectsFem.makeConstraintTie(doc), "Fem::ConstraintTie")) + self.assertTrue( + is_of_type(ObjectsFem.makeConstraintTransform(doc), "Fem::ConstraintTransform") + ) + self.assertTrue(is_of_type(ObjectsFem.makeElementFluid1D(doc), "Fem::ElementFluid1D")) + self.assertTrue(is_of_type(ObjectsFem.makeElementGeometry1D(doc), "Fem::ElementGeometry1D")) + self.assertTrue(is_of_type(ObjectsFem.makeElementGeometry2D(doc), "Fem::ElementGeometry2D")) + self.assertTrue(is_of_type(ObjectsFem.makeElementRotation1D(doc), "Fem::ElementRotation1D")) + materialsolid = ObjectsFem.makeMaterialSolid(doc) + self.assertTrue(is_of_type(ObjectsFem.makeMaterialFluid(doc), "Fem::MaterialCommon")) + self.assertTrue(is_of_type(materialsolid, "Fem::MaterialCommon")) + self.assertTrue( + is_of_type( + ObjectsFem.makeMaterialMechanicalNonlinear(doc, materialsolid), + "Fem::MaterialMechanicalNonlinear", + ) + ) + self.assertTrue( + is_of_type(ObjectsFem.makeMaterialReinforced(doc), "Fem::MaterialReinforced") + ) + mesh = ObjectsFem.makeMeshGmsh(doc) + self.assertTrue(is_of_type(mesh, "Fem::FemMeshGmsh")) + self.assertTrue( + is_of_type(ObjectsFem.makeMeshBoundaryLayer(doc, mesh), "Fem::MeshBoundaryLayer") + ) + self.assertTrue(is_of_type(ObjectsFem.makeMeshGroup(doc, mesh), "Fem::MeshGroup")) + self.assertTrue(is_of_type(ObjectsFem.makeMeshRegion(doc, mesh), "Fem::MeshRegion")) + self.assertTrue(is_of_type(ObjectsFem.makeMeshNetgen(doc), "Fem::FemMeshShapeNetgenObject")) + self.assertTrue(is_of_type(ObjectsFem.makeMeshResult(doc), "Fem::MeshResult")) + self.assertTrue(is_of_type(ObjectsFem.makeResultMechanical(doc), "Fem::ResultMechanical")) + solverelmer = ObjectsFem.makeSolverElmer(doc) + self.assertTrue( + is_of_type(ObjectsFem.makeSolverCalculiXCcxTools(doc), "Fem::SolverCcxTools") + ) + self.assertTrue(is_of_type(ObjectsFem.makeSolverCalculix(doc), "Fem::SolverCalculix")) + self.assertTrue(is_of_type(solverelmer, "Fem::SolverElmer")) + self.assertTrue(is_of_type(ObjectsFem.makeSolverMystran(doc), "Fem::SolverMystran")) + self.assertTrue(is_of_type(ObjectsFem.makeSolverZ88(doc), "Fem::SolverZ88")) + self.assertTrue( + is_of_type( + ObjectsFem.makeEquationDeformation(doc, solverelmer), + "Fem::EquationElmerDeformation", + ) + ) + self.assertTrue( + is_of_type( + ObjectsFem.makeEquationElasticity(doc, solverelmer), "Fem::EquationElmerElasticity" + ) + ) + self.assertTrue( + is_of_type( + ObjectsFem.makeEquationElectricforce(doc, solverelmer), + "Fem::EquationElmerElectricforce", + ) + ) + self.assertTrue( + is_of_type( + ObjectsFem.makeEquationElectrostatic(doc, solverelmer), + "Fem::EquationElmerElectrostatic", + ) + ) + self.assertTrue( + is_of_type(ObjectsFem.makeEquationFlow(doc, solverelmer), "Fem::EquationElmerFlow") + ) + self.assertTrue( + is_of_type(ObjectsFem.makeEquationFlux(doc, solverelmer), "Fem::EquationElmerFlux") + ) + self.assertTrue( + is_of_type(ObjectsFem.makeEquationHeat(doc, solverelmer), "Fem::EquationElmerHeat") + ) + self.assertTrue( + is_of_type( + ObjectsFem.makeEquationMagnetodynamic2D(doc, solverelmer), + "Fem::EquationElmerMagnetodynamic2D", + ) + ) + self.assertTrue( + is_of_type( + ObjectsFem.makeEquationMagnetodynamic(doc, solverelmer), + "Fem::EquationElmerMagnetodynamic", + ) + ) + + fcc_print( + "doc objects count: {}, method: {}".format( + len(doc.Objects), sys._getframe().f_code.co_name + ) ) # TODO: vtk post objs, thus 5 obj less than test_femobjects_make self.assertEqual(len(doc.Objects), testtools.get_defmake_count(False)) # ******************************************************************************************** - def test_femobjects_derivedfromfem( - self - ): + def test_femobjects_derivedfromfem(self): # try to add all possible True types from inheritance chain see # https://forum.freecad.org/viewtopic.php?f=10&t=32625 doc = self.document @@ -657,1210 +483,560 @@ class TestObjectType(unittest.TestCase): # FemAnalysis analysis = ObjectsFem.makeAnalysis(doc) - self.assertTrue(is_derived_from( - analysis, - "App::DocumentObject" - )) - self.assertTrue(is_derived_from( - analysis, - "Fem::FemAnalysis" - )) + self.assertTrue(is_derived_from(analysis, "App::DocumentObject")) + self.assertTrue(is_derived_from(analysis, "Fem::FemAnalysis")) # ConstantVacuumPermittivity constant_vacuumpermittivity = ObjectsFem.makeConstantVacuumPermittivity(doc) - self.assertTrue(is_derived_from( - constant_vacuumpermittivity, - "App::DocumentObject" - )) - self.assertTrue(is_derived_from( - constant_vacuumpermittivity, - "Fem::ConstraintPython" - )) - self.assertTrue(is_derived_from( - constant_vacuumpermittivity, - "Fem::ConstantVacuumPermittivity" - )) + self.assertTrue(is_derived_from(constant_vacuumpermittivity, "App::DocumentObject")) + self.assertTrue(is_derived_from(constant_vacuumpermittivity, "Fem::ConstraintPython")) + self.assertTrue( + is_derived_from(constant_vacuumpermittivity, "Fem::ConstantVacuumPermittivity") + ) # ConstraintBearing constraint_bearing = ObjectsFem.makeConstraintBearing(doc) - self.assertTrue(is_derived_from( - constraint_bearing, - "App::DocumentObject" - )) - self.assertTrue(is_derived_from( - constraint_bearing, - "Fem::Constraint" - )) - self.assertTrue(is_derived_from( - constraint_bearing, - "Fem::ConstraintBearing" - )) + self.assertTrue(is_derived_from(constraint_bearing, "App::DocumentObject")) + self.assertTrue(is_derived_from(constraint_bearing, "Fem::Constraint")) + self.assertTrue(is_derived_from(constraint_bearing, "Fem::ConstraintBearing")) # ConstraintBodyHeatSource constraint_body_heat_source = ObjectsFem.makeConstraintBodyHeatSource(doc) - self.assertTrue(is_derived_from( - constraint_body_heat_source, - "App::DocumentObject" - )) - self.assertTrue(is_derived_from( - constraint_body_heat_source, - "Fem::ConstraintPython" - )) - self.assertTrue(is_derived_from( - constraint_body_heat_source, - "Fem::ConstraintBodyHeatSource" - )) + self.assertTrue(is_derived_from(constraint_body_heat_source, "App::DocumentObject")) + self.assertTrue(is_derived_from(constraint_body_heat_source, "Fem::ConstraintPython")) + self.assertTrue( + is_derived_from(constraint_body_heat_source, "Fem::ConstraintBodyHeatSource") + ) # ConstraintContact constraint_contact = ObjectsFem.makeConstraintContact(doc) - self.assertTrue(is_derived_from( - constraint_contact, - "App::DocumentObject" - )) - self.assertTrue(is_derived_from( - constraint_contact, - "Fem::Constraint" - )) - self.assertTrue(is_derived_from( - constraint_contact, - "Fem::ConstraintContact" - )) + self.assertTrue(is_derived_from(constraint_contact, "App::DocumentObject")) + self.assertTrue(is_derived_from(constraint_contact, "Fem::Constraint")) + self.assertTrue(is_derived_from(constraint_contact, "Fem::ConstraintContact")) # ConstraintCurrentDensity constraint_currentdensity = ObjectsFem.makeConstraintCurrentDensity(doc) - self.assertTrue(is_derived_from( - constraint_currentdensity, - "App::DocumentObject" - )) - self.assertTrue(is_derived_from( - constraint_currentdensity, - "Fem::ConstraintPython" - )) - self.assertTrue(is_derived_from( - constraint_currentdensity, - "Fem::ConstraintCurrentDensity" - )) + self.assertTrue(is_derived_from(constraint_currentdensity, "App::DocumentObject")) + self.assertTrue(is_derived_from(constraint_currentdensity, "Fem::ConstraintPython")) + self.assertTrue(is_derived_from(constraint_currentdensity, "Fem::ConstraintCurrentDensity")) # ConstraintDisplacement constraint_displacement = ObjectsFem.makeConstraintDisplacement(doc) - self.assertTrue(is_derived_from( - constraint_displacement, - "App::DocumentObject" - )) - self.assertTrue(is_derived_from( - constraint_displacement, - "Fem::Constraint" - )) - self.assertTrue(is_derived_from( - constraint_displacement, - "Fem::ConstraintDisplacement" - )) + self.assertTrue(is_derived_from(constraint_displacement, "App::DocumentObject")) + self.assertTrue(is_derived_from(constraint_displacement, "Fem::Constraint")) + self.assertTrue(is_derived_from(constraint_displacement, "Fem::ConstraintDisplacement")) # ConstraintElectrostaticPotential constraint_electorstatic_potential = ObjectsFem.makeConstraintElectrostaticPotential(doc) - self.assertTrue(is_derived_from( - constraint_electorstatic_potential, - "App::DocumentObject" - )) - self.assertTrue(is_derived_from( - constraint_electorstatic_potential, - "Fem::ConstraintPython" - )) - self.assertTrue(is_derived_from( - constraint_electorstatic_potential, - "Fem::ConstraintElectrostaticPotential" - )) + self.assertTrue(is_derived_from(constraint_electorstatic_potential, "App::DocumentObject")) + self.assertTrue( + is_derived_from(constraint_electorstatic_potential, "Fem::ConstraintPython") + ) + self.assertTrue( + is_derived_from( + constraint_electorstatic_potential, "Fem::ConstraintElectrostaticPotential" + ) + ) # ConstraintFixed constraint_fixed = ObjectsFem.makeConstraintFixed(doc) - self.assertTrue(is_derived_from( - constraint_fixed, - "App::DocumentObject" - )) - self.assertTrue(is_derived_from( - constraint_fixed, - "Fem::Constraint" - )) - self.assertTrue(is_derived_from( - constraint_fixed, - "Fem::ConstraintFixed" - )) + self.assertTrue(is_derived_from(constraint_fixed, "App::DocumentObject")) + self.assertTrue(is_derived_from(constraint_fixed, "Fem::Constraint")) + self.assertTrue(is_derived_from(constraint_fixed, "Fem::ConstraintFixed")) # ConstraintRigidBody constraint_rigidbody = ObjectsFem.makeConstraintRigidBody(doc) - self.assertTrue(is_derived_from( - constraint_rigidbody, - "App::DocumentObject" - )) - self.assertTrue(is_derived_from( - constraint_rigidbody, - "Fem::Constraint" - )) - self.assertTrue(is_derived_from( - constraint_rigidbody, - "Fem::ConstraintRigidBody" - )) + self.assertTrue(is_derived_from(constraint_rigidbody, "App::DocumentObject")) + self.assertTrue(is_derived_from(constraint_rigidbody, "Fem::Constraint")) + self.assertTrue(is_derived_from(constraint_rigidbody, "Fem::ConstraintRigidBody")) # ConstraintFlowVelocity constraint_flow_velocity = ObjectsFem.makeConstraintFlowVelocity(doc) - self.assertTrue(is_derived_from( - constraint_flow_velocity, - "App::DocumentObject" - )) - self.assertTrue(is_derived_from( - constraint_flow_velocity, - "Fem::ConstraintPython" - )) - self.assertTrue(is_derived_from( - constraint_flow_velocity, - "Fem::ConstraintFlowVelocity" - )) + self.assertTrue(is_derived_from(constraint_flow_velocity, "App::DocumentObject")) + self.assertTrue(is_derived_from(constraint_flow_velocity, "Fem::ConstraintPython")) + self.assertTrue(is_derived_from(constraint_flow_velocity, "Fem::ConstraintFlowVelocity")) # ConstraintFluidBoundary constraint_fluid_boundary = ObjectsFem.makeConstraintFluidBoundary(doc) - self.assertTrue(is_derived_from( - constraint_fluid_boundary, - "App::DocumentObject" - )) - self.assertTrue(is_derived_from( - constraint_fluid_boundary, - "Fem::Constraint" - )) - self.assertTrue(is_derived_from( - constraint_fluid_boundary, - "Fem::ConstraintFluidBoundary" - )) + self.assertTrue(is_derived_from(constraint_fluid_boundary, "App::DocumentObject")) + self.assertTrue(is_derived_from(constraint_fluid_boundary, "Fem::Constraint")) + self.assertTrue(is_derived_from(constraint_fluid_boundary, "Fem::ConstraintFluidBoundary")) # ConstraintMagnetization constraint_magnetization = ObjectsFem.makeConstraintMagnetization(doc) - self.assertTrue(is_derived_from( - constraint_magnetization, - "App::DocumentObject" - )) - self.assertTrue(is_derived_from( - constraint_magnetization, - "Fem::ConstraintPython" - )) - self.assertTrue(is_derived_from( - constraint_magnetization, - "Fem::ConstraintMagnetization" - )) + self.assertTrue(is_derived_from(constraint_magnetization, "App::DocumentObject")) + self.assertTrue(is_derived_from(constraint_magnetization, "Fem::ConstraintPython")) + self.assertTrue(is_derived_from(constraint_magnetization, "Fem::ConstraintMagnetization")) # ConstraintSpring constraint_spring = ObjectsFem.makeConstraintSpring(doc) - self.assertTrue(is_derived_from( - constraint_spring, - "App::DocumentObject" - )) - self.assertTrue(is_derived_from( - constraint_spring, - "Fem::Constraint" - )) - self.assertTrue(is_derived_from( - constraint_spring, - "Fem::ConstraintSpring" - )) + self.assertTrue(is_derived_from(constraint_spring, "App::DocumentObject")) + self.assertTrue(is_derived_from(constraint_spring, "Fem::Constraint")) + self.assertTrue(is_derived_from(constraint_spring, "Fem::ConstraintSpring")) # ConstraintForce constraint_force = ObjectsFem.makeConstraintForce(doc) - self.assertTrue(is_derived_from( - constraint_force, - "App::DocumentObject" - )) - self.assertTrue(is_derived_from( - constraint_force, - "Fem::Constraint" - )) - self.assertTrue(is_derived_from( - constraint_force, - "Fem::ConstraintForce" - )) + self.assertTrue(is_derived_from(constraint_force, "App::DocumentObject")) + self.assertTrue(is_derived_from(constraint_force, "Fem::Constraint")) + self.assertTrue(is_derived_from(constraint_force, "Fem::ConstraintForce")) # ConstraintGear constraint_gear = ObjectsFem.makeConstraintGear(doc) - self.assertTrue(is_derived_from( - constraint_gear, - "App::DocumentObject" - )) - self.assertTrue(is_derived_from( - constraint_gear, - "Fem::Constraint" - )) - self.assertTrue(is_derived_from( - constraint_gear, - "Fem::ConstraintGear" - )) + self.assertTrue(is_derived_from(constraint_gear, "App::DocumentObject")) + self.assertTrue(is_derived_from(constraint_gear, "Fem::Constraint")) + self.assertTrue(is_derived_from(constraint_gear, "Fem::ConstraintGear")) # ConstraintHeatflux constraint_heat_flux = ObjectsFem.makeConstraintHeatflux(doc) - self.assertTrue(is_derived_from( - constraint_heat_flux, - "App::DocumentObject" - )) - self.assertTrue(is_derived_from( - constraint_heat_flux, - "Fem::Constraint" - )) - self.assertTrue(is_derived_from( - constraint_heat_flux, - "Fem::ConstraintHeatflux" - )) + self.assertTrue(is_derived_from(constraint_heat_flux, "App::DocumentObject")) + self.assertTrue(is_derived_from(constraint_heat_flux, "Fem::Constraint")) + self.assertTrue(is_derived_from(constraint_heat_flux, "Fem::ConstraintHeatflux")) # ConstraintInitialFlowVelocity constraint_initial_flow_velocity = ObjectsFem.makeConstraintInitialFlowVelocity(doc) - self.assertTrue(is_derived_from( - constraint_initial_flow_velocity, - "App::DocumentObject" - )) - self.assertTrue(is_derived_from( - constraint_initial_flow_velocity, - "Fem::ConstraintPython" - )) - self.assertTrue(is_derived_from( - constraint_initial_flow_velocity, - "Fem::ConstraintInitialFlowVelocity" - )) + self.assertTrue(is_derived_from(constraint_initial_flow_velocity, "App::DocumentObject")) + self.assertTrue(is_derived_from(constraint_initial_flow_velocity, "Fem::ConstraintPython")) + self.assertTrue( + is_derived_from(constraint_initial_flow_velocity, "Fem::ConstraintInitialFlowVelocity") + ) # ConstraintInitialPressure constraint_initial_pressure = ObjectsFem.makeConstraintInitialPressure(doc) - self.assertTrue(is_derived_from( - constraint_initial_pressure, - "App::DocumentObject" - )) - self.assertTrue(is_derived_from( - constraint_initial_pressure, - "Fem::ConstraintPython" - )) - self.assertTrue(is_derived_from( - constraint_initial_pressure, - "Fem::ConstraintInitialPressure" - )) + self.assertTrue(is_derived_from(constraint_initial_pressure, "App::DocumentObject")) + self.assertTrue(is_derived_from(constraint_initial_pressure, "Fem::ConstraintPython")) + self.assertTrue( + is_derived_from(constraint_initial_pressure, "Fem::ConstraintInitialPressure") + ) # ConstraintInitialTemperature constraint_initial_temperature = ObjectsFem.makeConstraintInitialTemperature(doc) - self.assertTrue(is_derived_from( - constraint_initial_temperature, - "App::DocumentObject" - )) - self.assertTrue(is_derived_from( - constraint_initial_temperature, - "Fem::Constraint" - )) - self.assertTrue(is_derived_from( - constraint_initial_temperature, - "Fem::ConstraintInitialTemperature" - )) + self.assertTrue(is_derived_from(constraint_initial_temperature, "App::DocumentObject")) + self.assertTrue(is_derived_from(constraint_initial_temperature, "Fem::Constraint")) + self.assertTrue( + is_derived_from(constraint_initial_temperature, "Fem::ConstraintInitialTemperature") + ) # ConstraintPlaneRotation constraint_plane_rotation = ObjectsFem.makeConstraintPlaneRotation(doc) - self.assertTrue(is_derived_from( - constraint_plane_rotation, - "App::DocumentObject" - )) - self.assertTrue(is_derived_from( - constraint_plane_rotation, - "Fem::Constraint" - )) - self.assertTrue(is_derived_from( - constraint_plane_rotation, - "Fem::ConstraintPlaneRotation" - )) + self.assertTrue(is_derived_from(constraint_plane_rotation, "App::DocumentObject")) + self.assertTrue(is_derived_from(constraint_plane_rotation, "Fem::Constraint")) + self.assertTrue(is_derived_from(constraint_plane_rotation, "Fem::ConstraintPlaneRotation")) # ConstraintPressure constraint_pressure = ObjectsFem.makeConstraintPressure(doc) - self.assertTrue(is_derived_from( - constraint_pressure, - "App::DocumentObject" - )) - self.assertTrue(is_derived_from( - constraint_pressure, - "Fem::Constraint" - )) - self.assertTrue(is_derived_from( - constraint_pressure, - "Fem::ConstraintPressure" - )) + self.assertTrue(is_derived_from(constraint_pressure, "App::DocumentObject")) + self.assertTrue(is_derived_from(constraint_pressure, "Fem::Constraint")) + self.assertTrue(is_derived_from(constraint_pressure, "Fem::ConstraintPressure")) # ConstraintPulley constraint_pulley = ObjectsFem.makeConstraintPulley(doc) - self.assertTrue(is_derived_from( - constraint_pulley, - "App::DocumentObject" - )) - self.assertTrue(is_derived_from( - constraint_pulley, - "Fem::Constraint" - )) - self.assertTrue(is_derived_from( - constraint_pulley, - "Fem::ConstraintPulley" - )) + self.assertTrue(is_derived_from(constraint_pulley, "App::DocumentObject")) + self.assertTrue(is_derived_from(constraint_pulley, "Fem::Constraint")) + self.assertTrue(is_derived_from(constraint_pulley, "Fem::ConstraintPulley")) # ConstraintSectionPrint constraint_self_weight = ObjectsFem.makeConstraintSectionPrint(doc) - self.assertTrue(is_derived_from( - constraint_self_weight, - "App::DocumentObject" - )) - self.assertTrue(is_derived_from( - constraint_self_weight, - "Fem::ConstraintPython" - )) - self.assertTrue(is_derived_from( - constraint_self_weight, - "Fem::ConstraintSectionPrint" - )) + self.assertTrue(is_derived_from(constraint_self_weight, "App::DocumentObject")) + self.assertTrue(is_derived_from(constraint_self_weight, "Fem::ConstraintPython")) + self.assertTrue(is_derived_from(constraint_self_weight, "Fem::ConstraintSectionPrint")) # ConstraintSelfWeight constraint_self_weight = ObjectsFem.makeConstraintSelfWeight(doc) - self.assertTrue(is_derived_from( - constraint_self_weight, - "App::DocumentObject" - )) - self.assertTrue(is_derived_from( - constraint_self_weight, - "Fem::ConstraintPython" - )) - self.assertTrue(is_derived_from( - constraint_self_weight, - "Fem::ConstraintSelfWeight" - )) + self.assertTrue(is_derived_from(constraint_self_weight, "App::DocumentObject")) + self.assertTrue(is_derived_from(constraint_self_weight, "Fem::ConstraintPython")) + self.assertTrue(is_derived_from(constraint_self_weight, "Fem::ConstraintSelfWeight")) # ConstraintCentrif constraint_centrif = ObjectsFem.makeConstraintCentrif(doc) - self.assertTrue(is_derived_from( - constraint_centrif, - "App::DocumentObject" - )) - self.assertTrue(is_derived_from( - constraint_centrif, - "Fem::ConstraintPython" - )) - self.assertTrue(is_derived_from( - constraint_centrif, - "Fem::ConstraintCentrif" - )) + self.assertTrue(is_derived_from(constraint_centrif, "App::DocumentObject")) + self.assertTrue(is_derived_from(constraint_centrif, "Fem::ConstraintPython")) + self.assertTrue(is_derived_from(constraint_centrif, "Fem::ConstraintCentrif")) # ConstraintTemperature constraint_temperature = ObjectsFem.makeConstraintTemperature(doc) - self.assertTrue(is_derived_from( - constraint_temperature, - "App::DocumentObject" - )) - self.assertTrue(is_derived_from( - constraint_temperature, - "Fem::Constraint" - )) - self.assertTrue(is_derived_from( - constraint_temperature, - "Fem::ConstraintTemperature" - )) + self.assertTrue(is_derived_from(constraint_temperature, "App::DocumentObject")) + self.assertTrue(is_derived_from(constraint_temperature, "Fem::Constraint")) + self.assertTrue(is_derived_from(constraint_temperature, "Fem::ConstraintTemperature")) # ConstraintTie constraint_tie = ObjectsFem.makeConstraintTie(doc) - self.assertTrue(is_derived_from( - constraint_tie, - "App::DocumentObject" - )) - self.assertTrue(is_derived_from( - constraint_tie, - "Fem::Constraint" - )) - self.assertTrue(is_derived_from( - constraint_tie, - "Fem::ConstraintPython" - )) - self.assertTrue(is_derived_from( - constraint_tie, - "Fem::ConstraintTie" - )) + self.assertTrue(is_derived_from(constraint_tie, "App::DocumentObject")) + self.assertTrue(is_derived_from(constraint_tie, "Fem::Constraint")) + self.assertTrue(is_derived_from(constraint_tie, "Fem::ConstraintPython")) + self.assertTrue(is_derived_from(constraint_tie, "Fem::ConstraintTie")) # ConstraintTransform constraint_transform = ObjectsFem.makeConstraintTransform(doc) - self.assertTrue(is_derived_from( - constraint_transform, - "App::DocumentObject" - )) - self.assertTrue(is_derived_from( - constraint_transform, - "Fem::ConstraintTransform" - )) + self.assertTrue(is_derived_from(constraint_transform, "App::DocumentObject")) + self.assertTrue(is_derived_from(constraint_transform, "Fem::ConstraintTransform")) # ElementFluid1D fluid1d = ObjectsFem.makeElementFluid1D(doc) - self.assertTrue(is_derived_from( - fluid1d, - "App::DocumentObject" - )) - self.assertTrue(is_derived_from( - fluid1d, - "Fem::FeaturePython" - )) - self.assertTrue(is_derived_from( - fluid1d, - "Fem::ElementFluid1D" - )) + self.assertTrue(is_derived_from(fluid1d, "App::DocumentObject")) + self.assertTrue(is_derived_from(fluid1d, "Fem::FeaturePython")) + self.assertTrue(is_derived_from(fluid1d, "Fem::ElementFluid1D")) # ElementGeometry1D geometry1d = ObjectsFem.makeElementGeometry1D(doc) - self.assertTrue(is_derived_from( - geometry1d, - "App::DocumentObject" - )) - self.assertTrue(is_derived_from( - geometry1d, - "Fem::FeaturePython" - )) - self.assertTrue(is_derived_from( - geometry1d, - "Fem::ElementGeometry1D" - )) + self.assertTrue(is_derived_from(geometry1d, "App::DocumentObject")) + self.assertTrue(is_derived_from(geometry1d, "Fem::FeaturePython")) + self.assertTrue(is_derived_from(geometry1d, "Fem::ElementGeometry1D")) # ElementGeometry2D geometry2d = ObjectsFem.makeElementGeometry2D(doc) - self.assertTrue(is_derived_from( - geometry2d, - "App::DocumentObject" - )) - self.assertTrue(is_derived_from( - geometry2d, - "Fem::FeaturePython" - )) - self.assertTrue(is_derived_from( - geometry2d, - "Fem::ElementGeometry2D" - )) + self.assertTrue(is_derived_from(geometry2d, "App::DocumentObject")) + self.assertTrue(is_derived_from(geometry2d, "Fem::FeaturePython")) + self.assertTrue(is_derived_from(geometry2d, "Fem::ElementGeometry2D")) # ElementRotation1D rotation1d = ObjectsFem.makeElementRotation1D(doc) - self.assertTrue(is_derived_from( - rotation1d, - "App::DocumentObject" - )) - self.assertTrue(is_derived_from( - rotation1d, - "Fem::FeaturePython" - )) - self.assertTrue(is_derived_from( - rotation1d, - "Fem::ElementRotation1D" - )) + self.assertTrue(is_derived_from(rotation1d, "App::DocumentObject")) + self.assertTrue(is_derived_from(rotation1d, "Fem::FeaturePython")) + self.assertTrue(is_derived_from(rotation1d, "Fem::ElementRotation1D")) # Material Fluid material_fluid = ObjectsFem.makeMaterialFluid(doc) - self.assertTrue(is_derived_from( - material_fluid, - "App::DocumentObject" - )) - self.assertTrue(is_derived_from( - material_fluid, - "App::MaterialObjectPython" - )) - self.assertTrue(is_derived_from( - material_fluid, - "Fem::MaterialCommon" - )) + self.assertTrue(is_derived_from(material_fluid, "App::DocumentObject")) + self.assertTrue(is_derived_from(material_fluid, "App::MaterialObjectPython")) + self.assertTrue(is_derived_from(material_fluid, "Fem::MaterialCommon")) # Material Solid material_solid = ObjectsFem.makeMaterialSolid(doc) - self.assertTrue(is_derived_from( - material_solid, - "App::DocumentObject" - )) - self.assertTrue(is_derived_from( - material_solid, - "App::MaterialObjectPython" - )) - self.assertTrue(is_derived_from( - material_solid, - "Fem::MaterialCommon" - )) + self.assertTrue(is_derived_from(material_solid, "App::DocumentObject")) + self.assertTrue(is_derived_from(material_solid, "App::MaterialObjectPython")) + self.assertTrue(is_derived_from(material_solid, "Fem::MaterialCommon")) # MaterialMechanicalNonlinear material_nonlinear = ObjectsFem.makeMaterialMechanicalNonlinear(doc, material_solid) - self.assertTrue(is_derived_from( - material_nonlinear, - "App::DocumentObject" - )) - self.assertTrue(is_derived_from( - material_nonlinear, - "Fem::FeaturePython" - )) - self.assertTrue(is_derived_from( - material_nonlinear, - "Fem::MaterialMechanicalNonlinear" - )) + self.assertTrue(is_derived_from(material_nonlinear, "App::DocumentObject")) + self.assertTrue(is_derived_from(material_nonlinear, "Fem::FeaturePython")) + self.assertTrue(is_derived_from(material_nonlinear, "Fem::MaterialMechanicalNonlinear")) # MaterialReinforced material_reinforced = ObjectsFem.makeMaterialReinforced(doc) - self.assertTrue(is_derived_from( - material_reinforced, - "App::DocumentObject" - )) - self.assertTrue(is_derived_from( - material_reinforced, - "App::MaterialObjectPython" - )) - self.assertTrue(is_derived_from( - material_reinforced, - "Fem::MaterialReinforced" - )) + self.assertTrue(is_derived_from(material_reinforced, "App::DocumentObject")) + self.assertTrue(is_derived_from(material_reinforced, "App::MaterialObjectPython")) + self.assertTrue(is_derived_from(material_reinforced, "Fem::MaterialReinforced")) # FemMeshGmsh mesh_gmsh = ObjectsFem.makeMeshGmsh(doc) - self.assertTrue(is_derived_from( - mesh_gmsh, - "App::DocumentObject" - )) - self.assertTrue(is_derived_from( - mesh_gmsh, - "Fem::FemMeshObjectPython" - )) - self.assertTrue(is_derived_from( - mesh_gmsh, - "Fem::FemMeshGmsh" - )) + self.assertTrue(is_derived_from(mesh_gmsh, "App::DocumentObject")) + self.assertTrue(is_derived_from(mesh_gmsh, "Fem::FemMeshObjectPython")) + self.assertTrue(is_derived_from(mesh_gmsh, "Fem::FemMeshGmsh")) # MeshBoundaryLayer mesh_boundarylayer = ObjectsFem.makeMeshBoundaryLayer(doc, mesh_gmsh) - self.assertTrue(is_derived_from( - mesh_boundarylayer, - "App::DocumentObject" - )) - self.assertTrue(is_derived_from( - mesh_boundarylayer, - "Fem::FeaturePython" - )) - self.assertTrue(is_derived_from( - mesh_boundarylayer, - "Fem::MeshBoundaryLayer" - )) + self.assertTrue(is_derived_from(mesh_boundarylayer, "App::DocumentObject")) + self.assertTrue(is_derived_from(mesh_boundarylayer, "Fem::FeaturePython")) + self.assertTrue(is_derived_from(mesh_boundarylayer, "Fem::MeshBoundaryLayer")) # MeshGroup mesh_group = ObjectsFem.makeMeshGroup(doc, mesh_gmsh) - self.assertTrue(is_derived_from( - mesh_group, - "App::DocumentObject" - )) - self.assertTrue(is_derived_from( - mesh_group, - "Fem::FeaturePython" - )) - self.assertTrue(is_derived_from( - mesh_group, - "Fem::MeshGroup" - )) + self.assertTrue(is_derived_from(mesh_group, "App::DocumentObject")) + self.assertTrue(is_derived_from(mesh_group, "Fem::FeaturePython")) + self.assertTrue(is_derived_from(mesh_group, "Fem::MeshGroup")) # MeshRegion mesh_region = ObjectsFem.makeMeshRegion(doc, mesh_gmsh) - self.assertTrue(is_derived_from( - mesh_region, - "App::DocumentObject" - )) - self.assertTrue(is_derived_from( - mesh_region, - "Fem::FeaturePython" - )) - self.assertTrue(is_derived_from( - mesh_region, - "Fem::MeshRegion" - )) + self.assertTrue(is_derived_from(mesh_region, "App::DocumentObject")) + self.assertTrue(is_derived_from(mesh_region, "Fem::FeaturePython")) + self.assertTrue(is_derived_from(mesh_region, "Fem::MeshRegion")) # FemMeshShapeNetgenObject mesh_netgen = ObjectsFem.makeMeshNetgen(doc) - self.assertTrue(is_derived_from( - mesh_netgen, - "App::DocumentObject" - )) - self.assertTrue(is_derived_from( - mesh_netgen, - "Fem::FemMeshShapeNetgenObject" - )) + self.assertTrue(is_derived_from(mesh_netgen, "App::DocumentObject")) + self.assertTrue(is_derived_from(mesh_netgen, "Fem::FemMeshShapeNetgenObject")) # MeshResult mesh_result = ObjectsFem.makeMeshResult(doc) - self.assertTrue(is_derived_from( - mesh_result, - "App::DocumentObject" - )) - self.assertTrue(is_derived_from( - mesh_result, - "Fem::FemMeshObjectPython" - )) - self.assertTrue(is_derived_from( - mesh_result, - "Fem::MeshResult" - )) + self.assertTrue(is_derived_from(mesh_result, "App::DocumentObject")) + self.assertTrue(is_derived_from(mesh_result, "Fem::FemMeshObjectPython")) + self.assertTrue(is_derived_from(mesh_result, "Fem::MeshResult")) # ResultMechanical result_mechanical = ObjectsFem.makeResultMechanical(doc) - self.assertTrue(is_derived_from( - result_mechanical, - "App::DocumentObject" - )) - self.assertTrue(is_derived_from( - result_mechanical, - "Fem::FemResultObjectPython" - )) - self.assertTrue(is_derived_from( - result_mechanical, - "Fem::ResultMechanical" - )) + self.assertTrue(is_derived_from(result_mechanical, "App::DocumentObject")) + self.assertTrue(is_derived_from(result_mechanical, "Fem::FemResultObjectPython")) + self.assertTrue(is_derived_from(result_mechanical, "Fem::ResultMechanical")) # SolverCcxTools solver_ccxtools = ObjectsFem.makeSolverCalculiXCcxTools(doc) - self.assertTrue(is_derived_from( - solver_ccxtools, - "App::DocumentObject" - )) - self.assertTrue(is_derived_from( - solver_ccxtools, - "Fem::FemSolverObject" - )) - self.assertTrue(is_derived_from( - solver_ccxtools, - "Fem::FemSolverObjectPython" - )) - self.assertTrue(is_derived_from( - solver_ccxtools, - "Fem::SolverCcxTools" - )) + self.assertTrue(is_derived_from(solver_ccxtools, "App::DocumentObject")) + self.assertTrue(is_derived_from(solver_ccxtools, "Fem::FemSolverObject")) + self.assertTrue(is_derived_from(solver_ccxtools, "Fem::FemSolverObjectPython")) + self.assertTrue(is_derived_from(solver_ccxtools, "Fem::SolverCcxTools")) # SolverCalculix solver_calculix = ObjectsFem.makeSolverCalculix(doc) - self.assertTrue(is_derived_from( - solver_calculix, - "App::DocumentObject" - )) - self.assertTrue(is_derived_from( - solver_calculix, - "Fem::FemSolverObject" - )) - self.assertTrue(is_derived_from( - solver_calculix, - "Fem::FemSolverObjectPython" - )) - self.assertTrue(is_derived_from( - solver_calculix, - "Fem::SolverCalculix" - )) + self.assertTrue(is_derived_from(solver_calculix, "App::DocumentObject")) + self.assertTrue(is_derived_from(solver_calculix, "Fem::FemSolverObject")) + self.assertTrue(is_derived_from(solver_calculix, "Fem::FemSolverObjectPython")) + self.assertTrue(is_derived_from(solver_calculix, "Fem::SolverCalculix")) # SolverElmer solver_elmer = ObjectsFem.makeSolverElmer(doc) - self.assertTrue(is_derived_from( - solver_elmer, - "App::DocumentObject" - )) - self.assertTrue(is_derived_from( - solver_elmer, - "Fem::FemSolverObject" - )) - self.assertTrue(is_derived_from( - solver_elmer, - "Fem::FemSolverObjectPython" - )) - self.assertTrue(is_derived_from( - solver_elmer, - "Fem::SolverElmer" - )) + self.assertTrue(is_derived_from(solver_elmer, "App::DocumentObject")) + self.assertTrue(is_derived_from(solver_elmer, "Fem::FemSolverObject")) + self.assertTrue(is_derived_from(solver_elmer, "Fem::FemSolverObjectPython")) + self.assertTrue(is_derived_from(solver_elmer, "Fem::SolverElmer")) # SolverMystran solver_mystran = ObjectsFem.makeSolverMystran(doc) - self.assertTrue(is_derived_from( - solver_mystran, - "App::DocumentObject" - )) - self.assertTrue(is_derived_from( - solver_mystran, - "Fem::FemSolverObject" - )) - self.assertTrue(is_derived_from( - solver_mystran, - "Fem::FemSolverObjectPython" - )) - self.assertTrue(is_derived_from( - solver_mystran, - "Fem::SolverMystran" - )) + self.assertTrue(is_derived_from(solver_mystran, "App::DocumentObject")) + self.assertTrue(is_derived_from(solver_mystran, "Fem::FemSolverObject")) + self.assertTrue(is_derived_from(solver_mystran, "Fem::FemSolverObjectPython")) + self.assertTrue(is_derived_from(solver_mystran, "Fem::SolverMystran")) # SolverZ88 solver_z88 = ObjectsFem.makeSolverZ88(doc) - self.assertTrue(is_derived_from( - solver_z88, - "App::DocumentObject" - )) - self.assertTrue(is_derived_from( - solver_z88, - "Fem::FemSolverObject" - )) - self.assertTrue(is_derived_from( - solver_z88, - "Fem::FemSolverObjectPython" - )) - self.assertTrue(is_derived_from( - solver_z88, - "Fem::SolverZ88" - )) + self.assertTrue(is_derived_from(solver_z88, "App::DocumentObject")) + self.assertTrue(is_derived_from(solver_z88, "Fem::FemSolverObject")) + self.assertTrue(is_derived_from(solver_z88, "Fem::FemSolverObjectPython")) + self.assertTrue(is_derived_from(solver_z88, "Fem::SolverZ88")) # EquationElmerDeformation equation_deformation = ObjectsFem.makeEquationDeformation(doc, solver_elmer) - self.assertTrue(is_derived_from( - equation_deformation, - "App::DocumentObject" - )) - self.assertTrue(is_derived_from( - equation_deformation, - "App::FeaturePython" - )) - self.assertTrue(is_derived_from( - equation_deformation, - "Fem::EquationElmerDeformation" - )) + self.assertTrue(is_derived_from(equation_deformation, "App::DocumentObject")) + self.assertTrue(is_derived_from(equation_deformation, "App::FeaturePython")) + self.assertTrue(is_derived_from(equation_deformation, "Fem::EquationElmerDeformation")) # EquationElmerElasticity equation_elasticity = ObjectsFem.makeEquationElasticity(doc, solver_elmer) - self.assertTrue(is_derived_from( - equation_elasticity, - "App::DocumentObject" - )) - self.assertTrue(is_derived_from( - equation_elasticity, - "App::FeaturePython" - )) - self.assertTrue(is_derived_from( - equation_elasticity, - "Fem::EquationElmerElasticity" - )) + self.assertTrue(is_derived_from(equation_elasticity, "App::DocumentObject")) + self.assertTrue(is_derived_from(equation_elasticity, "App::FeaturePython")) + self.assertTrue(is_derived_from(equation_elasticity, "Fem::EquationElmerElasticity")) # EquationElmerElectricforce equation_elasticity = ObjectsFem.makeEquationElectricforce(doc, solver_elmer) - self.assertTrue(is_derived_from( - equation_elasticity, - "App::DocumentObject" - )) - self.assertTrue(is_derived_from( - equation_elasticity, - "App::FeaturePython" - )) - self.assertTrue(is_derived_from( - equation_elasticity, - "Fem::EquationElmerElectricforce" - )) + self.assertTrue(is_derived_from(equation_elasticity, "App::DocumentObject")) + self.assertTrue(is_derived_from(equation_elasticity, "App::FeaturePython")) + self.assertTrue(is_derived_from(equation_elasticity, "Fem::EquationElmerElectricforce")) # EquationElmerElectrostatic equation_electrostatic = ObjectsFem.makeEquationElectrostatic(doc, solver_elmer) - self.assertTrue(is_derived_from( - equation_electrostatic, - "App::DocumentObject" - )) - self.assertTrue(is_derived_from( - equation_electrostatic, - "App::FeaturePython" - )) - self.assertTrue(is_derived_from( - equation_electrostatic, - "Fem::EquationElmerElectrostatic" - )) + self.assertTrue(is_derived_from(equation_electrostatic, "App::DocumentObject")) + self.assertTrue(is_derived_from(equation_electrostatic, "App::FeaturePython")) + self.assertTrue(is_derived_from(equation_electrostatic, "Fem::EquationElmerElectrostatic")) # EquationElmerFlow equation_flow = ObjectsFem.makeEquationFlow(doc, solver_elmer) - self.assertTrue(is_derived_from( - equation_flow, - "App::DocumentObject" - )) - self.assertTrue(is_derived_from( - equation_flow, - "App::FeaturePython" - )) - self.assertTrue(is_derived_from( - equation_flow, - "Fem::EquationElmerFlow" - )) + self.assertTrue(is_derived_from(equation_flow, "App::DocumentObject")) + self.assertTrue(is_derived_from(equation_flow, "App::FeaturePython")) + self.assertTrue(is_derived_from(equation_flow, "Fem::EquationElmerFlow")) # EquationElmerFlux equation_flux = ObjectsFem.makeEquationFlux(doc, solver_elmer) - self.assertTrue(is_derived_from( - equation_flux, - "App::DocumentObject" - )) - self.assertTrue(is_derived_from( - equation_flux, - "App::FeaturePython" - )) - self.assertTrue(is_derived_from( - equation_flux, - "Fem::EquationElmerFlux" - )) + self.assertTrue(is_derived_from(equation_flux, "App::DocumentObject")) + self.assertTrue(is_derived_from(equation_flux, "App::FeaturePython")) + self.assertTrue(is_derived_from(equation_flux, "Fem::EquationElmerFlux")) # EquationElmerHeat equation_heat = ObjectsFem.makeEquationHeat(doc, solver_elmer) - self.assertTrue(is_derived_from( - equation_heat, - "App::DocumentObject" - )) - self.assertTrue(is_derived_from( - equation_heat, - "App::FeaturePython" - )) - self.assertTrue(is_derived_from( - equation_heat, - "Fem::EquationElmerHeat" - )) + self.assertTrue(is_derived_from(equation_heat, "App::DocumentObject")) + self.assertTrue(is_derived_from(equation_heat, "App::FeaturePython")) + self.assertTrue(is_derived_from(equation_heat, "Fem::EquationElmerHeat")) # EquationElmerMagnetodynamic2D equation_magnetodynamic2D = ObjectsFem.makeEquationMagnetodynamic2D(doc, solver_elmer) - self.assertTrue(is_derived_from( - equation_magnetodynamic2D, - "App::DocumentObject" - )) - self.assertTrue(is_derived_from( - equation_magnetodynamic2D, - "App::FeaturePython" - )) - self.assertTrue(is_derived_from( - equation_magnetodynamic2D, - "Fem::EquationElmerMagnetodynamic2D" - )) + self.assertTrue(is_derived_from(equation_magnetodynamic2D, "App::DocumentObject")) + self.assertTrue(is_derived_from(equation_magnetodynamic2D, "App::FeaturePython")) + self.assertTrue( + is_derived_from(equation_magnetodynamic2D, "Fem::EquationElmerMagnetodynamic2D") + ) # EquationElmerMagnetodynamic equation_magnetodynamic = ObjectsFem.makeEquationMagnetodynamic(doc, solver_elmer) - self.assertTrue(is_derived_from( - equation_magnetodynamic, - "App::DocumentObject" - )) - self.assertTrue(is_derived_from( - equation_magnetodynamic, - "App::FeaturePython" - )) - self.assertTrue(is_derived_from( - equation_magnetodynamic, - "Fem::EquationElmerMagnetodynamic" - )) + self.assertTrue(is_derived_from(equation_magnetodynamic, "App::DocumentObject")) + self.assertTrue(is_derived_from(equation_magnetodynamic, "App::FeaturePython")) + self.assertTrue( + is_derived_from(equation_magnetodynamic, "Fem::EquationElmerMagnetodynamic") + ) - fcc_print("doc objects count: {}, method: {}".format( - len(doc.Objects), - sys._getframe().f_code.co_name) + fcc_print( + "doc objects count: {}, method: {}".format( + len(doc.Objects), sys._getframe().f_code.co_name + ) ) # TODO: vtk post objs, thus 5 obj less than test_femobjects_make self.assertEqual(len(doc.Objects), testtools.get_defmake_count(False)) # TODO constraint transform is not derived from "Fem::Constraint" ?!? # ******************************************************************************************** - def test_femobjects_derivedfromstd( - self - ): + def test_femobjects_derivedfromstd(self): # only the last True type is used doc = self.document + self.assertTrue(ObjectsFem.makeAnalysis(doc).isDerivedFrom("Fem::FemAnalysis")) self.assertTrue( - ObjectsFem.makeAnalysis( - doc - ).isDerivedFrom("Fem::FemAnalysis") + ObjectsFem.makeConstantVacuumPermittivity(doc).isDerivedFrom("Fem::ConstraintPython") ) self.assertTrue( - ObjectsFem.makeConstantVacuumPermittivity( - doc - ).isDerivedFrom("Fem::ConstraintPython") + ObjectsFem.makeConstraintBearing(doc).isDerivedFrom("Fem::ConstraintBearing") ) self.assertTrue( - ObjectsFem.makeConstraintBearing( - doc - ).isDerivedFrom("Fem::ConstraintBearing") + ObjectsFem.makeConstraintBodyHeatSource(doc).isDerivedFrom("Fem::ConstraintPython") ) self.assertTrue( - ObjectsFem.makeConstraintBodyHeatSource( - doc - ).isDerivedFrom("Fem::ConstraintPython") + ObjectsFem.makeConstraintContact(doc).isDerivedFrom("Fem::ConstraintContact") ) self.assertTrue( - ObjectsFem.makeConstraintContact( - doc - ).isDerivedFrom("Fem::ConstraintContact") + ObjectsFem.makeConstraintCurrentDensity(doc).isDerivedFrom("Fem::ConstraintPython") ) self.assertTrue( - ObjectsFem.makeConstraintCurrentDensity( - doc - ).isDerivedFrom("Fem::ConstraintPython") + ObjectsFem.makeConstraintDisplacement(doc).isDerivedFrom("Fem::ConstraintDisplacement") ) self.assertTrue( - ObjectsFem.makeConstraintDisplacement( - doc - ).isDerivedFrom("Fem::ConstraintDisplacement") + ObjectsFem.makeConstraintElectrostaticPotential(doc).isDerivedFrom( + "Fem::ConstraintPython" + ) + ) + self.assertTrue(ObjectsFem.makeConstraintFixed(doc).isDerivedFrom("Fem::ConstraintFixed")) + self.assertTrue( + ObjectsFem.makeConstraintRigidBody(doc).isDerivedFrom("Fem::ConstraintRigidBody") ) self.assertTrue( - ObjectsFem.makeConstraintElectrostaticPotential( - doc - ).isDerivedFrom("Fem::ConstraintPython") + ObjectsFem.makeConstraintFlowVelocity(doc).isDerivedFrom("Fem::ConstraintPython") ) self.assertTrue( - ObjectsFem.makeConstraintFixed( - doc).isDerivedFrom("Fem::ConstraintFixed") + ObjectsFem.makeConstraintFluidBoundary(doc).isDerivedFrom( + "Fem::ConstraintFluidBoundary" + ) ) self.assertTrue( - ObjectsFem.makeConstraintRigidBody( - doc).isDerivedFrom("Fem::ConstraintRigidBody") + ObjectsFem.makeConstraintMagnetization(doc).isDerivedFrom("Fem::ConstraintPython") + ) + self.assertTrue(ObjectsFem.makeConstraintSpring(doc).isDerivedFrom("Fem::ConstraintSpring")) + self.assertTrue(ObjectsFem.makeConstraintForce(doc).isDerivedFrom("Fem::ConstraintForce")) + self.assertTrue(ObjectsFem.makeConstraintGear(doc).isDerivedFrom("Fem::ConstraintGear")) + self.assertTrue( + ObjectsFem.makeConstraintHeatflux(doc).isDerivedFrom("Fem::ConstraintHeatflux") ) self.assertTrue( - ObjectsFem.makeConstraintFlowVelocity( - doc).isDerivedFrom("Fem::ConstraintPython") + ObjectsFem.makeConstraintInitialFlowVelocity(doc).isDerivedFrom("Fem::ConstraintPython") ) self.assertTrue( - ObjectsFem.makeConstraintFluidBoundary( - doc - ).isDerivedFrom("Fem::ConstraintFluidBoundary") + ObjectsFem.makeConstraintInitialPressure(doc).isDerivedFrom("Fem::ConstraintPython") ) self.assertTrue( - ObjectsFem.makeConstraintMagnetization( - doc - ).isDerivedFrom("Fem::ConstraintPython") + ObjectsFem.makeConstraintInitialTemperature(doc).isDerivedFrom( + "Fem::ConstraintInitialTemperature" + ) ) self.assertTrue( - ObjectsFem.makeConstraintSpring( - doc - ).isDerivedFrom("Fem::ConstraintSpring") + ObjectsFem.makeConstraintPlaneRotation(doc).isDerivedFrom( + "Fem::ConstraintPlaneRotation" + ) ) self.assertTrue( - ObjectsFem.makeConstraintForce( - doc - ).isDerivedFrom("Fem::ConstraintForce") + ObjectsFem.makeConstraintPressure(doc).isDerivedFrom("Fem::ConstraintPressure") + ) + self.assertTrue(ObjectsFem.makeConstraintPulley(doc).isDerivedFrom("Fem::ConstraintPulley")) + self.assertTrue( + ObjectsFem.makeConstraintSectionPrint(doc).isDerivedFrom("Fem::ConstraintPython") ) self.assertTrue( - ObjectsFem.makeConstraintGear( - doc - ).isDerivedFrom("Fem::ConstraintGear") + ObjectsFem.makeConstraintSelfWeight(doc).isDerivedFrom("Fem::ConstraintPython") ) self.assertTrue( - ObjectsFem.makeConstraintHeatflux( - doc - ).isDerivedFrom("Fem::ConstraintHeatflux") + ObjectsFem.makeConstraintCentrif(doc).isDerivedFrom("Fem::ConstraintPython") ) self.assertTrue( - ObjectsFem.makeConstraintInitialFlowVelocity( - doc - ).isDerivedFrom("Fem::ConstraintPython") + ObjectsFem.makeConstraintTemperature(doc).isDerivedFrom("Fem::ConstraintTemperature") ) + self.assertTrue(ObjectsFem.makeConstraintTie(doc).isDerivedFrom("Fem::ConstraintPython")) self.assertTrue( - ObjectsFem.makeConstraintInitialPressure( - doc - ).isDerivedFrom("Fem::ConstraintPython") - ) - self.assertTrue( - ObjectsFem.makeConstraintInitialTemperature( - doc - ).isDerivedFrom("Fem::ConstraintInitialTemperature") - ) - self.assertTrue( - ObjectsFem.makeConstraintPlaneRotation( - doc - ).isDerivedFrom("Fem::ConstraintPlaneRotation") - ) - self.assertTrue( - ObjectsFem.makeConstraintPressure( - doc - ).isDerivedFrom("Fem::ConstraintPressure") - ) - self.assertTrue( - ObjectsFem.makeConstraintPulley( - doc - ).isDerivedFrom("Fem::ConstraintPulley") - ) - self.assertTrue( - ObjectsFem.makeConstraintSectionPrint( - doc - ).isDerivedFrom("Fem::ConstraintPython") - ) - self.assertTrue( - ObjectsFem.makeConstraintSelfWeight( - doc - ).isDerivedFrom("Fem::ConstraintPython") - ) - self.assertTrue( - ObjectsFem.makeConstraintCentrif( - doc - ).isDerivedFrom("Fem::ConstraintPython") - ) - self.assertTrue( - ObjectsFem.makeConstraintTemperature( - doc - ).isDerivedFrom("Fem::ConstraintTemperature") - ) - self.assertTrue( - ObjectsFem.makeConstraintTie( - doc - ).isDerivedFrom("Fem::ConstraintPython") - ) - self.assertTrue( - ObjectsFem.makeConstraintTransform( - doc).isDerivedFrom("Fem::ConstraintTransform") - ) - self.assertTrue( - ObjectsFem.makeElementFluid1D( - doc - ).isDerivedFrom("Fem::FeaturePython") - ) - self.assertTrue( - ObjectsFem.makeElementGeometry1D( - doc - ).isDerivedFrom("Fem::FeaturePython") - ) - self.assertTrue( - ObjectsFem.makeElementGeometry2D( - doc - ).isDerivedFrom("Fem::FeaturePython") - ) - self.assertTrue( - ObjectsFem.makeElementRotation1D( - doc - ).isDerivedFrom("Fem::FeaturePython") + ObjectsFem.makeConstraintTransform(doc).isDerivedFrom("Fem::ConstraintTransform") ) + self.assertTrue(ObjectsFem.makeElementFluid1D(doc).isDerivedFrom("Fem::FeaturePython")) + self.assertTrue(ObjectsFem.makeElementGeometry1D(doc).isDerivedFrom("Fem::FeaturePython")) + self.assertTrue(ObjectsFem.makeElementGeometry2D(doc).isDerivedFrom("Fem::FeaturePython")) + self.assertTrue(ObjectsFem.makeElementRotation1D(doc).isDerivedFrom("Fem::FeaturePython")) materialsolid = ObjectsFem.makeMaterialSolid(doc) self.assertTrue( - ObjectsFem.makeMaterialFluid( - doc - ).isDerivedFrom("App::MaterialObjectPython") + ObjectsFem.makeMaterialFluid(doc).isDerivedFrom("App::MaterialObjectPython") + ) + self.assertTrue(materialsolid.isDerivedFrom("App::MaterialObjectPython")) + self.assertTrue( + ObjectsFem.makeMaterialMechanicalNonlinear(doc, materialsolid).isDerivedFrom( + "Fem::FeaturePython" + ) ) self.assertTrue( - materialsolid.isDerivedFrom("App::MaterialObjectPython") - ) - self.assertTrue( - ObjectsFem.makeMaterialMechanicalNonlinear( - doc, - materialsolid - ).isDerivedFrom("Fem::FeaturePython") - ) - self.assertTrue( - ObjectsFem.makeMaterialReinforced( - doc - ).isDerivedFrom("App::MaterialObjectPython") + ObjectsFem.makeMaterialReinforced(doc).isDerivedFrom("App::MaterialObjectPython") ) mesh = ObjectsFem.makeMeshGmsh(doc) + self.assertTrue(mesh.isDerivedFrom("Fem::FemMeshObjectPython")) self.assertTrue( - mesh.isDerivedFrom("Fem::FemMeshObjectPython") + ObjectsFem.makeMeshBoundaryLayer(doc, mesh).isDerivedFrom("Fem::FeaturePython") ) + self.assertTrue(ObjectsFem.makeMeshGroup(doc, mesh).isDerivedFrom("Fem::FeaturePython")) + self.assertTrue(ObjectsFem.makeMeshRegion(doc, mesh).isDerivedFrom("Fem::FeaturePython")) self.assertTrue( - ObjectsFem.makeMeshBoundaryLayer( - doc, - mesh - ).isDerivedFrom("Fem::FeaturePython") + ObjectsFem.makeMeshNetgen(doc).isDerivedFrom("Fem::FemMeshShapeNetgenObject") ) + self.assertTrue(ObjectsFem.makeMeshResult(doc).isDerivedFrom("Fem::FemMeshObjectPython")) self.assertTrue( - ObjectsFem.makeMeshGroup( - doc, - mesh - ).isDerivedFrom("Fem::FeaturePython") - ) - self.assertTrue( - ObjectsFem.makeMeshRegion( - doc, - mesh - ).isDerivedFrom("Fem::FeaturePython") - ) - self.assertTrue( - ObjectsFem.makeMeshNetgen( - doc - ).isDerivedFrom("Fem::FemMeshShapeNetgenObject") - ) - self.assertTrue( - ObjectsFem.makeMeshResult( - doc - ).isDerivedFrom("Fem::FemMeshObjectPython") - ) - self.assertTrue( - ObjectsFem.makeResultMechanical( - doc - ).isDerivedFrom("Fem::FemResultObjectPython") + ObjectsFem.makeResultMechanical(doc).isDerivedFrom("Fem::FemResultObjectPython") ) solverelmer = ObjectsFem.makeSolverElmer(doc) self.assertTrue( - ObjectsFem.makeSolverCalculiXCcxTools( - doc - ).isDerivedFrom("Fem::FemSolverObjectPython") + ObjectsFem.makeSolverCalculiXCcxTools(doc).isDerivedFrom("Fem::FemSolverObjectPython") ) self.assertTrue( - ObjectsFem.makeSolverCalculix( - doc - ).isDerivedFrom("Fem::FemSolverObjectPython") + ObjectsFem.makeSolverCalculix(doc).isDerivedFrom("Fem::FemSolverObjectPython") + ) + self.assertTrue(solverelmer.isDerivedFrom("Fem::FemSolverObjectPython")) + self.assertTrue( + ObjectsFem.makeSolverMystran(doc).isDerivedFrom("Fem::FemSolverObjectPython") + ) + self.assertTrue(ObjectsFem.makeSolverZ88(doc).isDerivedFrom("Fem::FemSolverObjectPython")) + self.assertTrue( + ObjectsFem.makeEquationDeformation(doc, solverelmer).isDerivedFrom("App::FeaturePython") ) self.assertTrue( - solverelmer.isDerivedFrom("Fem::FemSolverObjectPython") + ObjectsFem.makeEquationElasticity(doc, solverelmer).isDerivedFrom("App::FeaturePython") ) self.assertTrue( - ObjectsFem.makeSolverMystran( - doc - ).isDerivedFrom("Fem::FemSolverObjectPython") + ObjectsFem.makeEquationElectricforce(doc, solverelmer).isDerivedFrom( + "App::FeaturePython" + ) ) self.assertTrue( - ObjectsFem.makeSolverZ88( - doc - ).isDerivedFrom("Fem::FemSolverObjectPython") + ObjectsFem.makeEquationElectrostatic(doc, solverelmer).isDerivedFrom( + "App::FeaturePython" + ) ) self.assertTrue( - ObjectsFem.makeEquationDeformation( - doc, - solverelmer - ).isDerivedFrom("App::FeaturePython") + ObjectsFem.makeEquationFlow(doc, solverelmer).isDerivedFrom("App::FeaturePython") ) self.assertTrue( - ObjectsFem.makeEquationElasticity( - doc, - solverelmer - ).isDerivedFrom("App::FeaturePython") + ObjectsFem.makeEquationFlux(doc, solverelmer).isDerivedFrom("App::FeaturePython") ) self.assertTrue( - ObjectsFem.makeEquationElectricforce( - doc, - solverelmer - ).isDerivedFrom("App::FeaturePython") + ObjectsFem.makeEquationHeat(doc, solverelmer).isDerivedFrom("App::FeaturePython") ) self.assertTrue( - ObjectsFem.makeEquationElectrostatic( - doc, - solverelmer - ).isDerivedFrom("App::FeaturePython") + ObjectsFem.makeEquationMagnetodynamic2D(doc, solverelmer).isDerivedFrom( + "App::FeaturePython" + ) ) self.assertTrue( - ObjectsFem.makeEquationFlow( - doc, - solverelmer - ).isDerivedFrom("App::FeaturePython") - ) - self.assertTrue( - ObjectsFem.makeEquationFlux( - doc, - solverelmer - ).isDerivedFrom("App::FeaturePython") - ) - self.assertTrue( - ObjectsFem.makeEquationHeat( - doc, - solverelmer - ).isDerivedFrom("App::FeaturePython") - ) - self.assertTrue( - ObjectsFem.makeEquationMagnetodynamic2D( - doc, - solverelmer - ).isDerivedFrom("App::FeaturePython") - ) - self.assertTrue( - ObjectsFem.makeEquationMagnetodynamic( - doc, - solverelmer - ).isDerivedFrom("App::FeaturePython") + ObjectsFem.makeEquationMagnetodynamic(doc, solverelmer).isDerivedFrom( + "App::FeaturePython" + ) ) - fcc_print("doc objects count: {}, method: {}".format( - len(doc.Objects), - sys._getframe().f_code.co_name) + fcc_print( + "doc objects count: {}, method: {}".format( + len(doc.Objects), sys._getframe().f_code.co_name + ) ) # TODO: vtk post objs, thus 5 obj less than test_femobjects_make self.assertEqual(len(doc.Objects), testtools.get_defmake_count(False)) # helper -def create_all_fem_objects_doc( - doc -): +def create_all_fem_objects_doc(doc): analysis = ObjectsFem.makeAnalysis(doc) analysis.addObject(ObjectsFem.makeConstantVacuumPermittivity(doc)) diff --git a/src/Mod/Fem/femtest/app/test_open.py b/src/Mod/Fem/femtest/app/test_open.py index 362a5b4bf5..28928b01dc 100644 --- a/src/Mod/Fem/femtest/app/test_open.py +++ b/src/Mod/Fem/femtest/app/test_open.py @@ -64,47 +64,35 @@ class TestObjectOpen(unittest.TestCase): fcc_print("import TestObjectOpen") # ******************************************************************************************** - def setUp( - self - ): + def setUp(self): # setUp is executed before every test # new document self.document = FreeCAD.newDocument(self.__class__.__name__) - self.test_file_dir = join( - testtools.get_fem_test_home_dir(), - "open" - ) + self.test_file_dir = join(testtools.get_fem_test_home_dir(), "open") # ******************************************************************************************** - def tearDown( - self - ): + def tearDown(self): # tearDown is executed after every test FreeCAD.closeDocument(self.document.Name) # ******************************************************************************************** - def test_00print( - self - ): + def test_00print(self): # since method name starts with 00 this will be run first # this test just prints a line with stars - fcc_print("\n{0}\n{1} run FEM TestObjectOpen tests {2}\n{0}".format( - 100 * "*", - 10 * "*", - 60 * "*" - )) + fcc_print( + "\n{0}\n{1} run FEM TestObjectOpen tests {2}\n{0}".format(100 * "*", 10 * "*", 60 * "*") + ) # ******************************************************************************************** - def test_femobjects_open_head( - self - ): + def test_femobjects_open_head(self): fcc_print("load master head document objects") # get a document with all FEM objects from .test_object import create_all_fem_objects_doc + self.document = create_all_fem_objects_doc(self.document) # save and load the document @@ -120,15 +108,11 @@ class TestObjectOpen(unittest.TestCase): # standard name changed from femsolver.elmer.equations.flux import Proxy - self.assertEqual( - Proxy, - self.document.Flux.Proxy.__class__ - ) + + self.assertEqual(Proxy, self.document.Flux.Proxy.__class__) # ******************************************************************************************** - def test_femobjects_open_de9b3fb438( - self - ): + def test_femobjects_open_de9b3fb438(self): # migration modules fail on s390x (big endian) and trigger OOMs, # https://bugs.debian.org/984952 and # https://bugs.launchpad.net/ubuntu/+source/freecad/+bug/1918474. @@ -150,31 +134,20 @@ class TestObjectOpen(unittest.TestCase): # standard name changed from femsolver.elmer.equations.flux import Proxy - self.assertEqual( - Proxy, - self.document.Fluxsolver.Proxy.__class__ - ) + + self.assertEqual(Proxy, self.document.Fluxsolver.Proxy.__class__) # ******************************************************************************************** - def compare_cpp_objs( - self, - doc - ): + def compare_cpp_objs(self, doc): from femtools.femutils import type_of_obj - self.assertEqual( - "Fem::FemAnalysis", - type_of_obj(doc.Analysis) - ) + self.assertEqual("Fem::FemAnalysis", type_of_obj(doc.Analysis)) # TODO other C++ objects and view provider # Is just checking the type sufficient? # If there is a type there is at least a object with correct type ;-) # ******************************************************************************************** - def compare_feature_pythons_class_app( - self, - doc - ): + def compare_feature_pythons_class_app(self, doc): import ObjectsFem from femtools.femutils import type_of_obj @@ -188,191 +161,140 @@ class TestObjectOpen(unittest.TestCase): ) """ from femobjects.constraint_bodyheatsource import ConstraintBodyHeatSource - self.assertEqual( - ConstraintBodyHeatSource, - doc.ConstraintBodyHeatSource.Proxy.__class__ - ) + + self.assertEqual(ConstraintBodyHeatSource, doc.ConstraintBodyHeatSource.Proxy.__class__) self.assertEqual( "Fem::ConstraintCurrentDensity", - type_of_obj(ObjectsFem.makeConstraintCurrentDensity(doc)) + type_of_obj(ObjectsFem.makeConstraintCurrentDensity(doc)), ) from femobjects.constraint_electrostaticpotential import ConstraintElectrostaticPotential + self.assertEqual( - ConstraintElectrostaticPotential, - doc.ConstraintElectrostaticPotential.Proxy.__class__ + ConstraintElectrostaticPotential, doc.ConstraintElectrostaticPotential.Proxy.__class__ ) from femobjects.constraint_flowvelocity import ConstraintFlowVelocity - self.assertEqual( - ConstraintFlowVelocity, - doc.ConstraintFlowVelocity.Proxy.__class__ - ) + + self.assertEqual(ConstraintFlowVelocity, doc.ConstraintFlowVelocity.Proxy.__class__) from femobjects.constraint_initialflowvelocity import ConstraintInitialFlowVelocity + self.assertEqual( - ConstraintInitialFlowVelocity, - doc.ConstraintInitialFlowVelocity.Proxy.__class__ + ConstraintInitialFlowVelocity, doc.ConstraintInitialFlowVelocity.Proxy.__class__ ) self.assertEqual( - "Fem::ConstraintMagnetization", - type_of_obj(ObjectsFem.makeConstraintMagnetization(doc)) + "Fem::ConstraintMagnetization", type_of_obj(ObjectsFem.makeConstraintMagnetization(doc)) ) from femobjects.constraint_selfweight import ConstraintSelfWeight - self.assertEqual( - ConstraintSelfWeight, - doc.ConstraintSelfWeight.Proxy.__class__ - ) + + self.assertEqual(ConstraintSelfWeight, doc.ConstraintSelfWeight.Proxy.__class__) from femobjects.constraint_tie import ConstraintTie - self.assertEqual( - ConstraintTie, - doc.ConstraintTie.Proxy.__class__ - ) + + self.assertEqual(ConstraintTie, doc.ConstraintTie.Proxy.__class__) from femobjects.element_fluid1D import ElementFluid1D - self.assertEqual( - ElementFluid1D, - doc.ElementFluid1D.Proxy.__class__ - ) + + self.assertEqual(ElementFluid1D, doc.ElementFluid1D.Proxy.__class__) from femobjects.element_geometry1D import ElementGeometry1D - self.assertEqual( - ElementGeometry1D, - doc.ElementGeometry1D.Proxy.__class__ - ) + + self.assertEqual(ElementGeometry1D, doc.ElementGeometry1D.Proxy.__class__) from femobjects.element_geometry2D import ElementGeometry2D - self.assertEqual( - ElementGeometry2D, - doc.ElementGeometry2D.Proxy.__class__ - ) + + self.assertEqual(ElementGeometry2D, doc.ElementGeometry2D.Proxy.__class__) from femobjects.element_rotation1D import ElementRotation1D - self.assertEqual( - ElementRotation1D, - doc.ElementRotation1D.Proxy.__class__ - ) + + self.assertEqual(ElementRotation1D, doc.ElementRotation1D.Proxy.__class__) from femobjects.material_common import MaterialCommon - self.assertEqual( - MaterialCommon, - doc.MaterialFluid.Proxy.__class__ - ) + + self.assertEqual(MaterialCommon, doc.MaterialFluid.Proxy.__class__) from femobjects.material_common import MaterialCommon - self.assertEqual( - MaterialCommon, - doc.MaterialSolid.Proxy.__class__ - ) + + self.assertEqual(MaterialCommon, doc.MaterialSolid.Proxy.__class__) from femobjects.material_mechanicalnonlinear import MaterialMechanicalNonlinear + self.assertEqual( - MaterialMechanicalNonlinear, - doc.MaterialMechanicalNonlinear.Proxy.__class__ + MaterialMechanicalNonlinear, doc.MaterialMechanicalNonlinear.Proxy.__class__ ) from femobjects.material_reinforced import MaterialReinforced - self.assertEqual( - MaterialReinforced, - doc.MaterialReinforced.Proxy.__class__ - ) + + self.assertEqual(MaterialReinforced, doc.MaterialReinforced.Proxy.__class__) from femobjects.mesh_gmsh import MeshGmsh - self.assertEqual( - MeshGmsh, - doc.MeshGmsh.Proxy.__class__ - ) + + self.assertEqual(MeshGmsh, doc.MeshGmsh.Proxy.__class__) from femobjects.mesh_boundarylayer import MeshBoundaryLayer - self.assertEqual( - MeshBoundaryLayer, - doc.MeshBoundaryLayer.Proxy.__class__ - ) + + self.assertEqual(MeshBoundaryLayer, doc.MeshBoundaryLayer.Proxy.__class__) from femobjects.mesh_group import MeshGroup - self.assertEqual( - MeshGroup, - doc.MeshGroup.Proxy.__class__ - ) + + self.assertEqual(MeshGroup, doc.MeshGroup.Proxy.__class__) from femobjects.mesh_region import MeshRegion - self.assertEqual( - MeshRegion, - doc.MeshRegion.Proxy.__class__ - ) + + self.assertEqual(MeshRegion, doc.MeshRegion.Proxy.__class__) from femobjects.mesh_result import MeshResult - self.assertEqual( - MeshResult, - doc.MeshResult.Proxy.__class__ - ) + + self.assertEqual(MeshResult, doc.MeshResult.Proxy.__class__) from femobjects.result_mechanical import ResultMechanical - self.assertEqual( - ResultMechanical, - doc.ResultMechanical.Proxy.__class__ - ) + + self.assertEqual(ResultMechanical, doc.ResultMechanical.Proxy.__class__) from femobjects.solver_ccxtools import SolverCcxTools - self.assertEqual( - SolverCcxTools, - doc.SolverCcxTools.Proxy.__class__ - ) + + self.assertEqual(SolverCcxTools, doc.SolverCcxTools.Proxy.__class__) from femsolver.calculix.solver import Proxy - self.assertEqual( - Proxy, - doc.SolverCalculix.Proxy.__class__ - ) + + self.assertEqual(Proxy, doc.SolverCalculix.Proxy.__class__) from femsolver.elmer.solver import Proxy - self.assertEqual( - Proxy, - doc.SolverElmer.Proxy.__class__ - ) + + self.assertEqual(Proxy, doc.SolverElmer.Proxy.__class__) from femsolver.z88.solver import Proxy - self.assertEqual( - Proxy, - doc.SolverZ88.Proxy.__class__ - ) + + self.assertEqual(Proxy, doc.SolverZ88.Proxy.__class__) from femsolver.elmer.equations.elasticity import Proxy - self.assertEqual( - Proxy, - doc.Elasticity.Proxy.__class__ - ) + + self.assertEqual(Proxy, doc.Elasticity.Proxy.__class__) from femsolver.elmer.equations.electrostatic import Proxy - self.assertEqual( - Proxy, - doc.Electrostatic.Proxy.__class__ - ) + + self.assertEqual(Proxy, doc.Electrostatic.Proxy.__class__) from femsolver.elmer.equations.flow import Proxy - self.assertEqual( - Proxy, - doc.Flow.Proxy.__class__ - ) + + self.assertEqual(Proxy, doc.Flow.Proxy.__class__) from femsolver.elmer.equations.heat import Proxy - self.assertEqual( - Proxy, - doc.Heat.Proxy.__class__ - ) + + self.assertEqual(Proxy, doc.Heat.Proxy.__class__) self.assertEqual( "Fem::EquationElmerMagnetodynamic2D", - type_of_obj(ObjectsFem.makeEquationMagnetodynamic2D(doc)) + type_of_obj(ObjectsFem.makeEquationMagnetodynamic2D(doc)), ) self.assertEqual( "Fem::EquationElmerMagnetodynamic", - type_of_obj(ObjectsFem.makeEquationMagnetodynamic(doc)) + type_of_obj(ObjectsFem.makeEquationMagnetodynamic(doc)), ) diff --git a/src/Mod/Fem/femtest/app/test_result.py b/src/Mod/Fem/femtest/app/test_result.py index 988e221155..59736b63fa 100644 --- a/src/Mod/Fem/femtest/app/test_result.py +++ b/src/Mod/Fem/femtest/app/test_result.py @@ -38,37 +38,27 @@ class TestResult(unittest.TestCase): fcc_print("import TestResult") # ******************************************************************************************** - def setUp( - self - ): + def setUp(self): # setUp is executed before every test # new document self.document = FreeCAD.newDocument(self.__class__.__name__) # ******************************************************************************************** - def tearDown( - self - ): + def tearDown(self): # tearDown is executed after every test FreeCAD.closeDocument(self.document.Name) # ******************************************************************************************** - def test_00print( - self - ): + def test_00print(self): # since method name starts with 00 this will be run first # this test just prints a line with stars - fcc_print("\n{0}\n{1} run FEM TestResult tests {2}\n{0}".format( - 100 * "*", - 10 * "*", - 64 * "*" - )) + fcc_print( + "\n{0}\n{1} run FEM TestResult tests {2}\n{0}".format(100 * "*", 10 * "*", 64 * "*") + ) # ******************************************************************************************** - def get_stress_values( - self - ): + def get_stress_values(self): # node 5 von calculix cantilver 3D example # doc = FreeCAD.open( # FreeCAD.ConfigGet("AppHomePath") + "data/examples/FemCalculixCantilever3D.FCStd" @@ -85,77 +75,63 @@ class TestResult(unittest.TestCase): # res.NodeStressYZ[4] # ) stress = ( - -4.52840E+02, # Sxx - -1.94075E+02, # Syy - -1.94075E+02, # Szz - 6.11223E+01, # Sxy - -2.60754E+01, # Sxz - 6.92759E-05 # Syz + -4.52840e02, # Sxx + -1.94075e02, # Syy + -1.94075e02, # Szz + 6.11223e01, # Sxy + -2.60754e01, # Sxz + 6.92759e-05, # Syz ) return stress # ******************************************************************************************** - def test_stress_von_mises( - self - ): + def test_stress_von_mises(self): expected_mises = 283.2082 from femresult.resulttools import calculate_von_mises as vm + mises = vm(self.get_stress_values()) # fcc_print(round(mises, 4)) self.assertEqual( round(mises, 4), expected_mises, - "Calculated von Mises stress is not the expected value." + "Calculated von Mises stress is not the expected value.", ) # ******************************************************************************************** - def test_stress_principal_std( - self - ): + def test_stress_principal_std(self): expected_principal = (-178.0076, -194.0749, -468.9075, 145.4499) from femresult.resulttools import calculate_principal_stress_std as pr + prin = pr(self.get_stress_values()) - rounded_prin = ( - round(prin[0], 4), - round(prin[1], 4), - round(prin[2], 4), - round(prin[3], 4) - ) + rounded_prin = (round(prin[0], 4), round(prin[1], 4), round(prin[2], 4), round(prin[3], 4)) # fcc_print(rounded_prin) self.assertEqual( rounded_prin, expected_principal, - "Calculated principal stresses are not the expected values." + "Calculated principal stresses are not the expected values.", ) # ******************************************************************************************** - def test_stress_principal_reinforced( - self - ): + def test_stress_principal_reinforced(self): expected_principal = (-178.0076, -194.0749, -468.9075, 145.4499) from femresult.resulttools import calculate_principal_stress_reinforced as prrc + prin = prrc(self.get_stress_values()) - rounded_prin = ( - round(prin[0], 4), - round(prin[1], 4), - round(prin[2], 4), - round(prin[3], 4)) + rounded_prin = (round(prin[0], 4), round(prin[1], 4), round(prin[2], 4), round(prin[3], 4)) # fcc_print(rounded_prin) self.assertEqual( rounded_prin, expected_principal, - "Calculated principal reinforced stresses are not the expected values." + "Calculated principal reinforced stresses are not the expected values.", ) # ******************************************************************************************** - def test_rho( - self - ): + def test_rho(self): data = ( ( # Case1: Governing Eq.14 (2.000, -2.000, 5.000, 6.000, -4.000, 2.000), - (0.02400, 0.00400, 0.01400) + (0.02400, 0.00400, 0.01400), ), ( # Case2: Governing Eq.10+ @@ -165,77 +141,67 @@ class TestResult(unittest.TestCase): ( # Case3: Governing Eq.5 (-1.000, -7.000, 10.000, 0.000, 0.000, 5.000), - (0.00000, 0.00000, 0.02714) + (0.00000, 0.00000, 0.02714), ), ( # Case4: Governing Eq.13 (3.000, 0.000, 10.000, 0.000, 5.000, 0.000), - (0.01600, 0.00000, 0.03000) + (0.01600, 0.00000, 0.03000), ), ( # Case5: Governing Eq.11- (10.000, 7.000, -3.000, 3.000, 1.000, -2.000), - (0.02533, 0.02133, 0.00000) + (0.02533, 0.02133, 0.00000), ), ( # Case6: Governing Eq.14 (4.000, -7.000, 3.000, 7.000, 0.000, -5.000), - (0.02200, 0.01000, 0.01600) + (0.02200, 0.01000, 0.01600), ), ( # Case7: Governing Eq.14 (8.000, -14.000, 6.000, 14.000, 0.000, -10.000), - (0.04400, 0.02000, 0.03200) + (0.04400, 0.02000, 0.03200), ), ( # Case8: Governing Eq.17 (1.000, 0.000, 3.000, 10.000, -8.000, 7.000), - (0.02486, 0.01750, 0.01720) + (0.02486, 0.01750, 0.01720), ), ( # Case9: Governing Eq.13 (0.000, 0.000, 0.000, 10.000, 8.000, 7.000), - (0.03600, 0.03400, 0.03000) + (0.03600, 0.03400, 0.03000), ), ( # Case10: Governing Eq.13 (15.000, 0.000, 0.000, 0.000, 0.000, 0.000), - (0.03000, 0.00000, 0.00000) + (0.03000, 0.00000, 0.00000), ), ( # Case11: Governing Eq.13 (0.000, 0.000, 0.000, 5.000, 0.000, 0.000), - (0.01000, 0.01000, 0.00000) - ) + (0.01000, 0.01000, 0.00000), + ), ) from femresult.resulttools import calculate_rho as calrho + for i, case in enumerate(data): res = calrho(case[0], 500) - rhores = ( - round(res[0], 5), - round(res[1], 5), - round(res[2], 5) - ) + rhores = (round(res[0], 5), round(res[1], 5), round(res[2], 5)) # fcc_print("Case{}: {}".format(i + 1 , rhores)) - self.assertEqual( - rhores, case[1], - "Calculated rho are not the expected Case{}." - .format(i + 1) - ) + self.assertEqual(rhores, case[1], f"Calculated rho are not the expected Case{i + 1}.") # ******************************************************************************************** - def test_disp_abs( - self - ): + def test_disp_abs(self): expected_dispabs = 87.302986 # x, y, z in node 4 of CalculiX cantilver face load - disp_xyz = [FreeCAD.Vector(8.12900E+00, 3.38889E-02, -8.69237E+01)] + disp_xyz = [FreeCAD.Vector(8.12900e00, 3.38889e-02, -8.69237e01)] from femresult.resulttools import calculate_disp_abs as dp + disp_abs = round(dp(disp_xyz)[0], 6) # fcc_print(disp_abs) self.assertEqual( - disp_abs, - expected_dispabs, - "Calculated displacement abs are not the expected values." + disp_abs, expected_dispabs, "Calculated displacement abs are not the expected values." ) diff --git a/src/Mod/Fem/femtest/app/test_solver_elmer.py b/src/Mod/Fem/femtest/app/test_solver_elmer.py index ca9d3b0853..75ef099d92 100644 --- a/src/Mod/Fem/femtest/app/test_solver_elmer.py +++ b/src/Mod/Fem/femtest/app/test_solver_elmer.py @@ -40,9 +40,7 @@ class TestSolverElmer(unittest.TestCase): fcc_print("import TestSolverElmer") # ******************************************************************************************** - def setUp( - self - ): + def setUp(self): # setUp is executed before every test # new document @@ -52,10 +50,7 @@ class TestSolverElmer(unittest.TestCase): self.pre_dir_name = "solver_elmer_" self.ending = ".sif" self.infilename = "case" - self.test_file_dir = join( - testtools.get_fem_test_home_dir(), - "elmer" - ) + self.test_file_dir = join(testtools.get_fem_test_home_dir(), "elmer") # set Units # since in Elmer writer the FreeCAD pref is used, here we need to set the FreeCAD pref # the use of FreeCAD.Units.setScheme would not take affect because the pref is not changed @@ -64,14 +59,12 @@ class TestSolverElmer(unittest.TestCase): self.saved_unit_schema = param.GetInt("UserSchema") # ******************************************************************************************** - def tearDown( - self - ): + def tearDown(self): # set back unit unit schema param = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Units") unit_schema = param.GetInt("UserSchema") if unit_schema != self.saved_unit_schema: - fcc_print("Reset unit schema back to {}".format(self.saved_unit_schema)) + fcc_print(f"Reset unit schema back to {self.saved_unit_schema}") param = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Units") param.SetInt("UserSchema", self.saved_unit_schema) @@ -80,39 +73,34 @@ class TestSolverElmer(unittest.TestCase): fcc_print("") # ******************************************************************************************** - def test_00print( - self - ): + def test_00print(self): # since method name starts with 00 this will be run first # this test just prints a line with stars - fcc_print("\n{0}\n{1} run FEM TestSolverElmer tests {2}\n{0}".format( - 100 * "*", - 10 * "*", - 55 * "*" - )) + fcc_print( + "\n{0}\n{1} run FEM TestSolverElmer tests {2}\n{0}".format( + 100 * "*", 10 * "*", 55 * "*" + ) + ) # ******************************************************************************************** - def set_unit_schema( - self, - new_unit_schema=0 - ): + def set_unit_schema(self, new_unit_schema=0): fcc_print( - "\nSaved unit schema: {}. Set unit schema to {}." - .format(self.saved_unit_schema, new_unit_schema) + "\nSaved unit schema: {}. Set unit schema to {}.".format( + self.saved_unit_schema, new_unit_schema + ) ) param = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Units") param.SetInt("UserSchema", new_unit_schema) # ******************************************************************************************** - def test_box_static_0_mm( - self - ): + def test_box_static_0_mm(self): fcc_print("") self.set_unit_schema(0) # mm/kg/s # set up the Elmer static analysis example from femexamples.boxanalysis_static import setup + setup(self.document, "elmer") # for information: @@ -131,9 +119,7 @@ class TestSolverElmer(unittest.TestCase): # write input files # fcc_print("Checking FEM input file writing for Elmer solver framework solver ...") machine_elmer = self.document.SolverElmer.Proxy.createMachine( - self.document.SolverElmer, - analysis_dir, - True + self.document.SolverElmer, analysis_dir, True ) machine_elmer.target = femsolver.run.PREPARE machine_elmer.start() @@ -144,67 +130,60 @@ class TestSolverElmer(unittest.TestCase): startinfo_totest = join(analysis_dir, "ELMERSOLVER_STARTINFO") # fcc_print("Comparing {} to {}".format(startinfo_given, startinfo_totest)) ret = testtools.compare_files(startinfo_given, startinfo_totest) - self.assertFalse(ret, "STARTINFO write file test failed.\n{}".format(ret)) + self.assertFalse(ret, f"STARTINFO write file test failed.\n{ret}") fcc_print("Test writing case file") casefile_given = join(self.test_file_dir, base_name + self.ending) casefile_totest = join(analysis_dir, self.infilename + self.ending) # fcc_print("Comparing {} to {}".format(casefile_given, casefile_totest)) ret = testtools.compare_files(casefile_given, casefile_totest) - self.assertFalse(ret, "case write file test failed.\n{}".format(ret)) + self.assertFalse(ret, f"case write file test failed.\n{ret}") fcc_print("Test writing GMSH geo file") gmshgeofile_given = join(self.test_file_dir, "group_mesh.geo") gmshgeofile_totest = join(analysis_dir, "group_mesh.geo") # fcc_print("Comparing {} to {}".format(gmshgeofile_given, gmshgeofile_totest)) ret = testtools.compare_files(gmshgeofile_given, gmshgeofile_totest) - self.assertFalse(ret, "GMSH geo write file test failed.\n{}".format(ret)) + self.assertFalse(ret, f"GMSH geo write file test failed.\n{ret}") # ******************************************************************************************** - def test_ccxcantilever_faceload_0_mm( - self - ): + def test_ccxcantilever_faceload_0_mm(self): fcc_print("") self.set_unit_schema(0) # mm/kg/s from femexamples.ccx_cantilever_faceload import setup + setup(self.document, "elmer") self.input_file_writing_test(get_namefromdef("test_")) # ******************************************************************************************** - def test_ccxcantilever_faceload_1_si( - self - ): + def test_ccxcantilever_faceload_1_si(self): fcc_print("") self.set_unit_schema(1) # SI-units m/kg/s from femexamples.ccx_cantilever_faceload import setup + setup(self.document, "elmer") self.input_file_writing_test(get_namefromdef("test_")) # ******************************************************************************************** - def test_ccxcantilever_nodeload_0_mm( - self - ): + def test_ccxcantilever_nodeload_0_mm(self): fcc_print("") self.set_unit_schema(0) # mm/kg/s from femexamples.ccx_cantilever_nodeload import setup + setup(self.document, "elmer") self.input_file_writing_test(get_namefromdef("test_")) # ******************************************************************************************** - def test_ccxcantilever_prescribeddisplacement_0_mm( - self - ): + def test_ccxcantilever_prescribeddisplacement_0_mm(self): fcc_print("") self.set_unit_schema(0) # mm/kg/s from femexamples.ccx_cantilever_prescribeddisplacement import setup + setup(self.document, "elmer") self.input_file_writing_test(get_namefromdef("test_")) # ******************************************************************************************** - def input_file_writing_test( - self, - base_name - ): + def input_file_writing_test(self, base_name): self.document.recompute() # get analysis working directory and save FreeCAD file @@ -215,29 +194,15 @@ class TestSolverElmer(unittest.TestCase): # write input file machine = self.document.SolverElmer.Proxy.createMachine( - self.document.SolverElmer, - working_dir, - True # set testmode to True + self.document.SolverElmer, working_dir, True # set testmode to True ) machine.target = femsolver.run.PREPARE machine.start() machine.join() # wait for the machine to finish # compare input file with the given one - inpfile_given = join( - self.test_file_dir, - base_name + self.ending - ) - inpfile_totest = join( - working_dir, - self.infilename + self.ending - ) + inpfile_given = join(self.test_file_dir, base_name + self.ending) + inpfile_totest = join(working_dir, self.infilename + self.ending) # fcc_print("Comparing {} to {}".format(inpfile_given, inpfile_totest)) - ret = testtools.compare_inp_files( - inpfile_given, - inpfile_totest - ) - self.assertFalse( - ret, - "Elmer write_inp_file for {0} test failed.\n{1}".format(base_name, ret) - ) + ret = testtools.compare_inp_files(inpfile_given, inpfile_totest) + self.assertFalse(ret, f"Elmer write_inp_file for {base_name} test failed.\n{ret}") diff --git a/src/Mod/Fem/femtest/app/test_solver_mystran.py b/src/Mod/Fem/femtest/app/test_solver_mystran.py index 85f500f0c0..a6e2e5448b 100644 --- a/src/Mod/Fem/femtest/app/test_solver_mystran.py +++ b/src/Mod/Fem/femtest/app/test_solver_mystran.py @@ -40,9 +40,7 @@ class TestSolverMystran(unittest.TestCase): fcc_print("import TestSolverMystran") # ******************************************************************************************** - def setUp( - self - ): + def setUp(self): # setUp is executed before every test # new document @@ -52,90 +50,74 @@ class TestSolverMystran(unittest.TestCase): self.pre_dir_name = "solver_mystran_" self.ending = ".bdf" self.infilename = "Mesh" - self.test_file_dir = join( - testtools.get_fem_test_home_dir(), - "mystran" - ) + self.test_file_dir = join(testtools.get_fem_test_home_dir(), "mystran") # ******************************************************************************************** - def tearDown( - self - ): + def tearDown(self): # tearDown is executed after every test FreeCAD.closeDocument(self.document.Name) # ******************************************************************************************** - def test_00print( - self - ): + def test_00print(self): # since method name starts with 00 this will be run first # this test just prints a line with stars - fcc_print("\n{0}\n{1} run FEM TestSolverMystran tests {2}\n{0}".format( - 100 * "*", - 10 * "*", - 55 * "*" - )) + fcc_print( + "\n{0}\n{1} run FEM TestSolverMystran tests {2}\n{0}".format( + 100 * "*", 10 * "*", 55 * "*" + ) + ) # ******************************************************************************************** - def test_ccx_cantilever_ele_quad4( - self - ): + def test_ccx_cantilever_ele_quad4(self): fcc_print("") from femexamples.ccx_cantilever_ele_quad4 import setup + setup(self.document, "mystran") self.input_file_writing_test(get_namefromdef("test_")) # ******************************************************************************************** - def test_ccx_cantilever_ele_seg2( - self - ): + def test_ccx_cantilever_ele_seg2(self): fcc_print("") from femexamples.ccx_cantilever_ele_seg2 import setup + setup(self.document, "mystran") self.input_file_writing_test(get_namefromdef("test_")) # ******************************************************************************************** - def test_ccx_cantilever_ele_tria3( - self - ): + def test_ccx_cantilever_ele_tria3(self): fcc_print("") from femexamples.ccx_cantilever_ele_tria3 import setup + setup(self.document, "mystran") self.input_file_writing_test(get_namefromdef("test_")) # ******************************************************************************************** - def test_ccx_cantilever_faceload( - self - ): + def test_ccx_cantilever_faceload(self): fcc_print("") from femexamples.ccx_cantilever_faceload import setup + setup(self.document, "mystran") self.input_file_writing_test(get_namefromdef("test_")) # ******************************************************************************************** - def test_ccx_cantilever_nodeload( - self - ): + def test_ccx_cantilever_nodeload(self): fcc_print("") from femexamples.ccx_cantilever_nodeload import setup + setup(self.document, "mystran") self.input_file_writing_test(get_namefromdef("test_")) # ******************************************************************************************** - def test_mystran_plate( - self - ): + def test_mystran_plate(self): fcc_print("") from femexamples.mystran_plate import setup + setup(self.document, "mystran") self.input_file_writing_test(get_namefromdef("test_")) # ******************************************************************************************** - def input_file_writing_test( - self, - base_name - ): + def input_file_writing_test(self, base_name): self.document.recompute() # get analysis working directory and save FreeCAD file @@ -146,29 +128,15 @@ class TestSolverMystran(unittest.TestCase): # write input file machine = self.document.SolverMystran.Proxy.createMachine( - self.document.SolverMystran, - working_dir, - True # set testmode to True + self.document.SolverMystran, working_dir, True # set testmode to True ) machine.target = femsolver.run.PREPARE machine.start() machine.join() # wait for the machine to finish # compare input file with the given one - inpfile_given = join( - self.test_file_dir, - base_name + self.ending - ) - inpfile_totest = join( - working_dir, - self.infilename + self.ending - ) + inpfile_given = join(self.test_file_dir, base_name + self.ending) + inpfile_totest = join(working_dir, self.infilename + self.ending) # fcc_print("Comparing {} to {}".format(inpfile_given, inpfile_totest)) - ret = testtools.compare_inp_files( - inpfile_given, - inpfile_totest - ) - self.assertFalse( - ret, - "Mystran write_solver_input for {0} test failed.\n{1}".format(base_name, ret) - ) + ret = testtools.compare_inp_files(inpfile_given, inpfile_totest) + self.assertFalse(ret, f"Mystran write_solver_input for {base_name} test failed.\n{ret}") diff --git a/src/Mod/Fem/femtest/app/test_solver_z88.py b/src/Mod/Fem/femtest/app/test_solver_z88.py index 54b913eea1..8087b23c53 100644 --- a/src/Mod/Fem/femtest/app/test_solver_z88.py +++ b/src/Mod/Fem/femtest/app/test_solver_z88.py @@ -43,9 +43,7 @@ class TestSolverZ88(unittest.TestCase): fcc_print("import TestSolverZ88") # ******************************************************************************************** - def setUp( - self - ): + def setUp(self): # setUp is executed before every test # new document @@ -55,84 +53,68 @@ class TestSolverZ88(unittest.TestCase): self.mesh_name = "Mesh" # ******************************************************************************************** - def tearDown( - self - ): + def tearDown(self): # tearDown is executed after every test FreeCAD.closeDocument(self.document.Name) # ******************************************************************************************** - def test_00print( - self - ): + def test_00print(self): # since method name starts with 00 this will be run first # this test just prints a line with stars - fcc_print("\n{0}\n{1} run FEM TestSolverFrameWork tests {2}\n{0}".format( - 100 * "*", - 10 * "*", - 55 * "*" - )) + fcc_print( + "\n{0}\n{1} run FEM TestSolverFrameWork tests {2}\n{0}".format( + 100 * "*", 10 * "*", 55 * "*" + ) + ) # ******************************************************************************************** - def test_ccx_cantilever_ele_hexa20( - self - ): + def test_ccx_cantilever_ele_hexa20(self): from femexamples.ccx_cantilever_ele_hexa20 import setup + setup(self.document, "z88") self.inputfile_writing_test(get_namefromdef("test_")) # ******************************************************************************************** - def test_ccx_cantilever_ele_tria6( - self - ): + def test_ccx_cantilever_ele_tria6(self): # TODO does pass on my local machine, but not on ci return from femexamples.ccx_cantilever_ele_tria6 import setup + setup(self.document, "z88") self.inputfile_writing_test(get_namefromdef("test_")) # ******************************************************************************************** - def test_ccx_cantilever_faceload( - self - ): + def test_ccx_cantilever_faceload(self): from femexamples.ccx_cantilever_faceload import setup + setup(self.document, "z88") self.inputfile_writing_test(get_namefromdef("test_")) # ******************************************************************************************** - def test_ccx_cantilever_nodeload( - self - ): + def test_ccx_cantilever_nodeload(self): from femexamples.ccx_cantilever_nodeload import setup + setup(self.document, "z88") self.inputfile_writing_test(get_namefromdef("test_")) # ******************************************************************************************** - def inputfile_writing_test( - self, - base_name - ): + def inputfile_writing_test(self, base_name): self.document.recompute() # start - fcc_print( - "\n------------- Start of FEM Z88 tests for {} -------" - .format(base_name) - ) + fcc_print(f"\n------------- Start of FEM Z88 tests for {base_name} -------") # get analysis working directory and save FreeCAD file working_dir = testtools.get_fem_test_tmp_dir("solver_z88_" + base_name) save_fc_file = join(working_dir, base_name + ".FCStd") - fcc_print("Save FreeCAD file to {} ...".format(save_fc_file)) + fcc_print(f"Save FreeCAD file to {save_fc_file} ...") self.document.saveAs(save_fc_file) # write input file machine = self.document.SolverZ88.Proxy.createMachine( - self.document.SolverZ88, - working_dir, - True # set testmode to True + self.document.SolverZ88, working_dir, True # set testmode to True ) machine.target = femsolver.run.PREPARE machine.start() @@ -144,31 +126,13 @@ class TestSolverZ88(unittest.TestCase): # fcc_print(sorted(test_files)) not_files = ["__init__.py"] test_files = [f for f in test_files if f not in not_files] - fcc_print((test_files)) + fcc_print(test_files) for test_file in test_files: - inpfile_given = join( - test_path, - test_file - ) - inpfile_totest = join( - working_dir, - test_file - ) - fcc_print( - "Comparing {} to {}" - .format(inpfile_given, inpfile_totest) - ) - ret = testtools.compare_inp_files( - inpfile_given, - inpfile_totest - ) - self.assertFalse( - ret, - "Z88 write_inp_file for {0} test failed.\n{1}".format(base_name, ret) - ) + inpfile_given = join(test_path, test_file) + inpfile_totest = join(working_dir, test_file) + fcc_print(f"Comparing {inpfile_given} to {inpfile_totest}") + ret = testtools.compare_inp_files(inpfile_given, inpfile_totest) + self.assertFalse(ret, f"Z88 write_inp_file for {base_name} test failed.\n{ret}") # end - fcc_print( - "--------------- End of FEM Z88 tests for {} ---------" - .format(base_name) - ) + fcc_print(f"--------------- End of FEM Z88 tests for {base_name} ---------") diff --git a/src/Mod/Fem/femtest/data/calculix/box_frequency.dat b/src/Mod/Fem/femtest/data/calculix/box_frequency.dat index 6c1ce9fed4..31cc5be680 100644 --- a/src/Mod/Fem/femtest/data/calculix/box_frequency.dat +++ b/src/Mod/Fem/femtest/data/calculix/box_frequency.dat @@ -1,7 +1,7 @@ E I G E N V A L U E O U T P U T - MODE NO EIGENVALUE FREQUENCY + MODE NO EIGENVALUE FREQUENCY REAL PART IMAGINARY PART (RAD/TIME) (CYCLES/TIME (RAD/TIME) diff --git a/src/Mod/Fem/femtest/data/calculix/box_frequency.frd b/src/Mod/Fem/femtest/data/calculix/box_frequency.frd index dd0bec7675..b762fecc89 100644 --- a/src/Mod/Fem/femtest/data/calculix/box_frequency.frd +++ b/src/Mod/Fem/femtest/data/calculix/box_frequency.frd @@ -1,14 +1,14 @@ 1C - 1UUSER - 1UDATE 07.february.2018 - 1UTIME 13:19:12 - 1UHOST - 1UPGM CalculiX - 1UVERSION Version 2.11 - 1UCOMPILETIME So 31. Jul 13:26:31 CEST 2016 - 1UDIR - 1UDBN - 1UMAT 1MECHANICALMATERIAL + 1UUSER + 1UDATE 07.february.2018 + 1UTIME 13:19:12 + 1UHOST + 1UPGM CalculiX + 1UVERSION Version 2.11 + 1UCOMPILETIME So 31. Jul 13:26:31 CEST 2016 + 1UDIR + 1UDBN + 1UMAT 1MECHANICALMATERIAL 2C 280 1 -1 1 0.00000E+00 0.00000E+00 0.00000E+00 -1 2 0.00000E+00 0.00000E+00 1.00000E+01 @@ -551,12 +551,12 @@ -1 129 6 0 1 -2 45 15 122 49 67 138 280 61 69 260 -3 - 1PSTEP 1 1 1 - 1PGM 1.000000E+00 - 1PGK 1.483748E-02 - 1PHID -1 - 1PSUBC 0 - 1PMODE 1 + 1PSTEP 1 1 1 + 1PGM 1.000000E+00 + 1PGK 1.483748E-02 + 1PHID -1 + 1PSUBC 0 + 1PMODE 1 100CL 101 1.93865E-02 280 2 1MODAL 1 -4 DISP 4 1 -5 D1 1 2 1 0 @@ -844,12 +844,12 @@ -1 279 1.91139E+01 3.65645E+02-3.20043E+01 -1 280 2.39365E+02 4.59527E+02-1.66365E+01 -3 - 1PSTEP 2 1 1 - 1PGM 1.000000E+00 - 1PGK 1.483748E-02 - 1PHID -1 - 1PSUBC 0 - 1PMODE 1 + 1PSTEP 2 1 1 + 1PGM 1.000000E+00 + 1PGK 1.483748E-02 + 1PHID -1 + 1PSUBC 0 + 1PMODE 1 100CL 101 1.93865E-02 280 2 1MODAL 1 -4 STRESS 6 1 -5 SXX 1 4 1 1 @@ -1139,12 +1139,12 @@ -1 279 6.24174E+02 2.07621E+02 8.82868E+02 7.06900E+02 2.04411E+02-6.63187E+02 -1 280-6.65154E+02-2.38160E+02-7.50590E+01-2.70282E+02 5.57057E+02-4.57540E+02 -3 - 1PSTEP 3 1 1 - 1PGM 1.000000E+00 - 1PGK 1.483748E-02 - 1PHID -1 - 1PSUBC 0 - 1PMODE 1 + 1PSTEP 3 1 1 + 1PGM 1.000000E+00 + 1PGK 1.483748E-02 + 1PHID -1 + 1PSUBC 0 + 1PMODE 1 100CL 101 1.93865E-02 280 2 1MODAL 1 -4 TOSTRAIN 6 1 -5 EXX 1 4 1 1 diff --git a/src/Mod/Fem/femtest/data/calculix/box_frequency.inp b/src/Mod/Fem/femtest/data/calculix/box_frequency.inp index 7c91e6f771..7a06109c18 100644 --- a/src/Mod/Fem/femtest/data/calculix/box_frequency.inp +++ b/src/Mod/Fem/femtest/data/calculix/box_frequency.inp @@ -461,7 +461,7 @@ U S, E *OUTPUT, FREQUENCY=1 *********************************************************** -*END STEP +*END STEP *********************************************************** ** CalculiX Input file diff --git a/src/Mod/Fem/femtest/data/calculix/box_static.frd b/src/Mod/Fem/femtest/data/calculix/box_static.frd index c9940bf3d5..0e31735f75 100644 --- a/src/Mod/Fem/femtest/data/calculix/box_static.frd +++ b/src/Mod/Fem/femtest/data/calculix/box_static.frd @@ -1,14 +1,14 @@ 1C - 1UUSER - 1UDATE 07.february.2018 - 1UTIME 13:19:11 - 1UHOST - 1UPGM CalculiX - 1UVERSION Version 2.11 - 1UCOMPILETIME So 31. Jul 13:26:31 CEST 2016 - 1UDIR - 1UDBN - 1UMAT 1MECHANICALMATERIAL + 1UUSER + 1UDATE 07.february.2018 + 1UTIME 13:19:11 + 1UHOST + 1UPGM CalculiX + 1UVERSION Version 2.11 + 1UCOMPILETIME So 31. Jul 13:26:31 CEST 2016 + 1UDIR + 1UDBN + 1UMAT 1MECHANICALMATERIAL 2C 280 1 -1 1 0.00000E+00 0.00000E+00 0.00000E+00 -1 2 0.00000E+00 0.00000E+00 1.00000E+01 @@ -551,7 +551,7 @@ -1 129 6 0 1 -2 45 15 122 49 67 138 280 61 69 260 -3 - 1PSTEP 1 1 1 + 1PSTEP 1 1 1 100CL 101 1.000000000 280 0 1 1 -4 DISP 4 1 -5 D1 1 2 1 0 @@ -839,7 +839,7 @@ -1 279-2.80320E-03-1.20429E-03-1.42116E-02 -1 280-5.32384E-03 1.88752E-03-6.50264E-03 -3 - 1PSTEP 2 1 1 + 1PSTEP 2 1 1 100CL 101 1.000000000 280 0 1 1 -4 STRESS 6 1 -5 SXX 1 4 1 1 @@ -1129,7 +1129,7 @@ -1 279-5.37654E+02-8.69506E+01-3.13393E+02-1.84915E+01-6.76820E+00-2.28670E+02 -1 280-1.06012E+03-1.74273E+02-2.84613E+02 3.45887E+01-4.50833E+00-3.83611E+02 -3 - 1PSTEP 3 1 1 + 1PSTEP 3 1 1 100CL 101 1.000000000 280 0 1 1 -4 TOSTRAIN 6 1 -5 EXX 1 4 1 1 diff --git a/src/Mod/Fem/femtest/data/calculix/box_static.inp b/src/Mod/Fem/femtest/data/calculix/box_static.inp index 704e6a5ab4..0f49a0dd35 100644 --- a/src/Mod/Fem/femtest/data/calculix/box_static.inp +++ b/src/Mod/Fem/femtest/data/calculix/box_static.inp @@ -589,13 +589,13 @@ RF *OUTPUT, FREQUENCY=1 *********************************************************** -*END STEP +*END STEP *********************************************************** ** CalculiX Input file ** written by --> FreeCAD 0.21.0 ** written on --> Tue Mar 28 06:53:21 2023 -** file name --> +** file name --> box_static.FCStd ** analysis name --> Analysis ** ** diff --git a/src/Mod/Fem/femtest/data/calculix/ccx_buckling_flexuralbuckling.inp b/src/Mod/Fem/femtest/data/calculix/ccx_buckling_flexuralbuckling.inp index 6c40ca8225..9a2936876c 100644 --- a/src/Mod/Fem/femtest/data/calculix/ccx_buckling_flexuralbuckling.inp +++ b/src/Mod/Fem/femtest/data/calculix/ccx_buckling_flexuralbuckling.inp @@ -808,7 +808,7 @@ RF *OUTPUT, FREQUENCY=1 *********************************************************** -*END STEP +*END STEP *********************************************************** ** CalculiX Input file diff --git a/src/Mod/Fem/femtest/data/calculix/ccx_cantilever_beam_circle.inp b/src/Mod/Fem/femtest/data/calculix/ccx_cantilever_beam_circle.inp index bf9cdbf260..02a5142b02 100644 --- a/src/Mod/Fem/femtest/data/calculix/ccx_cantilever_beam_circle.inp +++ b/src/Mod/Fem/femtest/data/calculix/ccx_cantilever_beam_circle.inp @@ -103,13 +103,13 @@ RF *OUTPUT, FREQUENCY=1 *********************************************************** -*END STEP +*END STEP *********************************************************** ** CalculiX Input file ** written by --> FreeCAD 0.21.0 ** written on --> Tue Mar 28 05:29:54 2023 -** file name --> +** file name --> ccx_cantilever_beam_circle.FCStd ** analysis name --> Analysis ** ** diff --git a/src/Mod/Fem/femtest/data/calculix/ccx_cantilever_beam_pipe.inp b/src/Mod/Fem/femtest/data/calculix/ccx_cantilever_beam_pipe.inp index c5d6c44c41..6fa9db2bab 100644 --- a/src/Mod/Fem/femtest/data/calculix/ccx_cantilever_beam_pipe.inp +++ b/src/Mod/Fem/femtest/data/calculix/ccx_cantilever_beam_pipe.inp @@ -103,13 +103,13 @@ RF *OUTPUT, FREQUENCY=1 *********************************************************** -*END STEP +*END STEP *********************************************************** ** CalculiX Input file ** written by --> FreeCAD 0.21.0 ** written on --> Tue Mar 28 03:47:22 2023 -** file name --> +** file name --> ccx_cantilever_beam_pipe.FCStd ** analysis name --> Analysis ** ** diff --git a/src/Mod/Fem/femtest/data/calculix/ccx_cantilever_beam_rect.inp b/src/Mod/Fem/femtest/data/calculix/ccx_cantilever_beam_rect.inp index c407c4c081..94e87e949b 100644 --- a/src/Mod/Fem/femtest/data/calculix/ccx_cantilever_beam_rect.inp +++ b/src/Mod/Fem/femtest/data/calculix/ccx_cantilever_beam_rect.inp @@ -103,13 +103,13 @@ RF *OUTPUT, FREQUENCY=1 *********************************************************** -*END STEP +*END STEP *********************************************************** ** CalculiX Input file ** written by --> FreeCAD 0.21.0 ** written on --> Tue Mar 28 03:48:55 2023 -** file name --> +** file name --> ccx_cantilever_beam_rect.FCStd ** analysis name --> Analysis ** ** diff --git a/src/Mod/Fem/femtest/data/calculix/ccx_cantilever_ele_hexa20.inp b/src/Mod/Fem/femtest/data/calculix/ccx_cantilever_ele_hexa20.inp index a2b9db44ba..53d63bf29b 100644 --- a/src/Mod/Fem/femtest/data/calculix/ccx_cantilever_ele_hexa20.inp +++ b/src/Mod/Fem/femtest/data/calculix/ccx_cantilever_ele_hexa20.inp @@ -269,69 +269,69 @@ ** Volume elements *Element, TYPE=C3D20, ELSET=Evolumes 1, 1, 10, 95, 19, 61, 105, 222, 192, 9, 93, 94, 20, 104, 220, 221, -193, 62, 103, 219, 190, +193, 62, 103, 219, 190 2, 10, 2, 13, 95, 105, 34, 134, 222, 11, 12, 96, 93, 106, 133, 223, -220, 103, 33, 132, 219, +220, 103, 33, 132, 219 3, 19, 95, 16, 4, 192, 222, 163, 79, 94, 97, 17, 18, 221, 224, 164, -191, 190, 219, 161, 78, +191, 190, 219, 161, 78 4, 95, 13, 3, 16, 222, 134, 64, 163, 96, 14, 15, 97, 223, 135, 162, -224, 219, 132, 63, 161, +224, 219, 132, 63, 161 5, 61, 105, 222, 192, 59, 109, 228, 196, 104, 220, 221, 193, 108, 226, 227, -197, 60, 107, 225, 194, +197, 60, 107, 225, 194 6, 105, 34, 134, 222, 109, 36, 138, 228, 106, 133, 223, 220, 110, 137, 229, -226, 107, 35, 136, 225, +226, 107, 35, 136, 225 7, 192, 222, 163, 79, 196, 228, 167, 81, 221, 224, 164, 191, 227, 230, 168, -195, 194, 225, 165, 80, +195, 194, 225, 165, 80 8, 222, 134, 64, 163, 228, 138, 66, 167, 223, 135, 162, 224, 229, 139, 166, -230, 225, 136, 65, 165, +230, 225, 136, 65, 165 9, 59, 109, 228, 196, 57, 113, 234, 200, 108, 226, 227, 197, 112, 232, 233, -201, 58, 111, 231, 198, +201, 58, 111, 231, 198 10, 109, 36, 138, 228, 113, 38, 142, 234, 110, 137, 229, 226, 114, 141, 235, -232, 111, 37, 140, 231, +232, 111, 37, 140, 231 11, 196, 228, 167, 81, 200, 234, 171, 83, 227, 230, 168, 195, 233, 236, 172, -199, 198, 231, 169, 82, +199, 198, 231, 169, 82 12, 228, 138, 66, 167, 234, 142, 68, 171, 229, 139, 166, 230, 235, 143, 170, -236, 231, 140, 67, 169, +236, 231, 140, 67, 169 13, 57, 113, 234, 200, 55, 117, 240, 204, 112, 232, 233, 201, 116, 238, 239, -205, 56, 115, 237, 202, +205, 56, 115, 237, 202 14, 113, 38, 142, 234, 117, 40, 146, 240, 114, 141, 235, 232, 118, 145, 241, -238, 115, 39, 144, 237, +238, 115, 39, 144, 237 15, 200, 234, 171, 83, 204, 240, 175, 85, 233, 236, 172, 199, 239, 242, 176, -203, 202, 237, 173, 84, +203, 202, 237, 173, 84 16, 234, 142, 68, 171, 240, 146, 70, 175, 235, 143, 170, 236, 241, 147, 174, -242, 237, 144, 69, 173, +242, 237, 144, 69, 173 17, 55, 117, 240, 204, 53, 121, 246, 208, 116, 238, 239, 205, 120, 244, 245, -209, 54, 119, 243, 206, +209, 54, 119, 243, 206 18, 117, 40, 146, 240, 121, 42, 150, 246, 118, 145, 241, 238, 122, 149, 247, -244, 119, 41, 148, 243, +244, 119, 41, 148, 243 19, 204, 240, 175, 85, 208, 246, 179, 87, 239, 242, 176, 203, 245, 248, 180, -207, 206, 243, 177, 86, +207, 206, 243, 177, 86 20, 240, 146, 70, 175, 246, 150, 72, 179, 241, 147, 174, 242, 247, 151, 178, -248, 243, 148, 71, 177, +248, 243, 148, 71, 177 21, 53, 121, 246, 208, 51, 125, 252, 212, 120, 244, 245, 209, 124, 250, 251, -213, 52, 123, 249, 210, +213, 52, 123, 249, 210 22, 121, 42, 150, 246, 125, 44, 154, 252, 122, 149, 247, 244, 126, 153, 253, -250, 123, 43, 152, 249, +250, 123, 43, 152, 249 23, 208, 246, 179, 87, 212, 252, 183, 89, 245, 248, 180, 207, 251, 254, 184, -211, 210, 249, 181, 88, +211, 210, 249, 181, 88 24, 246, 150, 72, 179, 252, 154, 74, 183, 247, 151, 178, 248, 253, 155, 182, -254, 249, 152, 73, 181, +254, 249, 152, 73, 181 25, 51, 125, 252, 212, 49, 129, 258, 216, 124, 250, 251, 213, 128, 256, 257, -217, 50, 127, 255, 214, +217, 50, 127, 255, 214 26, 125, 44, 154, 252, 129, 46, 158, 258, 126, 153, 253, 250, 130, 157, 259, -256, 127, 45, 156, 255, +256, 127, 45, 156, 255 27, 212, 252, 183, 89, 216, 258, 187, 91, 251, 254, 184, 211, 257, 260, 188, -215, 214, 255, 185, 90, +215, 214, 255, 185, 90 28, 252, 154, 74, 183, 258, 158, 76, 187, 253, 155, 182, 254, 259, 159, 186, -260, 255, 156, 75, 185, +260, 255, 156, 75, 185 29, 49, 129, 258, 216, 5, 22, 100, 31, 128, 256, 257, 217, 21, 98, 99, -32, 48, 131, 261, 218, +32, 48, 131, 261, 218 30, 129, 46, 158, 258, 22, 6, 25, 100, 130, 157, 259, 256, 23, 24, 101, -98, 131, 47, 160, 261, +98, 131, 47, 160, 261 31, 216, 258, 187, 91, 31, 100, 28, 8, 257, 260, 188, 215, 99, 102, 29, -30, 218, 261, 189, 92, +30, 218, 261, 189, 92 32, 258, 158, 76, 187, 100, 25, 7, 28, 259, 159, 186, 260, 101, 26, 27, -102, 261, 160, 77, 189, +102, 261, 160, 77, 189 ** Define element set Eall *ELSET, ELSET=Eall @@ -443,7 +443,7 @@ RF *OUTPUT, FREQUENCY=1 *********************************************************** -*END STEP +*END STEP *********************************************************** ** CalculiX Input file diff --git a/src/Mod/Fem/femtest/data/calculix/ccx_cantilever_ele_quad4.inp b/src/Mod/Fem/femtest/data/calculix/ccx_cantilever_ele_quad4.inp index 4c3825f6bf..f1d8993f94 100644 --- a/src/Mod/Fem/femtest/data/calculix/ccx_cantilever_ele_quad4.inp +++ b/src/Mod/Fem/femtest/data/calculix/ccx_cantilever_ele_quad4.inp @@ -129,7 +129,7 @@ RF *OUTPUT, FREQUENCY=1 *********************************************************** -*END STEP +*END STEP *********************************************************** ** CalculiX Input file diff --git a/src/Mod/Fem/femtest/data/calculix/ccx_cantilever_ele_quad8.inp b/src/Mod/Fem/femtest/data/calculix/ccx_cantilever_ele_quad8.inp index 47cffa58ae..ce63593e02 100644 --- a/src/Mod/Fem/femtest/data/calculix/ccx_cantilever_ele_quad8.inp +++ b/src/Mod/Fem/femtest/data/calculix/ccx_cantilever_ele_quad8.inp @@ -119,7 +119,7 @@ RF *OUTPUT, FREQUENCY=1 *********************************************************** -*END STEP +*END STEP *********************************************************** ** CalculiX Input file diff --git a/src/Mod/Fem/femtest/data/calculix/ccx_cantilever_ele_seg2.inp b/src/Mod/Fem/femtest/data/calculix/ccx_cantilever_ele_seg2.inp index 550f337d06..113b3824d9 100644 --- a/src/Mod/Fem/femtest/data/calculix/ccx_cantilever_ele_seg2.inp +++ b/src/Mod/Fem/femtest/data/calculix/ccx_cantilever_ele_seg2.inp @@ -245,7 +245,7 @@ RF *OUTPUT, FREQUENCY=1 *********************************************************** -*END STEP +*END STEP *********************************************************** ** CalculiX Input file diff --git a/src/Mod/Fem/femtest/data/calculix/ccx_cantilever_ele_seg3.inp b/src/Mod/Fem/femtest/data/calculix/ccx_cantilever_ele_seg3.inp index ec76cb158b..a40a4ab2c8 100644 --- a/src/Mod/Fem/femtest/data/calculix/ccx_cantilever_ele_seg3.inp +++ b/src/Mod/Fem/femtest/data/calculix/ccx_cantilever_ele_seg3.inp @@ -103,7 +103,7 @@ RF *OUTPUT, FREQUENCY=1 *********************************************************** -*END STEP +*END STEP *********************************************************** ** CalculiX Input file diff --git a/src/Mod/Fem/femtest/data/calculix/ccx_cantilever_ele_tria3.inp b/src/Mod/Fem/femtest/data/calculix/ccx_cantilever_ele_tria3.inp index 6f391a16ca..613b6bc88f 100644 --- a/src/Mod/Fem/femtest/data/calculix/ccx_cantilever_ele_tria3.inp +++ b/src/Mod/Fem/femtest/data/calculix/ccx_cantilever_ele_tria3.inp @@ -1610,7 +1610,7 @@ RF *OUTPUT, FREQUENCY=1 *********************************************************** -*END STEP +*END STEP *********************************************************** ** CalculiX Input file diff --git a/src/Mod/Fem/femtest/data/calculix/ccx_cantilever_ele_tria6.inp b/src/Mod/Fem/femtest/data/calculix/ccx_cantilever_ele_tria6.inp index d4703f8010..2fe7c8a64b 100644 --- a/src/Mod/Fem/femtest/data/calculix/ccx_cantilever_ele_tria6.inp +++ b/src/Mod/Fem/femtest/data/calculix/ccx_cantilever_ele_tria6.inp @@ -337,7 +337,7 @@ RF *OUTPUT, FREQUENCY=1 *********************************************************** -*END STEP +*END STEP *********************************************************** ** CalculiX Input file diff --git a/src/Mod/Fem/femtest/data/calculix/ccx_cantilever_faceload.inp b/src/Mod/Fem/femtest/data/calculix/ccx_cantilever_faceload.inp index 3527e24f68..dfc549fd86 100644 --- a/src/Mod/Fem/femtest/data/calculix/ccx_cantilever_faceload.inp +++ b/src/Mod/Fem/femtest/data/calculix/ccx_cantilever_faceload.inp @@ -409,7 +409,7 @@ RF *OUTPUT, FREQUENCY=1 *********************************************************** -*END STEP +*END STEP *********************************************************** ** CalculiX Input file diff --git a/src/Mod/Fem/femtest/data/calculix/ccx_cantilever_nodeload.inp b/src/Mod/Fem/femtest/data/calculix/ccx_cantilever_nodeload.inp index 4c49e224a0..2b3a4e8cd8 100644 --- a/src/Mod/Fem/femtest/data/calculix/ccx_cantilever_nodeload.inp +++ b/src/Mod/Fem/femtest/data/calculix/ccx_cantilever_nodeload.inp @@ -406,7 +406,7 @@ RF *OUTPUT, FREQUENCY=1 *********************************************************** -*END STEP +*END STEP *********************************************************** ** CalculiX Input file diff --git a/src/Mod/Fem/femtest/data/calculix/ccx_cantilever_prescribeddisplacement.inp b/src/Mod/Fem/femtest/data/calculix/ccx_cantilever_prescribeddisplacement.inp index 95977a060f..a3cc4a2419 100644 --- a/src/Mod/Fem/femtest/data/calculix/ccx_cantilever_prescribeddisplacement.inp +++ b/src/Mod/Fem/femtest/data/calculix/ccx_cantilever_prescribeddisplacement.inp @@ -416,7 +416,7 @@ RF *OUTPUT, FREQUENCY=1 *********************************************************** -*END STEP +*END STEP *********************************************************** ** CalculiX Input file diff --git a/src/Mod/Fem/femtest/data/calculix/constraint_centrif.inp b/src/Mod/Fem/femtest/data/calculix/constraint_centrif.inp index f14fa7f3d4..c0866c76d3 100644 --- a/src/Mod/Fem/femtest/data/calculix/constraint_centrif.inp +++ b/src/Mod/Fem/femtest/data/calculix/constraint_centrif.inp @@ -18782,7 +18782,7 @@ RF *********************************************************** -*END STEP +*END STEP *********************************************************** ** CalculiX Input file diff --git a/src/Mod/Fem/femtest/data/calculix/constraint_contact_shell_shell.inp b/src/Mod/Fem/femtest/data/calculix/constraint_contact_shell_shell.inp index b09a14c044..5c982bd498 100644 --- a/src/Mod/Fem/femtest/data/calculix/constraint_contact_shell_shell.inp +++ b/src/Mod/Fem/femtest/data/calculix/constraint_contact_shell_shell.inp @@ -38414,7 +38414,7 @@ RF *OUTPUT, FREQUENCY=1 *********************************************************** -*END STEP +*END STEP *********************************************************** ** CalculiX Input file diff --git a/src/Mod/Fem/femtest/data/calculix/constraint_contact_solid_solid.inp b/src/Mod/Fem/femtest/data/calculix/constraint_contact_solid_solid.inp index 38bd34f15e..f0af8dd359 100644 --- a/src/Mod/Fem/femtest/data/calculix/constraint_contact_solid_solid.inp +++ b/src/Mod/Fem/femtest/data/calculix/constraint_contact_solid_solid.inp @@ -5624,13 +5624,13 @@ RF *********************************************************** -*END STEP +*END STEP *********************************************************** ** CalculiX Input file ** written by --> FreeCAD 0.21.0 ** written on --> Tue Mar 28 06:51:00 2023 -** file name --> +** file name --> constraint_contact_solid_solid.FCStd ** analysis name --> Analysis ** ** diff --git a/src/Mod/Fem/femtest/data/calculix/constraint_sectionprint.inp b/src/Mod/Fem/femtest/data/calculix/constraint_sectionprint.inp index 7b334e40cb..4c195149ef 100644 --- a/src/Mod/Fem/femtest/data/calculix/constraint_sectionprint.inp +++ b/src/Mod/Fem/femtest/data/calculix/constraint_sectionprint.inp @@ -3460,13 +3460,13 @@ RF *OUTPUT, FREQUENCY=1 *********************************************************** -*END STEP +*END STEP *********************************************************** ** CalculiX Input file ** written by --> FreeCAD 0.21.0 ** written on --> Tue Mar 28 06:49:11 2023 -** file name --> +** file name --> constraint_sectionprint.FCStd ** analysis name --> Analysis ** ** diff --git a/src/Mod/Fem/femtest/data/calculix/constraint_selfweight_cantilever.inp b/src/Mod/Fem/femtest/data/calculix/constraint_selfweight_cantilever.inp index 2f3eb68abe..1b0e7f0504 100644 --- a/src/Mod/Fem/femtest/data/calculix/constraint_selfweight_cantilever.inp +++ b/src/Mod/Fem/femtest/data/calculix/constraint_selfweight_cantilever.inp @@ -2189,13 +2189,13 @@ RF *OUTPUT, FREQUENCY=1 *********************************************************** -*END STEP +*END STEP *********************************************************** ** CalculiX Input file ** written by --> FreeCAD 0.19.21963 +19 (Git) ** written on --> Tue Jul 14 12:48:52 2020 -** file name --> +** file name --> constraint_selfweight_cantilever.FCStd ** analysis name --> Analysis ** ** diff --git a/src/Mod/Fem/femtest/data/calculix/constraint_tie.inp b/src/Mod/Fem/femtest/data/calculix/constraint_tie.inp index e30e24a712..05f5828199 100644 --- a/src/Mod/Fem/femtest/data/calculix/constraint_tie.inp +++ b/src/Mod/Fem/femtest/data/calculix/constraint_tie.inp @@ -18652,13 +18652,13 @@ RF *OUTPUT, FREQUENCY=1 *********************************************************** -*END STEP +*END STEP *********************************************************** ** CalculiX Input file ** written by --> FreeCAD 0.21.0 ** written on --> Tue Mar 28 04:35:16 2023 -** file name --> +** file name --> constraint_tie.FCStd ** analysis name --> Analysis ** ** diff --git a/src/Mod/Fem/femtest/data/calculix/constraint_transform_beam_hinged.inp b/src/Mod/Fem/femtest/data/calculix/constraint_transform_beam_hinged.inp index 1725927172..94a7a2bbc9 100644 --- a/src/Mod/Fem/femtest/data/calculix/constraint_transform_beam_hinged.inp +++ b/src/Mod/Fem/femtest/data/calculix/constraint_transform_beam_hinged.inp @@ -3790,7 +3790,7 @@ RF *OUTPUT, FREQUENCY=1 *********************************************************** -*END STEP +*END STEP *********************************************************** ** CalculiX Input file diff --git a/src/Mod/Fem/femtest/data/calculix/constraint_transform_torque.inp b/src/Mod/Fem/femtest/data/calculix/constraint_transform_torque.inp index a4f0b4dc22..884fa9d973 100644 --- a/src/Mod/Fem/femtest/data/calculix/constraint_transform_torque.inp +++ b/src/Mod/Fem/femtest/data/calculix/constraint_transform_torque.inp @@ -13163,7 +13163,7 @@ RF *OUTPUT, FREQUENCY=1 *********************************************************** -*END STEP +*END STEP *********************************************************** ** CalculiX Input file diff --git a/src/Mod/Fem/femtest/data/calculix/frequency_beamsimple.inp b/src/Mod/Fem/femtest/data/calculix/frequency_beamsimple.inp index 1a69e14305..5ffef0521c 100644 --- a/src/Mod/Fem/femtest/data/calculix/frequency_beamsimple.inp +++ b/src/Mod/Fem/femtest/data/calculix/frequency_beamsimple.inp @@ -17074,7 +17074,7 @@ RF *OUTPUT, FREQUENCY=1 *********************************************************** -*END STEP +*END STEP *********************************************************** ** CalculiX Input file diff --git a/src/Mod/Fem/femtest/data/calculix/material_multiple_bendingbeam_fiveboxes.inp b/src/Mod/Fem/femtest/data/calculix/material_multiple_bendingbeam_fiveboxes.inp index c8ada64052..c04c8939c7 100644 --- a/src/Mod/Fem/femtest/data/calculix/material_multiple_bendingbeam_fiveboxes.inp +++ b/src/Mod/Fem/femtest/data/calculix/material_multiple_bendingbeam_fiveboxes.inp @@ -29190,13 +29190,13 @@ RF *OUTPUT, FREQUENCY=1 *********************************************************** -*END STEP +*END STEP *********************************************************** ** CalculiX Input file ** written by --> FreeCAD 0.21.0 ** written on --> Tue Mar 28 05:32:06 2023 -** file name --> +** file name --> material_multiple_bendingbeam_fiveboxes.FCStd ** analysis name --> Analysis ** ** diff --git a/src/Mod/Fem/femtest/data/calculix/material_multiple_bendingbeam_fivefaces.inp b/src/Mod/Fem/femtest/data/calculix/material_multiple_bendingbeam_fivefaces.inp index 1ab5a82fb8..1958b31207 100644 --- a/src/Mod/Fem/femtest/data/calculix/material_multiple_bendingbeam_fivefaces.inp +++ b/src/Mod/Fem/femtest/data/calculix/material_multiple_bendingbeam_fivefaces.inp @@ -2701,13 +2701,13 @@ RF *OUTPUT, FREQUENCY=1 *********************************************************** -*END STEP +*END STEP *********************************************************** ** CalculiX Input file ** written by --> FreeCAD 0.21.0 ** written on --> Tue Mar 28 05:33:12 2023 -** file name --> +** file name --> material_multiple_bendingbeam_fivefaces.FCStd ** analysis name --> Analysis ** ** diff --git a/src/Mod/Fem/femtest/data/calculix/material_multiple_tensionrod_twoboxes.inp b/src/Mod/Fem/femtest/data/calculix/material_multiple_tensionrod_twoboxes.inp index cfbfbf5f04..17882d7c3a 100644 --- a/src/Mod/Fem/femtest/data/calculix/material_multiple_tensionrod_twoboxes.inp +++ b/src/Mod/Fem/femtest/data/calculix/material_multiple_tensionrod_twoboxes.inp @@ -1282,13 +1282,13 @@ RF *OUTPUT, FREQUENCY=1 *********************************************************** -*END STEP +*END STEP *********************************************************** ** CalculiX Input file ** written by --> FreeCAD 0.21.0 ** written on --> Tue Mar 28 06:48:16 2023 -** file name --> +** file name --> material_multiple_tensionrod_twoboxes.FCStd ** analysis name --> Analysis ** ** diff --git a/src/Mod/Fem/femtest/data/calculix/material_nonlinear.inp b/src/Mod/Fem/femtest/data/calculix/material_nonlinear.inp index 4de8010124..9ee5e70a93 100644 --- a/src/Mod/Fem/femtest/data/calculix/material_nonlinear.inp +++ b/src/Mod/Fem/femtest/data/calculix/material_nonlinear.inp @@ -20119,13 +20119,13 @@ RF *OUTPUT, FREQUENCY=1 *********************************************************** -*END STEP +*END STEP *********************************************************** ** CalculiX Input file ** written by --> FreeCAD 0.21.0 ** written on --> Tue Mar 28 07:12:17 2023 -** file name --> +** file name --> material_nonlinear.FCStd ** analysis name --> Analysis ** ** diff --git a/src/Mod/Fem/femtest/data/calculix/square_pipe_end_twisted_edgeforces.inp b/src/Mod/Fem/femtest/data/calculix/square_pipe_end_twisted_edgeforces.inp index 70ba07a949..872dda5a70 100644 --- a/src/Mod/Fem/femtest/data/calculix/square_pipe_end_twisted_edgeforces.inp +++ b/src/Mod/Fem/femtest/data/calculix/square_pipe_end_twisted_edgeforces.inp @@ -2664,13 +2664,13 @@ RF *OUTPUT, FREQUENCY=1 *********************************************************** -*END STEP +*END STEP *********************************************************** ** CalculiX Input file ** written by --> FreeCAD 0.21.0 ** written on --> Tue Mar 28 05:35:14 2023 -** file name --> +** file name --> square_pipe_end_twisted_edgeforces.FCStd ** analysis name --> Analysis ** ** diff --git a/src/Mod/Fem/femtest/data/calculix/square_pipe_end_twisted_nodeforces.inp b/src/Mod/Fem/femtest/data/calculix/square_pipe_end_twisted_nodeforces.inp index 54abe926fe..8b8b04d5a8 100644 --- a/src/Mod/Fem/femtest/data/calculix/square_pipe_end_twisted_nodeforces.inp +++ b/src/Mod/Fem/femtest/data/calculix/square_pipe_end_twisted_nodeforces.inp @@ -2776,13 +2776,13 @@ RF *OUTPUT, FREQUENCY=1 *********************************************************** -*END STEP +*END STEP *********************************************************** ** CalculiX Input file ** written by --> FreeCAD 0.21.0 ** written on --> Tue Mar 28 05:36:19 2023 -** file name --> +** file name --> square_pipe_end_twisted_nodeforces.FCStd ** analysis name --> Analysis ** ** diff --git a/src/Mod/Fem/femtest/data/calculix/thermomech_bimetall.inp b/src/Mod/Fem/femtest/data/calculix/thermomech_bimetall.inp index 6f638b535b..93175e2775 100644 --- a/src/Mod/Fem/femtest/data/calculix/thermomech_bimetall.inp +++ b/src/Mod/Fem/femtest/data/calculix/thermomech_bimetall.inp @@ -7119,13 +7119,13 @@ RF *OUTPUT, FREQUENCY=1 *********************************************************** -*END STEP +*END STEP *********************************************************** ** CalculiX Input file ** written by --> FreeCAD 0.20.1 ** written on --> Wed Aug 10 04:21:49 2022 -** file name --> +** file name --> thermomech_bimetall.FCStd ** analysis name --> Analysis ** ** diff --git a/src/Mod/Fem/femtest/data/elmer/ELMERSOLVER_STARTINFO b/src/Mod/Fem/femtest/data/elmer/ELMERSOLVER_STARTINFO index cc6932daf7..d21bd7ee27 100644 --- a/src/Mod/Fem/femtest/data/elmer/ELMERSOLVER_STARTINFO +++ b/src/Mod/Fem/femtest/data/elmer/ELMERSOLVER_STARTINFO @@ -1 +1 @@ -case.sif \ No newline at end of file +case.sif diff --git a/src/Mod/Fem/femtest/data/elmer/box_static_0_mm.sif b/src/Mod/Fem/femtest/data/elmer/box_static_0_mm.sif index 8d95069df6..9b8be4354b 100644 --- a/src/Mod/Fem/femtest/data/elmer/box_static_0_mm.sif +++ b/src/Mod/Fem/femtest/data/elmer/box_static_0_mm.sif @@ -23,7 +23,7 @@ Solver 1 Variable DOFs = Integer 3 End -Simulation +Simulation Coordinate Mapping(3) = Integer 1 2 3 Coordinate Scaling = Real 0.001 Coordinate System = String "Cartesian" @@ -33,7 +33,7 @@ Simulation Use Mesh Names = Logical True End -Constants +Constants End Body 1 @@ -83,4 +83,3 @@ Boundary Condition 3 Force 3 Normalize by Area = Logical True Name = String "Face6" End - diff --git a/src/Mod/Fem/femtest/data/elmer/ccxcantilever_faceload_0_mm.sif b/src/Mod/Fem/femtest/data/elmer/ccxcantilever_faceload_0_mm.sif index 32d5a1fed1..c8dfbdf43d 100644 --- a/src/Mod/Fem/femtest/data/elmer/ccxcantilever_faceload_0_mm.sif +++ b/src/Mod/Fem/femtest/data/elmer/ccxcantilever_faceload_0_mm.sif @@ -23,7 +23,7 @@ Solver 1 Variable DOFs = Integer 3 End -Simulation +Simulation Coordinate Mapping(3) = Integer 1 2 3 Coordinate Scaling = Real 0.001 Coordinate System = String "Cartesian" @@ -33,7 +33,7 @@ Simulation Use Mesh Names = Logical True End -Constants +Constants End Body 1 @@ -78,4 +78,3 @@ Boundary Condition 2 Force 3 Normalize by Area = Logical True Name = String "Face2" End - diff --git a/src/Mod/Fem/femtest/data/elmer/ccxcantilever_faceload_1_si.sif b/src/Mod/Fem/femtest/data/elmer/ccxcantilever_faceload_1_si.sif index 32d5a1fed1..c8dfbdf43d 100644 --- a/src/Mod/Fem/femtest/data/elmer/ccxcantilever_faceload_1_si.sif +++ b/src/Mod/Fem/femtest/data/elmer/ccxcantilever_faceload_1_si.sif @@ -23,7 +23,7 @@ Solver 1 Variable DOFs = Integer 3 End -Simulation +Simulation Coordinate Mapping(3) = Integer 1 2 3 Coordinate Scaling = Real 0.001 Coordinate System = String "Cartesian" @@ -33,7 +33,7 @@ Simulation Use Mesh Names = Logical True End -Constants +Constants End Body 1 @@ -78,4 +78,3 @@ Boundary Condition 2 Force 3 Normalize by Area = Logical True Name = String "Face2" End - diff --git a/src/Mod/Fem/femtest/data/elmer/ccxcantilever_nodeload_0_mm.sif b/src/Mod/Fem/femtest/data/elmer/ccxcantilever_nodeload_0_mm.sif index 95811e42d5..6a480ea518 100644 --- a/src/Mod/Fem/femtest/data/elmer/ccxcantilever_nodeload_0_mm.sif +++ b/src/Mod/Fem/femtest/data/elmer/ccxcantilever_nodeload_0_mm.sif @@ -23,7 +23,7 @@ Solver 1 Variable DOFs = Integer 3 End -Simulation +Simulation Coordinate Mapping(3) = Integer 1 2 3 Coordinate Scaling = Real 0.001 Coordinate System = String "Cartesian" @@ -33,7 +33,7 @@ Simulation Use Mesh Names = Logical True End -Constants +Constants End Body 1 @@ -108,4 +108,3 @@ Boundary Condition 5 Force 3 Normalize by Area = Logical True Name = String "Vertex8" End - diff --git a/src/Mod/Fem/femtest/data/elmer/ccxcantilever_prescribeddisplacement_0_mm.sif b/src/Mod/Fem/femtest/data/elmer/ccxcantilever_prescribeddisplacement_0_mm.sif index 7ccd3daa7a..4db843c99b 100644 --- a/src/Mod/Fem/femtest/data/elmer/ccxcantilever_prescribeddisplacement_0_mm.sif +++ b/src/Mod/Fem/femtest/data/elmer/ccxcantilever_prescribeddisplacement_0_mm.sif @@ -23,7 +23,7 @@ Solver 1 Variable DOFs = Integer 3 End -Simulation +Simulation Coordinate Mapping(3) = Integer 1 2 3 Coordinate Scaling = Real 0.001 Coordinate System = String "Cartesian" @@ -33,7 +33,7 @@ Simulation Use Mesh Names = Logical True End -Constants +Constants End Body 1 @@ -73,4 +73,3 @@ Boundary Condition 2 Displacement 3 = Real -0.25 Name = String "Face2" End - diff --git a/src/Mod/Fem/femtest/data/mesh/tetra10_mesh.vtk b/src/Mod/Fem/femtest/data/mesh/tetra10_mesh.vtk index bc946d3b70..f578b4d3b9 100644 --- a/src/Mod/Fem/femtest/data/mesh/tetra10_mesh.vtk +++ b/src/Mod/Fem/femtest/data/mesh/tetra10_mesh.vtk @@ -3,13 +3,12 @@ vtk output ASCII DATASET UNSTRUCTURED_GRID POINTS 10 float -6 12 18 0 0 18 12 0 18 -6 6 0 3 6 18 6 0 18 -9 6 18 6 9 9 3 3 9 -9 3 9 +6 12 18 0 0 18 12 0 18 +6 6 0 3 6 18 6 0 18 +9 6 18 6 9 9 3 3 9 +9 3 9 CELLS 1 11 10 0 2 1 3 6 5 4 7 9 8 CELL_TYPES 1 24 - diff --git a/src/Mod/Fem/femtest/data/z88/ccx_cantilever_ele_tria6/z88elp.txt b/src/Mod/Fem/femtest/data/z88/ccx_cantilever_ele_tria6/z88elp.txt index 2b73a45163..b4105ecfa9 100644 --- a/src/Mod/Fem/femtest/data/z88/ccx_cantilever_ele_tria6/z88elp.txt +++ b/src/Mod/Fem/femtest/data/z88/ccx_cantilever_ele_tria6/z88elp.txt @@ -1,2 +1,2 @@ 1 -1 70 1000.0 0 0 0 0 0 0 +1 70 1000.0 0 0 0 0 0 0 diff --git a/src/Mod/Fem/femtest/function_tests/test_support_utils.py b/src/Mod/Fem/femtest/function_tests/test_support_utils.py index 044edfff77..818a696d60 100644 --- a/src/Mod/Fem/femtest/function_tests/test_support_utils.py +++ b/src/Mod/Fem/femtest/function_tests/test_support_utils.py @@ -20,7 +20,7 @@ class TestParse_Diff(unittest.TestCase): def test_not_ignore_single_word(self) -> None: diff_lines = """--- -+++ ++++ @@ @@ -12, +11""".splitlines() @@ -35,8 +35,8 @@ class TestParse_Diff(unittest.TestCase): self.assertFalse(bad_lines, f"Double '@' signs are not ignored {bad_lines = }") def test_good_float_rounding(self) -> None: - diff_lines = """--- -+++ + diff_lines = """--- ++++ @@ -11717 +11717 @@ -2505,2,-9.5670268990152E-01 +2505,2,-9.5670268990153E-01 @@ -64,9 +64,7 @@ class TestParse_Diff(unittest.TestCase): -3327,2,-2.2462134450621E+00 +3327,2,-2.2462134450620E+00""".splitlines() bad_lines = support_utils.parse_diff(diff_lines=iter(diff_lines)) - self.assertFalse( - bad_lines, f"Good consecutive rounding changes failed {bad_lines = }" - ) + self.assertFalse(bad_lines, f"Good consecutive rounding changes failed {bad_lines = }") def test_good_rounding_space_split(self) -> None: diff_lines = """--- @@ -87,9 +85,7 @@ class TestParse_Diff(unittest.TestCase): -2505 2 -9.5670268990152E-01 +2505 2 -9.5680268990153E-01""".splitlines() bad_lines = support_utils.parse_diff(diff_lines=iter(diff_lines)) - self.assertTrue( - bad_lines, f"Bad rounding split by space shouldn't pass {bad_lines = }" - ) + self.assertTrue(bad_lines, f"Bad rounding split by space shouldn't pass {bad_lines = }") def test_good_rounding_space_with_extra_word(self) -> None: diff_lines = """--- @@ -98,9 +94,7 @@ class TestParse_Diff(unittest.TestCase): -EXTRA 2505 2 -9.5670268990152E-01 +EXTRA 2505 2 -9.5670268990153E-01""".splitlines() bad_lines = support_utils.parse_diff(diff_lines=iter(diff_lines)) - self.assertFalse( - bad_lines, f"Good rounding with extra word failed {bad_lines = }" - ) + self.assertFalse(bad_lines, f"Good rounding with extra word failed {bad_lines = }") def test_good_and_bad_rounding(self) -> None: diff_lines = """--- @@ -112,9 +106,7 @@ class TestParse_Diff(unittest.TestCase): -2505, 2, -9.5670268990152E-01 +2505, 2, -9.5680268990153E-01""".splitlines() bad_lines = support_utils.parse_diff(diff_lines=iter(diff_lines)) - self.assertTrue( - bad_lines, f"Bad rounding split by space shouldn't pass {bad_lines = }" - ) + self.assertTrue(bad_lines, f"Bad rounding split by space shouldn't pass {bad_lines = }") self.assertTrue( sum(line.startswith("@@") for line in bad_lines) == 1, f"Exactly one double '@' lines should be present {bad_lines = }", @@ -149,9 +141,7 @@ class TestParse_Diff(unittest.TestCase): -2505, 2, -9.5670268990152E-01 +2505, 2, -9.5680268990153E-01""".splitlines() bad_lines = support_utils.parse_diff(diff_lines=iter(diff_lines)) - self.assertTrue( - bad_lines, f"Bad rounding split by space shouldn't pass {bad_lines = }" - ) + self.assertTrue(bad_lines, f"Bad rounding split by space shouldn't pass {bad_lines = }") self.assertTrue( sum(line.startswith("@@") for line in bad_lines) == 2, f"Exactly two double '@' lines should be present {bad_lines = }", diff --git a/src/Mod/Fem/femtest/gui/test_open.py b/src/Mod/Fem/femtest/gui/test_open.py index 4fa598961a..8fea41e71b 100644 --- a/src/Mod/Fem/femtest/gui/test_open.py +++ b/src/Mod/Fem/femtest/gui/test_open.py @@ -64,42 +64,29 @@ class TestObjectOpen(unittest.TestCase): fcc_print("import TestObjectOpen") # ******************************************************************************************** - def setUp( - self - ): + def setUp(self): # setUp is executed before every test doc_name = self.__class__.__name__ self.document = FreeCAD.newDocument(doc_name) - self.test_file_dir = join( - testtools.get_fem_test_home_dir(), - "open" - ) + self.test_file_dir = join(testtools.get_fem_test_home_dir(), "open") # ******************************************************************************************** - def tearDown( - self - ): + def tearDown(self): # tearDown is executed after every test FreeCAD.closeDocument(self.document.Name) # ******************************************************************************************** - def test_00print( - self - ): + def test_00print(self): # since method name starts with 00 this will be run first # this test just prints a line with stars - fcc_print("\n{0}\n{1} run FEM TestObjectOpen tests {2}\n{0}".format( - 100 * "*", - 10 * "*", - 60 * "*" - )) + fcc_print( + "\n{0}\n{1} run FEM TestObjectOpen tests {2}\n{0}".format(100 * "*", 10 * "*", 60 * "*") + ) # ******************************************************************************************** - def test_femobjects_open_head( - self - ): + def test_femobjects_open_head(self): fcc_print("load master head document objects") # get a document with all FEM objects @@ -116,15 +103,11 @@ class TestObjectOpen(unittest.TestCase): # standard name changed from femsolver.elmer.equations.flux import ViewProxy - self.assertEqual( - ViewProxy, - self.document.Flux.ViewObject.Proxy.__class__ - ) + + self.assertEqual(ViewProxy, self.document.Flux.ViewObject.Proxy.__class__) # ******************************************************************************************** - def test_femobjects_open_de9b3fb438( - self - ): + def test_femobjects_open_de9b3fb438(self): # the number in method name is the FreeCAD commit the document was created with # https://github.com/FreeCAD/FreeCAD/commit/de9b3fb438 # the document was created by running the object create unit test @@ -138,209 +121,164 @@ class TestObjectOpen(unittest.TestCase): # standard name changed from femsolver.elmer.equations.flux import ViewProxy - self.assertEqual( - ViewProxy, - self.document.Fluxsolver.ViewObject.Proxy.__class__ - ) + + self.assertEqual(ViewProxy, self.document.Fluxsolver.ViewObject.Proxy.__class__) # ******************************************************************************************** - def compare_feature_pythons_class_gui( - self, - doc - ): + def compare_feature_pythons_class_gui(self, doc): import ObjectsFem from femtools.femutils import type_of_obj # see comments at file end, the code was created by some python code from femviewprovider.view_constraint_bodyheatsource import VPConstraintBodyHeatSource + self.assertEqual( - VPConstraintBodyHeatSource, - doc.ConstraintBodyHeatSource.ViewObject.Proxy.__class__ + VPConstraintBodyHeatSource, doc.ConstraintBodyHeatSource.ViewObject.Proxy.__class__ ) self.assertEqual( "Fem::ConstraintCurrentDensity", - type_of_obj(ObjectsFem.makeConstraintCurrentDensity(doc)) + type_of_obj(ObjectsFem.makeConstraintCurrentDensity(doc)), + ) + + from femviewprovider.view_constraint_electrostaticpotential import ( + VPConstraintElectroStaticPotential, ) - from femviewprovider.view_constraint_electrostaticpotential \ - import VPConstraintElectroStaticPotential self.assertEqual( VPConstraintElectroStaticPotential, - doc.ConstraintElectrostaticPotential.ViewObject.Proxy.__class__ + doc.ConstraintElectrostaticPotential.ViewObject.Proxy.__class__, ) from femviewprovider.view_constraint_flowvelocity import VPConstraintFlowVelocity + self.assertEqual( - VPConstraintFlowVelocity, - doc.ConstraintFlowVelocity.ViewObject.Proxy.__class__ + VPConstraintFlowVelocity, doc.ConstraintFlowVelocity.ViewObject.Proxy.__class__ + ) + + from femviewprovider.view_constraint_initialflowvelocity import ( + VPConstraintInitialFlowVelocity, ) - from femviewprovider.view_constraint_initialflowvelocity \ - import VPConstraintInitialFlowVelocity self.assertEqual( VPConstraintInitialFlowVelocity, - doc.ConstraintInitialFlowVelocity.ViewObject.Proxy.__class__ + doc.ConstraintInitialFlowVelocity.ViewObject.Proxy.__class__, ) self.assertEqual( - "Fem::ConstraintMagnetization", - type_of_obj(ObjectsFem.makeConstraintMagnetization(doc)) + "Fem::ConstraintMagnetization", type_of_obj(ObjectsFem.makeConstraintMagnetization(doc)) ) from femviewprovider.view_constraint_selfweight import VPConstraintSelfWeight + self.assertEqual( - VPConstraintSelfWeight, - doc.ConstraintSelfWeight.ViewObject.Proxy.__class__ + VPConstraintSelfWeight, doc.ConstraintSelfWeight.ViewObject.Proxy.__class__ ) from femviewprovider.view_constraint_tie import VPConstraintTie - self.assertEqual( - VPConstraintTie, - doc.ConstraintTie.ViewObject.Proxy.__class__ - ) + + self.assertEqual(VPConstraintTie, doc.ConstraintTie.ViewObject.Proxy.__class__) from femviewprovider.view_element_fluid1D import VPElementFluid1D - self.assertEqual( - VPElementFluid1D, - doc.ElementFluid1D.ViewObject.Proxy.__class__ - ) + + self.assertEqual(VPElementFluid1D, doc.ElementFluid1D.ViewObject.Proxy.__class__) from femviewprovider.view_element_geometry1D import VPElementGeometry1D - self.assertEqual( - VPElementGeometry1D, - doc.ElementGeometry1D.ViewObject.Proxy.__class__ - ) + + self.assertEqual(VPElementGeometry1D, doc.ElementGeometry1D.ViewObject.Proxy.__class__) from femviewprovider.view_element_geometry2D import VPElementGeometry2D - self.assertEqual( - VPElementGeometry2D, - doc.ElementGeometry2D.ViewObject.Proxy.__class__ - ) + + self.assertEqual(VPElementGeometry2D, doc.ElementGeometry2D.ViewObject.Proxy.__class__) from femviewprovider.view_element_rotation1D import VPElementRotation1D - self.assertEqual( - VPElementRotation1D, - doc.ElementRotation1D.ViewObject.Proxy.__class__ - ) + + self.assertEqual(VPElementRotation1D, doc.ElementRotation1D.ViewObject.Proxy.__class__) from femviewprovider.view_material_common import VPMaterialCommon - self.assertEqual( - VPMaterialCommon, - doc.MaterialFluid.ViewObject.Proxy.__class__ - ) + + self.assertEqual(VPMaterialCommon, doc.MaterialFluid.ViewObject.Proxy.__class__) from femviewprovider.view_material_common import VPMaterialCommon - self.assertEqual( - VPMaterialCommon, - doc.MaterialSolid.ViewObject.Proxy.__class__ - ) + + self.assertEqual(VPMaterialCommon, doc.MaterialSolid.ViewObject.Proxy.__class__) from femviewprovider.view_material_mechanicalnonlinear import VPMaterialMechanicalNonlinear + self.assertEqual( VPMaterialMechanicalNonlinear, - doc.MaterialMechanicalNonlinear.ViewObject.Proxy.__class__ + doc.MaterialMechanicalNonlinear.ViewObject.Proxy.__class__, ) from femviewprovider.view_material_reinforced import VPMaterialReinforced - self.assertEqual( - VPMaterialReinforced, - doc.MaterialReinforced.ViewObject.Proxy.__class__ - ) + + self.assertEqual(VPMaterialReinforced, doc.MaterialReinforced.ViewObject.Proxy.__class__) from femviewprovider.view_mesh_gmsh import VPMeshGmsh - self.assertEqual( - VPMeshGmsh, - doc.MeshGmsh.ViewObject.Proxy.__class__ - ) + + self.assertEqual(VPMeshGmsh, doc.MeshGmsh.ViewObject.Proxy.__class__) from femviewprovider.view_mesh_boundarylayer import VPMeshBoundaryLayer - self.assertEqual( - VPMeshBoundaryLayer, - doc.MeshBoundaryLayer.ViewObject.Proxy.__class__ - ) + + self.assertEqual(VPMeshBoundaryLayer, doc.MeshBoundaryLayer.ViewObject.Proxy.__class__) from femviewprovider.view_mesh_group import VPMeshGroup - self.assertEqual( - VPMeshGroup, - doc.MeshGroup.ViewObject.Proxy.__class__ - ) + + self.assertEqual(VPMeshGroup, doc.MeshGroup.ViewObject.Proxy.__class__) from femviewprovider.view_mesh_region import VPMeshRegion - self.assertEqual( - VPMeshRegion, - doc.MeshRegion.ViewObject.Proxy.__class__ - ) + + self.assertEqual(VPMeshRegion, doc.MeshRegion.ViewObject.Proxy.__class__) from femviewprovider.view_mesh_result import VPFemMeshResult - self.assertEqual( - VPFemMeshResult, - doc.MeshResult.ViewObject.Proxy.__class__ - ) + + self.assertEqual(VPFemMeshResult, doc.MeshResult.ViewObject.Proxy.__class__) from femviewprovider.view_result_mechanical import VPResultMechanical - self.assertEqual( - VPResultMechanical, - doc.ResultMechanical.ViewObject.Proxy.__class__ - ) + + self.assertEqual(VPResultMechanical, doc.ResultMechanical.ViewObject.Proxy.__class__) from femviewprovider.view_solver_ccxtools import VPSolverCcxTools - self.assertEqual( - VPSolverCcxTools, - doc.SolverCcxTools.ViewObject.Proxy.__class__ - ) + + self.assertEqual(VPSolverCcxTools, doc.SolverCcxTools.ViewObject.Proxy.__class__) from femsolver.calculix.solver import ViewProxy - self.assertEqual( - ViewProxy, - doc.SolverCalculix.ViewObject.Proxy.__class__ - ) + + self.assertEqual(ViewProxy, doc.SolverCalculix.ViewObject.Proxy.__class__) from femsolver.elmer.solver import ViewProxy - self.assertEqual( - ViewProxy, - doc.SolverElmer.ViewObject.Proxy.__class__ - ) + + self.assertEqual(ViewProxy, doc.SolverElmer.ViewObject.Proxy.__class__) from femsolver.z88.solver import ViewProxy - self.assertEqual( - ViewProxy, - doc.SolverZ88.ViewObject.Proxy.__class__ - ) + + self.assertEqual(ViewProxy, doc.SolverZ88.ViewObject.Proxy.__class__) from femsolver.elmer.equations.elasticity import ViewProxy - self.assertEqual( - ViewProxy, - doc.Elasticity.ViewObject.Proxy.__class__ - ) + + self.assertEqual(ViewProxy, doc.Elasticity.ViewObject.Proxy.__class__) from femsolver.elmer.equations.electrostatic import ViewProxy - self.assertEqual( - ViewProxy, - doc.Electrostatic.ViewObject.Proxy.__class__ - ) + + self.assertEqual(ViewProxy, doc.Electrostatic.ViewObject.Proxy.__class__) from femsolver.elmer.equations.flow import ViewProxy - self.assertEqual( - ViewProxy, - doc.Flow.ViewObject.Proxy.__class__ - ) + + self.assertEqual(ViewProxy, doc.Flow.ViewObject.Proxy.__class__) from femsolver.elmer.equations.heat import ViewProxy - self.assertEqual( - ViewProxy, - doc.Heat.ViewObject.Proxy.__class__ - ) + + self.assertEqual(ViewProxy, doc.Heat.ViewObject.Proxy.__class__) self.assertEqual( "Fem::EquationElmerMagnetodynamic2D", - type_of_obj(ObjectsFem.makeEquationMagnetodynamic2D(doc)) + type_of_obj(ObjectsFem.makeEquationMagnetodynamic2D(doc)), ) self.assertEqual( "Fem::EquationElmerMagnetodynamic", - type_of_obj(ObjectsFem.makeEquationMagnetodynamic(doc)) + type_of_obj(ObjectsFem.makeEquationMagnetodynamic(doc)), ) diff --git a/src/Mod/Fem/femtest/test_information.md b/src/Mod/Fem/femtest/test_information.md index dc5ab30bc1..e2a3567ecf 100644 --- a/src/Mod/Fem/femtest/test_information.md +++ b/src/Mod/Fem/femtest/test_information.md @@ -170,4 +170,3 @@ doc = FreeCAD.open(app_home + "data/examples/Fem2.FCStd") app_home = FreeCAD.ConfigGet("AppHomePath") doc = FreeCAD.open(FreeCAD.ConfigGet("AppHomePath") + 'Mod/Fem/femtest/data/open/all_objects_de9b3fb438.FCStd') ``` - diff --git a/src/Mod/Fem/femtools/ccxtools.py b/src/Mod/Fem/femtools/ccxtools.py index 2b224f4054..dcda11ead4 100644 --- a/src/Mod/Fem/femtools/ccxtools.py +++ b/src/Mod/Fem/femtools/ccxtools.py @@ -39,6 +39,7 @@ from femtools import femutils from femtools import membertools from PySide import QtCore # there might be a special reason this is not guarded ?!? + if FreeCAD.GuiUp: from PySide import QtGui import FemGui @@ -125,13 +126,9 @@ class FemToolsCcx(QtCore.QRunnable, QtCore.QObject): raise Exception("FEM: No solver found!") if self.analysis.Document is not self.solver.Document: - raise Exception( - "FEM: The analysis and solver are not in the same document!" - ) + raise Exception("FEM: The analysis and solver are not in the same document!") if self.solver not in self.analysis.Group: - raise Exception( - "FEM: The solver is not part of the analysis Group!" - ) + raise Exception("FEM: The solver is not part of the analysis Group!") # print(self.solver) # print(self.analysis) @@ -149,14 +146,13 @@ class FemToolsCcx(QtCore.QRunnable, QtCore.QObject): self.result_object = None else: raise Exception( - "FEM: Something went wrong, " - "the exception should have been raised earlier!" + "FEM: Something went wrong, the exception should have been raised earlier!" ) def purge_results(self): - """Remove all result objects and result meshes from an analysis group - """ + """Remove all result objects and result meshes from an analysis group""" from femresult.resulttools import purge_results as pr + pr(self.analysis) def reset_mesh_purge_results_checked(self): @@ -169,8 +165,7 @@ class FemToolsCcx(QtCore.QRunnable, QtCore.QObject): self.purge_results() def reset_all(self): - """Reset mesh color, deformation and removes all result objects - """ + """Reset mesh color, deformation and removes all result objects""" self.purge_results() def _get_several_member(self, obj_type): @@ -195,8 +190,7 @@ class FemToolsCcx(QtCore.QRunnable, QtCore.QObject): FemGui.setActiveAnalysis(self.analysis) def find_solver_analysis(self): - """ get the analysis group the solver belongs to - """ + """get the analysis group the solver belongs to""" if self.solver.getParentGroup(): obj = self.solver.getParentGroup() if femutils.is_of_type(obj, "Fem::FemAnalysis"): @@ -238,10 +232,7 @@ class FemToolsCcx(QtCore.QRunnable, QtCore.QObject): else: # the prerequisites will run anyway and they will print a message box anyway # thus do not print one here, but print a console warning - FreeCAD.Console.PrintWarning( - "{} The prerequisite check will fail.\n" - .format(message) - ) + FreeCAD.Console.PrintWarning(f"{message} The prerequisite check will fail.\n") ## @var members # members of the analysis. All except the solver and the mesh @@ -260,16 +251,11 @@ class FemToolsCcx(QtCore.QRunnable, QtCore.QObject): if not self.working_dir: message += "Working directory not set\n" if not os.path.isdir(self.working_dir): - message += ( - "Working directory \'{}\' doesn't exist." - .format(self.working_dir) - ) + message += f"Working directory '{self.working_dir}' doesn't exist." from femtools.checksanalysis import check_member_for_solver_calculix + message += check_member_for_solver_calculix( - self.analysis, - self.solver, - self.mesh, - self.member + self.analysis, self.solver, self.mesh, self.member ) return message @@ -323,52 +309,41 @@ class FemToolsCcx(QtCore.QRunnable, QtCore.QObject): if femutils.check_working_dir(self.working_dir) is not True: if create is True: FreeCAD.Console.PrintMessage( - "Dir given as parameter \'{}\' doesn't exist.\n".format(self.working_dir) + f"Dir given as parameter '{self.working_dir}' doesn't exist.\n" ) else: FreeCAD.Console.PrintError( - "Dir given as parameter \'{}\' doesn't exist " - "and create parameter is set to False.\n" - .format(self.working_dir) + "Dir given as parameter '{}' doesn't exist " + "and create parameter is set to False.\n".format(self.working_dir) ) self.working_dir = femutils.get_pref_working_dir(self.solver) FreeCAD.Console.PrintMessage( - "Dir \'{}\' will be used instead.\n" - .format(self.working_dir) + f"Dir '{self.working_dir}' will be used instead.\n" ) elif fem_general_prefs.GetBool("OverwriteSolverWorkingDirectory", True) is False: self.working_dir = self.solver.WorkingDir if femutils.check_working_dir(self.working_dir) is not True: - if self.working_dir == '': + if self.working_dir == "": FreeCAD.Console.PrintError( "Working Dir is set to be used from solver object " - "but Dir from solver object \'{}\' is empty.\n" - .format(self.working_dir) + "but Dir from solver object '{}' is empty.\n".format(self.working_dir) ) else: FreeCAD.Console.PrintError( - "Dir from solver object \'{}\' doesn't exist.\n" - .format(self.working_dir) + f"Dir from solver object '{self.working_dir}' doesn't exist.\n" ) self.working_dir = femutils.get_pref_working_dir(self.solver) - FreeCAD.Console.PrintMessage( - "Dir \'{}\' will be used instead.\n" - .format(self.working_dir) - ) + FreeCAD.Console.PrintMessage(f"Dir '{self.working_dir}' will be used instead.\n") else: self.working_dir = femutils.get_pref_working_dir(self.solver) # check working_dir exist, if not use a tmp dir and inform the user if femutils.check_working_dir(self.working_dir) is not True: FreeCAD.Console.PrintError( - "Dir \'{}\' doesn't exist or cannot be created.\n" - .format(self.working_dir) + f"Dir '{self.working_dir}' doesn't exist or cannot be created.\n" ) self.working_dir = femutils.get_temp_dir(self.solver) - FreeCAD.Console.PrintMessage( - "Dir \'{}\' will be used instead.\n" - .format(self.working_dir) - ) + FreeCAD.Console.PrintMessage(f"Dir '{self.working_dir}' will be used instead.\n") # Update inp file name self.set_inp_file_name() @@ -378,6 +353,7 @@ class FemToolsCcx(QtCore.QRunnable, QtCore.QObject): # get mesh set data # TODO use separate method for getting the mesh set data from femmesh import meshsetsgetter + meshdatagetter = meshsetsgetter.MeshSetsGetter( self.analysis, self.solver, @@ -389,6 +365,7 @@ class FemToolsCcx(QtCore.QRunnable, QtCore.QObject): # write input file import femsolver.calculix.writer as iw + self.inp_file_name = "" try: inp_writer = iw.FemInputWriterCcx( @@ -397,13 +374,12 @@ class FemToolsCcx(QtCore.QRunnable, QtCore.QObject): self.mesh, meshdatagetter.member, self.working_dir, - meshdatagetter.mat_geo_sets + meshdatagetter.mat_geo_sets, ) self.inp_file_name = inp_writer.write_solver_input() except Exception: FreeCAD.Console.PrintError( - "Unexpected error when writing CalculiX input file: {}\n" - .format(sys.exc_info()[1]) + f"Unexpected error when writing CalculiX input file: {sys.exc_info()[1]}\n" ) raise @@ -422,15 +398,16 @@ class FemToolsCcx(QtCore.QRunnable, QtCore.QObject): 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) + 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) @@ -449,14 +426,12 @@ class FemToolsCcx(QtCore.QRunnable, QtCore.QObject): self.ccx_binary = ccx_path else: if not ccx_binary: - self.ccx_prefs = FreeCAD.ParamGet( - "User parameter:BaseApp/Preferences/Mod/Fem/Ccx" - ) + 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) + 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 " @@ -480,7 +455,7 @@ class FemToolsCcx(QtCore.QRunnable, QtCore.QObject): stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False, - startupinfo=startup_info + startupinfo=startup_info, ) ccx_stdout, ccx_stderr = p.communicate() if ccx_binary_sig in str(ccx_stdout): @@ -494,26 +469,26 @@ class FemToolsCcx(QtCore.QRunnable, QtCore.QObject): # 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)) + FreeCAD.Console.PrintError(f"{e}\n") if e.errno == 2: error_message = ( - "FEM: CalculiX binary ccx \'{}\' not found. " + "FEM: CalculiX binary ccx '{}' not found. " "Please set the CalculiX binary ccx path in " - "FEM preferences tab CalculiX.\n" - .format(ccx_binary) + "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)) + FreeCAD.Console.PrintError(f"{e}\n") error_message = ( - "FEM: CalculiX ccx \'{}\' output \'{}\' doesn't " - "contain expected phrase \'{}\'. " + "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) + "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) @@ -521,6 +496,7 @@ class FemToolsCcx(QtCore.QRunnable, QtCore.QObject): def start_ccx(self): import multiprocessing + self.ccx_stdout = "" self.ccx_stderr = "" ont_backup = os.environ.get("OMP_NUM_THREADS") @@ -544,7 +520,7 @@ class FemToolsCcx(QtCore.QRunnable, QtCore.QObject): stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False, - env=_env + env=_env, ) self.ccx_stdout, self.ccx_stderr = p.communicate() self.ccx_stdout = self.ccx_stdout.decode() @@ -557,6 +533,7 @@ class FemToolsCcx(QtCore.QRunnable, QtCore.QObject): self.setup_ccx() import re from platform import system + startup_info = None if system() == "Windows": # Windows workaround to avoid blinking terminal window @@ -570,7 +547,7 @@ class FemToolsCcx(QtCore.QRunnable, QtCore.QObject): stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False, - startupinfo=startup_info + startupinfo=startup_info, ) ccx_stdout, ccx_stderr = p.communicate() ccx_stdout = ccx_stdout.decode() @@ -587,9 +564,10 @@ class FemToolsCcx(QtCore.QRunnable, QtCore.QObject): self.setup_ccx() if self.ccx_binary_present is False: error_message = ( - "FEM: CalculiX binary ccx \'{}\' not found. " - "Please set the CalculiX binary ccx path in FEM preferences tab CalculiX.\n" - .format(self.ccx_binary) + "FEM: CalculiX binary ccx '{}' not found. " + "Please set the CalculiX binary ccx path in FEM preferences tab CalculiX.\n".format( + self.ccx_binary + ) ) if FreeCAD.GuiUp: QtGui.QMessageBox.critical(None, "No CalculiX binary ccx", error_message) @@ -609,7 +587,7 @@ class FemToolsCcx(QtCore.QRunnable, QtCore.QObject): # https://forum.freecad.org/viewtopic.php?f=18&t=31303&start=10#p260743 ret_code = 0 else: - FreeCAD.Console.PrintError("CalculiX failed with exit code {}\n".format(ret_code)) + FreeCAD.Console.PrintError(f"CalculiX failed with exit code {ret_code}\n") FreeCAD.Console.PrintMessage("--------start of stderr-------\n") FreeCAD.Console.PrintMessage(self.ccx_stderr) FreeCAD.Console.PrintMessage("--------end of stderr---------\n") @@ -630,15 +608,11 @@ class FemToolsCcx(QtCore.QRunnable, QtCore.QObject): message = self.check_prerequisites() if message: text = "CalculiX can not be started due to missing prerequisites:\n" - error_app = "{}{}".format(text, message) - error_gui = "{}\n{}".format(text, message) + error_app = f"{text}{message}" + error_gui = f"{text}\n{message}" FreeCAD.Console.PrintError(error_app) if FreeCAD.GuiUp: - QtGui.QMessageBox.critical( - None, - "Missing prerequisite", - error_gui - ) + QtGui.QMessageBox.critical(None, "Missing prerequisite", error_gui) return False else: self.write_inp_file() @@ -646,42 +620,24 @@ class FemToolsCcx(QtCore.QRunnable, QtCore.QObject): error_message = "Error on writing CalculiX input file.\n" FreeCAD.Console.PrintError(error_message) if FreeCAD.GuiUp: - QtGui.QMessageBox.critical( - None, - "Error", - error_message - ) + QtGui.QMessageBox.critical(None, "Error", error_message) return False else: - FreeCAD.Console.PrintLog( - "Writing CalculiX input file completed.\n" - ) + FreeCAD.Console.PrintLog("Writing CalculiX input file completed.\n") ret_code = self.ccx_run() if ret_code is None: - error_message = ( - "CalculiX has not been run. The CalculiX binary search returned: {}.\n" - .format(self.ccx_binary_present) + error_message = "CalculiX has not been run. The CalculiX binary search returned: {}.\n".format( + self.ccx_binary_present ) FreeCAD.Console.PrintError(error_message) if FreeCAD.GuiUp: - QtGui.QMessageBox.critical( - None, - "Error", - error_message - ) + QtGui.QMessageBox.critical(None, "Error", error_message) return False if ret_code != 0: - error_message = ( - "CalculiX finished with error {}.\n" - .format(ret_code) - ) + error_message = f"CalculiX finished with error {ret_code}.\n" FreeCAD.Console.PrintError(error_message) if FreeCAD.GuiUp: - QtGui.QMessageBox.critical( - None, - "Error", - error_message - ) + QtGui.QMessageBox.critical(None, "Error", error_message) return False else: FreeCAD.Console.PrintLog("Try to read result files\n") @@ -706,25 +662,25 @@ class FemToolsCcx(QtCore.QRunnable, QtCore.QObject): without_material_elemnodes.append(n) without_material_elements = sorted(without_material_elements) without_material_elemnodes = sorted(without_material_elemnodes) - command_for_withoutmatnodes = ( - "without_material_elemnodes = {}" - .format(without_material_elemnodes) + command_for_withoutmatnodes = "without_material_elemnodes = {}".format( + without_material_elemnodes ) command_to_highlight = ( - "Gui.ActiveDocument.{}.HighlightedNodes = without_material_elemnodes" - .format(self.mesh.Name) + "Gui.ActiveDocument.{}.HighlightedNodes = without_material_elemnodes".format( + self.mesh.Name + ) ) # some output for the user FreeCAD.Console.PrintError( "\n\nCalculiX returned an error due to elements without materials.\n" ) FreeCAD.Console.PrintMessage( - "without_material_elements = {}\n" - .format(without_material_elements) + f"without_material_elements = {without_material_elements}\n" ) FreeCAD.Console.PrintMessage(command_for_withoutmatnodes + "\n") if FreeCAD.GuiUp: import FreeCADGui + # with this the list without_material_elemnodes # will be available for further user interaction FreeCADGui.doCommand(command_for_withoutmatnodes) @@ -738,8 +694,7 @@ class FemToolsCcx(QtCore.QRunnable, QtCore.QObject): FreeCAD.Console.PrintMessage(command_to_highlight + "\n") # command to reset the Highlighted Nodes FreeCAD.Console.PrintMessage( - "Gui.ActiveDocument.{}.HighlightedNodes = []\n\n" - .format(self.mesh.Name) + f"Gui.ActiveDocument.{self.mesh.Name}.HighlightedNodes = []\n\n" ) return True else: @@ -762,25 +717,25 @@ class FemToolsCcx(QtCore.QRunnable, QtCore.QObject): nonpositive_jacobian_elenodes.append(n) nonpositive_jacobian_elements = sorted(nonpositive_jacobian_elements) nonpositive_jacobian_elenodes = sorted(nonpositive_jacobian_elenodes) - command_for_nonposjacnodes = ( - "nonpositive_jacobian_elenodes = {}" - .format(nonpositive_jacobian_elenodes) + command_for_nonposjacnodes = "nonpositive_jacobian_elenodes = {}".format( + nonpositive_jacobian_elenodes ) command_to_highlight = ( - "Gui.ActiveDocument.{}.HighlightedNodes = nonpositive_jacobian_elenodes" - .format(self.mesh.Name) + "Gui.ActiveDocument.{}.HighlightedNodes = nonpositive_jacobian_elenodes".format( + self.mesh.Name + ) ) # some output for the user FreeCAD.Console.PrintError( "\n\nCalculiX returned an error due to nonpositive jacobian elements.\n" ) FreeCAD.Console.PrintMessage( - "nonpositive_jacobian_elements = {}\n" - .format(nonpositive_jacobian_elements) + f"nonpositive_jacobian_elements = {nonpositive_jacobian_elements}\n" ) FreeCAD.Console.PrintMessage(command_for_nonposjacnodes + "\n") if FreeCAD.GuiUp: import FreeCADGui + # with this the list nonpositive_jacobian_elenodes # will be available for further user interaction FreeCADGui.doCommand(command_for_nonposjacnodes) @@ -794,8 +749,7 @@ class FemToolsCcx(QtCore.QRunnable, QtCore.QObject): FreeCAD.Console.PrintMessage(command_to_highlight + "\n") # command to reset the Highlighted Nodes FreeCAD.Console.PrintMessage( - "Gui.ActiveDocument.{}.HighlightedNodes = []\n\n" - .format(self.mesh.Name) + f"Gui.ActiveDocument.{self.mesh.Name}.HighlightedNodes = []\n\n" ) return True else: @@ -810,16 +764,13 @@ class FemToolsCcx(QtCore.QRunnable, QtCore.QObject): self.analysis.Document.recompute() def load_results_ccxfrd(self): - """Load results of ccx calculations from .frd file. - """ + """Load results of ccx calculations from .frd file.""" import feminout.importCcxFrdResults as importCcxFrdResults + frd_result_file = os.path.splitext(self.inp_file_name)[0] + ".frd" if os.path.isfile(frd_result_file): importCcxFrdResults.importFrd( - frd_result_file, - self.analysis, - "CCX_", - self.solver.AnalysisType + frd_result_file, self.analysis, "CCX_", self.solver.AnalysisType ) for m in self.analysis.Group: if m.isDerivedFrom("Fem::FemResultObject"): @@ -835,15 +786,12 @@ class FemToolsCcx(QtCore.QRunnable, QtCore.QObject): else: FreeCAD.Console.PrintError("FEM: No result object in active Analysis.\n") else: - FreeCAD.Console.PrintError( - "FEM: No frd result file found at {}\n" - .format(frd_result_file) - ) + FreeCAD.Console.PrintError(f"FEM: No frd result file found at {frd_result_file}\n") def load_results_ccxdat(self): - """Load results of ccx calculations from .dat file. - """ + """Load results of ccx calculations from .dat file.""" import feminout.importCcxDatResults as importCcxDatResults + dat_result_file = os.path.splitext(self.inp_file_name)[0] + ".dat" mode_frequencies = None dat_content = None @@ -851,14 +799,11 @@ class FemToolsCcx(QtCore.QRunnable, QtCore.QObject): if os.path.isfile(dat_result_file): mode_frequencies = importCcxDatResults.import_dat(dat_result_file, self.analysis) - dat_file = open(dat_result_file, "r") + dat_file = open(dat_result_file) dat_content = dat_file.read() dat_file.close() else: - FreeCAD.Console.PrintError( - "FEM: No dat result file found at {}\n" - .format(dat_result_file) - ) + FreeCAD.Console.PrintError(f"FEM: No dat result file found at {dat_result_file}\n") if mode_frequencies: # print(mode_frequencies) @@ -883,4 +828,5 @@ class CcxTools(FemToolsCcx): def __init__(self, solver=None): FemToolsCcx.__init__(self, None, solver) + ## @} diff --git a/src/Mod/Fem/femtools/checksanalysis.py b/src/Mod/Fem/femtools/checksanalysis.py index afb7252813..f3fd2e0767 100644 --- a/src/Mod/Fem/femtools/checksanalysis.py +++ b/src/Mod/Fem/femtools/checksanalysis.py @@ -43,10 +43,7 @@ def check_member_for_solver_calculix(analysis, solver, mesh, member): # solver if solver.AnalysisType not in ANALYSIS_TYPES: - message += ( - "Unknown analysis type: {}\n" - .format(solver.AnalysisType) - ) + message += f"Unknown analysis type: {solver.AnalysisType}\n" if solver.AnalysisType == "frequency": if not hasattr(solver, "EigenmodeHighLimit"): message += "Frequency analysis: Solver has no EigenmodeHighLimit.\n" @@ -54,8 +51,7 @@ def check_member_for_solver_calculix(analysis, solver, mesh, member): message += "Frequency analysis: Solver has no EigenmodeLowLimit.\n" elif not hasattr(solver, "EigenmodesCount"): message += "Frequency analysis: Solver has no EigenmodesCount.\n" - if hasattr(solver, "MaterialNonlinearity") \ - and solver.MaterialNonlinearity == "nonlinear": + if hasattr(solver, "MaterialNonlinearity") and solver.MaterialNonlinearity == "nonlinear": if not member.mats_nonlinear: message += ( "Solver is set to nonlinear materials, " @@ -66,27 +62,33 @@ def check_member_for_solver_calculix(analysis, solver, mesh, member): if not mesh: message += "No mesh object defined in the analysis.\n" if mesh: - if mesh.FemMesh.VolumeCount == 0 \ - and mesh.FemMesh.FaceCount > 0 \ - and not member.geos_shellthickness: + if ( + mesh.FemMesh.VolumeCount == 0 + and mesh.FemMesh.FaceCount > 0 + and not member.geos_shellthickness + ): message += ( "FEM mesh has no volume elements, " "either define a shell thicknesses or " "provide a FEM mesh with volume elements.\n" ) - if mesh.FemMesh.VolumeCount == 0 \ - and mesh.FemMesh.FaceCount == 0 \ - and mesh.FemMesh.EdgeCount > 0 \ - and not member.geos_beamsection \ - and not member.geos_fluidsection: + if ( + mesh.FemMesh.VolumeCount == 0 + and mesh.FemMesh.FaceCount == 0 + and mesh.FemMesh.EdgeCount > 0 + and not member.geos_beamsection + and not member.geos_fluidsection + ): message += ( "FEM mesh has no volume and no shell elements, " "either define a beam/fluid section or provide " "a FEM mesh with volume elements.\n" ) - if mesh.FemMesh.VolumeCount == 0 \ - and mesh.FemMesh.FaceCount == 0 \ - and mesh.FemMesh.EdgeCount == 0: + if ( + mesh.FemMesh.VolumeCount == 0 + and mesh.FemMesh.FaceCount == 0 + and mesh.FemMesh.EdgeCount == 0 + ): message += ( "FEM mesh has neither volume nor shell or edge elements. " "Provide a FEM mesh with elements.\n" @@ -217,9 +219,7 @@ def check_member_for_solver_calculix(analysis, solver, mesh, member): # is done, because an analysis without loads at all is a valid analysis too if solver.AnalysisType == "static": if not (member.cons_fixed or member.cons_displacement or member.cons_rigidbody): - message += ( - "Static analysis: No mechanical boundary conditions defined.\n" - ) + message += "Static analysis: No mechanical boundary conditions defined.\n" if solver.AnalysisType == "thermomech": if not member.cons_initialtemperature: if not member.geos_fluidsection: @@ -255,9 +255,8 @@ def check_member_for_solver_calculix(analysis, solver, mesh, member): for reference in c["Object"].References: items += len(reference[1]) if items != 2: - message += ( - "{} doesn't reference exactly two needed faces.\n" - .format(c["Object"].Name) + message += "{} doesn't reference exactly two needed faces.\n".format( + c["Object"].Name ) # sectionprint if member.cons_sectionprint: @@ -266,9 +265,8 @@ def check_member_for_solver_calculix(analysis, solver, mesh, member): for reference in c["Object"].References: items += len(reference[1]) if items != 1: - message += ( - "{} doesn't reference exactly one needed face.\n" - .format(c["Object"].Name) + message += "{} doesn't reference exactly one needed face.\n".format( + c["Object"].Name ) # transform if member.cons_transform: @@ -322,25 +320,16 @@ def check_member_for_solver_calculix(analysis, solver, mesh, member): has_no_references = True if mesh: if mesh.FemMesh.FaceCount > 0 or mesh.FemMesh.VolumeCount > 0: - message += ( - "Beam sections defined but FEM mesh has volume or shell elements.\n" - ) + message += "Beam sections defined but FEM mesh has volume or shell elements.\n" if mesh.FemMesh.EdgeCount == 0: - message += ( - "Beam sections defined but FEM mesh has no edge elements.\n" - ) - if not ( - hasattr(mesh, "Shape") - or hasattr(mesh, "Part") - ): + message += "Beam sections defined but FEM mesh has no edge elements.\n" + if not (hasattr(mesh, "Shape") or hasattr(mesh, "Part")): message += ( "Mesh without geometry link. " "The mesh needs to know its geometry for the beam rotations.\n" ) if len(member.geos_beamrotation) > 1: - message += ( - "Multiple beam rotations in one analysis are not supported at the moment.\n" - ) + message += "Multiple beam rotations in one analysis are not supported at the moment.\n" # beam rotations if member.geos_beamrotation and not member.geos_beamsection: message += "Beam rotations in the analysis but no beam sections defined.\n" @@ -363,9 +352,7 @@ def check_member_for_solver_calculix(analysis, solver, mesh, member): # fluid section if member.geos_fluidsection: if not member.cons_selfweight: - message += ( - "A fluid network analysis requires self weight constraint to be applied\n" - ) + message += "A fluid network analysis requires self weight constraint to be applied\n" if solver.AnalysisType != "thermomech": message += "A fluid network analysis can only be done in a thermomech analysis\n" has_no_references = False @@ -379,12 +366,11 @@ def check_member_for_solver_calculix(analysis, solver, mesh, member): has_no_references = True if mesh: if mesh.FemMesh.FaceCount > 0 or mesh.FemMesh.VolumeCount > 0: - message += ( - "Fluid sections defined but FEM mesh has volume or shell elements.\n" - ) + message += "Fluid sections defined but FEM mesh has volume or shell elements.\n" if mesh.FemMesh.EdgeCount == 0: message += "Fluid sections defined but FEM mesh has no edge elements.\n" return message + ## @} diff --git a/src/Mod/Fem/femtools/femutils.py b/src/Mod/Fem/femtools/femutils.py index fed9b162a0..ccc7d57a3a 100644 --- a/src/Mod/Fem/femtools/femutils.py +++ b/src/Mod/Fem/femtools/femutils.py @@ -37,6 +37,7 @@ import subprocess from platform import system import FreeCAD + if FreeCAD.GuiUp: import FreeCADGui from PySide import QtGui @@ -45,7 +46,7 @@ if FreeCAD.GuiUp: # ************************************************************************************************ # document objects def createObject(doc, name, proxy, viewProxy=None): - """ Add python object to document using python type string. + """Add python object to document using python type string. Add a document object suitable for the *proxy* and the *viewProxy* to *doc* and attach it to the *proxy* and the *viewProxy*. This function can only be @@ -70,7 +71,7 @@ def createObject(doc, name, proxy, viewProxy=None): # typeID and object type defs def type_of_obj(obj): - """ Return type of *obj* honoring the special typesystem of Fem. + """Return type of *obj* honoring the special typesystem of Fem. Python objects of the Fem workbench define their type via a class member ``.Type``. Return this type if the property exists. If not return @@ -84,7 +85,7 @@ def type_of_obj(obj): def is_of_type(obj, ty): - """ Compare type of *obj* with *ty* honoring Fems typesystem. + """Compare type of *obj* with *ty* honoring Fems typesystem. See :py:func:`type_of_obj` for more info about the special typesystem of the Fem module. @@ -98,7 +99,7 @@ def is_of_type(obj, ty): def is_derived_from(obj, t): - """ Check if *obj* is derived from *t* honoring Fems typesystem. + """Check if *obj* is derived from *t* honoring Fems typesystem. Essentially just call ``obj.isDerivedFrom(t)`` and return it's value. For objects using Fems typesystem (see :py:func:`type_of_obj`) return always @@ -110,7 +111,7 @@ def is_derived_from(obj, t): ``obj.isDerivedFrom`` is called as usual. See https://forum.freecad.org/viewtopic.php?f=10&t=32625 """ - if (hasattr(obj, "Proxy") and hasattr(obj.Proxy, "Type") and obj.Proxy.Type == t): + if hasattr(obj, "Proxy") and hasattr(obj.Proxy, "Type") and obj.Proxy.Type == t: return True return obj.isDerivedFrom(t) @@ -118,7 +119,7 @@ def is_derived_from(obj, t): # ************************************************************************************************ # working dir def get_pref_working_dir(solver_obj): - """ Return working directory for solver honoring user settings. + """Return working directory for solver honoring user settings. :throws femtools.errors.MustSaveError: If user setting is set to BESIDE and the document isn't saved. @@ -129,6 +130,7 @@ def get_pref_working_dir(solver_obj): instead. """ from femsolver import settings + dir_setting = settings.get_dir_setting() if dir_setting == settings.DirSetting.TEMPORARY: setting_working_dir = get_temp_dir(solver_obj) @@ -146,6 +148,7 @@ def get_pref_working_dir(solver_obj): # the FEM preferences will be used by both def get_temp_dir(obj=None): from tempfile import mkdtemp + return mkdtemp(prefix="fcfem_") @@ -159,8 +162,7 @@ def get_beside_dir(obj): def get_custom_dir(obj): base = get_custom_base(obj) - specific_path = os.path.join( - base, obj.Document.Name, obj.Label) + specific_path = os.path.join(base, obj.Document.Name, obj.Label) if not os.path.isdir(specific_path): make_dir(specific_path) return specific_path @@ -173,15 +175,16 @@ def get_beside_base(obj): error_message = ( "Please save the file before executing a solver or creating a mesh. " "This must be done because the location of the working directory " - "is set to \"Beside *.FCStd File\". For the moment the tmp dir {} is used." - .format(new_path) + 'is set to "Beside *.FCStd File". For the moment the tmp dir {} is used.'.format( + new_path + ) ) - FreeCAD.Console.PrintError("{}\n".format(error_message)) + FreeCAD.Console.PrintError(f"{error_message}\n") if FreeCAD.GuiUp: QtGui.QMessageBox.critical( FreeCADGui.getMainWindow(), "Can't start Solver or Mesh creation besides FC file.", - error_message + error_message, ) # from .errors import MustSaveError @@ -193,20 +196,18 @@ def get_beside_base(obj): def get_custom_base(solver): from femsolver.settings import get_custom_dir + path = get_custom_dir() if not os.path.isdir(path): new_path = get_temp_dir() error_message = ( "Selected working directory {} doesn't exist. " - " For the moment the tmp dir {} is used." - .format(path, new_path) + " For the moment the tmp dir {} is used.".format(path, new_path) ) - FreeCAD.Console.PrintError("{}\n".format(error_message)) + FreeCAD.Console.PrintError(f"{error_message}\n") if FreeCAD.GuiUp: QtGui.QMessageBox.critical( - FreeCADGui.getMainWindow(), - "Can't start Solver or Mesh creation.", - error_message + FreeCADGui.getMainWindow(), "Can't start Solver or Mesh creation.", error_message ) # from .errors import DirectoryDoesNotExistError # raise DirectoryDoesNotExistError("Invalid path") @@ -218,6 +219,7 @@ def check_working_dir(wdir): # check if working_dir exist, if not use a tmp dir and inform the user # print(wdir) from os.path import isdir + if isdir(wdir): return True else: @@ -233,10 +235,9 @@ def make_dir(specific_path): # beside dir fails on installed FC examples from start wb error_message = ( "Failed to create the directory {}. " - " For the moment the tmp dir {} is used." - .format(specific_path, new_path) + " For the moment the tmp dir {} is used.".format(specific_path, new_path) ) - FreeCAD.Console.PrintError("{}\n".format(error_message)) + FreeCAD.Console.PrintError(f"{error_message}\n") return new_path return specific_path @@ -261,7 +262,7 @@ def get_part_to_mesh(mesh_obj): def getBoundBoxOfAllDocumentShapes(doc): - """ Calculate bounding box containing all objects inside *doc*. + """Calculate bounding box containing all objects inside *doc*. :returns: A bounding box containing all objects that have a *Shape* attribute (all @@ -279,18 +280,18 @@ def getBoundBoxOfAllDocumentShapes(doc): try: FreeCAD.Console.PrintMessage( - "trying: {}: getPropertyOfGeometry()\n".format(o.Label) + f"trying: {o.Label}: getPropertyOfGeometry()\n" ) # debug only bb = o.getPropertyOfGeometry().BoundBox - FreeCAD.Console.PrintMessage("{}\n".format(bb)) # debug only + FreeCAD.Console.PrintMessage(f"{bb}\n") # debug only except Exception: FreeCAD.Console.PrintMessage("exception \n") # debug only if bb is None: try: - FreeCAD.Console.PrintMessage("trying: {}: FemMesh\n".format(o.Label)) # debug only + FreeCAD.Console.PrintMessage(f"trying: {o.Label}: FemMesh\n") # debug only bb = o.FemMesh.BoundBox - FreeCAD.Console.PrintMessage("{}\n".format(bb)) # debug only + FreeCAD.Console.PrintMessage(f"{bb}\n") # debug only except Exception: FreeCAD.Console.PrintMessage("exception \n") # debug only @@ -300,15 +301,15 @@ def getBoundBoxOfAllDocumentShapes(doc): overallboundbox = bb else: overallboundbox.add(bb) - else: # debug only - FreeCAD.Console.PrintMessage("no bb\n") # debug only + else: # debug only + FreeCAD.Console.PrintMessage("no bb\n") # debug only - FreeCAD.Console.PrintMessage("overallBB:" + str(overallboundbox) + "\n") # debug only + FreeCAD.Console.PrintMessage("overallBB:" + str(overallboundbox) + "\n") # debug only return overallboundbox def getSelectedFace(selectionex): - """ Return selected face if exactly one face is selected. + """Return selected face if exactly one face is selected. :returns: The selected face as a ``Part::TopoShape`` if exactly one face is selected. @@ -337,7 +338,7 @@ def getSelectedFace(selectionex): def get_refshape_type(fem_doc_object): - """ Return shape type the constraints references. + """Return shape type the constraints references. Determine single shape type of references of *fem_doc_object* which must be a constraint (=have a *References* property). All references must be of the @@ -359,30 +360,29 @@ def get_refshape_type(fem_doc_object): Undefined behaviour if constraint contains no references (empty list). """ from femtools.geomtools import get_element + if hasattr(fem_doc_object, "References") and fem_doc_object.References: first_ref_obj = fem_doc_object.References[0] first_ref_shape = get_element(first_ref_obj[0], first_ref_obj[1][0]) st = first_ref_shape.ShapeType FreeCAD.Console.PrintLog( - "References: {} in {}, {}\n" - . format(st, fem_doc_object.Name, fem_doc_object.Label) + f"References: {st} in {fem_doc_object.Name}, {fem_doc_object.Label}\n" ) return st else: FreeCAD.Console.PrintLog( - "References: empty in {}, {}\n" - . format(fem_doc_object.Name, fem_doc_object.Label) + f"References: empty in {fem_doc_object.Name}, {fem_doc_object.Label}\n" ) return "" def pydecode(bytestring): - """ Return *bytestring* as a unicode string """ + """Return *bytestring* as a unicode string""" return bytestring.decode("utf-8") def startProgramInfo(code): - """ starts a program under Windows minimized, hidden or normal """ + """starts a program under Windows minimized, hidden or normal""" if system() == "Windows": info = subprocess.STARTUPINFO() if code == "hide": @@ -399,7 +399,7 @@ def startProgramInfo(code): def expandParentObject(): - """ expands parent and selected obj in tree view """ + """expands parent and selected obj in tree view""" trees = FreeCADGui.getMainWindow().findChildren(QtGui.QTreeWidget) for tree in trees: items = tree.selectedItems() @@ -413,7 +413,7 @@ def getOutputWinColor(type): """ type: 'Error', 'Warning', 'Logging', 'Text' """ - col_int = FreeCAD.ParamGet( - "User parameter:BaseApp/Preferences/OutputWindow" - ).GetUnsigned("color" + type) - return "#{:08X}".format(col_int)[:-2] + col_int = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/OutputWindow").GetUnsigned( + "color" + type + ) + return f"#{col_int:08X}"[:-2] diff --git a/src/Mod/Fem/femtools/geomtools.py b/src/Mod/Fem/femtools/geomtools.py index bd3f502df7..fd186877fb 100644 --- a/src/Mod/Fem/femtools/geomtools.py +++ b/src/Mod/Fem/femtools/geomtools.py @@ -29,10 +29,7 @@ import FreeCAD # ************************************************************************************************ -def find_element_in_shape( - aShape, - anElement -): +def find_element_in_shape(aShape, anElement): # import Part ele_st = anElement.ShapeType if ele_st == "Solid" or ele_st == "CompSolid": @@ -84,10 +81,7 @@ def find_element_in_shape( # ************************************************************************************************ -def get_vertexes_by_element( - aShape, - anElement -): +def get_vertexes_by_element(aShape, anElement): # we're going to extend the method find_element_in_shape and return the vertexes # import Part ele_vertexes = [] @@ -133,10 +127,7 @@ def get_vertexes_by_element( # ************************************************************************************************ -def is_same_geometry( - shape1, - shape2 -): +def is_same_geometry(shape1, shape2): # the vertexes and the CenterOfMass are compared # it is a hack, but I do not know any better ! # check of Volume and Area before starting with the vertices could be added @@ -172,10 +163,7 @@ def is_same_geometry( # ************************************************************************************************ -def get_element( - part, - element -): +def get_element(part, element): if element.startswith("Solid"): index = int(element.lstrip("Solid")) - 1 if index >= len(part.Shape.Solids): diff --git a/src/Mod/Fem/femtools/membertools.py b/src/Mod/Fem/femtools/membertools.py index 6445ff7e01..4ba30c7f6e 100644 --- a/src/Mod/Fem/femtools/membertools.py +++ b/src/Mod/Fem/femtools/membertools.py @@ -37,7 +37,7 @@ from . import femutils def get_member(analysis, t): - """ Return list of all members of *analysis* of type *t*. + """Return list of all members of *analysis* of type *t*. Search *analysis* for members of type *t*. This method checks the custom python typesystem (BaseType class property) used by the Fem module if @@ -59,16 +59,15 @@ def get_member(analysis, t): for m in analysis.Group: # since is _derived_from is used the father could be used # to test too (ex. "Fem::FemMeshObject") - if (femutils.is_derived_from(m, t) - and not (m.hasExtension("App::SuppressibleExtension") - and m.Suppressed) - ): + if femutils.is_derived_from(m, t) and not ( + m.hasExtension("App::SuppressibleExtension") and m.Suppressed + ): matching.append(m) return matching def get_single_member(analysis, t): - """ Return one object of type *t* and part of *analysis*. + """Return one object of type *t* and part of *analysis*. Search *analysis* for members of type *t* and return the first one that's found. This method checks the custom python typesystem (BaseType class @@ -90,7 +89,7 @@ def get_single_member(analysis, t): def get_several_member(analysis, t): - """ Get members and pack them for Calculix/Z88. + """Get members and pack them for Calculix/Z88. Collect members by calling :py:func:`get_member` and pack them into a data structure that can be consumed by calculix and Z88 solver modules. @@ -132,7 +131,7 @@ def get_several_member(analysis, t): def get_mesh_to_solve(analysis): - """ Find one and only mesh object of *analysis*. + """Find one and only mesh object of *analysis*. :returns: A tuple ``(object, message)``. If and only if the analysis contains @@ -157,7 +156,7 @@ def get_mesh_to_solve(analysis): return (None, "FEM: no mesh object found in analysis.") -class AnalysisMember(): +class AnalysisMember: def __init__(self, analysis): self.analysis = analysis @@ -254,89 +253,39 @@ class AnalysisMember(): # get member # constants - self.cota_vacuumpermittivity = self.get_several_member( - "Fem::ConstantVacuumPermittivity" - ) + self.cota_vacuumpermittivity = self.get_several_member("Fem::ConstantVacuumPermittivity") # materials - std_mats = self.get_several_member( - "Fem::MaterialCommon" - ) - rei_mats = self.get_several_member( - "Fem::MaterialReinforced" - ) + std_mats = self.get_several_member("Fem::MaterialCommon") + rei_mats = self.get_several_member("Fem::MaterialReinforced") self.mats_linear = std_mats + rei_mats - self.mats_nonlinear = self.get_several_member( - "Fem::MaterialMechanicalNonlinear" - ) + self.mats_nonlinear = self.get_several_member("Fem::MaterialMechanicalNonlinear") # geometries - self.geos_beamsection = self.get_several_member( - "Fem::ElementGeometry1D" - ) - self.geos_beamrotation = self.get_several_member( - "Fem::ElementRotation1D" - ) - self.geos_fluidsection = self.get_several_member( - "Fem::ElementFluid1D" - ) - self.geos_shellthickness = self.get_several_member( - "Fem::ElementGeometry2D" - ) + self.geos_beamsection = self.get_several_member("Fem::ElementGeometry1D") + self.geos_beamrotation = self.get_several_member("Fem::ElementRotation1D") + self.geos_fluidsection = self.get_several_member("Fem::ElementFluid1D") + self.geos_shellthickness = self.get_several_member("Fem::ElementGeometry2D") # constraints - self.cons_centrif = self.get_several_member( - "Fem::ConstraintCentrif" - ) - self.cons_bodyheatsource = self.get_several_member( - "Fem::ConstraintBodyHeatSource" - ) - self.cons_contact = self.get_several_member( - "Fem::ConstraintContact" - ) - self.cons_displacement = self.get_several_member( - "Fem::ConstraintDisplacement" - ) - self.cons_fixed = self.get_several_member( - "Fem::ConstraintFixed" - ) - self.cons_rigidbody = self.get_several_member( - "Fem::ConstraintRigidBody" - ) - self.cons_rigidbody_step = self.get_several_member( - "Fem::ConstraintRigidBody" - ) - self.cons_force = self.get_several_member( - "Fem::ConstraintForce" - ) - self.cons_heatflux = self.get_several_member( - "Fem::ConstraintHeatflux" - ) - self.cons_initialtemperature = self.get_several_member( - "Fem::ConstraintInitialTemperature" - ) - self.cons_planerotation = self.get_several_member( - "Fem::ConstraintPlaneRotation" - ) - self.cons_pressure = self.get_several_member( - "Fem::ConstraintPressure" - ) - self.cons_sectionprint = self.get_several_member( - "Fem::ConstraintSectionPrint" - ) - self.cons_selfweight = self.get_several_member( - "Fem::ConstraintSelfWeight" - ) - self.cons_temperature = self.get_several_member( - "Fem::ConstraintTemperature" - ) - self.cons_tie = self.get_several_member( - "Fem::ConstraintTie" - ) - self.cons_transform = self.get_several_member( - "Fem::ConstraintTransform" - ) + self.cons_centrif = self.get_several_member("Fem::ConstraintCentrif") + self.cons_bodyheatsource = self.get_several_member("Fem::ConstraintBodyHeatSource") + self.cons_contact = self.get_several_member("Fem::ConstraintContact") + self.cons_displacement = self.get_several_member("Fem::ConstraintDisplacement") + self.cons_fixed = self.get_several_member("Fem::ConstraintFixed") + self.cons_rigidbody = self.get_several_member("Fem::ConstraintRigidBody") + self.cons_rigidbody_step = self.get_several_member("Fem::ConstraintRigidBody") + self.cons_force = self.get_several_member("Fem::ConstraintForce") + self.cons_heatflux = self.get_several_member("Fem::ConstraintHeatflux") + self.cons_initialtemperature = self.get_several_member("Fem::ConstraintInitialTemperature") + self.cons_planerotation = self.get_several_member("Fem::ConstraintPlaneRotation") + self.cons_pressure = self.get_several_member("Fem::ConstraintPressure") + self.cons_sectionprint = self.get_several_member("Fem::ConstraintSectionPrint") + self.cons_selfweight = self.get_several_member("Fem::ConstraintSelfWeight") + self.cons_temperature = self.get_several_member("Fem::ConstraintTemperature") + self.cons_tie = self.get_several_member("Fem::ConstraintTie") + self.cons_transform = self.get_several_member("Fem::ConstraintTransform") def get_several_member(self, t): return get_several_member(self.analysis, t) diff --git a/src/Mod/Fem/femtools/migrate_app.py b/src/Mod/Fem/femtools/migrate_app.py index ad3086f18b..48a09fbe0f 100644 --- a/src/Mod/Fem/femtools/migrate_app.py +++ b/src/Mod/Fem/femtools/migrate_app.py @@ -33,7 +33,7 @@ __url__ = "https://www.freecad.org" import FreeCAD -class FemMigrateApp(object): +class FemMigrateApp: def find_module(self, fullname, path): @@ -185,6 +185,7 @@ class FemMigrateApp(object): return self if module.__name__ == "femsolver.elmer.equations.fluxsolver": import femsolver.elmer.equations.flux + module.Proxy = femsolver.elmer.equations.flux.Proxy if FreeCAD.GuiUp: module.ViewProxy = femsolver.elmer.equations.flux.ViewProxy @@ -193,212 +194,285 @@ class FemMigrateApp(object): module.__path__ = "femobjects" if module.__name__ == "femobjects._FemConstraintBodyHeatSource": import femobjects.constraint_bodyheatsource + module.Proxy = femobjects.constraint_bodyheatsource.ConstraintBodyHeatSource if module.__name__ == "femobjects._FemConstraintElectrostaticPotential": import femobjects.constraint_electrostaticpotential - module.Proxy = \ + + module.Proxy = ( femobjects.constraint_electrostaticpotential.ConstraintElectrostaticPotential + ) if module.__name__ == "femobjects._FemConstraintFlowVelocity": import femobjects.constraint_flowvelocity + module.Proxy = femobjects.constraint_flowvelocity.ConstraintFlowVelocity if module.__name__ == "femobjects._FemConstraintInitialFlowVelocity": import femobjects.constraint_initialflowvelocity + module.Proxy = femobjects.constraint_initialflowvelocity.ConstraintInitialFlowVelocity if module.__name__ == "femobjects._FemConstraintSelfWeight": import femobjects.constraint_selfweight + module._FemConstraintSelfWeight = femobjects.constraint_selfweight.ConstraintSelfWeight if module.__name__ == "femobjects._FemConstraintTie": import femobjects.constraint_tie + module._FemConstraintTie = femobjects.constraint_tie.ConstraintTie if module.__name__ == "femobjects._FemElementFluid1D": import femobjects.element_fluid1D + module._FemElementFluid1D = femobjects.element_fluid1D.ElementFluid1D if module.__name__ == "femobjects._FemElementGeometry1D": import femobjects.element_geometry1D + module._FemElementGeometry1D = femobjects.element_geometry1D.ElementGeometry1D if module.__name__ == "femobjects._FemElementGeometry2D": import femobjects.element_geometry2D + module._FemElementGeometry2D = femobjects.element_geometry2D.ElementGeometry2D if module.__name__ == "femobjects._FemElementRotation1D": import femobjects.element_rotation1D + module._FemElementRotation1D = femobjects.element_rotation1D.ElementRotation1D if module.__name__ == "femobjects._FemMaterial": import femobjects.material_common + module._FemMaterial = femobjects.material_common.MaterialCommon if module.__name__ == "femobjects._FemMaterialMechanicalNonlinear": import femobjects.material_mechanicalnonlinear - module._FemMaterialMechanicalNonlinear = \ + + module._FemMaterialMechanicalNonlinear = ( femobjects.material_mechanicalnonlinear.MaterialMechanicalNonlinear + ) if module.__name__ == "femobjects._FemMaterialReinforced": import femobjects.material_reinforced + module._FemMaterialReinforced = femobjects.material_reinforced.MaterialReinforced if module.__name__ == "femobjects._FemMeshBoundaryLayer": import femobjects.mesh_boundarylayer + module._FemMeshBoundaryLayer = femobjects.mesh_boundarylayer.MeshBoundaryLayer if module.__name__ == "femobjects._FemMeshGmsh": import femobjects.mesh_gmsh + module._FemMeshGmsh = femobjects.mesh_gmsh.MeshGmsh if module.__name__ == "femobjects._FemMeshGroup": import femobjects.mesh_group + module._FemMeshGroup = femobjects.mesh_group.MeshGroup if module.__name__ == "femobjects._FemMeshRegion": import femobjects.mesh_region + module._FemMeshRegion = femobjects.mesh_region.MeshRegion if module.__name__ == "femobjects._FemMeshResult": import femobjects.mesh_result + module._FemMeshResult = femobjects.mesh_result.MeshResult if module.__name__ == "femobjects._FemResultMechanical": import femobjects.result_mechanical + module._FemResultMechanical = femobjects.result_mechanical.ResultMechanical if module.__name__ == "femobjects._FemSolverCalculix": import femobjects.solver_ccxtools + module._FemSolverCalculix = femobjects.solver_ccxtools.SolverCcxTools if module.__name__ == "PyObjects": module.__path__ = "PyObjects" if module.__name__ == "PyObjects._FemConstraintBodyHeatSource": import femobjects.constraint_bodyheatsource + module.Proxy = femobjects.constraint_bodyheatsource.ConstraintBodyHeatSource if module.__name__ == "PyObjects._FemConstraintElectrostaticPotential": import femobjects.constraint_electrostaticpotential - module.Proxy = \ + + module.Proxy = ( femobjects.constraint_electrostaticpotential.ConstraintElectrostaticPotential + ) if module.__name__ == "PyObjects._FemConstraintFlowVelocity": import femobjects.constraint_flowvelocity + module.Proxy = femobjects.constraint_flowvelocity.ConstraintFlowVelocity if module.__name__ == "PyObjects._FemConstraintInitialFlowVelocity": import femobjects.constraint_initialflowvelocity + module.Proxy = femobjects.constraint_initialflowvelocity.ConstraintInitialFlowVelocity if module.__name__ == "PyObjects._FemConstraintSelfWeight": import femobjects.constraint_selfweight + module._FemConstraintSelfWeight = femobjects.constraint_selfweight.ConstraintSelfWeight if module.__name__ == "PyObjects._FemElementFluid1D": import femobjects.element_fluid1D + module._FemElementFluid1D = femobjects.element_fluid1D.ElementFluid1D if module.__name__ == "PyObjects._FemElementGeometry1D": import femobjects.element_geometry1D + module._FemElementGeometry1D = femobjects.element_geometry1D.ElementGeometry1D if module.__name__ == "PyObjects._FemElementGeometry2D": import femobjects.element_geometry2D + module._FemElementGeometry2D = femobjects.element_geometry2D.ElementGeometry2D if module.__name__ == "PyObjects._FemElementRotation1D": import femobjects.element_rotation1D + module._FemElementRotation1D = femobjects.element_rotation1D.ElementRotation1D if module.__name__ == "PyObjects._FemMaterial": import femobjects.material_common + module._FemMaterial = femobjects.material_common.MaterialCommon if module.__name__ == "PyObjects._FemMaterialMechanicalNonlinear": import femobjects.material_mechanicalnonlinear - module._FemMaterialMechanicalNonlinear = \ + + module._FemMaterialMechanicalNonlinear = ( femobjects.material_mechanicalnonlinear.MaterialMechanicalNonlinear + ) if module.__name__ == "PyObjects._FemMeshBoundaryLayer": import femobjects.mesh_boundarylayer + module._FemMeshBoundaryLayer = femobjects.mesh_boundarylayer.MeshBoundaryLayer if module.__name__ == "PyObjects._FemMeshGmsh": import femobjects.mesh_gmsh + module._FemMeshGmsh = femobjects.mesh_gmsh.MeshGmsh if module.__name__ == "PyObjects._FemMeshGroup": import femobjects.mesh_group + module._FemMeshGroup = femobjects.mesh_group.MeshGroup if module.__name__ == "PyObjects._FemMeshRegion": import femobjects.mesh_region + module._FemMeshRegion = femobjects.mesh_region.MeshRegion if module.__name__ == "PyObjects._FemMeshResult": import femobjects.mesh_result + module._FemMeshResult = femobjects.mesh_result.MeshResult if module.__name__ == "PyObjects._FemResultMechanical": import femobjects.result_mechanical + module._FemResultMechanical = femobjects.result_mechanical.ResultMechanical if module.__name__ == "PyObjects._FemSolverCalculix": import femobjects.solver_ccxtools + module._FemSolverCalculix = femobjects.solver_ccxtools.SolverCcxTools if module.__name__ == "PyObjects._FemSolverZ88": import femsolver.z88.solver + module._FemSolverZ88 = femsolver.z88.solver.Proxy if module.__name__ == "PyObjects._FemBeamSection": import femobjects.element_geometry1D + module._FemBeamSection = femobjects.element_geometry1D.ElementGeometry1D if module.__name__ == "PyObjects._FemFluidSection": import femobjects.element_fluid1D + module._FemFluidSection = femobjects.element_fluid1D.ElementFluid1D if module.__name__ == "PyObjects._FemShellThickness": import femobjects.element_geometry2D + module._FemShellThickness = femobjects.element_geometry2D.ElementGeometry2D if module.__name__ == "_FemBeamSection": import femobjects.element_geometry1D + module._FemBeamSection = femobjects.element_geometry1D.ElementGeometry1D if module.__name__ == "_FemConstraintSelfWeight": import femobjects.constraint_selfweight + module._FemConstraintSelfWeight = femobjects.constraint_selfweight.ConstraintSelfWeight if module.__name__ == "_FemMaterial": import femobjects.material_common + module._FemMaterial = femobjects.material_common.MaterialCommon if module.__name__ == "_FemMaterialMechanicalNonlinear": import femobjects.material_mechanicalnonlinear - module._FemMaterialMechanicalNonlinear = \ + + module._FemMaterialMechanicalNonlinear = ( femobjects.material_mechanicalnonlinear.MaterialMechanicalNonlinear + ) if module.__name__ == "_FemMeshGmsh": import femobjects.mesh_gmsh + module._FemMeshGmsh = femobjects.mesh_gmsh.MeshGmsh if module.__name__ == "_FemMeshGroup": import femobjects.mesh_group + module._FemMeshGroup = femobjects.mesh_group.MeshGroup if module.__name__ == "_FemMeshRegion": import femobjects.mesh_region + module._FemMeshRegion = femobjects.mesh_region.MeshRegion if module.__name__ == "_FemResultMechanical": import femobjects.result_mechanical + module._FemResultMechanical = femobjects.result_mechanical.ResultMechanical if module.__name__ == "_FemShellThickness": import femobjects.element_geometry2D + module._FemShellThickness = femobjects.element_geometry2D.ElementGeometry2D if module.__name__ == "_FemSolverCalculix": import femobjects.solver_ccxtools + module._FemSolverCalculix = femobjects.solver_ccxtools.SolverCcxTools if module.__name__ == "_FemSolverZ88": import femsolver.z88.solver + module._FemSolverZ88 = femsolver.z88.solver.Proxy if module.__name__ == "_FemMechanicalResult": import femobjects.result_mechanical + module._FemMechanicalResult = femobjects.result_mechanical.ResultMechanical if module.__name__ == "FemResult": import femobjects.result_mechanical + module.FemResult = femobjects.result_mechanical.ResultMechanical if module.__name__ == "_MechanicalMaterial": import femobjects.material_common + module._MechanicalMaterial = femobjects.material_common.MaterialCommon if module.__name__ == "FemBeamSection": import femobjects.element_geometry1D + module._FemBeamSection = femobjects.element_geometry1D.ElementGeometry1D if FreeCAD.GuiUp: import femviewprovider.view_element_geometry1D - module._ViewProviderFemBeamSection = \ + + module._ViewProviderFemBeamSection = ( femviewprovider.view_element_geometry1D.VPElementGeometry1D + ) if module.__name__ == "FemShellThickness": import femobjects.element_geometry2D + module._FemShellThickness = femobjects.element_geometry2D.ElementGeometry2D if FreeCAD.GuiUp: import femviewprovider.view_element_geometry2D - module._ViewProviderFemShellThickness = \ + + module._ViewProviderFemShellThickness = ( femviewprovider.view_element_geometry2D.VPElementGeometry2D + ) if module.__name__ == "MechanicalAnalysis": import femobjects.base_fempythonobject + module._FemAnalysis = femobjects.base_fempythonobject.BaseFemPythonObject if FreeCAD.GuiUp: import femviewprovider.view_base_femobject - module._ViewProviderFemAnalysis = \ + + module._ViewProviderFemAnalysis = ( femviewprovider.view_base_femobject.VPBaseFemObject + ) if module.__name__ == "MechanicalMaterial": import femobjects.material_common + module._MechanicalMaterial = femobjects.material_common.MaterialCommon if FreeCAD.GuiUp: import femviewprovider.view_material_common - module._ViewProviderMechanicalMaterial = \ + + module._ViewProviderMechanicalMaterial = ( femviewprovider.view_material_common.VPMaterialCommon + ) return None diff --git a/src/Mod/Fem/femtools/tokrules.py b/src/Mod/Fem/femtools/tokrules.py index bfeb2bb1a1..c1438b1336 100644 --- a/src/Mod/Fem/femtools/tokrules.py +++ b/src/Mod/Fem/femtools/tokrules.py @@ -26,40 +26,40 @@ __author__ = "Werner Mayer" __url__ = "https://www.freecad.org" tokens = ( - 'NAME', - 'FLOAT', - 'INT', - 'PLUS', - 'MINUS', - 'TIMES', - 'DIVIDE', - 'EQUALS', - 'LPAREN', - 'RPAREN', - 'POWER' + "NAME", + "FLOAT", + "INT", + "PLUS", + "MINUS", + "TIMES", + "DIVIDE", + "EQUALS", + "LPAREN", + "RPAREN", + "POWER", ) # Tokens -t_PLUS = r'\+' -t_MINUS = r'-' -t_TIMES = r'\*' -t_DIVIDE = r'/' -t_EQUALS = r'=' -t_LPAREN = r'\(' -t_RPAREN = r'\)' -t_POWER = r'\^' -t_NAME = r'[a-zA-Z_][a-zA-Z0-9_]*' +t_PLUS = r"\+" +t_MINUS = r"-" +t_TIMES = r"\*" +t_DIVIDE = r"/" +t_EQUALS = r"=" +t_LPAREN = r"\(" +t_RPAREN = r"\)" +t_POWER = r"\^" +t_NAME = r"[a-zA-Z_][a-zA-Z0-9_]*" def t_FLOAT(t): - r'\d+\.(\d+)?([eE][-+]?\d+)?' + r"\d+\.(\d+)?([eE][-+]?\d+)?" t.value = float(t.value) return t def t_INT(t): - r'\d+' + r"\d+" t.value = int(t.value) return t @@ -69,12 +69,12 @@ t_ignore = " \t" def t_COMMENT(t): - r'\#.*' + r"\#.*" pass def t_newline(t): - r'\n+' + r"\n+" t.lexer.lineno += t.value.count("\n") @@ -85,15 +85,16 @@ def t_error(t): # Build the lexer import ply.lex as lex + lex.lex() # Precedence rules for the arithmetic operators precedence = ( - ('left', 'PLUS', 'MINUS'), - ('left', 'TIMES', 'DIVIDE'), - ('left', 'POWER'), - ('right', 'UMINUS') + ("left", "PLUS", "MINUS"), + ("left", "TIMES", "DIVIDE"), + ("left", "POWER"), + ("right", "UMINUS"), ) # dictionary of names (for storing variables) @@ -101,50 +102,55 @@ names = {} def p_statement_assign(p): - 'statement : NAME EQUALS expression' + "statement : NAME EQUALS expression" names[p[1]] = p[3] def p_statement_expr(p): - 'statement : expression' + "statement : expression" print(p[1]) def p_expression_binop(p): - '''expression : expression PLUS expression - | expression MINUS expression - | expression TIMES expression - | expression DIVIDE expression - | expression POWER expression''' - if p[2] == '+' : p[0] = p[1] + p[3] - elif p[2] == '-': p[0] = p[1] - p[3] - elif p[2] == '*': p[0] = p[1] * p[3] - elif p[2] == '/': p[0] = p[1] / p[3] - elif p[2] == '^': p[0] = p[1] ** p[3] + """expression : expression PLUS expression + | expression MINUS expression + | expression TIMES expression + | expression DIVIDE expression + | expression POWER expression""" + if p[2] == "+": + p[0] = p[1] + p[3] + elif p[2] == "-": + p[0] = p[1] - p[3] + elif p[2] == "*": + p[0] = p[1] * p[3] + elif p[2] == "/": + p[0] = p[1] / p[3] + elif p[2] == "^": + p[0] = p[1] ** p[3] def p_expression_uminus(p): - 'expression : MINUS expression %prec UMINUS' + "expression : MINUS expression %prec UMINUS" p[0] = -p[2] def p_expression_group(p): - 'expression : LPAREN expression RPAREN' + "expression : LPAREN expression RPAREN" p[0] = p[2] def p_expression_float(p): - 'expression : FLOAT' + "expression : FLOAT" p[0] = p[1] def p_expression_int(p): - 'expression : INT' + "expression : INT" p[0] = p[1] def p_expression_name(p): - 'expression : NAME' + "expression : NAME" try: p[0] = names[p[1]] except LookupError: @@ -157,4 +163,5 @@ def p_error(p): import ply.yacc as yacc + yacc.yacc(debug=False, write_tables=False) diff --git a/src/Mod/Fem/femviewprovider/view_base_femelement.py b/src/Mod/Fem/femviewprovider/view_base_femelement.py index c6c8ba8f7e..fc50180227 100644 --- a/src/Mod/Fem/femviewprovider/view_base_femelement.py +++ b/src/Mod/Fem/femviewprovider/view_base_femelement.py @@ -1,6 +1,6 @@ # SPDX-License-Identifier: LGPL-2.1-or-later -#/*************************************************************************** +# /*************************************************************************** # * Copyright (c) 2024 Mario Passaglia * # * * # * This file is part of FreeCAD. * diff --git a/src/Mod/Fem/femviewprovider/view_base_femmaterial.py b/src/Mod/Fem/femviewprovider/view_base_femmaterial.py index 1115478351..6dc9409e81 100644 --- a/src/Mod/Fem/femviewprovider/view_base_femmaterial.py +++ b/src/Mod/Fem/femviewprovider/view_base_femmaterial.py @@ -1,6 +1,6 @@ # SPDX-License-Identifier: LGPL-2.1-or-later -#/*************************************************************************** +# /*************************************************************************** # * Copyright (c) 2024 Mario Passaglia * # * * # * This file is part of FreeCAD. * diff --git a/src/Mod/Fem/femviewprovider/view_base_femmeshelement.py b/src/Mod/Fem/femviewprovider/view_base_femmeshelement.py index c9749851b9..9afa9f93fd 100644 --- a/src/Mod/Fem/femviewprovider/view_base_femmeshelement.py +++ b/src/Mod/Fem/femviewprovider/view_base_femmeshelement.py @@ -1,6 +1,6 @@ # SPDX-License-Identifier: LGPL-2.1-or-later -#/*************************************************************************** +# /*************************************************************************** # * Copyright (c) 2024 Mario Passaglia * # * * # * This file is part of FreeCAD. * diff --git a/src/Mod/Fem/femviewprovider/view_base_femobject.py b/src/Mod/Fem/femviewprovider/view_base_femobject.py index b71d30f2a0..dc7e6ba8ba 100644 --- a/src/Mod/Fem/femviewprovider/view_base_femobject.py +++ b/src/Mod/Fem/femviewprovider/view_base_femobject.py @@ -39,7 +39,7 @@ import FemGui # needed to display the icons in TreeView False if FemGui.__name__ else True # flake8, dummy FemGui usage -class VPBaseFemObject(object): +class VPBaseFemObject: """Proxy View Provider for FEM FeaturePythons base constraint.""" def __init__(self, vobj): @@ -51,24 +51,20 @@ class VPBaseFemObject(object): """after load from FCStd file, self.icon does not exist, return constant path instead""" # https://forum.freecad.org/viewtopic.php?f=18&t=44009 if not hasattr(self.Object, "Proxy"): - FreeCAD.Console.PrintMessage("{}, has no Proxy.\n".format(self.Object.Name)) + FreeCAD.Console.PrintMessage(f"{self.Object.Name}, has no Proxy.\n") return "" if not hasattr(self.Object.Proxy, "Type"): FreeCAD.Console.PrintMessage( - "{}: Proxy does has not have attribute Type.\n" - .format(self.Object.Name) + f"{self.Object.Name}: Proxy does has not have attribute Type.\n" ) return "" - if ( - isinstance(self.Object.Proxy.Type, str) - and self.Object.Proxy.Type.startswith("Fem::") - ): + if isinstance(self.Object.Proxy.Type, str) and self.Object.Proxy.Type.startswith("Fem::"): icon_path = "/icons/{}.svg".format(self.Object.Proxy.Type.replace("Fem::", "FEM_")) - FreeCAD.Console.PrintLog("{} --> {}\n".format(self.Object.Name, icon_path)) - return ":/{}".format(icon_path) + FreeCAD.Console.PrintLog(f"{self.Object.Name} --> {icon_path}\n") + return f":/{icon_path}" else: - FreeCAD.Console.PrintError("No icon returned for {}\n".format(self.Object.Name)) - FreeCAD.Console.PrintMessage("{}\n".format(self.Object.Proxy.Type)) + FreeCAD.Console.PrintError(f"No icon returned for {self.Object.Name}\n") + FreeCAD.Console.PrintMessage(f"{self.Object.Proxy.Type}\n") return "" def attach(self, vobj): @@ -106,6 +102,7 @@ class VPBaseFemObject(object): guidoc.setEdit(vobj.Object.Name) else: from PySide.QtGui import QMessageBox + message = "Active Task Dialog found! Please close this one before opening a new one!" QMessageBox.critical(None, "Error in tree view", message) FreeCAD.Console.PrintError(message + "\n") diff --git a/src/Mod/Fem/femviewprovider/view_constraint_bodyheatsource.py b/src/Mod/Fem/femviewprovider/view_constraint_bodyheatsource.py index f0814b1df3..0436bbed78 100644 --- a/src/Mod/Fem/femviewprovider/view_constraint_bodyheatsource.py +++ b/src/Mod/Fem/femviewprovider/view_constraint_bodyheatsource.py @@ -38,8 +38,5 @@ class VPConstraintBodyHeatSource(view_base_femconstraint.VPBaseFemConstraint): def setEdit(self, vobj, mode=0): view_base_femconstraint.VPBaseFemConstraint.setEdit( - self, - vobj, - mode, - task_constraint_bodyheatsource._TaskPanel + self, vobj, mode, task_constraint_bodyheatsource._TaskPanel ) diff --git a/src/Mod/Fem/femviewprovider/view_constraint_centrif.py b/src/Mod/Fem/femviewprovider/view_constraint_centrif.py index 4aefdc70c6..2d2c1d1c85 100644 --- a/src/Mod/Fem/femviewprovider/view_constraint_centrif.py +++ b/src/Mod/Fem/femviewprovider/view_constraint_centrif.py @@ -40,8 +40,5 @@ class VPConstraintCentrif(view_base_femconstraint.VPBaseFemConstraint): def setEdit(self, vobj, mode=0): view_base_femconstraint.VPBaseFemConstraint.setEdit( - self, - vobj, - mode, - task_constraint_centrif._TaskPanel + self, vobj, mode, task_constraint_centrif._TaskPanel ) diff --git a/src/Mod/Fem/femviewprovider/view_constraint_currentdensity.py b/src/Mod/Fem/femviewprovider/view_constraint_currentdensity.py index 7a4cdd4967..c5a53c9d38 100644 --- a/src/Mod/Fem/femviewprovider/view_constraint_currentdensity.py +++ b/src/Mod/Fem/femviewprovider/view_constraint_currentdensity.py @@ -37,8 +37,5 @@ class VPConstraintCurrentDensity(view_base_femconstraint.VPBaseFemConstraint): def setEdit(self, vobj, mode=0): view_base_femconstraint.VPBaseFemConstraint.setEdit( - self, - vobj, - mode, - task_constraint_currentdensity._TaskPanel + self, vobj, mode, task_constraint_currentdensity._TaskPanel ) diff --git a/src/Mod/Fem/femviewprovider/view_constraint_electrostaticpotential.py b/src/Mod/Fem/femviewprovider/view_constraint_electrostaticpotential.py index 3f2dfaf3c8..75df41f826 100644 --- a/src/Mod/Fem/femviewprovider/view_constraint_electrostaticpotential.py +++ b/src/Mod/Fem/femviewprovider/view_constraint_electrostaticpotential.py @@ -38,8 +38,5 @@ class VPConstraintElectroStaticPotential(view_base_femconstraint.VPBaseFemConstr def setEdit(self, vobj, mode=0): view_base_femconstraint.VPBaseFemConstraint.setEdit( - self, - vobj, - mode, - task_constraint_electrostaticpotential._TaskPanel + self, vobj, mode, task_constraint_electrostaticpotential._TaskPanel ) diff --git a/src/Mod/Fem/femviewprovider/view_constraint_flowvelocity.py b/src/Mod/Fem/femviewprovider/view_constraint_flowvelocity.py index 91d28993f9..7ee91870f7 100644 --- a/src/Mod/Fem/femviewprovider/view_constraint_flowvelocity.py +++ b/src/Mod/Fem/femviewprovider/view_constraint_flowvelocity.py @@ -38,8 +38,5 @@ class VPConstraintFlowVelocity(view_base_femconstraint.VPBaseFemConstraint): def setEdit(self, vobj, mode=0): view_base_femconstraint.VPBaseFemConstraint.setEdit( - self, - vobj, - mode, - task_constraint_flowvelocity._TaskPanel + self, vobj, mode, task_constraint_flowvelocity._TaskPanel ) diff --git a/src/Mod/Fem/femviewprovider/view_constraint_initialflowvelocity.py b/src/Mod/Fem/femviewprovider/view_constraint_initialflowvelocity.py index 3cb1c95ec5..4760f069d1 100644 --- a/src/Mod/Fem/femviewprovider/view_constraint_initialflowvelocity.py +++ b/src/Mod/Fem/femviewprovider/view_constraint_initialflowvelocity.py @@ -38,8 +38,5 @@ class VPConstraintInitialFlowVelocity(view_base_femconstraint.VPBaseFemConstrain def setEdit(self, vobj, mode=0): view_base_femconstraint.VPBaseFemConstraint.setEdit( - self, - vobj, - mode, - task_constraint_initialflowvelocity._TaskPanel + self, vobj, mode, task_constraint_initialflowvelocity._TaskPanel ) diff --git a/src/Mod/Fem/femviewprovider/view_constraint_initialpressure.py b/src/Mod/Fem/femviewprovider/view_constraint_initialpressure.py index f6c66b4f7e..81483be256 100644 --- a/src/Mod/Fem/femviewprovider/view_constraint_initialpressure.py +++ b/src/Mod/Fem/femviewprovider/view_constraint_initialpressure.py @@ -37,8 +37,5 @@ class VPConstraintInitialPressure(view_base_femconstraint.VPBaseFemConstraint): def setEdit(self, vobj, mode=0): view_base_femconstraint.VPBaseFemConstraint.setEdit( - self, - vobj, - mode, - task_constraint_initialpressure._TaskPanel + self, vobj, mode, task_constraint_initialpressure._TaskPanel ) diff --git a/src/Mod/Fem/femviewprovider/view_constraint_magnetization.py b/src/Mod/Fem/femviewprovider/view_constraint_magnetization.py index 7f649309d3..6a051892d7 100644 --- a/src/Mod/Fem/femviewprovider/view_constraint_magnetization.py +++ b/src/Mod/Fem/femviewprovider/view_constraint_magnetization.py @@ -37,8 +37,5 @@ class VPConstraintMagnetization(view_base_femconstraint.VPBaseFemConstraint): def setEdit(self, vobj, mode=0): view_base_femconstraint.VPBaseFemConstraint.setEdit( - self, - vobj, - mode, - task_constraint_magnetization._TaskPanel + self, vobj, mode, task_constraint_magnetization._TaskPanel ) diff --git a/src/Mod/Fem/femviewprovider/view_constraint_sectionprint.py b/src/Mod/Fem/femviewprovider/view_constraint_sectionprint.py index f4f5f703d5..edf5cdc194 100644 --- a/src/Mod/Fem/femviewprovider/view_constraint_sectionprint.py +++ b/src/Mod/Fem/femviewprovider/view_constraint_sectionprint.py @@ -46,10 +46,7 @@ class VPConstraintSectionPrint(view_base_femconstraint.VPBaseFemConstraint): def setEdit(self, vobj, mode=0): view_base_femconstraint.VPBaseFemConstraint.setEdit( - self, - vobj, - mode, - task_constraint_sectionprint._TaskPanel + self, vobj, mode, task_constraint_sectionprint._TaskPanel ) def attach(self, vobj): diff --git a/src/Mod/Fem/femviewprovider/view_constraint_tie.py b/src/Mod/Fem/femviewprovider/view_constraint_tie.py index 4e466f9958..f86fe805bc 100644 --- a/src/Mod/Fem/femviewprovider/view_constraint_tie.py +++ b/src/Mod/Fem/femviewprovider/view_constraint_tie.py @@ -46,10 +46,7 @@ class VPConstraintTie(view_base_femconstraint.VPBaseFemConstraint): def setEdit(self, vobj, mode=0): view_base_femconstraint.VPBaseFemConstraint.setEdit( - self, - vobj, - mode, - task_constraint_tie._TaskPanel + self, vobj, mode, task_constraint_tie._TaskPanel ) def attach(self, vobj): diff --git a/src/Mod/Fem/femviewprovider/view_element_fluid1D.py b/src/Mod/Fem/femviewprovider/view_element_fluid1D.py index 8023643f58..c46221ff39 100644 --- a/src/Mod/Fem/femviewprovider/view_element_fluid1D.py +++ b/src/Mod/Fem/femviewprovider/view_element_fluid1D.py @@ -32,17 +32,15 @@ __url__ = "https://www.freecad.org" # \brief view provider for element fluid 1D object from femtaskpanels import task_element_fluid1D -from . import view_base_femelement +from . import view_base_femconstraint -class VPElementFluid1D(view_base_femelement.VPBaseFemElement): +class VPElementFluid1D(view_base_femconstraint.VPBaseFemConstraint): """ A View Provider for the ElementFluid1D object """ def setEdit(self, vobj, mode=0): - super().setEdit( - vobj, - mode, - task_element_fluid1D._TaskPanel + view_base_femconstraint.VPBaseFemConstraint.setEdit( + self, vobj, mode, task_element_fluid1D._TaskPanel ) diff --git a/src/Mod/Fem/femviewprovider/view_element_geometry1D.py b/src/Mod/Fem/femviewprovider/view_element_geometry1D.py index b563b29df5..49388e99a3 100644 --- a/src/Mod/Fem/femviewprovider/view_element_geometry1D.py +++ b/src/Mod/Fem/femviewprovider/view_element_geometry1D.py @@ -30,17 +30,15 @@ __url__ = "https://www.freecad.org" # \brief view provider for element geometry 1D object from femtaskpanels import task_element_geometry1D -from . import view_base_femelement +from . import view_base_femconstraint -class VPElementGeometry1D(view_base_femelement.VPBaseFemElement): +class VPElementGeometry1D(view_base_femconstraint.VPBaseFemConstraint): """ A View Provider for the ElementGeometry1D object """ def setEdit(self, vobj, mode=0): - super().setEdit( - vobj, - mode, - task_element_geometry1D._TaskPanel + view_base_femconstraint.VPBaseFemConstraint.setEdit( + self, vobj, mode, task_element_geometry1D._TaskPanel ) diff --git a/src/Mod/Fem/femviewprovider/view_element_geometry2D.py b/src/Mod/Fem/femviewprovider/view_element_geometry2D.py index dc9e04c991..28deaef29a 100644 --- a/src/Mod/Fem/femviewprovider/view_element_geometry2D.py +++ b/src/Mod/Fem/femviewprovider/view_element_geometry2D.py @@ -30,17 +30,15 @@ __url__ = "https://www.freecad.org" # \brief view provider for element geometry 2D object from femtaskpanels import task_element_geometry2D -from . import view_base_femelement +from . import view_base_femconstraint -class VPElementGeometry2D(view_base_femelement.VPBaseFemElement): +class VPElementGeometry2D(view_base_femconstraint.VPBaseFemConstraint): """ A View Provider for the ElementGeometry2D object """ def setEdit(self, vobj, mode=0): - super().setEdit( - vobj, - mode, - task_element_geometry2D._TaskPanel + view_base_femconstraint.VPBaseFemConstraint.setEdit( + self, vobj, mode, task_element_geometry2D._TaskPanel ) diff --git a/src/Mod/Fem/femviewprovider/view_material_common.py b/src/Mod/Fem/femviewprovider/view_material_common.py index f04f86a629..1b6a0a066c 100644 --- a/src/Mod/Fem/femviewprovider/view_material_common.py +++ b/src/Mod/Fem/femviewprovider/view_material_common.py @@ -34,10 +34,10 @@ __url__ = "https://www.freecad.org" import FreeCAD from femtaskpanels import task_material_common -from . import view_base_femmaterial +from . import view_base_femconstraint -class VPMaterialCommon(view_base_femmaterial.VPBaseFemMaterial): +class VPMaterialCommon(view_base_femconstraint.VPBaseFemConstraint): """ A View Provider for the MaterialCommon object """ @@ -55,8 +55,6 @@ class VPMaterialCommon(view_base_femmaterial.VPBaseFemMaterial): return "" def setEdit(self, vobj, mode=0): - super().setEdit( - vobj, - mode, - task_material_common._TaskPanel + view_base_femconstraint.VPBaseFemConstraint.setEdit( + self, vobj, mode, task_material_common._TaskPanel ) diff --git a/src/Mod/Fem/femviewprovider/view_material_reinforced.py b/src/Mod/Fem/femviewprovider/view_material_reinforced.py index de3e5a6334..3fa4c2ff5b 100644 --- a/src/Mod/Fem/femviewprovider/view_material_reinforced.py +++ b/src/Mod/Fem/femviewprovider/view_material_reinforced.py @@ -30,17 +30,15 @@ __url__ = "https://www.freecad.org" # \brief view provider for reinforced material object from femtaskpanels import task_material_reinforced -from . import view_base_femmaterial +from . import view_base_femconstraint -class VPMaterialReinforced(view_base_femmaterial.VPBaseFemMaterial): +class VPMaterialReinforced(view_base_femconstraint.VPBaseFemConstraint): """ A View Provider for the MaterialReinforced object """ def setEdit(self, vobj, mode=0): - super().setEdit( - vobj, - mode, - task_material_reinforced._TaskPanel + view_base_femconstraint.VPBaseFemConstraint.setEdit( + self, vobj, mode, task_material_reinforced._TaskPanel ) diff --git a/src/Mod/Fem/femviewprovider/view_mesh_boundarylayer.py b/src/Mod/Fem/femviewprovider/view_mesh_boundarylayer.py index 7821aa4f18..02fcc88e98 100644 --- a/src/Mod/Fem/femviewprovider/view_mesh_boundarylayer.py +++ b/src/Mod/Fem/femviewprovider/view_mesh_boundarylayer.py @@ -30,17 +30,15 @@ __url__ = "https://www.freecad.org" # \brief view provider for mesh boundary object from femtaskpanels import task_mesh_boundarylayer -from . import view_base_femmeshelement +from . import view_base_femconstraint -class VPMeshBoundaryLayer(view_base_femmeshelement.VPBaseFemMeshElement): +class VPMeshBoundaryLayer(view_base_femconstraint.VPBaseFemConstraint): """ A View Provider for the MeshBoundaryLayer object """ def setEdit(self, vobj, mode=0): - super().setEdit( - vobj, - mode, - task_mesh_boundarylayer._TaskPanel + view_base_femconstraint.VPBaseFemConstraint.setEdit( + self, vobj, mode, task_mesh_boundarylayer._TaskPanel ) diff --git a/src/Mod/Fem/femviewprovider/view_mesh_gmsh.py b/src/Mod/Fem/femviewprovider/view_mesh_gmsh.py index d30d2220a3..0a7218fd67 100644 --- a/src/Mod/Fem/femviewprovider/view_mesh_gmsh.py +++ b/src/Mod/Fem/femviewprovider/view_mesh_gmsh.py @@ -140,8 +140,9 @@ class VPMeshGmsh: FemGui.setActiveAnalysis(o) FreeCAD.Console.PrintMessage( "The analysis the Gmsh FEM mesh object " - "belongs to was found and activated: {}\n" - .format(o.Name) + "belongs to was found and activated: {}\n".format( + o.Name + ) ) gui_doc.setEdit(vobj.Object.Name) break @@ -168,8 +169,7 @@ class VPMeshGmsh: FemGui.setActiveAnalysis(o) FreeCAD.Console.PrintMessage( "The analysis the Gmsh FEM mesh object " - "belongs to was found and activated: {}\n" - .format(o.Name) + "belongs to was found and activated: {}\n".format(o.Name) ) gui_doc.setEdit(vobj.Object.Name) break @@ -184,6 +184,7 @@ class VPMeshGmsh: gui_doc.setEdit(vobj.Object.Name) else: from PySide.QtGui import QMessageBox + message = "Active Task Dialog found! Please close this one before opening a new one!" QMessageBox.critical(None, "Error in tree view", message) FreeCAD.Console.PrintError(message + "\n") @@ -199,7 +200,7 @@ class VPMeshGmsh: reg_childs = self.Object.MeshRegionList gro_childs = self.Object.MeshGroupList bou_childs = self.Object.MeshBoundaryLayerList - return (reg_childs + gro_childs + bou_childs) + return reg_childs + gro_childs + bou_childs def onDelete(self, feature, subelements): children = self.claimChildren() @@ -217,7 +218,7 @@ class VPMeshGmsh: "Object dependencies", message_text, QtGui.QMessageBox.Yes | QtGui.QMessageBox.No, - QtGui.QMessageBox.No + QtGui.QMessageBox.No, ) if reply == QtGui.QMessageBox.Yes: return True diff --git a/src/Mod/Fem/femviewprovider/view_mesh_group.py b/src/Mod/Fem/femviewprovider/view_mesh_group.py index 6396c32a13..a638fc1ff1 100644 --- a/src/Mod/Fem/femviewprovider/view_mesh_group.py +++ b/src/Mod/Fem/femviewprovider/view_mesh_group.py @@ -30,17 +30,15 @@ __url__ = "https://www.freecad.org" # \brief view provider for mesh group object from femtaskpanels import task_mesh_group -from . import view_base_femmeshelement +from . import view_base_femconstraint -class VPMeshGroup(view_base_femmeshelement.VPBaseFemMeshElement): +class VPMeshGroup(view_base_femconstraint.VPBaseFemConstraint): """ A View Provider for the MeshGroup object """ def setEdit(self, vobj, mode=0): - super().setEdit( - vobj, - mode, - task_mesh_group._TaskPanel + view_base_femconstraint.VPBaseFemConstraint.setEdit( + self, vobj, mode, task_mesh_group._TaskPanel ) diff --git a/src/Mod/Fem/femviewprovider/view_mesh_region.py b/src/Mod/Fem/femviewprovider/view_mesh_region.py index 317a4b9106..3b90b2a5c0 100644 --- a/src/Mod/Fem/femviewprovider/view_mesh_region.py +++ b/src/Mod/Fem/femviewprovider/view_mesh_region.py @@ -30,17 +30,15 @@ __url__ = "https://www.freecad.org" # \brief view provider for mesh region object from femtaskpanels import task_mesh_region -from . import view_base_femmeshelement +from . import view_base_femconstraint -class VPMeshRegion(view_base_femmeshelement.VPBaseFemMeshElement): +class VPMeshRegion(view_base_femconstraint.VPBaseFemConstraint): """ A View Provider for the FemMeshRegion object """ def setEdit(self, vobj, mode=0): - super().setEdit( - vobj, - mode, - task_mesh_region._TaskPanel + view_base_femconstraint.VPBaseFemConstraint.setEdit( + self, vobj, mode, task_mesh_region._TaskPanel ) diff --git a/src/Mod/Fem/femviewprovider/view_result_mechanical.py b/src/Mod/Fem/femviewprovider/view_result_mechanical.py index 3f11b0a309..91b90650e7 100644 --- a/src/Mod/Fem/femviewprovider/view_result_mechanical.py +++ b/src/Mod/Fem/femviewprovider/view_result_mechanical.py @@ -78,7 +78,7 @@ class VPResultMechanical(view_base_femconstraint.VPBaseFemConstraint): "Object dependencies", bodyMessage, QtGui.QMessageBox.Yes | QtGui.QMessageBox.No, - QtGui.QMessageBox.No + QtGui.QMessageBox.No, ) if reply == QtGui.QMessageBox.Yes: return True diff --git a/src/Mod/Fem/femviewprovider/view_solver_ccxtools.py b/src/Mod/Fem/femviewprovider/view_solver_ccxtools.py index d8382f6734..6e702d0ac9 100644 --- a/src/Mod/Fem/femviewprovider/view_solver_ccxtools.py +++ b/src/Mod/Fem/femviewprovider/view_solver_ccxtools.py @@ -43,9 +43,5 @@ class VPSolverCcxTools(view_base_femconstraint.VPBaseFemConstraint): def setEdit(self, vobj, mode=0): view_base_femconstraint.VPBaseFemConstraint.setEdit( - self, - vobj, - mode, - task_solver_ccxtools._TaskPanel, - hide_mesh=False + self, vobj, mode, task_solver_ccxtools._TaskPanel, hide_mesh=False )