def CreateFastestAvailableDirectLinearSolver():
    # Using a default linear solver (selecting the fastest one available)
    if kratos_utils.CheckIfApplicationsAvailable("LinearSolversApplication"):
        from KratosMultiphysics import LinearSolversApplication
    elif kratos_utils.CheckIfApplicationsAvailable(
            "ExternalSolversApplication"):
        from KratosMultiphysics import ExternalSolversApplication

    linear_solvers_by_speed = [
        "pardiso_lu",  # LinearSolversApplication (if compiled with Intel-support)
        "sparse_lu",  # LinearSolversApplication
        "pastix",  # ExternalSolversApplication (if Pastix is included in compilation)
        "super_lu",  # ExternalSolversApplication
        "skyline_lu_factorization"  # in Core, always available, but slow
    ]

    for solver_name in linear_solvers_by_speed:
        if KM.LinearSolverFactory().Has(solver_name):
            linear_solver_configuration = KM.Parameters(
                """{ "solver_type" : "%s"}""" % solver_name)

            KM.Logger.PrintInfo(
                'Linear-Solver-Factory',
                'Creating "{}" as fastest available direct solver'.format(
                    solver_name))
            return KM.LinearSolverFactory().Create(linear_solver_configuration)

    raise Exception("Linear-Solver could not be constructed!")
Exemple #2
0
    def _create_linear_solver(self):
        linear_solver_configuration = self.settings["linear_solver_settings"]
        if linear_solver_configuration.Has("solver_type"): # user specified a linear solver
            from KratosMultiphysics import python_linear_solver_factory as linear_solver_factory
            return linear_solver_factory.ConstructSolver(linear_solver_configuration)
        else:
            # using a default linear solver (selecting the fastest one available)
            import KratosMultiphysics.kratos_utilities as kratos_utils
            if kratos_utils.CheckIfApplicationsAvailable("EigenSolversApplication"):
                from KratosMultiphysics import EigenSolversApplication
            elif kratos_utils.CheckIfApplicationsAvailable("ExternalSolversApplication"):
                from KratosMultiphysics import ExternalSolversApplication

            linear_solvers_by_speed = [
                "pardiso_lu", # EigenSolversApplication (if compiled with Intel-support)
                "sparse_lu",  # EigenSolversApplication
                "pastix",     # ExternalSolversApplication (if Pastix is included in compilation)
                "super_lu",   # ExternalSolversApplication
                "skyline_lu_factorization" # in Core, always available, but slow
            ]

            for solver_name in linear_solvers_by_speed:
                if KratosMultiphysics.LinearSolverFactory().Has(solver_name):
                    linear_solver_configuration.AddEmptyValue("solver_type").SetString(solver_name)
                    KratosMultiphysics.Logger.PrintInfo('::[MechanicalSolver]:: ',\
                        'Using "' + solver_name + '" as default linear solver')
                    return KratosMultiphysics.LinearSolverFactory().Create(linear_solver_configuration)

        raise Exception("Linear-Solver could not be constructed!")
def ConstructSolver(settings):
    if not isinstance(settings, KM.Parameters):
        raise Exception("Input is expected to be provided as a Kratos Parameters object")

    solver_type = settings["solver_type"].GetString()

    if solver_type == "eigen_eigensystem":
        if kratos_utils.CheckIfApplicationsAvailable("EigenSolversApplication"):
            import KratosMultiphysics.EigenSolversApplication as EiSA
            eigen_solver = EiSA.EigensystemSolver(settings)
            return eigen_solver
        else:
            raise Exception("EigenSolversApplication not available")
    elif solver_type == "feast":
        if kratos_utils.CheckIfApplicationsAvailable("EigenSolversApplication"):
            import KratosMultiphysics.EigenSolversApplication as EiSA
            if EiSA.HasFEAST():
                is_symmetric = settings["symmetric"].GetBool() if settings.Has("symmetric") else True
                eigen_solver = EiSA.FEASTSymmetricEigensystemSolver(settings) if is_symmetric else EiSA.FEASTGeneralEigensystemSolver(settings)
                return eigen_solver
            else:
                raise Exception("FEAST not available in EigenSolversApplication")
        else:
            raise Exception("EigenSolversApplication not available")
    elif solver_type == "feast_complex":
        if kratos_utils.CheckIfApplicationsAvailable("EigenSolversApplication"):
            import KratosMultiphysics.EigenSolversApplication as EiSA
            if EiSA.HasFEAST():
                is_symmetric = settings["symmetric"].GetBool() if settings.Has("symmetric") else True
                eigen_solver = EiSA.ComplexFEASTSymmetricEigensystemSolver(settings) if is_symmetric else EiSA.ComplexFEASTGeneralEigensystemSolver(settings)
                return eigen_solver
            else:
                raise Exception("FEAST not available in EigenSolversApplication")
        else:
            raise Exception("EigenSolversApplication not available")

    linear_solver_configuration = settings["linear_solver_settings"]
    if linear_solver_configuration.Has("solver_type"): # user specified a linear solver
        linear_solver = linear_solver_factory.ConstructSolver(linear_solver_configuration)
    else:
        linear_solver = linear_solver_factory.CreateFastestAvailableDirectLinearSolver()

    if solver_type == "power_iteration_eigenvalue_solver":
        eigen_solver = KM.PowerIterationEigenvalueSolver( settings, linear_solver)
    elif solver_type == "power_iteration_highest_eigenvalue_solver":
        eigen_solver = KM.PowerIterationHighestEigenvalueSolver( settings, linear_solver)
    elif solver_type == "rayleigh_quotient_iteration_eigenvalue_solver":
        eigen_solver = KM.RayleighQuotientIterationEigenvalueSolver( settings, linear_solver)
    else:
        raise Exception("Solver type not found. Asking for :" + solver_type)

    return eigen_solver
    def test_harmonic_mdpa_input(self):
        if not kratos_utils.CheckIfApplicationsAvailable("HDF5Application"):
            self.skipTest(
                "HDF5Application not found: Skipping harmonic analysis mdpa test"
            )

        with ControlledExecutionScope(
                os.path.dirname(os.path.realpath(__file__))):
            #run simulation and write to hdf5 file
            model = KratosMultiphysics.Model()
            project_parameter_file_name = "harmonic_analysis_test/harmonic_analysis_test_eigenproblem_parameters.json"
            with open(project_parameter_file_name, 'r') as parameter_file:
                project_parameters = KratosMultiphysics.Parameters(
                    parameter_file.read())
            test = structural_mechanics_analysis.StructuralMechanicsAnalysis(
                model, project_parameters)
            test.Run()

            #start new simulation and read from hdf5 file
            model = KratosMultiphysics.Model()
            project_parameter_file_name = "harmonic_analysis_test/harmonic_analysis_test_parameters.json"
            with open(project_parameter_file_name, 'r') as parameter_file:
                project_parameters = KratosMultiphysics.Parameters(
                    parameter_file.read())
            test = structural_mechanics_analysis.StructuralMechanicsAnalysis(
                model, project_parameters)
            test.Run()

            # remove hdf5 file
            kratos_utils.DeleteFileIfExisting(
                "harmonic_analysis_test/eigen_results.h5")
            kratos_utils.DeleteFileIfExisting(
                "harmonic_analysis_test/harmonic_analysis_test.time")
def SelectAndVerifyLinearSolver(settings, skiptest):
    # The mechanical solver selects automatically the fastest linear-solver available
    # this might not be appropriate for a test, therefore in case nothing is specified,
    # the previous default linear-solver is set
    if not settings["solver_settings"].Has("linear_solver_settings"):
        # check if running in MPI because there we use a different default linear solver
        if IsDistributedRun():
            default_lin_solver_settings = KratosMultiphysics.Parameters("""{
                "solver_type" : "amesos",
                "amesos_solver_type" : "Amesos_Klu"
            }""")

        else:
            default_lin_solver_settings = KratosMultiphysics.Parameters("""{
                "solver_type": "EigenSolversApplication.sparse_lu"
            }""")
        settings["solver_settings"].AddValue("linear_solver_settings",
                                             default_lin_solver_settings)

    solver_type = settings["solver_settings"]["linear_solver_settings"][
        "solver_type"].GetString()
    solver_type_splitted = solver_type.split(".")
    if len(solver_type_splitted) == 2:
        # this means that we use a solver from an application
        # hence we have to check if it exists, otherwise skip the test
        app_name = solver_type_splitted[0]
        solver_name = solver_type_splitted[1]
        if not kratos_utils.CheckIfApplicationsAvailable(app_name):
            skiptest(
                'Application "{}" is needed for the specified solver "{}" but is not available'
                .format(app_name, solver_name))
Exemple #6
0
    def setUp(self):
        # Within this location context:
        with KratosUnittest.WorkFolderScope(".", __file__):

            # Reading the ProjectParameters
            with open(self.file_name + "_parameters.json",
                      'r') as parameter_file:
                ProjectParameters = KratosMultiphysics.Parameters(
                    parameter_file.read())

            # The mechanical solver selects automatically the fastest linear-solver available
            # this might not be appropriate for a test, therefore in case nothing is specified,
            # the previous default linear-solver is set
            if not ProjectParameters["solver_settings"].Has(
                    "linear_solver_settings"):
                # check if running in MPI because there we use a different default linear solver
                if IsDistributedRun():
                    default_lin_solver_settings = KratosMultiphysics.Parameters(
                        """{
                        "solver_type" : "amesos",
                        "amesos_solver_type" : "Amesos_Klu"
                    }""")

                else:
                    default_lin_solver_settings = KratosMultiphysics.Parameters(
                        """{
                        "solver_type": "EigenSolversApplication.sparse_lu"
                    }""")
                ProjectParameters["solver_settings"].AddValue(
                    "linear_solver_settings", default_lin_solver_settings)

            solver_type = ProjectParameters["solver_settings"][
                "linear_solver_settings"]["solver_type"].GetString()
            solver_type_splitted = solver_type.split(".")
            if len(solver_type_splitted) == 2:
                # this means that we use a solver from an application
                # hence we have to check if it exists, otherwise skip the test
                app_name = solver_type_splitted[0]
                solver_name = solver_type_splitted[1]
                if not kratos_utils.CheckIfApplicationsAvailable(app_name):
                    self.skipTest(
                        'Application "{}" is needed for the specified solver "{}" but is not available'
                        .format(app_name, solver_name))

            self.modify_parameters(ProjectParameters)

            # To avoid many prints
            if ProjectParameters["problem_data"]["echo_level"].GetInt() == 0:
                KratosMultiphysics.Logger.GetDefaultOutput().SetSeverity(
                    KratosMultiphysics.Logger.Severity.WARNING)
            else:
                KratosMultiphysics.Logger.GetDefaultOutput().SetSeverity(
                    KratosMultiphysics.Logger.Severity.INFO)

            # Creating the test
            model = KratosMultiphysics.Model()
            self.test = StructuralMechanicsAnalysis(model, ProjectParameters)
            self.test.Initialize()
Exemple #7
0
def __DeprecatedApplicationImport(solver_type):
    # dict specifying in which applications the linear-solvers are defined
    # it is necessary to import the applications in which the linear-solvers
    # are defined, because otherwise they are not registered in the kernel
    # and hence cannot be created by the C-linear-solver-factory
    # NOTE: this is only for backwards-compatibility!!!
    # the correct way is to specify the application in which the linear solver
    # is defined, e.g. "solver_type" : "ExternalSolversApplication.super_lu"

    linear_solver_apps = {
        "ExternalSolversApplication" : [
            "gmres",
            "super_lu",
            "super_lu_iterative",
            "pastix",
            "pastix_complex",
            "feast"
        ],
        "EigenSolversApplication" : [
            "sparse_lu",
            "sparse_lu_complex",
            "sparse_qr",
            "sparse_qr_complex",
            "pardiso_llt",
            "pardiso_ldlt",
            "pardiso_lu",
            "pardiso_lu_complex"
        ]
    }

    for app_name, linear_solver_names in linear_solver_apps.items():
        if solver_type in linear_solver_names:
            depr_msg  = 'DEPRECATION-WARNING:\nThe linear-solver "' + solver_type + '" is defined in the "' + app_name +  '"\n'
            depr_msg += 'Please specify the "solver_type" including the name of the application:\n'
            depr_msg += '"' + app_name + '.' + solver_type + '"'
            depr_msg += '\nPlease update your settings accordingly, the current settings are deprecated!'
            KM.Logger.PrintWarning('Linear-Solver-Factory', depr_msg)

            from KratosMultiphysics import kratos_utilities as kratos_utils
            if not kratos_utils.CheckIfApplicationsAvailable(app_name):
                err_msg  = 'Trying to use the linear-solver "' + solver_type
                err_msg += '"\nThis solver is defined in the "' + app_name
                err_msg += '" which is not compiled'
                raise Exception(err_msg)
            # import the Application in which the linear solver is defined
            __import__("KratosMultiphysics." + app_name)
            break
Exemple #8
0
import KratosMultiphysics as KM

import KratosMultiphysics.KratosUnittest as KratosUnittest
import KratosMultiphysics.kratos_utilities as kratos_utils

import co_simulation_test_case
import os

try:
    import numpy
    numpy_available = True
except ImportError:
    numpy_available = False

have_fsi_dependencies = kratos_utils.CheckIfApplicationsAvailable(
    "FluidDynamicsApplication", "StructuralMechanicsApplication",
    "MappingApplication", "MeshMovingApplication", "LinearSolversApplication")


def GetFilePath(fileName):
    return os.path.join(os.path.dirname(os.path.realpath(__file__)), fileName)


class TestMokFSI(co_simulation_test_case.CoSimulationTestCase):
    cfd_tes_file_name = "fsi_mok/ProjectParametersCFD_for_test.json"

    def setUp(self):
        if not numpy_available:
            self.skipTest("Numpy not available")
        if not have_fsi_dependencies:
            self.skipTest("FSI dependencies are not available!")
Exemple #9
0
# import Kratos
import KratosMultiphysics
import KratosMultiphysics.StructuralMechanicsApplication as StructuralMechanicsApplication
import run_cpp_unit_tests
import KratosMultiphysics.kratos_utilities as kratos_utilities

# Import Kratos "wrapper" for unittests
import KratosMultiphysics.KratosUnittest as KratosUnittest

import os, subprocess

if kratos_utilities.CheckIfApplicationsAvailable("ExternalSolversApplication"):
    has_external_solvers_application = True
else:
    has_external_solvers_application = False

# Import the tests or test_classes to create the suits

##### SELF-CONTAINED TESTS #####
# CL tests
from test_constitutive_law import TestConstitutiveLaw as TTestConstitutiveLaw
from test_perfect_plasticity_implementation_verification import TestPerfectPlasticityImplementationVerification as TTestPerfectPlasticityImplementationVerification
# Processes test
from test_mass_calculation import TestMassCalculation as TTestMassCalculation
from test_compute_center_of_gravity import TestComputeCenterOfGravity as TTestComputeCenterOfGravity
from test_compute_mass_moment_of_inertia import TestComputeMassMomentOfInertia as TTestComputeMassMomentOfInertia
# Simple patch tests
from test_patch_test_small_strain import TestPatchTestSmallStrain as TTestPatchTestSmallStrain
from test_patch_test_small_strain_bbar import TestPatchTestSmallStrainBbar as TTestPatchTestSmallStrainBbar
from test_patch_test_large_strain import TestPatchTestLargeStrain as TTestPatchTestLargeStrain
from test_quadratic_elements import TestQuadraticElements as TTestQuadraticElements
# Importing the Kratos Library
import KratosMultiphysics as KM

# Import applications
import KratosMultiphysics.StructuralMechanicsApplication as SMA
import KratosMultiphysics.ContactStructuralMechanicsApplication as CSMA

import KratosMultiphysics.kratos_utilities as kratos_utilities
if kratos_utilities.CheckIfApplicationsAvailable("MeshingApplication"):
    has_meshing_application = True
else:
    has_meshing_application = False

# Import adaptive remeshing utilities
import KratosMultiphysics.ContactStructuralMechanicsApplication.adaptative_remeshing_contact_structural_mechanics_utilities as adaptative_remeshing_contact_structural_mechanics_utilities

# Import base class file
import KratosMultiphysics.ContactStructuralMechanicsApplication.contact_structural_mechanics_static_solver as contact_structural_mechanics_static_solver


def CreateSolver(model, custom_settings):
    return AdaptativeRemeshingContactStaticMechanicalSolver(
        model, custom_settings)


class AdaptativeRemeshingContactStaticMechanicalSolver(
        contact_structural_mechanics_static_solver.
        ContactStaticMechanicalSolver):
    """The structural mechanics static solver. (Fot adaptative remeshing)
    See contact_structural_mechanics_static_solver.py for more information.
    """
# Importing the Kratos Library
import KratosMultiphysics
import KratosMultiphysics.CompressiblePotentialFlowApplication as CPFApp

# Import KratosUnittest
import KratosMultiphysics.KratosUnittest as UnitTest

# Other imports
from KratosMultiphysics.CompressiblePotentialFlowApplication.potential_flow_analysis import PotentialFlowAnalysis
import KratosMultiphysics.kratos_utilities as kratos_utilities
from KratosMultiphysics.KratosUnittest import isclose as t_isclose

import os

# Check other applications dependency
hdf5_is_available = kratos_utilities.CheckIfApplicationsAvailable("HDF5Application")
meshing_is_available = kratos_utilities.CheckIfApplicationsAvailable("MeshingApplication")
try:
    import stl
    numpy_stl_is_available = True
except:
    numpy_stl_is_available = False

class WorkFolderScope:
    def __init__(self, work_folder):
        self.currentPath = os.getcwd()
        self.scope = os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)),work_folder))

    def __enter__(self):
        os.chdir(self.scope)
Exemple #12
0
# Making KratosMultiphysics backward compatible with python 2.6 and 2.7
from __future__ import print_function, absolute_import, division
import os

# Import Kratos core and apps
import KratosMultiphysics as KM
import KratosMultiphysics.StructuralMechanicsApplication as StructuralMechanicsApplication
import KratosMultiphysics.KratosUnittest as KratosUnittest
from KratosMultiphysics.StructuralMechanicsApplication import structural_response_function_factory
import KratosMultiphysics.kratos_utilities as kratos_utils

has_eigensolvers_application = kratos_utils.CheckIfApplicationsAvailable(
    "EigenSolversApplication")


def _get_test_working_dir():
    this_file_dir = os.path.dirname(os.path.realpath(__file__))
    return os.path.join(this_file_dir, "response_function_tests")


class StructuralResponseFunctionTestFactory(KratosUnittest.TestCase):
    def setUp(self):
        with KratosUnittest.WorkFolderScope(_get_test_working_dir(), __file__):
            with open(self.file_name + "_parameters.json",
                      'r') as parameter_file:
                parameters = KM.Parameters(parameter_file.read())

            # To avoid many prints
            if (parameters["problem_data"]["echo_level"].GetInt() == 0):
                KM.Logger.GetDefaultOutput().SetSeverity(
                    KM.Logger.Severity.WARNING)
Exemple #13
0
# import Kratos
import KratosMultiphysics
import KratosMultiphysics.StructuralMechanicsApplication as StructuralMechanicsApplication
import run_cpp_unit_tests
import KratosMultiphysics.kratos_utilities as kratos_utilities

# Import Kratos "wrapper" for unittests
import KratosMultiphysics.KratosUnittest as KratosUnittest

import os, subprocess

has_linear_solvers_application = kratos_utilities.CheckIfApplicationsAvailable(
    "LinearSolversApplication")

# Import the tests or test_classes to create the suits

##### SELF-CONTAINED TESTS #####
# CL tests
from test_constitutive_law import TestConstitutiveLaw as TTestConstitutiveLaw
from test_perfect_plasticity_implementation_verification import TestPerfectPlasticityImplementationVerification as TTestPerfectPlasticityImplementationVerification
# Processes test
from test_mass_calculation import TestMassCalculation as TTestMassCalculation
from test_compute_center_of_gravity import TestComputeCenterOfGravity as TTestComputeCenterOfGravity
from test_compute_mass_moment_of_inertia import TestComputeMassMomentOfInertia as TTestComputeMassMomentOfInertia
from test_axis_projection import TestAxisProjection as TTestAxisProjection
from test_distribute_load_on_surface_process import TestDistributeLoadOnSurfaceProcess as TTestDistributeLoadOnSurfaceProcess
from test_perturb_geometry_utility import TestPerturbGeometryUtility as TTestPerturbGeometryUtility
# Simple patch tests
from test_patch_test_small_strain import TestPatchTestSmallStrain as TTestPatchTestSmallStrain
from test_patch_test_small_strain_bbar import TestPatchTestSmallStrainBbar as TTestPatchTestSmallStrainBbar
from test_patch_test_small_displacement_mixed_volumetric_strain import TestPatchTestSmallDisplacementMixedVolumetricStrain as TTestPatchTestSmallDisplacementMixedVolumetricStrain
Exemple #14
0
import KratosMultiphysics as KM
import KratosMultiphysics.CoSimulationApplication as KMC
import KratosMultiphysics.KratosUnittest as KratosUnittest
import KratosMultiphysics.kratos_utilities as kratos_utils

from KratosMultiphysics.CoSimulationApplication.factories import data_transfer_operator_factory
from KratosMultiphysics.CoSimulationApplication.coupling_interface_data import CouplingInterfaceData

mapping_app_available = kratos_utils.CheckIfApplicationsAvailable(
    "MappingApplication")


class TestDataTransferOperators(KratosUnittest.TestCase):
    def setUp(self):
        self.model = KM.Model()
        mp_o = self.model.CreateModelPart("mp_origin", 2)
        mp_d_m = self.model.CreateModelPart("mp_destination_matching", 2)
        mp_d_nm = self.model.CreateModelPart("mp_destination_non_matching", 2)
        mp_one_n = self.model.CreateModelPart("mp_single_node", 2)

        mp_o.AddNodalSolutionStepVariable(KM.PRESSURE)
        mp_o.AddNodalSolutionStepVariable(KM.DISPLACEMENT)
        mp_d_m.AddNodalSolutionStepVariable(KM.TEMPERATURE)
        mp_d_m.AddNodalSolutionStepVariable(KM.FORCE)
        mp_d_nm.AddNodalSolutionStepVariable(KM.TEMPERATURE)
        mp_d_nm.AddNodalSolutionStepVariable(KM.FORCE)
        mp_one_n.AddNodalSolutionStepVariable(KMC.SCALAR_DISPLACEMENT)
        mp_one_n.AddNodalSolutionStepVariable(KMC.SCALAR_FORCE)

        mp_o.ProcessInfo[KM.DOMAIN_SIZE] = 2
        mp_d_m.ProcessInfo[KM.DOMAIN_SIZE] = 2
from __future__ import print_function, absolute_import, division

import KratosMultiphysics

import KratosMultiphysics.StructuralMechanicsApplication as StructuralMechanicsApplication
import KratosMultiphysics.KratosUnittest as KratosUnittest
from KratosMultiphysics import eigen_solver_factory

from math import sqrt, sin, cos, pi, exp, atan

from KratosMultiphysics import kratos_utilities as kratos_utils
eigen_solvers_application_available = kratos_utils.CheckIfApplicationsAvailable(
    "EigenSolversApplication")
if eigen_solvers_application_available:
    import KratosMultiphysics.EigenSolversApplication as EiSA
    feast_available = EiSA.HasFEAST()
else:
    feast_available = False


class SpringDamperElementTests(KratosUnittest.TestCase):
    def setUp(self):
        pass

    def _add_variables(self, mp):
        mp.AddNodalSolutionStepVariable(KratosMultiphysics.DISPLACEMENT)
        mp.AddNodalSolutionStepVariable(KratosMultiphysics.ROTATION)
        mp.AddNodalSolutionStepVariable(KratosMultiphysics.REACTION)
        mp.AddNodalSolutionStepVariable(KratosMultiphysics.REACTION_MOMENT)
        mp.AddNodalSolutionStepVariable(KratosMultiphysics.VELOCITY)
        mp.AddNodalSolutionStepVariable(KratosMultiphysics.ANGULAR_VELOCITY)
from __future__ import print_function, absolute_import, division  # makes KratosMultiphysics backward compatible with python 2.6 and 2.7

import KratosMultiphysics as KM

# Import KratosUnittest
import KratosMultiphysics.KratosUnittest as kratos_unittest
import KratosMultiphysics.kratos_utilities as kratos_utilities

# Other imports
import os

# Check if external Apps are available
has_eigen_app = kratos_utilities.CheckIfApplicationsAvailable(
    "EigenSolversApplication")
has_csm_app = kratos_utilities.CheckIfApplicationsAvailable(
    "StructuralMechanicsApplication")
has_mesh_moving_app = kratos_utilities.CheckIfApplicationsAvailable(
    "MeshMovingApplication")
has_mapping_app = kratos_utilities.CheckIfApplicationsAvailable(
    "MappingApplication")


# ==============================================================================
class ShapeOptimizationTestFactory(kratos_unittest.TestCase):
    # --------------------------------------------------------------------------
    def setUp(self):
        KM.Logger.GetDefaultOutput().SetSeverity(KM.Logger.Severity.WARNING)

    # --------------------------------------------------------------------------
    def test_execution(self):
        with kratos_unittest.WorkFolderScope(self.execution_directory,
# import Kratos
import KratosMultiphysics
import KratosMultiphysics.StructuralMechanicsApplication as StructuralMechanicsApplication
import run_cpp_unit_tests
import KratosMultiphysics.kratos_utilities as kratos_utilities

# Import Kratos "wrapper" for unittests
import KratosMultiphysics.KratosUnittest as KratosUnittest

import os, subprocess

has_eigen_solvers_application = kratos_utilities.CheckIfApplicationsAvailable("EigenSolversApplication")

# Import the tests or test_classes to create the suits

##### SELF-CONTAINED TESTS #####
# CL tests
from test_constitutive_law import TestConstitutiveLaw as TTestConstitutiveLaw
from test_perfect_plasticity_implementation_verification import TestPerfectPlasticityImplementationVerification as TTestPerfectPlasticityImplementationVerification
# Processes test
from test_mass_calculation import TestMassCalculation as TTestMassCalculation
from test_compute_center_of_gravity import TestComputeCenterOfGravity as TTestComputeCenterOfGravity
from test_compute_mass_moment_of_inertia import TestComputeMassMomentOfInertia as TTestComputeMassMomentOfInertia
from test_axis_projection import TestAxisProjection as TTestAxisProjection
from test_distribute_load_on_surface_process import TestDistributeLoadOnSurfaceProcess as TTestDistributeLoadOnSurfaceProcess
# Simple patch tests
from test_patch_test_small_strain import TestPatchTestSmallStrain as TTestPatchTestSmallStrain
from test_patch_test_small_strain_bbar import TestPatchTestSmallStrainBbar as TTestPatchTestSmallStrainBbar
from test_patch_test_small_displacement_mixed_volumetric_strain import TestPatchTestSmallDisplacementMixedVolumetricStrain as TTestPatchTestSmallDisplacementMixedVolumetricStrain
from test_patch_test_large_strain import TestPatchTestLargeStrain as TTestPatchTestLargeStrain
from test_quadratic_elements import TestQuadraticElements as TTestQuadraticElements
    return suites


if __name__ == '__main__':
    KratosMultiphysics.Logger.GetDefaultOutput().SetSeverity(
        KratosMultiphysics.Logger.Severity.WARNING)
    KratosMultiphysics.Logger.PrintInfo("Unittests",
                                        "\nRunning cpp unit tests ...")
    KratosMultiphysics.Tester.SetVerbosity(
        KratosMultiphysics.Tester.Verbosity.PROGRESS)  # TESTS_OUTPUTS
    KratosMultiphysics.Tester.RunTestSuite("FluidDynamicsApplicationFastSuite")
    KratosMultiphysics.Logger.PrintInfo("Unittests",
                                        "Finished running cpp unit tests!")

    if kratos_utilities.IsMPIAvailable(
    ) and kratos_utilities.CheckIfApplicationsAvailable(
            "MetisApplication", "TrilinosApplication"):
        KratosMultiphysics.Logger.PrintInfo("Unittests",
                                            "\nRunning mpi python tests ...")
        p = subprocess.Popen([
            "mpiexec", "-np", "2", "python3",
            "test_FluidDynamicsApplication_mpi.py"
        ],
                             stdout=subprocess.PIPE,
                             cwd=os.path.dirname(os.path.abspath(__file__)))
        p.wait()
        KratosMultiphysics.Logger.PrintInfo("Unittests",
                                            "Finished mpi python tests!")
    else:
        KratosMultiphysics.Logger.PrintInfo(
            "Unittests",
            "\nSkipping mpi python tests due to missing dependencies")
from KratosMultiphysics import *
from KratosMultiphysics.FSIApplication import *
import KratosMultiphysics.StructuralMechanicsApplication as KratosStructural

import KratosMultiphysics.KratosUnittest as UnitTest
import KratosMultiphysics.kratos_utilities as KratosUtils

if KratosUtils.CheckIfApplicationsAvailable("StructuralMechanicsApplication"):
    from KratosMultiphysics.StructuralMechanicsApplication import python_solvers_wrapper_structural

from os import remove

class WorkFolderScope:
    # TODO use KratosUnittest.WorkFolderScope
    def __init__(self, work_folder):
        self.currentPath = os.getcwd()
        self.scope = os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)),work_folder))

    def __enter__(self):
        os.chdir(self.scope)

    def __exit__(self, type, value, traceback):
        os.chdir(self.currentPath)

@UnitTest.skipIfApplicationsNotAvailable("StructuralMechanicsApplication", "LinearSolversApplication")
class FSIProblemEmulatorTest(UnitTest.TestCase):

    def setUp(self):
        self.work_folder = "FSIProblemEmulatorTest"
        self.input_file = "test_FSI_emulator_Structural"
Exemple #20
0
import math
import KratosMultiphysics
import KratosMultiphysics.KratosUnittest as UnitTest
import KratosMultiphysics.kratos_utilities as KratosUtilities

have_mesh_moving = KratosUtilities.CheckIfApplicationsAvailable(
    "MeshMovingApplication")

from KratosMultiphysics.FluidDynamicsApplication.fluid_dynamics_analysis import FluidDynamicsAnalysis


class CustomFluidDynamicsAnalysis(FluidDynamicsAnalysis):
    def __init__(self,
                 model,
                 project_parameters,
                 A=1.5,
                 w=2.0 * math.pi,
                 print_output=False):
        self.A = A  # Piston amplitude
        self.w = w  # Piston angular frequency
        self.print_output = print_output  # Print output flag
        super(CustomFluidDynamicsAnalysis,
              self).__init__(model, project_parameters)

    def ModifyInitialGeometry(self):
        # Call the parent ModifyInitialGeometry()
        super(CustomFluidDynamicsAnalysis, self).ModifyInitialGeometry()

        # Create and read the structure model part
        structure_model_part = self.model.CreateModelPart("Structure")
        structure_model_part.SetBufferSize(2)
Exemple #21
0
# Importing the Kratos Library
import KratosMultiphysics
import KratosMultiphysics.CompressiblePotentialFlowApplication as CPFApp

# Import KratosUnittest
import KratosMultiphysics.KratosUnittest as UnitTest

# Other imports
from KratosMultiphysics.CompressiblePotentialFlowApplication.potential_flow_analysis import PotentialFlowAnalysis
import KratosMultiphysics.kratos_utilities as kratos_utilities
from KratosMultiphysics.KratosUnittest import isclose as t_isclose

import os

# Check other applications dependency
hdf5_is_available = kratos_utilities.CheckIfApplicationsAvailable(
    "HDF5Application")
eignsolver_is_available = kratos_utilities.CheckIfApplicationsAvailable(
    "EigenSolversApplication")
meshing_is_available = kratos_utilities.CheckIfApplicationsAvailable(
    "MeshingApplication")
try:
    import stl
    numpy_stl_is_available = True
except:
    numpy_stl_is_available = False


class WorkFolderScope:
    def __init__(self, work_folder):
        self.currentPath = os.getcwd()
        self.scope = os.path.abspath(
import os
import sys

# Importing the Kratos Library
import KratosMultiphysics
import KratosMultiphysics.KratosUnittest as KratosUnittest
import KratosMultiphysics.kratos_utilities as KratosUtils
from KratosMultiphysics import read_materials_process

dependencies_are_available = KratosUtils.CheckIfApplicationsAvailable("StructuralMechanicsApplication", "FluidDynamicsApplication")
if dependencies_are_available:
    import KratosMultiphysics.FluidDynamicsApplication as KratosFluid
    import KratosMultiphysics.StructuralMechanicsApplication


def GetFilePath(fileName):
    return os.path.join(os.path.dirname(os.path.realpath(__file__)), fileName)

class TestMaterialsInput(KratosUnittest.TestCase):
    def _prepare_test(self, input_file = "materials.json"):
        # Define a Model
        self.current_model = KratosMultiphysics.Model()

        self.model_part = self.current_model.CreateModelPart("Main")

        self.model_part.AddNodalSolutionStepVariable(KratosMultiphysics.DISPLACEMENT)
        self.model_part.AddNodalSolutionStepVariable(KratosMultiphysics.VISCOSITY)
        self.model_part_io = KratosMultiphysics.ModelPartIO(GetFilePath("auxiliar_files_for_python_unittest/mdpa_files/test_model_part_io_read")) #reusing the file that is already in the directory
        self.model_part_io.ReadModelPart(self.model_part)

        self.test_settings = KratosMultiphysics.Parameters("""
Exemple #23
0
from __future__ import print_function, absolute_import, division  # makes KratosMultiphysics backward compatible with python 2.6 and 2.7

# Importing the Kratos Library
import KratosMultiphysics
import KratosMultiphysics.kratos_utilities as KratosUtilities

# Import applications
import KratosMultiphysics.FluidDynamicsApplication as KratosCFD
have_conv_diff = KratosUtilities.CheckIfApplicationsAvailable(
    "ConvectionDiffusionApplication")
if have_conv_diff:
    import KratosMultiphysics.ConvectionDiffusionApplication as KratosConvDiff

# Import base class file
from KratosMultiphysics.FluidDynamicsApplication.fluid_solver import FluidSolver
from KratosMultiphysics.FluidDynamicsApplication.read_distance_from_file import DistanceImportUtility

import KratosMultiphysics.python_linear_solver_factory as linear_solver_factory


def CreateSolver(model, custom_settings):
    return NavierStokesTwoFluidsSolver(model, custom_settings)


class NavierStokesTwoFluidsSolver(FluidSolver):
    @classmethod
    def GetDefaultSettings(cls):
        ##settings string in json format
        default_settings = KratosMultiphysics.Parameters("""
        {
            "solver_type": "two_fluids_solver_from_defaults",
from __future__ import print_function, absolute_import, division  #makes KratosMultiphysics backward compatible with python 2.6 and 2.7
#import kratos core and applications
from KratosMultiphysics import *
from KratosMultiphysics.StructuralMechanicsApplication import *
import KratosMultiphysics.KratosUnittest as KratosUnittest
import structural_mechanics_analysis
import KratosMultiphysics.kratos_utilities as kratos_utilities

if kratos_utilities.CheckIfApplicationsAvailable("HDF5Application"):
    has_hdf5_application = True
else:
    has_hdf5_application = False

# This utility will control the execution scope in case we need to access files or we depend
# on specific relative locations of the files.


# TODO: Should we move this to KratosUnittest?
class controlledExecutionScope:
    def __init__(self, scope):
        self.currentPath = os.getcwd()
        self.scope = scope

    def __enter__(self):
        os.chdir(self.scope)

    def __exit__(self, type, value, traceback):
        os.chdir(self.currentPath)


def solve_primal_problem():
import KratosMultiphysics
import KratosMultiphysics.process_factory as process_factory
import KratosMultiphysics.KratosUnittest as UnitTest
import KratosMultiphysics.kratos_utilities as KratosUtilities
from KratosMultiphysics.FluidDynamicsApplication import python_solvers_wrapper_fluid

import KratosMultiphysics.FluidDynamicsApplication as KratosFluid

have_external_solvers = KratosUtilities.CheckIfApplicationsAvailable(
    "ExternalSolversApplication")


@UnitTest.skipUnless(have_external_solvers,
                     "Missing required application: ExternalSolversApplication"
                     )
class EmbeddedCouetteTest(UnitTest.TestCase):

    # Embedded element tests
    def testEmbeddedCouette2D(self):
        self.distance = 0.25
        self.slip_flag = False
        self.work_folder = "EmbeddedCouette2DTest"
        self.reference_file = "reference_couette_embedded_2D"
        self.settings = "EmbeddedCouette2DTestParameters.json"
        self.ExecuteEmbeddedCouetteTest()

    def testEmbeddedCouette3D(self):
        self.distance = 0.25
        self.slip_flag = False
        self.work_folder = "EmbeddedCouette3DTest"
        self.reference_file = "reference_couette_embedded_3D"
Exemple #26
0
# import Kratos
import KratosMultiphysics
import KratosMultiphysics.StructuralMechanicsApplication as StructuralMechanicsApplication
import run_cpp_unit_tests
import KratosMultiphysics.kratos_utilities as kratos_utilities

# Import Kratos "wrapper" for unittests
import KratosMultiphysics.KratosUnittest as KratosUnittest

import subprocess

if kratos_utilities.CheckIfApplicationsAvailable("ExternalSolversApplication"):
    has_external_solvers_application = True
else:
    has_external_solvers_application = False

# Import the tests or test_classes to create the suits

##### SELF-CONTAINED TESTS #####
# CL tests
from test_constitutive_law import TestConstitutiveLaw as TTestConstitutiveLaw
from test_perfect_plasticity_implementation_verification import TestPerfectPlasticityImplementationVerification as TTestPerfectPlasticityImplementationVerification
# Processes test
from test_mass_calculation import TestMassCalculation as TTestMassCalculation
from test_compute_center_of_gravity import TestComputeCenterOfGravity as TTestComputeCenterOfGravity
from test_compute_mass_moment_of_inertia import TestComputeMassMomentOfInertia as TTestComputeMassMomentOfInertia
# Simple patch tests
from test_patch_test_small_strain import TestPatchTestSmallStrain as TTestPatchTestSmallStrain
from test_patch_test_small_strain_bbar import TestPatchTestSmallStrainBbar as TTestPatchTestSmallStrainBbar
from test_patch_test_large_strain import TestPatchTestLargeStrain as TTestPatchTestLargeStrain
from test_quadratic_elements import TestQuadraticElements as TTestQuadraticElements
Exemple #27
0
import KratosMultiphysics.KratosUnittest as KratosUnittest
import KratosMultiphysics.kratos_utilities as kratos_utils

import co_simulation_test_case
import os

try:
    import numpy
    numpy_available = True
except ImportError:
    numpy_available = False

have_fsi_dependencies = kratos_utils.CheckIfApplicationsAvailable("FluidDynamicsApplication", "StructuralMechanicsApplication", "MappingApplication", "MeshMovingApplication", "LinearSolversApplication")
have_potential_fsi_dependencies = kratos_utils.CheckIfApplicationsAvailable("CompressiblePotentialFlowApplication", "StructuralMechanicsApplication", "MappingApplication", "MeshMovingApplication", "LinearSolversApplication")
have_mpm_fem_dependencies = kratos_utils.CheckIfApplicationsAvailable("ParticleMechanicsApplication", "StructuralMechanicsApplication", "MappingApplication", "LinearSolversApplication")
have_dem_fem_dependencies = kratos_utils.CheckIfApplicationsAvailable("DEMApplication", "StructuralMechanicsApplication", "MappingApplication", "LinearSolversApplication")
have_fem_fem_dependencies = kratos_utils.CheckIfApplicationsAvailable("StructuralMechanicsApplication", "MappingApplication")

def GetFilePath(fileName):
    return os.path.join(os.path.dirname(os.path.realpath(__file__)), fileName)

class TestTinyFetiCoSimulationCases(co_simulation_test_case.CoSimulationTestCase):
    '''This class contains "tiny" FETI CoSimulation-Cases, small enough to run in the CI
    '''
    def test_FEM_FEM_small_2d_plate_feti_explict_explicit(self):
        if not numpy_available:
            self.skipTest("Numpy not available")
        if not have_fem_fem_dependencies:
            self.skipTest("FEM-FEM dependencies are not available!")

        self.name = "test_FEM_FEM_small_2d_plate_feti_explict_explicit"
import os

#import kratos core and applications
import KratosMultiphysics
import KratosMultiphysics.StructuralMechanicsApplication as StructuralMechanicsApplication
import KratosMultiphysics.KratosUnittest as KratosUnittest
from KratosMultiphysics.StructuralMechanicsApplication import structural_mechanics_analysis
import KratosMultiphysics.kratos_utilities as kratos_utilities
from KratosMultiphysics import IsDistributedRun
from structural_mechanics_test_factory import SelectAndVerifyLinearSolver

has_hdf5_application = kratos_utilities.CheckIfApplicationsAvailable(
    "HDF5Application")


class AdjointSensitivityAnalysisTestFactory(KratosUnittest.TestCase):
    def setUp(self):
        # Within this location context:
        with KratosUnittest.WorkFolderScope(".", __file__):
            # Reading the ProjectParameters
            with open(self.primal_file_name, 'r') as parameter_file:
                primal_parameters = KratosMultiphysics.Parameters(
                    parameter_file.read())
            with open(self.adjoint_file_name, 'r') as parameter_file:
                self.adjoint_parameters = KratosMultiphysics.Parameters(
                    parameter_file.read())
            self.problem_name = primal_parameters["problem_data"][
                "problem_name"].GetString()
            self.model_part_name = primal_parameters["solver_settings"][
                "model_part_name"].GetString()
from __future__ import print_function, absolute_import, division

import os
import sys

# Importing the Kratos Library
import KratosMultiphysics
import KratosMultiphysics.KratosUnittest as KratosUnittest
import KratosMultiphysics.kratos_utilities as KratosUtils

structural_mechanics_is_available = KratosUtils.CheckIfApplicationsAvailable("StructuralMechanicsApplication")
if structural_mechanics_is_available:
    import KratosMultiphysics.StructuralMechanicsApplication


def GetFilePath(fileName):
    return os.path.join(os.path.dirname(os.path.realpath(__file__)), fileName)


class TestModelPartIO(KratosUnittest.TestCase):
    def tearDown(self):
        # Clean up temporary files
        KratosUtils.DeleteFileIfExisting(GetFilePath("test_model_part_io_write.out.mdpa"))
        KratosUtils.DeleteFileIfExisting(GetFilePath("test_model_part_io_write.out.time"))
        KratosUtils.DeleteFileIfExisting(GetFilePath("test_model_part_io_write.time"))

    def test_model_part_io_read_model_part(self):
        current_model = KratosMultiphysics.Model()

        model_part = current_model.CreateModelPart("Main")
        model_part.AddNodalSolutionStepVariable(KratosMultiphysics.DISPLACEMENT)
from __future__ import print_function, absolute_import, division  # makes KratosMultiphysics backward compatible with python 2.6 and 2.7

# Importing the Kratos Library
import KratosMultiphysics

# Import KratosUnittest
import KratosMultiphysics.KratosUnittest as KratosUnittest
from KratosMultiphysics.ConvectionDiffusionApplication.convection_diffusion_analysis import ConvectionDiffusionAnalysis
import KratosMultiphysics.kratos_utilities as kratos_utilities

have_eigen_solvers_dependencies = kratos_utilities.CheckIfApplicationsAvailable(
    "EigenSolversApplication")

# Other imports
import os

# This utility will control the execution scope in case we need to access files or we depend
# on specific relative locations of the files.


# TODO: Should we move this to KratosUnittest?
class controlledExecutionScope:
    def __init__(self, scope):
        self.currentPath = os.getcwd()
        self.scope = scope

    def __enter__(self):
        os.chdir(self.scope)

    def __exit__(self, type, value, traceback):
        os.chdir(self.currentPath)