Skip to content

Commit

Permalink
Merge branch 'master' into PfemFluid/add-constitutive-laws
Browse files Browse the repository at this point in the history
  • Loading branch information
MZecchetto committed May 3, 2020
2 parents 0b7dd9e + e6e2613 commit 2ff8f27
Show file tree
Hide file tree
Showing 287 changed files with 9,920 additions and 3,433 deletions.
1 change: 1 addition & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ jobs:
set KRATOS_APPLICATIONS=%KRATOS_APPLICATIONS%%KRATOS_APP_DIR%\MeshMovingApplication;
set KRATOS_APPLICATIONS=%KRATOS_APPLICATIONS%%KRATOS_APP_DIR%\EigenSolversApplication;
set KRATOS_APPLICATIONS=%KRATOS_APPLICATIONS%%KRATOS_APP_DIR%\StructuralMechanicsApplication;
set KRATOS_APPLICATIONS=%KRATOS_APPLICATIONS%%KRATOS_APP_DIR%\DEMApplication;
set KRATOS_APPLICATIONS=%KRATOS_APPLICATIONS%%KRATOS_APP_DIR%\ChimeraApplication;
set KRATOS_APPLICATIONS=%KRATOS_APPLICATIONS%%KRATOS_APP_DIR%\IgaApplication;
set KRATOS_APPLICATIONS=%KRATOS_APPLICATIONS%%KRATOS_APP_DIR%\ParticleMechanicsApplication;
Expand Down
27 changes: 15 additions & 12 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -86,20 +86,23 @@ SET( CMAKE_MODULE_LINKER_FLAGS_FULLDEBUG "${CMAKE_MODULE_LINKER_FLAGS}")
SET( CMAKE_MODULE_LINKER_FLAGS_CUSTOM "${CMAKE_MODULE_LINKER_FLAGS}")

# If build mode is not defined, assume Release
if(DEFINED ENV{KRATOS_BUILD_TYPE})
list(FIND CMAKE_CONFIGURATION_TYPES $ENV{KRATOS_BUILD_TYPE} FOUND_MODE)
if(FOUND_MODE EQUAL -1)
message("Unknown CMAKE_BUILD_TYPE '${CMAKE_BUILD_TYPE}', using 'Release'.")
set(CMAKE_BUILD_TYPE Release)
else(FOUND_MODE EQUAL -1)
set(CMAKE_BUILD_TYPE $ENV{KRATOS_BUILD_TYPE})
endif(FOUND_MODE EQUAL -1)
else(DEFINED ENV{KRATOS_BUILD_TYPE})
message("--No CMAKE_BUILD_TYPE is defined, building in 'Release' mode.")
set(CMAKE_BUILD_TYPE Release)
endif(DEFINED ENV{KRATOS_BUILD_TYPE})
if(NOT CMAKE_BUILD_TYPE)
if(DEFINED ENV{KRATOS_BUILD_TYPE})
list(FIND CMAKE_CONFIGURATION_TYPES $ENV{KRATOS_BUILD_TYPE} FOUND_MODE)
if(FOUND_MODE EQUAL -1)
message("Unknown CMAKE_BUILD_TYPE '${CMAKE_BUILD_TYPE}', using 'Release'.")
set(CMAKE_BUILD_TYPE Release)
else(FOUND_MODE EQUAL -1)
set(CMAKE_BUILD_TYPE $ENV{KRATOS_BUILD_TYPE})
endif(FOUND_MODE EQUAL -1)
else(DEFINED ENV{KRATOS_BUILD_TYPE})
message("--No CMAKE_BUILD_TYPE is defined, building in 'Release' mode.")
set(CMAKE_BUILD_TYPE Release)
endif(DEFINED ENV{KRATOS_BUILD_TYPE})
endif(NOT CMAKE_BUILD_TYPE)
set (KratosMultiphysics_BUILD_TYPE ${CMAKE_BUILD_TYPE})


if(USE_COTIRE MATCHES ON)
include(cotire)
set(CMAKE_SKIP_RPATH ON)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@ def __init__(self, settings, solver_name):

super(CoSimulationCoupledSolver, self).__init__(settings, solver_name)

self.process_info = KM.ProcessInfo()

self.solver_wrappers = self.__CreateSolverWrappers()

self.coupling_sequence = self.__GetSolverCoSimulationDetails()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ def __init__(self, custom_settings, model, name="default", solver_name="default_

self.variable_type = KM.KratosGlobals.GetVariableType(variable_name)

admissible_scalar_variable_types = ["Bool", "Integer", "Unsigned Integer", "Double", "Component"]
admissible_scalar_variable_types = ["Bool", "Integer", "Unsigned Integer", "Double"]
admissible_vector_variable_types = ["Array"]

if not self.variable_type in admissible_scalar_variable_types and not self.variable_type in admissible_vector_variable_types:
Expand Down Expand Up @@ -91,13 +91,8 @@ def Initialize(self):
if domain_size != self.dimension:
cs_tools.cs_print_warning('CouplingInterfaceData', '"DOMAIN_SIZE" ({}) of ModelPart "{}" does not match dimension ({})'.format(domain_size, self.model_part_name, self.dimension))

if self.location == "node_historical":
if self.variable_type == "Component":
var_to_check = self.variable.GetSourceVariable()
else:
var_to_check = self.variable
if not self.model_part.HasNodalSolutionStepVariable(var_to_check):
self.__RaiseException('"{}" is missing as SolutionStepVariable in ModelPart "{}"'.format(var_to_check.Name(), self.model_part_name))
if self.location == "node_historical" and not self.model_part.HasNodalSolutionStepVariable(self.variable):
self.__RaiseException('"{}" is missing as SolutionStepVariable in ModelPart "{}"'.format(self.variable.Name(), self.model_part_name))

self.is_initialized = True

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
from __future__ import print_function, absolute_import, division # makes KratosMultiphysics backward compatible with python 2.6 and 2.7

# Importing the Kratos Library
from KratosMultiphysics.kratos_utilities import CheckIfApplicationsAvailable

if not CheckIfApplicationsAvailable("CompressiblePotentialFlowApplication"):
raise ImportError("The CompressiblePotentialFlowApplication is not available!")

# Importing the base class
from KratosMultiphysics.CoSimulationApplication.solver_wrappers.kratos import kratos_base_wrapper

# Other imports
from KratosMultiphysics.CompressiblePotentialFlowApplication.potential_flow_analysis import PotentialFlowAnalysis
from KratosMultiphysics.CompressiblePotentialFlowApplication.compute_forces_on_nodes_process import ComputeForcesOnNodesProcess
from KratosMultiphysics.CompressiblePotentialFlowApplication.define_wake_process_2d import DefineWakeProcess2D
from KratosMultiphysics.CompressiblePotentialFlowApplication.compute_lift_process import ComputeLiftProcess

def Create(settings, solver_name):
return PotentialFlowWrapper(settings, solver_name)

class PotentialFlowWrapper(kratos_base_wrapper.KratosBaseWrapper):
def _CreateAnalysisStage(self):
return PotentialFlowAnalysis(self.model, self.project_parameters)

def Predict(self):
pass

def Initialize(self):

super(PotentialFlowWrapper, self).Initialize()

sub_project_parameters = self.project_parameters["processes"]["boundary_conditions_process_list"]

for i in range(sub_project_parameters.size()):
if sub_project_parameters[i]["python_module"].GetString() == "define_wake_process_2d":
self.wake_process = DefineWakeProcess2D(self.model, sub_project_parameters[i]["Parameters"])
if not hasattr(self, "wake_process"):
raise Exception("potential flow requires specification of a process for the wake (currently specifically using 'define_wake_process_2d')")

if sub_project_parameters[i]["python_module"].GetString() == "compute_forces_on_nodes_process":
self.conversion_process = ComputeForcesOnNodesProcess(self.model, sub_project_parameters[i]["Parameters"])
if sub_project_parameters[i]["python_module"].GetString() == "compute_lift_process":
self.lift_process = ComputeLiftProcess(self.model, sub_project_parameters[i]["Parameters"])

def SolveSolutionStep(self):
self.wake_process.ExecuteInitialize()

## the next two lines are needed in order to add Wake DoFs to the new Wake Elements Nodes
## and delete the ones that are no longer in the Wake Region.
self._analysis_stage._GetSolver().Clear()
self._analysis_stage._GetSolver().InitializeSolutionStep()

super(PotentialFlowWrapper, self).SolveSolutionStep()

self.lift_process.ExecuteFinalizeSolutionStep()
self.conversion_process.ExecuteFinalizeSolutionStep()
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
from __future__ import print_function, absolute_import, division # makes these scripts backward compatible with python 2.6 and 2.7
# Importing the base class
import KratosMultiphysics
from KratosMultiphysics.CoSimulationApplication.function_callback_utility import GenericCallFunction

# Other imports
import json
import os

class SDoFStaticSolver(object):
def __init__(self, input_name):

# mimicing two constructors
if isinstance(input_name, dict):
parameters = input_name

elif isinstance(input_name, str):
if not input_name.endswith(".json"):
input_name += ".json"

with open(input_name,'r') as ProjectParameters:
parameters = json.load(ProjectParameters)

else:
raise Exception("The input has to be provided as a dict or a string")

default_settings = {
"system_parameters":{
"stiffness" : 4000.0
},
"initial_values":{
"displacement" : 0.0,
},
"boundary_conditions":{
"external_load" : 5000.0
},
"solver_parameters": {
"buffer_size" : 1
},
"output_parameters":{
"write_output_file": False,
"file_name" : "sdof_static_solver/results_sdof.dat"
}}

RecursivelyValidateAndAssignDefaults(default_settings, parameters)

self.stiffness = parameters["system_parameters"]["stiffness"]

self.initial_displacement = parameters["initial_values"]["displacement"]

self.force = parameters["boundary_conditions"]["external_load"]

self.buffer_size = parameters["solver_parameters"]["buffer_size"]

self.output_file_name = parameters["output_parameters"]["file_name"]

self.write_output_file = parameters["output_parameters"]["write_output_file"]

def Initialize(self):
initial_values = self.initial_displacement
self.dx = initial_values

if self.write_output_file:
if os.path.isfile(self.output_file_name):
os.remove(self.output_file_name)
self.InitializeOutput()
self.time = 0.0

def InitializeOutput(self):
with open(self.output_file_name, "w") as results_sdof_static:
results_sdof_static.write("displacement" + "\n")
self.OutputSolutionStep()

def OutputSolutionStep(self):
if self.write_output_file:
with open(self.output_file_name, "a") as results_sdof_static:
#outputs results
results_sdof_static.write(str(self.dx) + "\n")

def AdvanceInTime(self, current_time):
self.time = 0.0
return self.time

def SolveSolutionStep(self):
self.dx = self.force/self.stiffness
KratosMultiphysics.Logger.PrintInfo('SDoFStaticSolver', 'Force Imported = ', self.force)
KratosMultiphysics.Logger.PrintInfo('SDoFStaticSolver', 'Structure Stiffness = ', self.stiffness)
KratosMultiphysics.Logger.PrintInfo('SDoFStaticSolver', 'New Displacement = ', self.dx)

def CalculateReaction(self, buffer_idx=0):
reaction = self.stiffness * (self.dx)
return reaction

def GetSolutionStepValue(self, identifier, buffer_idx=0):
if identifier == "DISPLACEMENT":
return self.dx
elif identifier == "REACTION":
return self.CalculateReaction()
else:
raise Exception("Identifier is unknown!")

def SetSolutionStepValue(self, identifier, value, buffer_idx=0):
if identifier == "DISPLACEMENT":
self.dx= value
elif identifier == "LOAD":
self.force = 0.0
self.force = value
elif identifier == "ROOT_POINT_DISPLACEMENT":
self.root_point_displacement = 0.0
self.root_point_displacement = value
else:
raise Exception("Identifier is unknown!")

def ValidateAndAssignDefaults(defaults, settings, recursive=False):
for key, val in settings.items():
# check if the current entry also exists in the defaults
if not key in defaults.keys():
err_msg = 'The item with name "' + key + '" is present in this '
err_msg += 'settings\nbut NOT in the defaults!\n'
err_msg += 'settings are:\n'
err_msg += json.dumps(settings, indent=4)
err_msg += '\ndefaults are:\n'
err_msg += json.dumps(defaults, indent=4)
raise Exception(err_msg)

# check if the type is the same in the defaults
if type(settings[key]) != type(defaults[key]):
err_msg = 'The type of the item with name "' + key + '" (type: "'
err_msg += str(type(settings[key]).__name__)+'") in this '
err_msg += 'settings\nis NOT the same as in the defaults (type: "'
err_msg += str(type(defaults[key]).__name__)+'")!\n'
err_msg += 'settings are:\n'
err_msg += json.dumps(settings, indent=4)
err_msg += '\ndefaults are:\n'
err_msg += json.dumps(defaults, indent=4)
raise Exception(err_msg)

# loop the defaults and add the missing entries
for key_d, val_d in defaults.items():
if key_d not in settings: # add the default in case the setting is not present
settings[key_d] = val_d
elif recursive and type(val_d) is dict:
RecursivelyValidateAndAssignDefaults(val_d, settings[key_d])

def RecursivelyValidateAndAssignDefaults(defaults, settings):
ValidateAndAssignDefaults(defaults, settings, recursive=True)
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
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 as KM
import KratosMultiphysics.CoSimulationApplication as KMC

# Importing the base class
from KratosMultiphysics.CoSimulationApplication.base_classes.co_simulation_solver_wrapper import CoSimulationSolverWrapper

# Other imports
from .sdof_static_solver import SDoFStaticSolver
from .sdof_solver_wrapper import SdofSolverWrapper

def Create(settings, solver_name):
return SdofStaticSolverWrapper(settings, solver_name)

class SdofStaticSolverWrapper(SdofSolverWrapper):
""" This class implements a wrapper for an SDof solver to be used in CoSimulation
"""
def __init__(self, settings, solver_name):
CoSimulationSolverWrapper.__init__(self,settings, solver_name)

input_file_name = self.settings["solver_wrapper_settings"]["input_file"].GetString()

self.mp = self.model.CreateModelPart("Sdof_Static")
self.mp.ProcessInfo[KM.DOMAIN_SIZE] = 1
self._sdof_solver = SDoFStaticSolver(input_file_name)

def SolveSolutionStep(self):
self._sdof_solver.SetSolutionStepValue("ROOT_POINT_DISPLACEMENT", self.mp[KMC.SCALAR_ROOT_POINT_DISPLACEMENT], 0)
self._sdof_solver.SetSolutionStepValue("LOAD", self.mp[KMC.SCALAR_FORCE], 0)

self._sdof_solver.SolveSolutionStep()

self.mp[KMC.SCALAR_DISPLACEMENT] = self._sdof_solver.GetSolutionStepValue("DISPLACEMENT", 0)
self.mp[KMC.SCALAR_REACTION] = self._sdof_solver.GetSolutionStepValue("REACTION", 0)

def Check(self):
# making sure only a set of vaiables can be used
admissible_variables = [
"SCALAR_FORCE",
"SCALAR_DISPLACEMENT",
"SCALAR_REACTION",
]
for data in self.data_dict.values():
if data.variable.Name() not in admissible_variables:
raise Exception('Variable "{}" of interface data "{}" of solver "{}" cannot be used for the SDof Solver!\nOnly the following variables are allowed: {}'.format(data.variable.Name(), data.name, data.solver_name, admissible_variables))
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
numpy_available = False

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

Expand Down Expand Up @@ -159,6 +160,19 @@ def test_sdof_fsi(self):
# self.__AddVtkOutputToCFD() # uncomment to get output
self._runTest()

def test_sdof_static_fsi(self):
if not numpy_available:
self.skipTest("Numpy not available")
if using_pykratos:
self.skipTest("This test cannot be run with pyKratos!")
if not have_potential_fsi_dependencies:
self.skipTest("FSI dependencies are not available!")

with KratosUnittest.WorkFolderScope(".", __file__):
self._createTest("fsi_sdof_static", "project_cosim_naca0012_small_fsi")
# self.__AddVtkOutputToCFD() # uncomment to get output
self._runTest()

@classmethod
def tearDownClass(cls):
super(TestCoSimulationCases,cls).tearDownClass()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"system_parameters":{
"stiffness" : 50000.00
},
"initial_values":{
"displacement": 0.0
},
"boundary_conditions":{
"external_load": 10000.0
},
"solver_parameters": {
"buffer_size": 3
},
"output_parameters":{
"write_output_file": false,
"file_name": "fsi_sdof_static/results_final_sdof.dat"
}

}
Loading

0 comments on commit 2ff8f27

Please sign in to comment.