def test_Struct_Static_HROM_2D(self): with KratosUnittest.WorkFolderScope(".", __file__): with open("ProjectParametersHROM.json", 'r') as parameter_file: parameters = KratosMultiphysics.Parameters( parameter_file.read()) model = KratosMultiphysics.Model() Simulation = TestStructuralMechanicsStaticHROM(model, parameters) Simulation.Run() ObtainedOutput = Simulation.EvaluateQuantityOfInterest() ExpectedOutput = np.load('ExpectedOutputHROM.npy') NodalArea = Simulation.EvaluateQuantityOfInterest2() print(NodalArea) UP = 0 DOWN = 0 for i in range(len(ObtainedOutput)): if ExpectedOutput[i] != 0: UP += (NodalArea[i] * ((1 - (ObtainedOutput[i] / ExpectedOutput[i]))**2)) DOWN += NodalArea[i] L2 = (np.sqrt(UP / DOWN)) * 100 self.assertLess(L2, 1e-12) #percent # Cleaning kratos_utilities.DeleteDirectoryIfExisting("__pycache__") kratos_utilities.DeleteDirectoryIfExisting("vtk_output") for file_name in os.listdir(os.getcwd()): if file_name.endswith(".bin") or file_name.endswith(".lst"): kratos_utilities.DeleteFileIfExisting(file_name)
def tearDownClass(cls): super().tearDownClass() # delete superfluous dem files kratos_utils.DeleteFileIfExisting(GetFilePath("dem_fem_cable_net/cableNet.post.lst")) kratos_utils.DeleteDirectoryIfExisting(GetFilePath("dem_fem_cable_net/cableNet_Graphs")) kratos_utils.DeleteDirectoryIfExisting(GetFilePath("dem_fem_cable_net/cableNet_MPI_results")) kratos_utils.DeleteDirectoryIfExisting(GetFilePath("dem_fem_cable_net/cableNet_Post_Files")) kratos_utils.DeleteDirectoryIfExisting(GetFilePath("dem_fem_cable_net/cableNet_Results_and_Data"))
def tearDown(self): with controlledExecutionScope( os.path.dirname(os.path.realpath(__file__))): kratos_utilities.DeleteDirectoryIfExisting("__pycache__") test_scope = os.path.join(os.path.dirname(os.path.realpath(__file__)), self.execution_directory) with controlledExecutionScope(test_scope): kratos_utilities.DeleteDirectoryIfExisting("__pycache__")
def tearDownClass(cls): super(TestCableNetCoSimulationCases,cls).tearDownClass() # delete superfluous dem files dir_name_list = ["sliding_edges_with_friction_dem_fem","ring_set_up_dem_fem"] project_name_list = ["slidingDEM", "smallNet"] for dir_name, project_name in zip(dir_name_list, project_name_list): kratos_utils.DeleteFileIfExisting(GetFilePath(dir_name+"/"+project_name+".post.lst")) kratos_utils.DeleteDirectoryIfExisting(GetFilePath(dir_name+"/"+project_name+"_Graphs")) kratos_utils.DeleteDirectoryIfExisting(GetFilePath(dir_name+"/"+project_name+"_MPI_results")) kratos_utils.DeleteDirectoryIfExisting(GetFilePath(dir_name+"/"+project_name+"_Post_Files")) kratos_utils.DeleteDirectoryIfExisting(GetFilePath(dir_name+"/"+project_name+"_Results_and_Data"))
def Factory(settings, Model): if(type(settings) != KratosMultiphysics.Parameters): raise Exception("Expected input shall be a Parameters object, encapsulating a json string") process_settings = settings["Parameters"] folder_settings = KratosMultiphysics.Parameters("""{ "folder_name" : "EigenResults", "save_output_files_in_folder" : true }""") process_settings.AddMissingParameters(folder_settings) if process_settings["save_output_files_in_folder"].GetBool(): folder_name = process_settings["folder_name"].GetString() kratos_utils.DeleteDirectoryIfExisting(folder_name) # make sure to remove old results os.mkdir(folder_name) if process_settings.Has("computing_model_part_name"): computing_model_part = Model[process_settings["computing_model_part_name"].GetString()] else: # using default name computing_model_part = Model["Structure"] process_settings.RemoveValue("computing_model_part_name") process_settings.RemoveValue("help") return KSM.PostprocessEigenvaluesProcess(computing_model_part, process_settings)
def __init__(self, model, settings): super().__init__() model_part_name = settings["model_part_name"].GetString() self.model_part = model[model_part_name] # Warning: we may be changing the parameters object here: self.TranslateLegacyVariablesAccordingToCurrentStandard(settings) if settings.Has("write_properties_id"): KratosMultiphysics.Logger.PrintWarning( "VtkOutputProcess", "The setting `write_properties_id` is deprecated, use `write_ids` instead!" ) if not settings.Has("write_ids"): settings.AddEmptyValue("write_ids").SetBool( settings["write_properties_id"].GetBool()) settings.RemoveValue("write_properties_id") # default settings can be found in "vtk_output.cpp" self.vtk_io = KratosMultiphysics.VtkOutput( self.model_part, settings) # this also validates the settings if settings["save_output_files_in_folder"].GetBool(): if self.model_part.GetCommunicator().MyPID() == 0: output_path = settings["output_path"].GetString() if not self.model_part.ProcessInfo[ KratosMultiphysics.IS_RESTARTED]: kratos_utils.DeleteDirectoryIfExisting(output_path) self.model_part.GetCommunicator().GetDataCommunicator().Barrier() self.output_interval = settings["output_interval"].GetDouble() self.output_control = settings["output_control_type"].GetString() self.next_output = 0.0 self.__ScheduleNextOutput() # required here esp for restart
def __init__(self, model, settings): KratosMultiphysics.Process.__init__(self) model_part_name = settings["model_part_name"].GetString() self.model_part = model[model_part_name] if settings.Has("write_properties_id"): KratosMultiphysics.Logger.PringWarning( "VtkOutputProcess", "The setting `write_properties_id` is deprecated, use `write_ids` instead!" ) if not settings.Has("write_ids"): settings.AddEmptyValue("write_ids").SetBool( settings["write_properties_id"].GetBool()) settings.RemoveValue("write_properties_id") # default settings can be found in "vtk_output.cpp" self.vtk_io = KratosMultiphysics.VtkOutput( self.model_part, settings) # this also validates the settings if settings["save_output_files_in_folder"].GetBool(): if self.model_part.GetCommunicator().MyPID() == 0: folder_name = settings["folder_name"].GetString() if not self.model_part.ProcessInfo[ KratosMultiphysics.IS_RESTARTED]: kratos_utils.DeleteDirectoryIfExisting(folder_name) if not os.path.isdir(folder_name): os.mkdir(folder_name) self.model_part.GetCommunicator().GetDataCommunicator().Barrier() self.output_frequency = settings["output_frequency"].GetDouble() self.output_control = settings["output_control_type"].GetString() self.next_output = 0.0 self.__ScheduleNextOutput() # required here esp for restart
def test_ConvDiff_Stationary_ROM_2D(self): with KratosUnittest.WorkFolderScope(".", __file__): with open("ProjectParametersROM.json", 'r') as parameter_file: parameters = KratosMultiphysics.Parameters( parameter_file.read()) model = KratosMultiphysics.Model() simulation = TestConvectionDiffusionStationaryROM( model, parameters) simulation.Run() ObtainedOutput = simulation.EvaluateQuantityOfInterest() ExpectedOutput = np.array([ -12.148084271927585, 14.819025485595288, -155.5281654573427, -9.353101257284601, 10.72554942206833, -124.59170838744552, 86.38273570629585, 16.913999272914044, 111.60080675691219, 37.69212146428647, 90.0, 90.0, 232.55768788233212, 253.10649201246736, 90.0, 90.0 ]) NodalArea = np.array([ 0.03703703702962964, 0.05555555555555557, 0.055555555555555566, 0.11111111112222223, 0.05555555555000001, 0.05555555555, 0.11111111112222222, 0.11111111112222222, 0.11111111112222222, 0.01851851851481482, 0.018518518514814813, 0.055555555549999996, 0.055555555549999996, 0.05555555555555555, 0.05555555555555555, 0.03703703702962963 ]) L2 = np.sqrt( (sum(NodalArea * ((ExpectedOutput / ExpectedOutput - ObtainedOutput / ExpectedOutput)**2))) / (sum(NodalArea))) * 100 self.assertLess(L2, 0.1) #percent # Cleaning kratos_utilities.DeleteDirectoryIfExisting("__pycache__")
def __init__(self, model, settings): KratosMultiphysics.Process.__init__(self) model_part_name = settings["model_part_name"].GetString() self.model_part = model[model_part_name] # default settings can be found in "vtk_output.cpp" self.vtk_io = KratosMultiphysics.VtkOutput( self.model_part, settings) # this also validates the settings if settings["save_output_files_in_folder"].GetBool(): if self.model_part.GetCommunicator().MyPID() == 0: folder_name = settings["folder_name"].GetString() if not self.model_part.ProcessInfo[ KratosMultiphysics.IS_RESTARTED]: import KratosMultiphysics.kratos_utilities as kratos_utils kratos_utils.DeleteDirectoryIfExisting(folder_name) if not os.path.isdir(folder_name): os.mkdir(folder_name) self.model_part.GetCommunicator().GetDataCommunicator().Barrier() self.output_frequency = settings["output_frequency"].GetDouble() self.output_control = settings["output_control_type"].GetString() self.next_output = 0.0 self.__ScheduleNextOutput() # required here esp for restart
def __del__(self): # make sure no communication files are left even if simulation is terminated prematurely if os.path.isdir(communication_folder): kratos_utilities.DeleteDirectoryIfExisting(communication_folder) if self.echo_level > 0: cs_tools.cs_print_info( self._ClassName(), "Deleting Communication folder in destructor")
def tearDown(self): # Within this location context: with controlledExecutionScope(os.path.dirname(os.path.realpath(__file__))): # remove the created restart files raw_path, raw_file_name = os.path.split(self.file_name) folder_name = raw_file_name + "__restart_files" kratos_utils.DeleteDirectoryIfExisting(GetFilePath(folder_name))
def __init__(self, settings, model, solver_name): super(EmpireIO, self).__init__(settings, model, solver_name) KratosCoSim.EMPIRE_API.EMPIRE_API_Connect( self.settings["api_configuration_file_name"].GetString()) # delete and recreate communication folder to avoid leftover files kratos_utilities.DeleteDirectoryIfExisting(communication_folder) os.mkdir(communication_folder)
def __init__(self, Model, settings): """ The default constructor of the class Keyword arguments: self -- It signifies an instance of a class. Model -- the container of the different model parts. settings -- Kratos parameters containing solver settings. """ KratosMultiphysics.Process.__init__(self) #The value can be a double or a string (function) default_settings = KratosMultiphysics.Parameters(""" { "model_part_name" : "PLEASE_SPECIFY_MODEL_PART_NAME", "output_control_type" : "step", "output_interval" : 1.0, "folder_name" : "tikZ_Output", "save_output_files_in_folder" : true, "cmyk_colors_fill" : [0, 1.0, 1.0, 1.0], "include_nodes_label" : true, "include_elements_label" : true, "include_axis" : true, "include_grid" : true, "landscape_mode" : true, "include_caption" : false, "sans_fonts" : false, "prefix_nodes" : "", "prefix_elements" : "" } """) self.settings = settings self.settings.ValidateAndAssignDefaults(default_settings) self.model_part = Model[self.settings["model_part_name"].GetString()] # Checking dimension of the problem if self.model_part.ProcessInfo[KratosMultiphysics.DOMAIN_SIZE] != 2: raise Exception("Expected 2 dimensional problem") # Warning: we may be changing the parameters object here: self.TranslateLegacyVariablesAccordingToCurrentStandard(settings) if self.settings["save_output_files_in_folder"].GetBool(): if self.model_part.GetCommunicator().MyPID() == 0: folder_name = self.settings["folder_name"].GetString() if not self.model_part.ProcessInfo[ KratosMultiphysics.IS_RESTARTED]: kratos_utils.DeleteDirectoryIfExisting(folder_name) if not os.path.isdir(folder_name): os.mkdir(folder_name) self.model_part.GetCommunicator().Barrier() self.output_interval = self.settings["output_interval"].GetDouble() self.output_control = self.settings["output_control_type"].GetString() self.next_output = 0.0 self.step_count = 0
def LoadRestart(self, restart_file_name=""): for name in self.file_names: restart_utility = self.restart_utilities[name] restart_utility.raw_path, restart_utility.raw_file_name = os.path.split(name) restart_utility.raw_path = os.path.join(os.getcwd(), self.raw_path) restart_utility.LoadRestart() kratos_utilities.DeleteDirectoryIfExisting(restart_utility._RestartUtility__GetFolderPathLoad())
def __init__(self, settings, model, solver_name): super().__init__(settings, model, solver_name) # Note: calling "EMPIRE_API_Connect" is NOT necessary, it is replaced by the next two lines KratosCoSim.EMPIRE_API.EMPIRE_API_SetEchoLevel(self.echo_level) KratosCoSim.EMPIRE_API.EMPIRE_API_PrintTiming( self.settings["api_print_timing"].GetBool()) # delete and recreate communication folder to avoid leftover files kratos_utilities.DeleteDirectoryIfExisting(communication_folder) os.mkdir(communication_folder)
def tearDown(self): my_pid = self.model_part.GetCommunicator().MyPID() # Remove the .time file KratosUtils.DeleteFileIfExisting("levelset_convection_process_mesh.time") # Remove the Metis partitioning files KratosUtils.DeleteDirectoryIfExisting("levelset_convection_process_mesh_partitioned") # While compining in debug, in memory partitioner also writes down the mpda in plain text # and needs to be cleaned. KratosUtils.DeleteFileIfExisting("debug_modelpart_" + str(my_pid) + ".mdpa")
class TestRandomizedSVD(KratosUnittest.TestCase): @KratosUnittest.skipIf(numpy_available == False, "numpy is required for RomApplication") def test_radomized_svd(self): svd_truncation_tolerance = 1e-5 for rank in range(5,10): TestMatrix = synthetic_matrix(rank) #create a matrix of known rank using polynomials U,S,V,error = RandomizedSingularValueDecomposition().Calculate(TestMatrix, svd_truncation_tolerance) #calculate randomized svd Randomized_Reconstruction = [email protected](S)@V.T #reconstruct matrix #check that the difference of the reconstruction is below tolerance self.assertLess( np.linalg.norm(Randomized_Reconstruction - TestMatrix), svd_truncation_tolerance*np.linalg.norm(TestMatrix)) # Cleaning kratos_utilities.DeleteDirectoryIfExisting("__pycache__")
def test_ConvDiff_Dynamic_ROM_2D(self): with KratosUnittest.WorkFolderScope(".", __file__): with open("ProjectParametersROM.json",'r') as parameter_file: parameters = KratosMultiphysics.Parameters(parameter_file.read()) model = KratosMultiphysics.Model() Simulation = TestConvectionDiffusionTransientROM(model,parameters) Simulation.Run() ObtainedOutput = Simulation.EvaluateQuantityOfInterest() ExpectedOutput = np.load('ExpectedOutput.npy') NodalArea = Simulation.EvaluateQuantityOfInterest2() for i in range (np.shape(ObtainedOutput)[1]): L2 = np.sqrt( (sum(NodalArea*((ExpectedOutput[:,i]/ExpectedOutput[:,i] - ObtainedOutput[:,i]/ExpectedOutput[:,i] )**2))) / (sum(NodalArea)) )*100 self.assertLess(L2, 0.1) #percent # Cleaning kratos_utilities.DeleteDirectoryIfExisting("__pycache__")
def __init__(self, model, settings ): KratosMultiphysics.Process.__init__(self) # IMPORTANT: when "output_control_type" is "time", # then paraview will not be able to group them default_parameters = KratosMultiphysics.Parameters("""{ "model_part_name" : "PLEASE_SPECIFY_MODEL_PART_NAME", "file_format" : "ascii", "output_precision" : 7, "output_control_type" : "step", "output_frequency" : 1.0, "output_sub_model_parts" : false, "folder_name" : "VTK_Output", "custom_name_prefix" : "", "save_output_files_in_folder" : true, "nodal_solution_step_data_variables" : [], "nodal_data_value_variables" : [], "element_data_value_variables" : [], "condition_data_value_variables" : [], "gauss_point_variables" : [] }""") model_part_name = settings["model_part_name"].GetString() self.model_part = model[model_part_name] self.settings = settings self.settings.ValidateAndAssignDefaults(default_parameters) if self.settings["save_output_files_in_folder"].GetBool(): if self.model_part.GetCommunicator().MyPID() == 0: folder_name = self.settings["folder_name"].GetString() if not self.model_part.ProcessInfo[KratosMultiphysics.IS_RESTARTED]: import KratosMultiphysics.kratos_utilities as kratos_utils kratos_utils.DeleteDirectoryIfExisting(folder_name) if not os.path.isdir(folder_name): os.mkdir(folder_name) self.model_part.GetCommunicator().Barrier() self.vtk_io = KratosMultiphysics.VtkOutput(self.model_part, self.settings) self.output_frequency = self.settings["output_frequency"].GetDouble() self.output_control = self.settings["output_control_type"].GetString() self.next_output = 0.0 self.step_count = 0
def test_Fluid_Dynamics_ROM_2D(self): with KratosUnittest.WorkFolderScope(".", __file__): with open("ProjectParameters.json", 'r') as parameter_file: parameters = KratosMultiphysics.Parameters( parameter_file.read()) model = KratosMultiphysics.Model() Simulation = TestFluidDynamicsROM(model, parameters) Simulation.Run() ObtainedOutput = Simulation.EvaluateQuantityOfInterest() ExpectedOutput = np.load('ExpectedOutput.npy') for i in range(np.shape(ObtainedOutput)[1]): up = sum((ExpectedOutput[:, i] - ObtainedOutput[:, i])**2) down = sum((ExpectedOutput[:, i])**2) l2 = np.sqrt(up / down) self.assertLess(l2, 1e-12) # Cleaning kratos_utilities.DeleteDirectoryIfExisting("__pycache__")
def test_Struct_Dynamic_ROM_2D(self): with KratosUnittest.WorkFolderScope(".", __file__): with open("ProjectParameters.json",'r') as parameter_file: parameters = KratosMultiphysics.Parameters(parameter_file.read()) model = KratosMultiphysics.Model() Simulation = TestStructuralMechanicsDynamicROM(model,parameters) Simulation.Run() ObtainedOutput = Simulation.EvaluateQuantityOfInterest() ExpectedOutput = np.load('ExpectedOutput.npy') NodalArea = Simulation.EvaluateQuantityOfInterest2() for i in range (np.shape(ObtainedOutput)[1]): UP = sum((ExpectedOutput[:,i] - ObtainedOutput[:,i])**2) DOWN = sum((ExpectedOutput[:,i])**2) L2 = np.sqrt(UP/DOWN) self.assertLess(L2, 1e-10) # Cleaning kratos_utilities.DeleteDirectoryIfExisting("__pycache__")
def test_ConvDiff_Stationary_ROM_2D(self): with KratosUnittest.WorkFolderScope(".", __file__): with open("ProjectParameters.json", 'r') as parameter_file: parameters = KratosMultiphysics.Parameters( parameter_file.read()) model = KratosMultiphysics.Model() simulation = TestConvectionDiffusionStationaryROM( model, parameters) simulation.Run() ObtainedOutput = simulation.EvaluateQuantityOfInterest() ExpectedOutput = np.load('ExpectedOutput.npy') NodalArea = simulation.EvaluateQuantityOfInterest2() L2 = np.sqrt( (sum(NodalArea * ((1 - ObtainedOutput / ExpectedOutput)**2))) / (sum(NodalArea))) * 100 self.assertLess(L2, 1e-12) #percent # Cleaning kratos_utilities.DeleteDirectoryIfExisting("__pycache__")
class TestEmpiricalCubatureMethod(KratosUnittest.TestCase): @KratosUnittest.skipUnless(numpy_available, "numpy is required for RomApplication") def test_empirical_cubature_method(self): for degree in range(5, 10): TestMatrix = synthetic_matrix( degree ) #Get a synthetic matrix (During the training of a ROM model, this is a matrix of residuals projected onto a basis) #Pass the matrix to the ECM and obtain a set of elements(points) and weights (these steps are contained in the Run method of the ElementSelector base class) ElementSelector = EmpiricalCubatureMethod(SVD_tolerance=0, ECM_tolerance=0) ElementSelector.SetUp(TestMatrix, 'test_number_of_elements', 'test_model_part_name') ElementSelector.Initialize() ElementSelector.Calculate() self.assertEqual( len(ElementSelector.z), degree + 1 ) #for a polynomial of degree n, n+1 points are to be selected # Cleaning kratos_utilities.DeleteDirectoryIfExisting("__pycache__")
def tearDown(self): kratos_utils.DeleteFileIfExisting("test_restart_file.rest") kratos_utils.DeleteFileIfExisting("test_restart_file_15.0.rest") kratos_utils.DeleteDirectoryIfExisting("MainRestart__restart_files")
def tearDown(self): kratos_utils.DeleteDirectoryIfExisting("test_vtk_output")
def tearDown(self): with kratos_unittest.WorkFolderScope(self.execution_directory, __file__): kratos_utilities.DeleteDirectoryIfExisting("__pycache__")
def tearDown(self): # remove the created restart files raw_path, raw_file_name = os.path.split(self.file_name) folder_name = os.path.join(raw_path, raw_file_name + "__restart_files") kratos_utils.DeleteDirectoryIfExisting(GetFilePath(folder_name))
def tearDown(cls): kratos_utils.DeleteDirectoryIfExisting("test_tikz_output")
# Run simulation model = KM.Model() response = structural_response_function_factory.CreateResponseFunction( kratos_response_settings["response_type"].GetString(), kratos_response_settings, model) response.RunCalculation(True) # Write results gradient_of_interest = response.GetNodalGradient( KM.SHAPE_SENSITIVITY)[move_node_id] with open(results_filename, 'a') as open_file: line_to_write = '%.0E' % Decimal(str(current_delta)) + ",\t" line_to_write += '%.6E' % Decimal(str( gradient_of_interest[0])) + ",\t" line_to_write += '%.6E' % Decimal(str( gradient_of_interest[1])) + ",\t" line_to_write += '%.6E' % Decimal(str( gradient_of_interest[2])) + ",\t" line_to_write += str(time.ctime()) + "\n" open_file.write(line_to_write) # ============================================================================== # Postprocessing # ============================================================================== if delete_results_afterwards: kratos_utilities.DeleteDirectoryIfExisting("__pycache__") kratos_utilities.DeleteFileIfExisting( "sensitivity_verification_process_test.post.lst") kratos_utilities.DeleteFileIfExisting(results_filename) kratos_utilities.DeleteFileIfExisting("structure.post.bin")
def tearDownClass(cls): # Cleaning kratos_utils.DeleteDirectoryIfExisting("__pycache__")