def create_cube_test_results(): import os import shutil cube_file = test_file_dir + '/cube.fcstd' FreeCAD.open(cube_file) import FemGui FemGui.setActiveAnalysis(FreeCAD.ActiveDocument.MechanicalAnalysis) import FemToolsCcx fea = FemToolsCcx.FemToolsCcx() # static fea.reset_all() fea.run() fea.load_results() stat_types = ["U1", "U2", "U3", "Uabs", "Sabs"] stats_static = [] # we only have one result object so we are fine for s in stat_types: stats_static.append("{}: {}\n".format(s, fea.get_stats(s))) static_expected_values_file = temp_dir + '/cube_static_expected_values' f = open(static_expected_values_file, 'w') for s in stats_static: f.write(s) f.close() # could be added in FemToolsCcx to the self object as an Attribut frd_result_file = os.path.splitext(fea.inp_file_name)[0] + '.frd' dat_result_file = os.path.splitext(fea.inp_file_name)[0] + '.dat' frd_static_test_result_file = temp_dir + '/cube_static.frd' dat_static_test_result_file = temp_dir + '/cube_static.dat' shutil.copyfile(frd_result_file, frd_static_test_result_file) shutil.copyfile(dat_result_file, dat_static_test_result_file) # frequency fea.reset_all() fea.set_analysis_type('frequency') fea.solver.EigenmodesCount = 1 # we should only have one result object fea.run() fea.load_results() stats_frequency = [] # since we set eigenmodeno. we only have one result object so we are fine for s in stat_types: stats_frequency.append("{}: {}\n".format(s, fea.get_stats(s))) frequency_expected_values_file = temp_dir + '/cube_frequency_expected_values' f = open(frequency_expected_values_file, 'w') for s in stats_frequency: f.write(s) f.close() frd_frequency_test_result_file = temp_dir + '/cube_frequency.frd' dat_frequency_test_result_file = temp_dir + '/cube_frequency.dat' shutil.copyfile(frd_result_file, frd_frequency_test_result_file) shutil.copyfile(dat_result_file, dat_frequency_test_result_file) print('Results copied to: ' + temp_dir)
def get_objects(self): path_assise = self.path + "assise2_banc.FCStd" path_barre = self.path + "barre2_banc.FCStd" path_montant = self.path + "montant2_banc.FCStd" path_banc = self.path + "banc_untothislast_final.FCStd" doc_assise = FreeCAD.open(path_assise) doc_barre = FreeCAD.open(path_barre) doc_montant = FreeCAD.open(path_montant) doc_banc = FreeCAD.open(path_banc) self.objects = [doc_assise, doc_barre, doc_montant] self.assembly = doc_banc
def setup(part,view): date = datetime.date.today().strftime("%m_%d_%Y") printerDir = gv.printerDir+"Printer_"+date+"/" #part: "printBedSupport" #subpart: App.ActiveDocument.Pocket001 FreeCAD.open(printerDir+"Parts/"+part+".FCStd") App.setActiveDocument(part) view = eval('App.ActiveDocument.'+view) create(view) App.getDocument(part).save() App.closeDocument(part)
def get_objects(self): path_CP = self.path + "CenterPart.FCStd" path_SP = self.path + "SidePart.FCStd" path_LP = self.path + "LinkPart.FCStd" path_Leg = self.path + "LegPart.FCStd" path_Stool = self.path + "StoolAssembly.FCStd" doc_CP = FreeCAD.open(path_CP) doc_SP = FreeCAD.open(path_SP) doc_LP = FreeCAD.open(path_LP) doc_Leg = FreeCAD.open(path_Leg) doc_Stool = FreeCAD.open(path_Stool) self.objects = [doc_CP, doc_SP, doc_LP, doc_Leg] self.assembly = doc_Stool
def _test_file( self, testFile_basename, solution = None ): testFile = os.path.join( test_assembly_path, testFile_basename + '.fcstd' ) debugPrint(1, testFile_basename ) stats.n_attempted += 1 #if testFile == 'tests/testAssembly11-Pipe_assembly.fcstd': # print('Skipping known fail') # continue doc = FreeCAD.open(testFile) t_start_solver = time.time() constraintSystem = solveConstraints( doc, solver_name = 'dof_reduction_solver', use_cache = self.use_cache, showFailureErrorDialog=False ) if solution: self.check_solution( constraintSystem, solution ) stats.t_solver += time.time() - t_start_solver if self.use_cache: debugPrint(1,'\n\n') X_org = constraintSystem.variableManager.X t_start_cache = time.time() #cache.debugMode = 1 constraintSystem = solveConstraints( doc, solver_name = 'dof_reduction_solver', use_cache = self.use_cache ) self.assertTrue( numpy.allclose( X_org , constraintSystem.variableManager.X ), 'Cache solution differs from originial solution: %s != %s' % ( X_org , constraintSystem.variableManager.X ) ) #cache.debugMode = 0 stats.t_cache += time.time() - t_start_cache constraintSystem.update() stats.n_solved += 1 FreeCAD.closeDocument( doc.Name ) debugPrint(1,'\n\n\n')
def testSaveAndRestore(self): # saving and restoring SaveName = self.TempPath + os.sep + "SaveRestoreTests.FCStd" self.Doc.FileName = SaveName self.failUnless(self.Doc.Label_1.TypeTransient == 4711) self.Doc.Label_1.TypeTransient = 4712 # setup Linking self.Doc.Label_1.Link = self.Doc.Label_2 self.Doc.Label_2.Link = self.Doc.Label_1 self.Doc.Label_1.LinkSub = (self.Doc.Label_2,["Sub1","Sub2"]) self.Doc.Label_2.LinkSub = (self.Doc.Label_1,["Sub3","Sub4"]) # save the document self.Doc.save() FreeCAD.closeDocument("SaveRestoreTests") self.Doc = FreeCAD.open(SaveName) self.failUnless(self.Doc.Label_1.Integer == 4711) self.failUnless(self.Doc.Label_2.Integer == 4711) # test Linkage self.failUnless(self.Doc.Label_1.Link == self.Doc.Label_2) self.failUnless(self.Doc.Label_2.Link == self.Doc.Label_1) self.failUnless(self.Doc.Label_1.LinkSub == (self.Doc.Label_2,["Sub1","Sub2"])) self.failUnless(self.Doc.Label_2.LinkSub == (self.Doc.Label_1,["Sub3","Sub4"])) # do NOT save transient properties self.failUnless(self.Doc.Label_1.TypeTransient == 4711) self.failUnless(self.Doc == FreeCAD.getDocument(self.Doc.Name))
def testExtensionSaveRestore(self): # saving and restoring SaveName = self.TempPath + os.sep + "SaveRestoreExtensions.FCStd" Doc = FreeCAD.newDocument("SaveRestoreExtensions") #we try to create a normal python object and add a extension to it obj = Doc.addObject("App::DocumentObject", "Obj") grp1 = Doc.addObject("App::DocumentObject", "Extension_1") grp2 = Doc.addObject("App::FeaturePython", "Extension_2") grp1.addExtension("App::GroupExtensionPython", None) SaveRestoreSpecialGroup(grp2) if FreeCAD.GuiUp: SaveRestoreSpecialGroupViewProvider(grp2.ViewObject) grp2.Group = [obj] Doc.saveAs(SaveName) FreeCAD.closeDocument("SaveRestoreExtensions") Doc = FreeCAD.open(SaveName) self.failUnless(Doc.Extension_1.hasExtension("App::GroupExtension")) self.failUnless(Doc.Extension_2.hasExtension("App::GroupExtension")) self.failUnless(Doc.Extension_1.ExtensionProxy is None) self.failUnless(Doc.Extension_2.ExtensionProxy is not None) self.failUnless(Doc.Extension_2.Group[0] is Doc.Obj) self.failUnless(hasattr(Doc.Extension_2.Proxy, 'allowObject')) self.failUnless(hasattr(Doc.Extension_2.ExtensionProxy, 'allowObject')) if FreeCAD.GuiUp: self.failUnless(Doc.Extension_2.ViewObject.hasExtension("Gui::ViewProviderGroupExtensionPython")) self.failUnless(hasattr(Doc.Extension_2.ViewObject.Proxy, 'testFunction')) self.failUnless(hasattr(Doc.Extension_2.ViewObject.ExtensionProxy, 'testFunction')) FreeCAD.closeDocument("SaveRestoreExtensions")
def fcstd2stp(filename): doc = FreeCAD.open(filename) objects = doc.Objects fn = doc.Label for ob in objects: if ob.InList == [] and ob.OutList.__len__() > 0 : ob.Shape.exportStep(cur_dir + '/STEP/'+ fn + '.stp' )
def testSaveAndRestore(self): # saving and restoring SaveName = self.TempPath + os.sep + "UnicodeTest.FCStd" self.Doc.FileName = SaveName self.Doc.save() self.Doc.FileName = "" self.Doc = FreeCAD.open(SaveName) self.failUnless(self.Doc.Label_1.Label == u"हिन्दी") FreeCAD.closeDocument("UnicodeTest")
def testVectorList(self): self.Doc.Test.VectorList = [(-0.05, 2.5, 5.2),(-0.05, 2.5, 5.2)] # saving and restoring self.Doc.saveAs(self.DocName) FreeCAD.closeDocument("PlatformTests") self.Doc = FreeCAD.open(self.DocName) self.failUnless(len(self.Doc.Test.VectorList) == 2)
def accept(self): path = Paths.modulePath() + "/Examples/" if(self.form.ship.currentIndex() == 0): # s60 from Iowa University App.open(path + "s60.fcstd") elif(self.form.ship.currentIndex() == 1): # Wigley canonical ship App.open(path + "wigley.fcstd") elif(self.form.ship.currentIndex() == 2): # s60 (Katamaran) App.open(path + "s60_katamaran.fcstd") elif(self.form.ship.currentIndex() == 2): # Wigley (Katamaran) App.open(path + "wigley_katamaran.fcstd") return True
def accept(self): path = Paths.modulePath() + "/Resources/VENDING/" if(self.form.ship.currentIndex() == 0): # box2 App.open(path + "box2.fcstd") elif(self.form.ship.currentIndex() == 1): # CircleFan App.open(path + "CircleFan.fcstd") elif(self.form.ship.currentIndex() == 2): # Part 1 App.open(path + "Part1.fcstd") elif(self.form.ship.currentIndex() == 2): # Part 4 App.open(path + "Part4.fcstd") return True
def testDescent(self): # testing the up and downstream stuff props=self.Obj.supportedProperties() for i in props: self.Obj.addProperty(i,i) tempPath = tempfile.gettempdir() tempFile = tempPath + os.sep + "PropertyTests.FCStd" self.Doc.saveAs(tempFile) FreeCAD.closeDocument("PropertyTests") self.Doc = FreeCAD.open(tempFile)
def checkFile(fileName): if fileName.startswith('./'): fileName = os.path.join(os.path.dirname(FreeCAD.ActiveDocument.FileName), fileName) try: return [FreeCAD.open(fileName), True] except Exception, e: # file is already open for i in FreeCAD.listDocuments().values(): if i.FileName == fileName: return [FreeCAD.getDocument(i.Label), False]
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') ) return doc
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') ) return doc
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') ) return doc
def testFloatList(self): self.Doc.Test.FloatList = [-0.05, 2.5, 5.2] # saving and restoring self.Doc.saveAs(self.DocName) FreeCAD.closeDocument("PlatformTests") self.Doc = FreeCAD.open(self.DocName) self.failUnless(abs(self.Doc.Test.FloatList[0] + .05) < 0.01) self.failUnless(abs(self.Doc.Test.FloatList[1] - 2.5) < 0.01) self.failUnless(abs(self.Doc.Test.FloatList[2] - 5.2) < 0.01)
def testPoints(self): try: self.Doc.addObject("Points::Feature", "Points") # saving and restoring self.Doc.saveAs(self.DocName) FreeCAD.closeDocument("PlatformTests") self.Doc = FreeCAD.open(self.DocName) self.failUnless(self.Doc.Points.Points.count() == 0) except: pass
def setUp(self): testfile = FreeCAD.getHomePath() + 'Mod/Path/PathTests/boxtest.fcstd' self.doc = FreeCAD.open(testfile) self.job = FreeCAD.ActiveDocument.getObject("Job") self.postlist = [] currTool = None for obj in self.job.Group: if not isinstance(obj.Proxy, PathScripts.PathToolController.ToolController): tc = PathScripts.PathUtil.toolControllerForOp(obj) if tc is not None: if tc.ToolNumber != currTool: self.postlist.append(tc) self.postlist.append(obj)
def accept(self): """Load the selected hull example.""" path = Paths.modulePath() + "/resources/examples/" mw = self.getMainWindow() form = mw.findChild(QtGui.QWidget, "TaskPanel") form.ship = self.widget(QtGui.QComboBox, "Ship") if(form.ship.currentIndex() == 0): # s60 from Iowa University App.open(path + "s60.fcstd") elif(form.ship.currentIndex() == 1): # Wigley canonical ship App.open(path + "wigley.fcstd") elif(form.ship.currentIndex() == 2): # s60 (Katamaran) App.open(path + "s60_katamaran.fcstd") elif(form.ship.currentIndex() == 2): # Wigley (Katamaran) App.open(path + "wigley_katamaran.fcstd") return True
def accept(self): path = Paths.modulePath() + "/Examples/" if(self.form.ship.currentIndex() == 0): # s60 from Iowa University App.open(path + "s60.fcstd") elif(self.form.ship.currentIndex() == 1): # Barehull 5415 App.open(path + "barehull5415.fcstd") elif(self.form.ship.currentIndex() == 2): # s60 (Katamaran) App.open(path + "s60_katamaran.fcstd") return True
def testColorList(self): self.Doc.Test.ColourList = [(1.0,0.5,0.0),(0.0,0.5,1.0)] # saving and restoring self.Doc.saveAs(self.DocName) FreeCAD.closeDocument("PlatformTests") self.Doc = FreeCAD.open(self.DocName) self.failUnless(abs(self.Doc.Test.ColourList[0][0] - 1.0) < 0.01) self.failUnless(abs(self.Doc.Test.ColourList[0][1] - 0.5) < 0.01) self.failUnless(abs(self.Doc.Test.ColourList[0][2] - 0.0) < 0.01) self.failUnless(abs(self.Doc.Test.ColourList[0][3] - 0.0) < 0.01) self.failUnless(abs(self.Doc.Test.ColourList[1][0] - 0.0) < 0.01) self.failUnless(abs(self.Doc.Test.ColourList[1][1] - 0.5) < 0.01) self.failUnless(abs(self.Doc.Test.ColourList[1][2] - 1.0) < 0.01) self.failUnless(abs(self.Doc.Test.ColourList[1][3] - 0.0) < 0.01)
def main(): doc = FreeCAD.open("C:/Users/User/Desktop/CAD_Data/bridge.FCStd") fcverticelist = doc.Sketch.Shape.Vertexes fcedgelist = doc.Sketch.Shape.Edges edgelist=[] numnodes = len(fcverticelist) verticelist = [] for i in range(0, numnodes): index = [i,str(id(fcverticelist[i]))] coordlist = [] for j in range(0, 3): coordlist.append(fcverticelist[i].Point[j]) verticelist.append(Vertice(index,coordlist)) print(verticelist[4].coordinates) pickle.dump(verticelist, open("save.p", "wb"))
def _test_file( self, testFile_basename, solution = None ): testFile = os.path.join( test_assembly_path, testFile_basename + '.fcstd' ) debugPrint(1, testFile_basename ) stats.n_attempted += 1 #if testFile == 'tests/testAssembly11-Pipe_assembly.fcstd': # print('Skipping known fail') # continue doc = FreeCAD.open(testFile) t_start_solver = time.time() xOpt = solveConstraints( doc, solver_name = 'newton_solver_slsqp', use_cache = self.use_cache, showFailureErrorDialog=False ) if solution: self.check_solution( xOpt, solution ) stats.t_solver += time.time() - t_start_solver assert not self.use_cache if not xOpt is None: stats.n_solved += 1 FreeCAD.closeDocument( doc.Name ) debugPrint(1,'\n\n\n') return xOpt
def main(): import FreeCAD import FreeCADGui import Part data = ["test-S2R-2","Compound","Compound001"] #data = ["Gordon-sphere","Compound","Compound001"] data = ["test-birail-3","Compound","Compound001"] #data = ["Gordon-2","profiles","guides"] doc = FreeCAD.open(u"/home/tomate/.FreeCAD/Mod/CurvesWB/TestFiles/%s.fcstd"%data[0]) # Create array of curves guide_edges = doc.getObject(data[1]).Shape.Edges profile_edges = doc.getObject(data[2]).Shape.Edges guide_curves = [e.Curve.toBSpline() for e in guide_edges] profile_curves = [e.Curve.toBSpline() for e in profile_edges] # create the gordon surface gordon = InterpolateCurveNetwork(profile_curves, guide_curves, 1e-5) # display curves and resulting surface Part.show(gordon.surface().toShape()) FreeCAD.ActiveDocument.recompute()
obj = doc.getObjectsByLabel(label) # print(obj) if len(obj) > 0: obj = obj[0] print_obj(obj) else: print("object with label '{}' not found.".format(label)) # ****************************************** # # Main experimetns # # ****************************************** doc = FreeCAD.open("./MyLittleWorld.FCStd") docname = doc.Name # ****************************************** print("~" * 42) objects = doc.Objects print("doc.Objects", len(objects)) print_objects(objects) print("~" * 42) print_obj_with_label(doc, "World_Body") print_obj_with_label(doc, "Sun_Sphere") print_obj_with_label(doc, "Seagull_Body") print("~" * 42) print("tests done :-)")
# print(obj) if len(obj) > 0: obj = obj[0] print_obj(obj) else: print("object with label '{}' not found.".format(label)) # ****************************************** # # Main experimetns # # ****************************************** doc = FreeCAD.open( "./BodyTest.FCStd" ) docname = doc.Name # ****************************************** print("~"*42) objects = doc.Objects print("doc.Objects", len(objects)) print_objects(objects) print("~"*42) print_obj_with_label(doc, "BodyTest_Part") print_obj_with_label(doc, "Body_Hex") print_obj_with_label(doc, "Sphere_Sun") print("~"*42)
def FC_WRITE_PARTS(fc_dir, fc_file, verts, faces): sys.path.append(bpy.path.abspath(fc_dir)) #sys.path.append(fc_dir) import FreeCAD as F try: F.open(bpy.path.abspath(fc_file)) #F.open(fc_file) except: return Fname = bpy.path.display_name_from_filepath(fc_file) import Mesh F.setActiveDocument(Fname) fc_root = F.getDocument(Fname) try: obj_names = set([i.Name for i in fc_root.Objects]) if "Mesh" in obj_names: fc_root.removeObject("Mesh") meshdata = [] faces = faces[0] verts = verts[0] for f in faces: v1, v2, v3 = f[0], f[1], f[2] meshdata.append(verts[v1]) meshdata.append(verts[v2]) meshdata.append(verts[v3]) MeshObject = Mesh.Mesh(meshdata) Mesh.show(MeshObject) to_solid = False if to_solid: obj_names = set([i.Name for i in fc_root.Objects]) if "Mesh001" in obj_names: fc_root.removeObject("Mesh001") if "Mesh002" in obj_names: fc_root.removeObject("Mesh002") if "Mesh002 (Solid)" in obj_names: fc_root.removeObject("Mesh002 (Solid)") F.ActiveDocument.recompute() import Part fc_root.addObject("Part::Feature", "Mesh001") __shape__ = Part.Shape() __shape__.makeShapeFromMesh( fc_root.getObject("Mesh").Mesh.Topology, 0.100000) fc_root.getObject("Mesh001").Shape = __shape__ fc_root.getObject("Mesh001").purgeTouched() del __shape__ #refine F.ActiveDocument.addObject( 'Part::Feature', 'Mesh001' ).Shape = F.ActiveDocument.Mesh001.Shape.removeSplitter() F.ActiveDocument.ActiveObject.Label = F.ActiveDocument.Mesh001.Label #to solid __s__ = F.ActiveDocument.Mesh001001.Shape __s__ = Part.Solid(__s__) __o__ = F.ActiveDocument.addObject("Part::Feature", "Mesh001001_solid") __o__.Label = "Mesh002 (Solid)" __o__.Shape = __s__ del __s__, __o__ F.ActiveDocument.recompute() F.getDocument(Fname).save() F.closeDocument(Fname) except: F.closeDocument(Fname)
#!/usr/bin/python # -*- coding: utf-8 -*- import os, sys FREECADPATH = '/usr/lib/freecad/lib/' sys.path.append(FREECADPATH) import FreeCAD, Mesh assembly_file = os.path.abspath( os.path.join('..', '..', 'src', 'SunriseAssembly.FCStd')) out_path = os.path.abspath('./stl') if __name__ == '__main__': try: os.stat(out_path) except OSError: os.mkdir(out_path) FreeCAD.open(assembly_file) doc = App.getDocument("SunriseAssembly") printable = doc.getObjectsByLabel('Printable') + doc.getObjectsByLabel( 'Printable001') for group in printable: for obj in group.Group: Mesh.export([obj], os.path.join(out_path, obj.Label + '.stl')) FreeCAD.closeDocument("SunriseAssembly")
def create_test_results(): import shutil import os import FemGui import femresult.resulttools as resulttools from femtools import ccxtools stat_types = ["U1", "U2", "U3", "Uabs", "Sabs", "MaxPrin", "MidPrin", "MinPrin", "MaxShear", "Peeq", "Temp", "MFlow", "NPress"] temp_dir = testtools.get_fem_test_tmp_dir() static_analysis_dir = temp_dir + 'FEM_ccx_static/' frequency_analysis_dir = temp_dir + 'FEM_ccx_frequency/' thermomech_analysis_dir = temp_dir + 'FEM_ccx_thermomech/' Flow1D_thermomech_analysis_dir = temp_dir + 'FEM_ccx_Flow1D_thermomech/' # run unit test from tests classes from this module import Test import sys current_module = sys.modules[__name__] Test.runTestsFromModule(current_module) # static cube FreeCAD.open(static_analysis_dir + 'cube_static.fcstd') FemGui.setActiveAnalysis(FreeCAD.ActiveDocument.Analysis) fea = ccxtools.FemToolsCcx() print("create static result files") fea.reset_all() fea.run() fea.load_results() stats_static = [] for s in stat_types: statval = resulttools.get_stats(FreeCAD.ActiveDocument.getObject('CalculiX_static_results'), s) stats_static.append("{0}: ({1:.14g}, {2:.14g}, {3:.14g})\n".format(s, statval[0], statval[1], statval[2])) static_expected_values_file = static_analysis_dir + 'cube_static_expected_values' f = open(static_expected_values_file, 'w') for s in stats_static: f.write(s) f.close() frd_result_file = os.path.splitext(fea.inp_file_name)[0] + '.frd' dat_result_file = os.path.splitext(fea.inp_file_name)[0] + '.dat' frd_static_test_result_file = static_analysis_dir + 'cube_static.frd' dat_static_test_result_file = static_analysis_dir + 'cube_static.dat' shutil.copyfile(frd_result_file, frd_static_test_result_file) shutil.copyfile(dat_result_file, dat_static_test_result_file) # frequency cube FreeCAD.open(frequency_analysis_dir + 'cube_frequency.fcstd') FemGui.setActiveAnalysis(FreeCAD.ActiveDocument.Analysis) fea = ccxtools.FemToolsCcx() print("create frequency result files") fea.reset_all() fea.solver.EigenmodesCount = 1 # we should only have one result object fea.run() fea.load_results() stats_frequency = [] for s in stat_types: statval = resulttools.get_stats(FreeCAD.ActiveDocument.getObject('CalculiX_frequency_mode_1_results'), s) stats_frequency.append("{0}: ({1:.14g}, {2:.14g}, {3:.14g})\n".format(s, statval[0], statval[1], statval[2])) frequency_expected_values_file = frequency_analysis_dir + 'cube_frequency_expected_values' f = open(frequency_expected_values_file, 'w') for s in stats_frequency: f.write(s) f.close() frd_frequency_test_result_file = frequency_analysis_dir + 'cube_frequency.frd' dat_frequency_test_result_file = frequency_analysis_dir + 'cube_frequency.dat' shutil.copyfile(frd_result_file, frd_frequency_test_result_file) shutil.copyfile(dat_result_file, dat_frequency_test_result_file) # thermomech print("create thermomech result files") FreeCAD.open(thermomech_analysis_dir + 'spine_thermomech.fcstd') FemGui.setActiveAnalysis(FreeCAD.ActiveDocument.Analysis) fea = ccxtools.FemToolsCcx() fea.reset_all() fea.run() fea.load_results() stats_thermomech = [] for s in stat_types: statval = resulttools.get_stats(FreeCAD.ActiveDocument.getObject('CalculiX_thermomech_results'), s) stats_thermomech.append("{0}: ({1:.14g}, {2:.14g}, {3:.14g})\n".format(s, statval[0], statval[1], statval[2])) thermomech_expected_values_file = thermomech_analysis_dir + 'spine_thermomech_expected_values' f = open(thermomech_expected_values_file, 'w') for s in stats_thermomech: f.write(s) f.close() frd_result_file = os.path.splitext(fea.inp_file_name)[0] + '.frd' dat_result_file = os.path.splitext(fea.inp_file_name)[0] + '.dat' frd_thermomech_test_result_file = thermomech_analysis_dir + 'spine_thermomech.frd' dat_thermomech_test_result_file = thermomech_analysis_dir + 'spine_thermomech.dat' shutil.copyfile(frd_result_file, frd_thermomech_test_result_file) shutil.copyfile(dat_result_file, dat_thermomech_test_result_file) print('Results copied to the appropriate FEM test dirs in: ' + temp_dir) # Flow1D print("create Flow1D result files") FreeCAD.open(Flow1D_thermomech_analysis_dir + 'Flow1D_thermomech.fcstd') FemGui.setActiveAnalysis(FreeCAD.ActiveDocument.Analysis) fea = ccxtools.FemToolsCcx() fea.reset_all() fea.run() fea.load_results() stats_flow1D = [] for s in stat_types: statval = resulttools.get_stats(FreeCAD.ActiveDocument.getObject('CalculiX_thermomech_time_1_0_results'), s) stats_flow1D.append("{0}: ({1:.14g}, {2:.14g}, {3:.14g})\n".format(s, statval[0], statval[1], statval[2])) Flow1D_thermomech_expected_values_file = Flow1D_thermomech_analysis_dir + 'Flow1D_thermomech_expected_values' f = open(Flow1D_thermomech_expected_values_file, 'w') for s in stats_flow1D: f.write(s) f.close() frd_result_file = os.path.splitext(fea.inp_file_name)[0] + '.frd' dat_result_file = os.path.splitext(fea.inp_file_name)[0] + '.dat' frd_Flow1D_thermomech_test_result_file = Flow1D_thermomech_analysis_dir + 'Flow1D_thermomech.frd' dat_Flow1D_thermomech_test_result_file = Flow1D_thermomech_analysis_dir + 'Flow1D_thermomech.dat' shutil.copyfile(frd_result_file, frd_Flow1D_thermomech_test_result_file) shutil.copyfile(dat_result_file, dat_Flow1D_thermomech_test_result_file) print('Flow1D thermomech results copied to the appropriate FEM test dirs in: ' + temp_dir)
def get_vector(self, vector, numbers, var_name, vectors, vectors_text): str_vector = f"App.Vector({vector.x:.3f}, {vector.y:.3f}, {vector.z:.3f})" start_point = vectors.get(str_vector, None) if not start_point: numbers["vector"] += 1 v_n = numbers["vector"] vector_var_name = f"{var_name}_vector_{v_n}" vectors_text.append(f"{vector_var_name} = {str_vector}") vectors[str_vector] = vector_var_name start_point = vector_var_name return start_point #d = FreeCAD.open('left_y_motor_plate.FCStd') #d = FreeCAD.open('left_y_idler_plate.FCStd') d = FreeCAD.open('x_carriage_plate.FCStd') #d = FreeCAD.open('plate.FCStd') for obj in d.Objects: #print(obj.TypeId, obj.Name, obj.Label) #print(obj.PropertiesList) if obj.TypeId == 'PartDesign::Body': bodies.append(Body(obj)) elif obj.TypeId == 'App::Origin': pass elif obj.TypeId == 'App::Line': pass elif obj.TypeId == 'App::Plane': pass elif obj.TypeId == 'PartDesign::ShapeBinder': #print(obj.PropertiesList) #print(obj.Placement)
# # # #***************************************************************************** import Part, TechDraw, Spreadsheet, TechDrawGui import FreeCADGui from FreeCAD import Console from FreeCAD import Base import FreeCAD as App import os import sys sys.path.append(os.path.dirname(__file__)) import datetime if __name__ == '__main__': if "BananaPiM64Model" in App.listDocuments().keys(): pass else: App.open("BananaPiM64Model.fcstd") doc = App.getDocument('BananaPiM64Model') App.ActiveDocument = doc for o in doc.findObjects("Part::Feature"): if o.Name.find("_pcb_") == -1: o.ViewObject.Visibility = False doc.recompute() Gui.SendMsgToActiveView("ViewFit") Gui.activeDocument().activeView().viewTop() Gui.activeDocument().activeView().viewBottom()
# # create an elevation grid # import FreeCAD,FreeCADGui Gui=FreeCADGui FreeCAD.open(u"/home/thomas/Dokumente/freecad_buch/b204_pcl/wires3.fcstd") App.setActiveDocument("wires3") App.ActiveDocument=App.getDocument("wires3") Gui.ActiveDocument=Gui.getDocument("wires3") import reconstruction.CV2 t2=reconstruction.CV2.createCV('ElevationGrid') # # Fusion is a collection of 3 wires # example: 3 walks with the gps tracker in my garden # t2.sourceObject=App.ActiveDocument.Fusion FreeCAD.ActiveDocument.recompute() reconstruction.CV2.run_elevationgrid(t2,None)
'''dynamic offset node''' from say import * Gui.ActiveDocument = None import FreeCAD if 0: try: FreeCAD.open(u"/home/thomas/Schreibtisch/tt_offset_example.fcstd") App.setActiveDocument("tt_offset_example") App.ActiveDocument = App.getDocument("tt_offset_example") Gui.ActiveDocument = Gui.getDocument("tt_offset_example") except: pass import nurbswb.datatools reload(nurbswb.datatools) import scipy.interpolate ## calculates a scipy.interpolate.interp1d # for the floatlist obj.datalist # # in debugmode the calculated shape contains wires for both curves and # connecting lines beween corresponding points on all curves def myupdate(obj): '''interpolate the obj.datalist to get the obj.Shape as BSpline''' fl = obj.data
if 1: import FreeCADGui from PySide2.QtWidgets import QApplication qt_app = QApplication(["bubu"]) FreeCADGui.showMainWindow() App = FreeCAD in_gui = False if App.ActiveDocument: assert (App.ActiveDocument.Name == "frame") in_gui = True if not in_gui: FreeCAD.open("vitamins/vitamins.FCStd") App.setActiveDocument("vitamins") base_x = 450 - 42 - 44 base_x2 = 450 - 44 base_y = 400 base_z = 100 Y = 400 Z = 100 if 1: #DEFAULT FOR BUILD X1 = base_x X2 = base_x2 Y = base_y Z = base_z
import FreeCAD as App import Part, Drawing from FreeCAD import Base import os import sys sys.path.append(os.path.dirname(__file__)) from SectionList import * from Case import * if __name__ == '__main__': if not App.listDocuments().has_key("BananaPiM64Model"): App.open("/home/heller/BananaPi_M64_Portable/3DModel/BananaPiM64Model.fcstd") App.setActiveDocument("BananaPiM64Model") App.ActiveDocument=App.getDocument("BananaPiM64Model") doc = App.activeDocument() garbage = doc.findObjects('Drawing::FeatureViewPart') for g in garbage: doc.removeObject(g.Name) garbage = doc.findObjects('Drawing::FeaturePage') for g in garbage: doc.removeObject(g.Name) doc.addObject('Drawing::FeaturePage','TeensyThumbStickCoverPlatePage') doc.TeensyThumbStickCoverPlatePage.Template = "/home/heller/BananaPi_M64_Portable/3DModel/Letter_Portrait_ISO7200.svg" edt = doc.TeensyThumbStickCoverPlatePage.EditableTexts edt[0] = unicode("Robert Heller") edt[1] = unicode("Teensy ThumbStick Cover Plate") edt[4] = unicode("Banana Pi M64 Case (Plastic Machine Work)")
def testApplyFiles(self): self.Doc.openTransaction("Transaction0") self.L1 = self.Doc.addObject("App::DocumentObjectFileIncluded", "FileObject1") self.failUnless(self.L1.File == "") self.Filename = self.L1.File self.Doc.openTransaction("Transaction1") self.TempPath = tempfile.gettempdir() # creating a file in the Transient directory of the document file = open(self.Doc.getTempFileName("test"), "w") file.write("test No1") file.close() # applying the file self.L1.File = (file.name, "Test.txt") self.failUnless(self.L1.File.split("/")[-1] == "Test.txt") # read again file = open(self.L1.File, "r") self.failUnless(file.read() == "test No1") file.close() file = open(self.TempPath + "/testNest.txt", "w") file.write("test No2") file.close() # applying the file self.Doc.openTransaction("Transaction2") self.L1.File = file.name self.failUnless(self.L1.File.split("/")[-1] == "Test.txt") # read again file = open(self.L1.File, "r") self.failUnless(file.read() == "test No2") file.close() self.Doc.undo() self.failUnless(self.L1.File.split("/")[-1] == "Test.txt") # read again file = open(self.L1.File, "r") self.failUnless(file.read() == "test No1") file.close() self.Doc.undo() # read again self.failUnless(self.L1.File == "") self.Doc.redo() self.failUnless(self.L1.File.split("/")[-1] == "Test.txt") # read again file = open(self.L1.File, "r") self.failUnless(file.read() == "test No1") file.close() self.Doc.redo() self.failUnless(self.L1.File.split("/")[-1] == "Test.txt") # read again file = open(self.L1.File, "r") self.failUnless(file.read() == "test No2") file.close() # Save restore test FileName = self.TempPath + "/FileIncludeTests.fcstd" self.Doc.saveAs(FileName) FreeCAD.closeDocument("FileIncludeTests") self.Doc = FreeCAD.open(self.TempPath + "/FileIncludeTests.fcstd") # check if the file is still there self.L1 = self.Doc.getObject("FileObject1") file = open(self.L1.File, "r") res = file.read() FreeCAD.Console.PrintLog(res + "\n") self.failUnless(res == "test No2") self.failUnless(self.L1.File.split("/")[-1] == "Test.txt") file.close() # test for bug #94 (File overlap in PropertyFileIncluded) L2 = self.Doc.addObject("App::DocumentObjectFileIncluded", "FileObject2") L3 = self.Doc.addObject("App::DocumentObjectFileIncluded", "FileObject3") # creating two files in the Transient directory of the document file1 = open(self.Doc.getTempFileName("test"), "w") file1.write("test No1") file1.close() file2 = open(self.Doc.getTempFileName("test"), "w") file2.write("test No2") file2.close() # applying the file with the same base name L2.File = (file1.name, "Test.txt") L3.File = (file2.name, "Test.txt") file = open(L2.File, "r") self.failUnless(file.read() == "test No1") file.close() file = open(L3.File, "r") self.failUnless(file.read() == "test No2") file.close() # create a second document, copy a file and close the document # the test is about to put the file to the correct transient dir doc2 = FreeCAD.newDocument("Doc2") L4 = doc2.addObject("App::DocumentObjectFileIncluded", "FileObject") L5 = doc2.addObject("App::DocumentObjectFileIncluded", "FileObject") L6 = doc2.addObject("App::DocumentObjectFileIncluded", "FileObject") L4.File = (L3.File, "Test.txt") L5.File = L3.File L6.File = L3.File FreeCAD.closeDocument("FileIncludeTests") self.Doc = FreeCAD.open(self.TempPath + "/FileIncludeTests.fcstd") self.failUnless(os.path.exists(L4.File)) self.failUnless(os.path.exists(L5.File)) self.failUnless(os.path.exists(L6.File)) self.failUnless(L5.File != L6.File) # copy file from L5 which is in the same directory L7 = doc2.addObject("App::DocumentObjectFileIncluded", "FileObject3") L7.File = (L5.File, "Copy.txt") self.failUnless(os.path.exists(L5.File)) FreeCAD.closeDocument("Doc2")
def setUp(self): self.doc = App.open(App.getHomePath() + "/Mod/Path/PathTests/Drilling_1.FCStd") self.obj = self.doc.getObject("Pocket011")
import FreeCAD, FreeCADGui FreeCADGui.activateWorkbench("DrawingWorkbench") FreeCAD.open(FreeCAD.getResourceDir() + "examples/DrawingExample.FCStd") FreeCADGui.SendMsgToActiveView("ViewFit") FreeCADGui.activeDocument().activeView().viewAxometric()
def export_gazebo_model(assembly_file, model_dir, configs={}): doc = FreeCAD.open(assembly_file) robot_name = configs.get('name', doc.Label) scale = configs.get('scale', 0.001) scale_vec = FreeCAD.Vector([scale] * 3) density = configs.get('density', 1000) export_mesh = configs.get('export', True) assembly_dir = os.path.split(doc.FileName)[0] bounding_box = FreeCAD.BoundBox() for obj in doc.findObjects('Part::Feature'): bounding_box.add(obj.Shape.BoundBox) bounding_box.scale(*scale_vec) global_pose_base = FreeCAD.Vector(bounding_box.XLength / 2, bounding_box.YLength / 2, bounding_box.ZLength / 2) global_pose_base -= bounding_box.Center global_pose = FreeCAD.Placement() global_pose.Base = global_pose_base model = Model(name=robot_name, pose=global_pose) model.self_collide = configs.get('self_collide', False) model.sdf_version = '1.5' joint_limits = configs.get('joints_limits', {}) joint_dynamics = configs.get('joints_dynamics', {}) constraints = [] for obj in doc.Objects: if a2plib.isA2pPart(obj): name = obj.Label shape = obj.Shape mass = shape.Mass * scale**3 * density com = shape.CenterOfMass * scale inr = shape.MatrixOfInertia inr.scale(*scale_vec * (scale**4) * density) placement = shape.Placement placement.Base.scale(*scale_vec) part_file = os.path.join(assembly_dir, obj.sourceFile) part_file = os.path.normpath(part_file) mesh_file = os.path.join(model_dir, 'meshes', os.path.relpath(part_file, assembly_dir)) mesh_file = os.path.splitext(mesh_file)[0] + '.dae' mesh_dir = os.path.split(mesh_file)[0] if export_mesh: os.makedirs(mesh_dir, exist_ok=True) export(doc, [obj], mesh_file, scale=scale, offset=com * -1) pose = placement.copy() pose.Base = com pose_rpy = pose.copy() pose_rpy.Base = (np.zeros(3)) inertia = Inertia(inertia=np.array(inr.A)[[0, 1, 2, 5, 6, 10]]) inertial = Inertial(pose=pose_rpy, mass=mass, inertia=inertia) package = configs.get('ros_package', robot_name) mesh_uri = os.path.join(package, os.path.relpath(mesh_file, model_dir)) mesh_uri = os.path.normpath(mesh_uri) visual = Visual(name=name + '_visual', mesh=mesh_uri) collision = Collision(name=name + '_collision', mesh=mesh_uri) link = Link(name=name, pose=pose, inertial=inertial, visual=visual, collision=collision) model.links.append(link) elif a2plib.isA2pConstraint(obj): parent = doc.getObject(obj.Object1) child = doc.getObject(obj.Object2) if sorted([parent.Label, child.Label]) in constraints: continue if obj.Type == 'axial' and not obj.lockRotation: pose = a2plib.getPos(parent, obj.SubElement1) pose = pose - child.Shape.CenterOfMass pose.scale(*scale_vec) joint_pose = FreeCAD.Placement() joint_pose.Base = pose axis_pose = a2plib.getAxis(parent, obj.SubElement1) axis = Axis(pose=axis_pose, lower_limit=joint_limits.get('lower', -90), upper_limit=joint_limits.get('upper', 90), effort_limit=joint_limits.get('effort', 10), velocity_limit=joint_limits.get('velocity', 10), friction=joint_dynamics.get('friction', 0), damping=joint_dynamics.get('damping', 0)) joint = Joint(name=parent.Label + '_' + child.Label, pose=joint_pose, parent=parent.Label, child=child.Label, type='revolute', axis=axis) model.joints.append(joint) constraints.append(sorted([parent.Label, child.Label])) os.makedirs(os.path.join(model_dir, 'models'), exist_ok=True) with open(os.path.join(model_dir, 'models', robot_name + '.sdf'), 'w') as sdf_file: sdf_file.write(model.to_xml_string('sdf')) if not configs.get('sdf_only', None): with open(os.path.join(model_dir, 'models', robot_name + '.urdf'), 'w') as urdf_file: urdf_file.write(model.to_xml_string('urdf')) actuators = ET.Element('robot', name=robot_name) gazebo = ET.SubElement(actuators, 'gazebo') plugin = ET.SubElement(gazebo, 'plugin') plugin.set('filename', 'libgazebo_ros_control.so') plugin.set('name', 'gazebo_ros_control') namespace = ET.SubElement(plugin, 'robotNamespace') namespace.text = '/' + robot_name simtype = ET.SubElement(plugin, 'robotSimType') simtype.text = 'gazebo_ros_control/DefaultRobotHWSim' tr_configs = configs.get('transmission', {}) jt_configs = configs.get('joints_config') pid = configs.get('joints_pid') joint_names = [joint.name for joint in model.joints] for joint in joint_names: transmission = ET.SubElement(actuators, 'transmission', name=joint) tr_type = ET.SubElement(transmission, 'type') tr_type.text = tr_configs.get( 'type', 'transmission_interface/SimpleTransmission') actuator = ET.SubElement(transmission, 'actuator', name=joint) hw_interface = ET.SubElement(actuator, 'hardwareInterface') hw_interface.text = tr_configs.get( 'hardware_interface', 'hardware_interface/PositionJointInterface') reduction = ET.SubElement(actuator, 'mechanicalReduction') reduction.text = '1' tr_joint = ET.SubElement(transmission, 'joint', name=joint) hw_interface = ET.SubElement(tr_joint, 'hardwareInterface') hw_interface.text = tr_configs.get( 'hardware_interface', 'hardware_interface/PositionJointInterface') with open( os.path.join(model_dir, 'models', robot_name + '_actuators.urdf'), 'w') as actuators_file: actuators_file.write( parseString(ET.tostring(actuators)).toprettyxml(indent=' ' * 2)) control_configs = {} control_configs[robot_name] = { 'joint_state_controller': { 'type': 'joint_state_controller/JointStateController', 'publish_rate': 50, } } if jt_configs.get('groupped', False): for joint in joint_names: control_configs[robot_name][joint + '_controller'] = { 'type': jt_configs.get( 'type', 'position_controllers/JointGroupPositionController'), 'joint': joint, 'pid': pid.copy() } else: control_configs[robot_name]['joints_controller'] = { 'type': jt_configs.get( 'type', 'position_controllers/JointGroupPositionController'), 'publish_rate': 50, 'joints': joint_names } control_configs[robot_name]['gazebo_ros_control/pid_gains'] = {} for joint in joint_names: control_configs[robot_name]['gazebo_ros_control/pid_gains'][ joint] = pid.copy() os.makedirs(os.path.join(model_dir, 'config'), exist_ok=True) with open( os.path.join(model_dir, 'config', robot_name + '_controll.yaml'), 'w') as control_configs_file: yaml.dump_all([control_configs], control_configs_file, sort_keys=False)
class TestBuildPostList(unittest.TestCase): """ The postlist is the list of postprocessable elements from the job. The list varies depending on -The operations -The tool controllers -The work coordinate systems (WCS) or 'fixtures' -How the job is ordering the output (WCS, tool, operation) -Whether or not the output is being split to multiple files This test case ensures that the correct sequence of postable objects is created. The list will be comprised of a list of tuples. Each tuple consists of (subobject string, [list of objects]) The subobject string can be used in output name generation if splitting output the list of objects is all postable elements to be written to that file """ testfile = FreeCAD.getHomePath( ) + "Mod/Path/PathTests/test_filenaming.fcstd" doc = FreeCAD.open(testfile) job = doc.getObjectsByLabel("MainJob")[0] def setUp(self): pass def tearDown(self): pass def test000(self): # check that the test file is structured correctly self.assertTrue(len(self.job.Tools.Group) == 2) self.assertTrue(len(self.job.Fixtures) == 2) self.assertTrue(len(self.job.Operations.Group) == 3) self.job.SplitOutput = False self.job.OrderOutputBy = "Operation" def test010(self): postlist = PathPost.buildPostList(self.job) self.assertTrue(type(postlist) is list) firstoutputitem = postlist[0] self.assertTrue(type(firstoutputitem) is tuple) self.assertTrue(type(firstoutputitem[0]) is str) self.assertTrue(type(firstoutputitem[1]) is list) def test020(self): # Without splitting, result should be list of one item self.job.SplitOutput = False self.job.OrderOutputBy = "Operation" postlist = PathPost.buildPostList(self.job) self.assertTrue(len(postlist) == 1) def test030(self): # No splitting should include all ops, tools, and fixtures self.job.SplitOutput = False self.job.OrderOutputBy = "Operation" postlist = PathPost.buildPostList(self.job) firstoutputitem = postlist[0] firstoplist = firstoutputitem[1] self.assertTrue(len(firstoplist) == 14) def test040(self): # Test splitting by tool # ordering by tool with toolnumber for string teststring = "%T.nc" self.job.SplitOutput = True self.job.PostProcessorOutputFile = teststring self.job.OrderOutputBy = "Tool" postlist = PathPost.buildPostList(self.job) firstoutputitem = postlist[0] self.assertTrue(firstoutputitem[0] == str(5)) # check length of output firstoplist = firstoutputitem[1] self.assertTrue(len(firstoplist) == 5) def test050(self): # ordering by tool with tool description for string teststring = "%t.nc" self.job.SplitOutput = True self.job.PostProcessorOutputFile = teststring self.job.OrderOutputBy = "Tool" postlist = PathPost.buildPostList(self.job) firstoutputitem = postlist[0] self.assertTrue(firstoutputitem[0] == "TC__7_16__two_flute") def test060(self): # Ordering by fixture and splitting teststring = "%W.nc" self.job.SplitOutput = True self.job.PostProcessorOutputFile = teststring self.job.OrderOutputBy = "Fixture" postlist = PathPost.buildPostList(self.job) firstoutputitem = postlist[0] firstoplist = firstoutputitem[1] self.assertTrue(len(firstoplist) == 6) self.assertTrue(firstoutputitem[0] == "G54")
def setUp(self): self.clone = None self.doc = FreeCAD.open(FreeCAD.getHomePath() + 'Mod/Path/PathTests/test_holes00.fcstd') self.job = PathJob.Create('Job', [self.doc.Body])
class TestOutputNameSubstitution(unittest.TestCase): """ String substitution allows the following: %D ... directory of the active document %d ... name of the active document (with extension) %M ... user macro directory %j ... name of the active Job object The Following can be used if output is being split. If Output is not split these will be ignored. %S ... Sequence Number (default) %T ... Tool Number %t ... Tool Controller label %W ... Work Coordinate System %O ... Operation Label self.job.Fixtures = ["G54"] self.job.SplitOutput = False self.job.OrderOutputBy = "Fixture" Assume: active document: self.assertTrue(filename, f"{home}/testdoc.fcstd user macro: ~/.local/share/FreeCAD/Macro Job: MainJob Operations: OutsideProfile DrillAllHoles TC: 7/16" two flute (5) TC: Drill (2) Fixtures: (G54, G55) Strings should be sanitized like this to ensure valid filenames # import re # filename="TC: 7/16" two flute" # >>> re.sub(r"[^\w\d-]","_",filename) # "TC__7_16__two_flute" """ testfile = FreeCAD.getHomePath( ) + "Mod/Path/PathTests/test_filenaming.fcstd" testfilepath, testfilename = os.path.split(testfile) testfilename, ext = os.path.splitext(testfilename) doc = FreeCAD.open(testfile) job = doc.getObjectsByLabel("MainJob")[0] macro = FreeCAD.getUserMacroDir() def test000(self): # Test basic name generation with empty string FreeCAD.setActiveDocument(self.doc.Label) teststring = "" self.job.PostProcessorOutputFile = teststring self.job.SplitOutput = False outlist = PathPost.buildPostList(self.job) self.assertTrue(len(outlist) == 1) subpart, objs = outlist[0] filename = PathPost.resolveFileName(self.job, subpart, 0) self.assertEqual(filename, f"{self.testfilename}.nc") def test015(self): # Test basic string substitution without splitting teststring = "~/Desktop/%j.nc" self.job.PostProcessorOutputFile = teststring self.job.SplitOutput = False outlist = PathPost.buildPostList(self.job) self.assertTrue(len(outlist) == 1) subpart, objs = outlist[0] filename = PathPost.resolveFileName(self.job, subpart, 0) self.assertEqual(filename, "~/Desktop/MainJob.nc") def test010(self): # Substitute current file path teststring = "%D/testfile.nc" self.job.PostProcessorOutputFile = teststring outlist = PathPost.buildPostList(self.job) subpart, objs = outlist[0] filename = PathPost.resolveFileName(self.job, subpart, 0) self.assertEqual(filename, f"{self.testfilepath}/testfile.nc") def test020(self): teststring = "%d.nc" self.job.PostProcessorOutputFile = teststring outlist = PathPost.buildPostList(self.job) subpart, objs = outlist[0] filename = PathPost.resolveFileName(self.job, subpart, 0) self.assertEqual(filename, f"{self.testfilename}.nc") def test030(self): teststring = "%M/outfile.nc" self.job.PostProcessorOutputFile = teststring outlist = PathPost.buildPostList(self.job) subpart, objs = outlist[0] filename = PathPost.resolveFileName(self.job, subpart, 0) self.assertEqual(filename, f"{self.macro}outfile.nc") def test040(self): # unused substitution strings should be ignored teststring = "%d%T%t%W%O/testdoc.nc" self.job.PostProcessorOutputFile = teststring outlist = PathPost.buildPostList(self.job) subpart, objs = outlist[0] filename = PathPost.resolveFileName(self.job, subpart, 0) self.assertEqual(filename, f"{self.testfilename}/testdoc.nc") def test050(self): # explicitly using the sequence number should include it where indicated. teststring = "%S-%d.nc" self.job.PostProcessorOutputFile = teststring outlist = PathPost.buildPostList(self.job) subpart, objs = outlist[0] filename = PathPost.resolveFileName(self.job, subpart, 0) self.assertEqual(filename, "0-test_filenaming.nc") def test060(self): # # Split by Tool self.job.SplitOutput = True self.job.OrderOutputBy = "Tool" outlist = PathPost.buildPostList(self.job) # substitute jobname and use default sequence numbers teststring = "%j.nc" self.job.PostProcessorOutputFile = teststring subpart, objs = outlist[0] filename = PathPost.resolveFileName(self.job, subpart, 0) self.assertEqual(filename, "MainJob-0.nc") subpart, objs = outlist[1] filename = PathPost.resolveFileName(self.job, subpart, 1) self.assertEqual(filename, "MainJob-1.nc") # Use Toolnumbers and default sequence numbers teststring = "%T.nc" self.job.PostProcessorOutputFile = teststring outlist = PathPost.buildPostList(self.job) subpart, objs = outlist[0] filename = PathPost.resolveFileName(self.job, subpart, 0) self.assertEqual(filename, "5-0.nc") subpart, objs = outlist[1] filename = PathPost.resolveFileName(self.job, subpart, 1) self.assertEqual(filename, "2-1.nc") # Use Tooldescriptions and default sequence numbers teststring = "%t.nc" self.job.PostProcessorOutputFile = teststring outlist = PathPost.buildPostList(self.job) subpart, objs = outlist[0] filename = PathPost.resolveFileName(self.job, subpart, 0) self.assertEqual(filename, "TC__7_16__two_flute-0.nc") subpart, objs = outlist[1] filename = PathPost.resolveFileName(self.job, subpart, 1) self.assertEqual(filename, "TC__Drill-1.nc") def test070(self): # Split by WCS self.job.SplitOutput = True self.job.OrderOutputBy = "Fixture" outlist = PathPost.buildPostList(self.job) teststring = "%j.nc" self.job.PostProcessorOutputFile = teststring subpart, objs = outlist[0] filename = PathPost.resolveFileName(self.job, subpart, 0) self.assertEqual(filename, "MainJob-0.nc") subpart, objs = outlist[1] filename = PathPost.resolveFileName(self.job, subpart, 1) self.assertEqual(filename, "MainJob-1.nc") teststring = "%W-%j.nc" self.job.PostProcessorOutputFile = teststring subpart, objs = outlist[0] filename = PathPost.resolveFileName(self.job, subpart, 0) self.assertEqual(filename, "G54-MainJob-0.nc") subpart, objs = outlist[1] filename = PathPost.resolveFileName(self.job, subpart, 1) self.assertEqual(filename, "G55-MainJob-1.nc") def test080(self): # Split by Operation self.job.SplitOutput = True self.job.OrderOutputBy = "Operation" outlist = PathPost.buildPostList(self.job) teststring = "%j.nc" self.job.PostProcessorOutputFile = teststring subpart, objs = outlist[0] filename = PathPost.resolveFileName(self.job, subpart, 0) self.assertEqual(filename, "MainJob-0.nc") subpart, objs = outlist[1] filename = PathPost.resolveFileName(self.job, subpart, 1) self.assertEqual(filename, "MainJob-1.nc") teststring = "%O-%j.nc" self.job.PostProcessorOutputFile = teststring subpart, objs = outlist[0] filename = PathPost.resolveFileName(self.job, subpart, 0) self.assertEqual(filename, "OutsideProfile-MainJob-0.nc") subpart, objs = outlist[1] filename = PathPost.resolveFileName(self.job, subpart, 1) self.assertEqual(filename, "DrillAllHoles-MainJob-1.nc")
#*************************************************************************** #* * #* Copyright (c) 2012 * #* Yorik van Havre <*****@*****.**> * #* * #* This program is free software; you can redistribute it and/or modify * #* it under the terms of the GNU Lesser General Public License (LGPL) * #* as published by the Free Software Foundation; either version 2 of * #* the License, or (at your option) any later version. * #* for detail see the LICENCE text file. * #* * #* This program is distributed in the hope that it will be useful, * #* but WITHOUT ANY WARRANTY; without even the implied warranty of * #* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * #* GNU Library General Public License for more details. * #* * #* You should have received a copy of the GNU Library General Public * #* License along with this program; if not, write to the Free Software * #* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * #* USA * #* * #*************************************************************************** import FreeCAD, FreeCADGui FreeCAD.open(FreeCAD.getResourceDir() + "examples/PartDesignExample.FCStd") FreeCADGui.activeDocument().sendMsgToViews("ViewFit") FreeCADGui.activeDocument().sendMsgToViews("ViewAxo")
import time import sys def pp(msg): sys.stderr.write(str(msg)+"\n") if 0: import FreeCADGui from PySide2.QtWidgets import QApplication qt_app = QApplication(["bubu"]) FreeCADGui.showMainWindow() new_part = "left_x_opto_mount" FreeCAD.open("frame.FCStd") FreeCAD.newDocument(new_part) FreeCAD.setActiveDocument(new_part) FreeCAD.ActiveDocument.saveAs(f"{new_part}.FCStd") body = FreeCAD.activeDocument().addObject('PartDesign::Body', new_part) for o in [ "XVSlot", "XFrontRail", "XFrontCarriage", "XFrontTitanMount", "XFrontMGN" ]: print(o) sb = body.newObject('PartDesign::SubShapeBinder', o + '_bind')
'/usr/share/freecad/Mod/Tux', '/usr/share/freecad/Mod/Material', '/usr/share/freecad/Mod/Mesh', '/usr/share/freecad/Mod/OpenSCAD', '/usr/share/freecad/Mod/Sketcher', '/usr/share/freecad/Mod/ReverseEngineering', '/usr/share/freecad/Mod/Part', '/usr/share/freecad/Mod', '/usr/lib/freecad/lib64', '/usr/lib/freecad-python3/lib', '/usr/share/freecad/Ext', '', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '{}/.local/lib/python3.6/site-packages'.format(USER_HOME_DIR), '/usr/local/lib/python3.6/dist-packages', '/usr/lib/python3/dist-packages', '{}/.FreeCAD/Macro'.format(USER_HOME_DIR), '/usr/lib/freecad/Macro' ] for freecad_path in freecad_paths: sys.path.append(freecad_path) import FreeCAD as App import Import freecad_file_to_test = sys.argv[1] freecad_document_name = os.path.basename(freecad_file_to_test).split('.')[0] print('testing freecad file {}'.format(freecad_file_to_test)) # filename = '{}/_workspace/freecad-playlist/common_parts.FCStd'.format(USER_HOME_DIR) App.open(freecad_file_to_test) App.setActiveDocument(freecad_document_name.replace('-', '_')) App.ActiveDocument.recompute() App.setActiveDocument("") App.ActiveDocument = None print('done')
#* GNU Library General Public License for more details. * #* * #* You should have received a copy of the GNU Library General Public * #* License along with this program; if not, write to the Free Software * #* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * #* USA * #* * #*************************************************************************** import FreeCAD, FreeCADGui, os, sys if sys.version_info.major < 3: from urllib import unquote else: from urllib.parse import unquote # filename will be given before this script is run cfolder = FreeCAD.ParamGet( "User parameter:BaseApp/Preferences/Mod/Start").GetString( "ShowCustomFolder", "") if cfolder: if not os.path.isdir(cfolder): cfolder = os.path.dirname(cfolder) f = unquote(filename).replace("+", " ") if f.lower().endswith(".fcstd"): FreeCAD.open(os.path.join(cfolder, f)) else: FreeCAD.loadFile(os.path.join(cfolder, f)) FreeCADGui.activeDocument().sendMsgToViews("ViewFit") from StartPage import StartPage StartPage.postStart()
#* * #* This program is distributed in the hope that it will be useful, * #* but WITHOUT ANY WARRANTY; without even the implied warranty of * #* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * #* GNU Library General Public License for more details. * #* * #* You should have received a copy of the GNU Library General Public * #* License along with this program; if not, write to the Free Software * #* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * #* USA * #* * #*************************************************************************** import FreeCAD,FreeCADGui,os,sys if sys.version_info.major < 3: from urrlib import unquote else: from urllib.parse import unquote # filename will be given before this script is run cfolder = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Start").GetString("ShowCustomFolder","") if cfolder: if not os.path.isdir(cfolder): cfolder = os.path.dirname(cfolder) f = unquote(filename).replace("+"," ") FreeCAD.open(os.path.join(cfolder,f)) FreeCADGui.activeDocument().sendMsgToViews("ViewFit") from StartPage import StartPage StartPage.postStart()
def open_cube_test(): cube_file = test_file_dir + '/cube.fcstd' FreeCAD.open(cube_file)
#*************************************************************************** #* * #* Copyright (c) 2012 * #* Yorik van Havre <*****@*****.**> * #* * #* This program is free software; you can redistribute it and/or modify * #* it under the terms of the GNU Lesser General Public License (LGPL) * #* as published by the Free Software Foundation; either version 2 of * #* the License, or (at your option) any later version. * #* for detail see the LICENCE text file. * #* * #* This program is distributed in the hope that it will be useful, * #* but WITHOUT ANY WARRANTY; without even the implied warranty of * #* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * #* GNU Library General Public License for more details. * #* * #* You should have received a copy of the GNU Library General Public * #* License along with this program; if not, write to the Free Software * #* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * #* USA * #* * #*************************************************************************** import FreeCAD, FreeCADGui FreeCAD.open(FreeCAD.getResourceDir() + "examples/ArchDetail.FCStd") FreeCADGui.activeDocument().sendMsgToViews("ViewFit")
# load all documents and create links within the groups # before we can start to create links we will have to save the assembly document App.getDocument("assembly").saveAs(os.path.join(cwd, 'assembly.fcstd')) # now load all parts and create the links for part in parts: # open the fcstd rel_file_path = '{0}/{1}'.format(part[1], part[2]) # the group this part belongs to is the last part of the relativ path group = part[1].split("/")[-1] print('opening file: {}').format(rel_file_path) print('belongs to group: {}').format(group) doc = FreeCAD.open(rel_file_path) objects = doc.RootObjects for object in objects: # API here: https://www.freecadweb.org/wiki/Object_API label = object.Label name = object.Name content = object.Content print(object.PropertiesList) # for each root object create a link in the assembly document App.getDocument('assembly').addObject('App::Link', label).setLink(object) App.getDocument('assembly').getObject(label).Label = label
import FreeCAD, FreeCADGui App = FreeCAD Gui = FreeCADGui import Part, Points import networkx as nx import matplotlib.pyplot as plt import random import os import nurbswb if 0: # load a testfile try: FreeCAD.open(u"/home/thomas/Schreibtisch/netz_test_data.fcstd") App.setActiveDocument("netz_test_data") App.ActiveDocument = App.getDocument("netz_test_data") Gui.ActiveDocument = Gui.getDocument("netz_test_data") except: pass def copySketch(source, target): '''Sketch uebernehmen''' for g in source.Geometry: target.addGeometry(g) for eg in source.ExternalGeometry: # print (eg, eg[0],eg[1]) for g in eg[1]: target.addExternal(eg[0].Name, g)
#*************************************************************************** #* * #* Copyright (c) 2012 * #* Yorik van Havre <*****@*****.**> * #* * #* This program is free software; you can redistribute it and/or modify * #* it under the terms of the GNU Lesser General Public License (LGPL) * #* as published by the Free Software Foundation; either version 2 of * #* the License, or (at your option) any later version. * #* for detail see the LICENCE text file. * #* * #* This program is distributed in the hope that it will be useful, * #* but WITHOUT ANY WARRANTY; without even the implied warranty of * #* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * #* GNU Library General Public License for more details. * #* * #* You should have received a copy of the GNU Library General Public * #* License along with this program; if not, write to the Free Software * #* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * #* USA * #* * #*************************************************************************** import FreeCAD,FreeCADGui FreeCAD.open(FreeCAD.getResourceDir()+"examples/FemCalculixCantilever3D_newSolver.FCStd") FreeCADGui.activeDocument().sendMsgToViews("ViewFit")
def create_test_results(): # run FEM unit tests run_fem_unittests() import os import shutil import FemGui import FemToolsCcx # static and frequency cube FreeCAD.open(static_save_fc_file) FemGui.setActiveAnalysis(FreeCAD.ActiveDocument.Analysis) fea = FemToolsCcx.FemToolsCcx() # static fea.reset_all() fea.run() fea.load_results() stat_types = ["U1", "U2", "U3", "Uabs", "Sabs"] stats_static = [] # we only have one result object so we are fine for s in stat_types: stats_static.append("{}: {}\n".format(s, fea.get_stats(s))) static_expected_values_file = static_analysis_dir + '/cube_static_expected_values' f = open(static_expected_values_file, 'w') for s in stats_static: f.write(s) f.close() # could be added in FemToolsCcx to the self object as an Attribut frd_result_file = os.path.splitext(fea.inp_file_name)[0] + '.frd' dat_result_file = os.path.splitext(fea.inp_file_name)[0] + '.dat' frd_static_test_result_file = static_analysis_dir + '/cube_static.frd' dat_static_test_result_file = static_analysis_dir + '/cube_static.dat' shutil.copyfile(frd_result_file, frd_static_test_result_file) shutil.copyfile(dat_result_file, dat_static_test_result_file) # frequency fea.reset_all() fea.set_analysis_type('frequency') fea.solver.EigenmodesCount = 1 # we should only have one result object fea.run() fea.load_results() stats_frequency = [] # since we set eigenmodeno. we only have one result object so we are fine for s in stat_types: stats_frequency.append("{}: {}\n".format(s, fea.get_stats(s))) frequency_expected_values_file = frequency_analysis_dir + '/cube_frequency_expected_values' f = open(frequency_expected_values_file, 'w') for s in stats_frequency: f.write(s) f.close() frd_frequency_test_result_file = frequency_analysis_dir + '/cube_frequency.frd' dat_frequency_test_result_file = frequency_analysis_dir + '/cube_frequency.dat' shutil.copyfile(frd_result_file, frd_frequency_test_result_file) shutil.copyfile(dat_result_file, dat_frequency_test_result_file) # thermomech FreeCAD.open(thermomech_save_fc_file) FemGui.setActiveAnalysis(FreeCAD.ActiveDocument.Analysis) fea = FemToolsCcx.FemToolsCcx() fea.reset_all() fea.run() fea.load_results() stat_types = ["U1", "U2", "U3", "Uabs", "Sabs"] stats_thermomech = [] # we only have one result object so we are fine for s in stat_types: stats_thermomech.append("{}: {}\n".format(s, fea.get_stats(s))) thermomech_expected_values_file = thermomech_analysis_dir + '/expected_values_thermomech' f = open(thermomech_expected_values_file, 'w') for s in stats_thermomech: f.write(s) f.close() # could be added in FemToolsCcx to the self object as an Attribut frd_result_file = os.path.splitext(fea.inp_file_name)[0] + '.frd' dat_result_file = os.path.splitext(fea.inp_file_name)[0] + '.dat' frd_thermomech_test_result_file = thermomech_analysis_dir + '/spine_thermomech.frd' dat_thermomech_test_result_file = thermomech_analysis_dir + '/spine_thermomech.dat' shutil.copyfile(frd_result_file, frd_thermomech_test_result_file) shutil.copyfile(dat_result_file, dat_thermomech_test_result_file) print('Results copied to the appropriate FEM test dirs in: ' + temp_dir)
def testApplyFiles(self): self.Doc.openTransaction("Transaction0") self.L1 = self.Doc.addObject("App::DocumentObjectFileIncluded","FileObject1") self.failUnless(self.L1.File =="") self.Filename = self.L1.File self.Doc.openTransaction("Transaction1") self.TempPath = tempfile.gettempdir() # creating a file in the Transient directory of the document file = open(self.Doc.getTempFileName("test"),"w") file.write("test No1") file.close() # applying the file self.L1.File = (file.name,"Test.txt") self.failUnless(self.L1.File.split("/")[-1] == "Test.txt") # read again file = open(self.L1.File,"r") self.failUnless(file.read()=="test No1") file.close() file = open(self.TempPath+"/testNest.txt","w") file.write("test No2") file.close() # applying the file self.Doc.openTransaction("Transaction2") self.L1.File = file.name self.failUnless(self.L1.File.split("/")[-1] == "Test.txt") # read again file = open(self.L1.File,"r") self.failUnless(file.read()=="test No2") file.close() self.Doc.undo() self.failUnless(self.L1.File.split("/")[-1] == "Test.txt") # read again file = open(self.L1.File,"r") self.failUnless(file.read()=="test No1") file.close() self.Doc.undo() # read again self.failUnless(self.L1.File == "") self.Doc.redo() self.failUnless(self.L1.File.split("/")[-1] == "Test.txt") # read again file = open(self.L1.File,"r") self.failUnless(file.read()=="test No1") file.close() self.Doc.redo() self.failUnless(self.L1.File.split("/")[-1] == "Test.txt") # read again file = open(self.L1.File,"r") self.failUnless(file.read()=="test No2") file.close() # Save restore test FileName = self.TempPath+"/FileIncludeTests.fcstd" self.Doc.saveAs(FileName) FreeCAD.closeDocument("FileIncludeTests") self.Doc = FreeCAD.open(self.TempPath+"/FileIncludeTests.fcstd") # check if the file is still there self.L1 = self.Doc.getObject("FileObject1") file = open(self.L1.File,"r") res = file.read() FreeCAD.Console.PrintLog( res +"\n") self.failUnless(res=="test No2") self.failUnless(self.L1.File.split("/")[-1] == "Test.txt") file.close() # test for bug #94 (File overlap in PropertyFileIncluded) L2 = self.Doc.addObject("App::DocumentObjectFileIncluded","FileObject2") L3 = self.Doc.addObject("App::DocumentObjectFileIncluded","FileObject3") # creating two files in the Transient directory of the document file1 = open(self.Doc.getTempFileName("test"),"w") file1.write("test No1") file1.close() file2 = open(self.Doc.getTempFileName("test"),"w") file2.write("test No2") file2.close() # applying the file with the same base name L2.File = (file1.name,"Test.txt") L3.File = (file2.name,"Test.txt") file = open(L2.File,"r") self.failUnless(file.read()=="test No1") file.close() file = open(L3.File,"r") self.failUnless(file.read()=="test No2") file.close() # create a second document, copy a file and close the document # the test is about to put the file to the correct transient dir doc2 = FreeCAD.newDocument("Doc2") L4 = doc2.addObject("App::DocumentObjectFileIncluded","FileObject") L5 = doc2.addObject("App::DocumentObjectFileIncluded","FileObject") L6 = doc2.addObject("App::DocumentObjectFileIncluded","FileObject") L4.File = (L3.File,"Test.txt") L5.File = L3.File L6.File = L3.File FreeCAD.closeDocument("FileIncludeTests") self.Doc = FreeCAD.open(self.TempPath+"/FileIncludeTests.fcstd") self.failUnless(os.path.exists(L4.File)) self.failUnless(os.path.exists(L5.File)) self.failUnless(os.path.exists(L6.File)) self.failUnless(L5.File != L6.File) # copy file from L5 which is in the same directory L7 = doc2.addObject("App::DocumentObjectFileIncluded","FileObject3") L7.File = (L5.File,"Copy.txt") self.failUnless(os.path.exists(L5.File)) FreeCAD.closeDocument("Doc2")
def create_test_results(): import os import shutil import unittest import FemGui from femresult import resulttools from femtools import ccxtools temp_dir = testtools.get_fem_test_tmp_dir() test_class = "femtest.app.test_ccxtools.TestCcxTools" # unit test class stat_types = [ "U1", "U2", "U3", "Uabs", "Sabs", "MaxPrin", "MidPrin", "MinPrin", "MaxShear", "Peeq", "Temp", "MFlow", "NPress" ] # **************************************************************************** # static cube print("create static result files") unittest.TextTestRunner().run( unittest.TestLoader().loadTestsFromName(test_class + ".test_static_analysis")) static_analysis_dir = join(temp_dir, "FEM_ccx_static") doc_static_cube = FreeCAD.open( join(static_analysis_dir, "cube_static.FCStd")) FemGui.setActiveAnalysis(doc_static_cube.Analysis) fea = ccxtools.FemToolsCcx() fea.update_objects() fea.reset_all() fea.run() fea.load_results() stats_static = [] 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") f = open(static_expected_values_file, "w") for s in stats_static: f.write(s) f.close() frd_result_file = os.path.splitext(fea.inp_file_name)[0] + ".frd" dat_result_file = os.path.splitext(fea.inp_file_name)[0] + ".dat" frd_static_test_result_file = join(static_analysis_dir, "cube_static.frd") dat_static_test_result_file = join(static_analysis_dir, "cube_static.dat") shutil.copyfile(frd_result_file, frd_static_test_result_file) shutil.copyfile(dat_result_file, dat_static_test_result_file) print("Results copied to the appropriate FEM test dirs in: " + temp_dir) # **************************************************************************** # frequency cube print("create frequency result files") unittest.TextTestRunner().run( 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")) FemGui.setActiveAnalysis(doc_frequency_cube.Analysis) fea = ccxtools.FemToolsCcx() fea.update_objects() fea.reset_all() # we should only have one result object 1 to 6 will be less than 0.01 and ignored fea.solver.EigenmodesCount = 7 doc_frequency_cube.recompute() fea.run() fea.load_results() stats_frequency = [] 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") f = open(frequency_expected_values_file, "w") for s in stats_frequency: f.write(s) f.close() frd_result_file = os.path.splitext(fea.inp_file_name)[0] + ".frd" dat_result_file = os.path.splitext(fea.inp_file_name)[0] + ".dat" frd_frequency_test_result_file = join(frequency_analysis_dir, "cube_frequency.frd") dat_frequency_test_result_file = join(frequency_analysis_dir, "cube_frequency.dat") shutil.copyfile(frd_result_file, frd_frequency_test_result_file) shutil.copyfile(dat_result_file, dat_frequency_test_result_file) print("Results copied to the appropriate FEM test dirs in: " + temp_dir) # **************************************************************************** # thermomech print("create thermomech result files") unittest.TextTestRunner().run(unittest.TestLoader().loadTestsFromName( test_class + ".test_thermomech_spine_analysis")) thermomech_analysis_dir = join(temp_dir, "FEM_ccx_thermomech") doc_thermomech = FreeCAD.open( join(thermomech_analysis_dir, "spine_thermomech.FCStd")) FemGui.setActiveAnalysis(doc_thermomech.Analysis) fea = ccxtools.FemToolsCcx() fea.reset_all() fea.run() fea.load_results() stats_thermomech = [] res_obj_thermo = doc_thermomech.getObject( "CCX_Results001") # two time step results after run for s in stat_types: statval = resulttools.get_stats(res_obj_thermo, s) stats_thermomech.append("{0}: ({1:.14g}, {2:.14g})\n".format( s, statval[0], statval[1])) thermomech_expected_values_file = join(thermomech_analysis_dir, "spine_thermomech_expected_values") f = open(thermomech_expected_values_file, "w") for s in stats_thermomech: f.write(s) f.close() frd_result_file = os.path.splitext(fea.inp_file_name)[0] + ".frd" dat_result_file = os.path.splitext(fea.inp_file_name)[0] + ".dat" frd_thermomech_test_result_file = join(thermomech_analysis_dir, "spine_thermomech.frd") dat_thermomech_test_result_file = join(thermomech_analysis_dir, "spine_thermomech.dat") shutil.copyfile(frd_result_file, frd_thermomech_test_result_file) shutil.copyfile(dat_result_file, dat_thermomech_test_result_file) print("Results copied to the appropriate FEM test dirs in: " + temp_dir) # **************************************************************************** # Flow1D print("create Flow1D result files") unittest.TextTestRunner().run(unittest.TestLoader().loadTestsFromName( test_class + ".test_thermomech_flow1D_analysis")) Flow1D_thermomech_analysis_dir = join(temp_dir, "FEM_ccx_Flow1D_thermomech") doc_flow1d = FreeCAD.open( join(Flow1D_thermomech_analysis_dir, "Flow1D_thermomech.FCStd")) FemGui.setActiveAnalysis(doc_flow1d.Analysis) fea = ccxtools.FemToolsCcx() fea.reset_all() fea.run() fea.load_results() stats_flow1D = [] res_obj_flow1d = doc_flow1d.getObject("CCX_Time1_0_Results001") for s in stat_types: statval = resulttools.get_stats(res_obj_flow1d, s) stats_flow1D.append("{0}: ({1:.14g}, {2:.14g})\n".format( s, statval[0], statval[1])) Flow1D_thermomech_expected_values_file = join( Flow1D_thermomech_analysis_dir, "Flow1D_thermomech_expected_values") f = open(Flow1D_thermomech_expected_values_file, "w") for s in stats_flow1D: f.write(s) f.close() frd_result_file = os.path.splitext(fea.inp_file_name)[0] + ".frd" dat_result_file = os.path.splitext(fea.inp_file_name)[0] + ".dat" frd_Flow1D_thermomech_test_result_file = join( Flow1D_thermomech_analysis_dir, "Flow1D_thermomech.frd") dat_Flow1D_thermomech_test_result_file = join( Flow1D_thermomech_analysis_dir, "Flow1D_thermomech.dat") shutil.copyfile(frd_result_file, frd_Flow1D_thermomech_test_result_file) shutil.copyfile(dat_result_file, dat_Flow1D_thermomech_test_result_file) print( "Flow1D thermomech results copied to the appropriate FEM test dirs in: " + temp_dir)
def create_test_results(): import shutil import os import FemGui import femresult.resulttools as resulttools from femtools import ccxtools stat_types = ["U1", "U2", "U3", "Uabs", "Sabs", "MaxPrin", "MidPrin", "MinPrin", "MaxShear", "Peeq", "Temp", "MFlow", "NPress"] temp_dir = testtools.get_fem_test_tmp_dir() static_analysis_dir = temp_dir + 'FEM_ccx_static/' frequency_analysis_dir = temp_dir + 'FEM_ccx_frequency/' thermomech_analysis_dir = temp_dir + 'FEM_ccx_thermomech/' Flow1D_thermomech_analysis_dir = temp_dir + 'FEM_ccx_Flow1D_thermomech/' # run all unit tests from this module import Test import sys current_module = sys.modules[__name__] Test.runTestsFromModule(current_module) # static cube FreeCAD.open(static_analysis_dir + 'cube_static.fcstd') FemGui.setActiveAnalysis(FreeCAD.ActiveDocument.Analysis) fea = ccxtools.FemToolsCcx() print("create static result files") fea.reset_all() fea.run() fea.load_results() stats_static = [] for s in stat_types: statval = resulttools.get_stats(FreeCAD.ActiveDocument.getObject('CalculiX_static_results'), s) stats_static.append("{0}: ({1:.14g}, {2:.14g}, {3:.14g})\n".format(s, statval[0], statval[1], statval[2])) static_expected_values_file = static_analysis_dir + 'cube_static_expected_values' f = open(static_expected_values_file, 'w') for s in stats_static: f.write(s) f.close() frd_result_file = os.path.splitext(fea.inp_file_name)[0] + '.frd' dat_result_file = os.path.splitext(fea.inp_file_name)[0] + '.dat' frd_static_test_result_file = static_analysis_dir + 'cube_static.frd' dat_static_test_result_file = static_analysis_dir + 'cube_static.dat' shutil.copyfile(frd_result_file, frd_static_test_result_file) shutil.copyfile(dat_result_file, dat_static_test_result_file) # frequency cube FreeCAD.open(frequency_analysis_dir + 'cube_frequency.fcstd') FemGui.setActiveAnalysis(FreeCAD.ActiveDocument.Analysis) fea = ccxtools.FemToolsCcx() print("create frequency result files") fea.reset_all() fea.solver.EigenmodesCount = 1 # we should only have one result object fea.run() fea.load_results() stats_frequency = [] for s in stat_types: statval = resulttools.get_stats(FreeCAD.ActiveDocument.getObject('CalculiX_frequency_mode_1_results'), s) stats_frequency.append("{0}: ({1:.14g}, {2:.14g}, {3:.14g})\n".format(s, statval[0], statval[1], statval[2])) frequency_expected_values_file = frequency_analysis_dir + 'cube_frequency_expected_values' f = open(frequency_expected_values_file, 'w') for s in stats_frequency: f.write(s) f.close() frd_frequency_test_result_file = frequency_analysis_dir + 'cube_frequency.frd' dat_frequency_test_result_file = frequency_analysis_dir + 'cube_frequency.dat' shutil.copyfile(frd_result_file, frd_frequency_test_result_file) shutil.copyfile(dat_result_file, dat_frequency_test_result_file) # thermomech print("create thermomech result files") FreeCAD.open(thermomech_analysis_dir + 'spine_thermomech.fcstd') FemGui.setActiveAnalysis(FreeCAD.ActiveDocument.Analysis) fea = ccxtools.FemToolsCcx() fea.reset_all() fea.run() fea.load_results() stats_thermomech = [] for s in stat_types: statval = resulttools.get_stats(FreeCAD.ActiveDocument.getObject('CalculiX_thermomech_results'), s) stats_thermomech.append("{0}: ({1:.14g}, {2:.14g}, {3:.14g})\n".format(s, statval[0], statval[1], statval[2])) thermomech_expected_values_file = thermomech_analysis_dir + 'spine_thermomech_expected_values' f = open(thermomech_expected_values_file, 'w') for s in stats_thermomech: f.write(s) f.close() frd_result_file = os.path.splitext(fea.inp_file_name)[0] + '.frd' dat_result_file = os.path.splitext(fea.inp_file_name)[0] + '.dat' frd_thermomech_test_result_file = thermomech_analysis_dir + 'spine_thermomech.frd' dat_thermomech_test_result_file = thermomech_analysis_dir + 'spine_thermomech.dat' shutil.copyfile(frd_result_file, frd_thermomech_test_result_file) shutil.copyfile(dat_result_file, dat_thermomech_test_result_file) print('Results copied to the appropriate FEM test dirs in: ' + temp_dir) # Flow1D print("create Flow1D result files") FreeCAD.open(Flow1D_thermomech_analysis_dir + 'Flow1D_thermomech.fcstd') FemGui.setActiveAnalysis(FreeCAD.ActiveDocument.Analysis) fea = ccxtools.FemToolsCcx() fea.reset_all() fea.run() fea.load_results() stats_flow1D = [] for s in stat_types: statval = resulttools.get_stats(FreeCAD.ActiveDocument.getObject('CalculiX_thermomech_time_1_0_results'), s) stats_flow1D.append("{0}: ({1:.14g}, {2:.14g}, {3:.14g})\n".format(s, statval[0], statval[1], statval[2])) Flow1D_thermomech_expected_values_file = Flow1D_thermomech_analysis_dir + 'Flow1D_thermomech_expected_values' f = open(Flow1D_thermomech_expected_values_file, 'w') for s in stats_flow1D: f.write(s) f.close() frd_result_file = os.path.splitext(fea.inp_file_name)[0] + '.frd' dat_result_file = os.path.splitext(fea.inp_file_name)[0] + '.dat' frd_Flow1D_thermomech_test_result_file = Flow1D_thermomech_analysis_dir + 'Flow1D_thermomech.frd' dat_Flow1D_thermomech_test_result_file = Flow1D_thermomech_analysis_dir + 'Flow1D_thermomech.dat' shutil.copyfile(frd_result_file, frd_Flow1D_thermomech_test_result_file) shutil.copyfile(dat_result_file, dat_Flow1D_thermomech_test_result_file) print('Flow1D thermomech results copied to the appropriate FEM test dirs in: ' + temp_dir)
def read(filename): "reads the file and creates objects in the active document" #import importZip; reload(importZip) print("open Zip STEP version " + ___ZipVersion___) z = zipfile.ZipFile(filename) l = z.printdir() #il = z.infolist() nl = z.namelist() print("file list: ", nl) import ImportGui, FreeCADGui for f in nl: if '.stp' in f.lower() or '.step' in f.lower(): #\ #or '.igs' in f.lower() or '.iges' in f.lower(): file_content = z.read(f) #sfe = z.extract(f) #print ('extracted ',sfe) print('extracted ', f) # fname=os.path.splitext(os.path.basename(filename))[0] # ext = os.path.splitext(os.path.basename(filename))[1] fname = f print('fname ', f) tempdir = tempfile.gettempdir( ) # get the current temporary directory tempfilepath = os.path.join(tempdir, fname) # + ext) z.extract(fname, tempdir) doc = FreeCAD.ActiveDocument ImportGui.insert(tempfilepath, doc.Name) FreeCADGui.SendMsgToActiveView("ViewFit") try: os.remove(tempfilepath) except OSError: FreeCAD.Console.PrintError("error on removing " + tempfilepath + " file") pass elif '.fcstd' in f.lower(): #\ fname = f tempdir = tempfile.gettempdir( ) # get the current temporary directory tempfilepath = os.path.join(tempdir, fname) # + ext) z.extract(fname, tempdir) doc = FreeCAD.ActiveDocument i = 0 for obj in FreeCAD.ActiveDocument.Objects: i += 1 if i == 0: FreeCAD.closeDocument(doc.Name) FreeCAD.open(tempfilepath) #ImportGui.insert(tempfilepath,doc.Name) FreeCADGui.SendMsgToActiveView("ViewFit") try: os.remove(tempfilepath) except OSError: FreeCAD.Console.PrintError("error on removing " + tempfilepath + " file") pass elif '.brep' in f.lower(): #\ fname = f tempdir = tempfile.gettempdir( ) # get the current temporary directory tempfilepath = os.path.join(tempdir, fname) # + ext) z.extract(fname, tempdir) doc = FreeCAD.ActiveDocument import Part #Part.open(tempfilepath,doc.Name) Part.insert(tempfilepath, doc.Name) #FreeCAD.open(tempfilepath) #ImportGui.insert(tempfilepath,doc.Name) FreeCADGui.SendMsgToActiveView("ViewFit") try: os.remove(tempfilepath) except OSError: FreeCAD.Console.PrintError("error on removing " + tempfilepath + " file") pass