Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[OptApp] Small fixes to RGP, Conv Crit, NLOPT test #12844

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,11 @@ def Solve(self):

self.UpdateControl()

self.converged = self.__convergence_criteria.IsConverged()
converged = self.__convergence_criteria.IsConverged()

converged &= all([value <= 0.0 for value in self.__constr_value])

self.converged |= self.__convergence_criteria.IsMaxIterationsReached()

self._optimization_problem.AdvanceStep()

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -294,9 +294,11 @@ def Solve(self):

self.UpdateControl()

self.converged = self.__convergence_criteria.IsConverged()
converged = self.__convergence_criteria.IsConverged()

self.converged &= all([c.IsSatisfied() for c in self.__constraints_list])
converged &= all([c.IsSatisfied() for c in self.__constraints_list])

self.converged |= self.__convergence_criteria.IsMaxIterationsReached()

self._optimization_problem.AdvanceStep()

Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import KratosMultiphysics as Kratos
import KratosMultiphysics.OptimizationApplication as KratosOA
from KratosMultiphysics.OptimizationApplication.controls.control import Control
from KratosMultiphysics.OptimizationApplication.utilities.union_utilities import SupportedSensitivityFieldVariableTypes
Expand Down Expand Up @@ -181,6 +182,10 @@ def Update(self, update_collective_expressions: KratosOA.CollectiveExpression) -
update_map: 'dict[Control, bool]' = {}
for control, container_expression in zip(self.__list_of_controls, update_collective_expressions.GetContainerExpressions()):
update_map[control] = control.Update(container_expression)
if update_map[control]:
Kratos.Logger.PrintInfo(f"Control {control.GetName()} updated.")
else:
Kratos.Logger.PrintInfo(f"Control {control.GetName()} not updated")
Comment on lines +185 to +188
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice :)


return update_map

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from KratosMultiphysics.OptimizationApplication.utilities.optimization_problem import OptimizationProblem
from KratosMultiphysics.OptimizationApplication.utilities.logger_utilities import time_decorator
from KratosMultiphysics.OptimizationApplication.filtering.filter import Factory as FilterFactory
import math

def Factory(model: Kratos.Model, parameters: Kratos.Parameters, optimization_problem: OptimizationProblem) -> Control:
if not parameters.Has("name"):
Expand Down Expand Up @@ -147,7 +148,8 @@ def MapGradient(self, physical_gradient_variable_container_expression_map: 'dict
def Update(self, new_control_field: ContainerExpressionTypes) -> bool:
if not IsSameContainerExpression(new_control_field, self.GetEmptyField()):
raise RuntimeError(f"Updates for the required element container not found for control \"{self.GetName()}\". [ required model part name: {self.model_part.FullName()}, given model part name: {new_control_field.GetModelPart().FullName()} ]")
if Kratos.Expression.Utils.NormL2(self.control_field - new_control_field) > 1e-15:
diff_norm = Kratos.Expression.Utils.NormL2(self.control_field - new_control_field)
if not math.isclose(diff_norm, 0.0, abs_tol=1e-16):
# update the control SHAPE field
control_update = new_control_field - self.control_field
self.control_field = new_control_field
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,26 @@ def CreateConvergenceCriteria(parameters: Kratos.Parameters, optimization_proble
raise RuntimeError(f"CreateConvergenceCriteria: unsupported convergence type {type}.")

class MaxIterConvCriterion:
"""
A convergence criterion class that checks if the maximum number of iterations has been reached.

Methods
-------
GetDefaultParameters():
Returns the default parameters for the convergence criterion.

__init__(parameters: Kratos.Parameters, optimization_problem: OptimizationProblem):
Initializes the convergence criterion with the given parameters and optimization problem.

IsMaxIterationsReached():
Checks if the maximum number of iterations has been reached.

IsConverged(search_direction=None) -> bool:
Checks if the optimization problem has converged based on the maximum number of iterations.

GetInfo() -> dict:
Returns a dictionary with information about the current state of convergence.
"""
Comment on lines +25 to +44
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@matekelemen, does this way of writing method docs within the class doc works? can doxygen decipher this and put it to correct method?

@classmethod
def GetDefaultParameters(cls):
return Kratos.Parameters("""{
Expand All @@ -34,6 +54,9 @@ def __init__(self, parameters: Kratos.Parameters, optimization_problem: Optimiza
self.__max_iter = parameters["max_iter"].GetInt()
self.__optimization_problem = optimization_problem

def IsMaxIterationsReached(self):
return self.__optimization_problem.GetStep() >= self.__max_iter

@time_decorator()
def IsConverged(self, search_direction=None) -> bool:
iter = self.__optimization_problem.GetStep()
Expand All @@ -50,6 +73,26 @@ def GetInfo(self) -> dict:
return info

class L2ConvCriterion:
"""
A class to check the convergence of an optimization problem using the L2 norm criterion.

Methods
-------
GetDefaultParameters():
Returns the default parameters for the L2ConvCriterion.

__init__(parameters: Kratos.Parameters, optimization_problem: OptimizationProblem):
Initializes the L2ConvCriterion with given parameters and optimization problem.

IsMaxIterationsReached() -> bool:
Checks if the maximum number of iterations has been reached.

IsConverged() -> bool:
Checks if the optimization problem has converged based on the L2 norm of the search direction.

GetInfo() -> dict:
Returns a dictionary with information about the current state of convergence.
"""
@classmethod
def GetDefaultParameters(cls):
return Kratos.Parameters("""{
Expand All @@ -64,6 +107,9 @@ def __init__(self, parameters: Kratos.Parameters, optimization_problem: Optimiza
self.__optimization_problem = optimization_problem
self.__tolerance = parameters["tolerance"].GetDouble()

def IsMaxIterationsReached(self):
return self.__optimization_problem.GetStep() >= self.__max_iter

@time_decorator()
def IsConverged(self) -> bool:
iter = self.__optimization_problem.GetStep()
Expand All @@ -90,6 +136,27 @@ def GetInfo(self) -> dict:
return info

class AverageAbsoluteImprovement:
"""
A class to monitor the convergence of an optimization problem based on the average absolute improvement
of a tracked value over a specified number of iterations.

Methods
-------
GetDefaultParameters():
Returns the default parameters for the convergence criteria.

__init__(parameters: Kratos.Parameters, optimization_problem: OptimizationProblem):
Initializes the convergence criteria with the given parameters and optimization problem.

IsMaxIterationsReached() -> bool:
Checks if the maximum number of iterations has been reached.

IsConverged() -> bool:
Checks if the optimization problem has converged based on the average absolute improvement.

GetInfo() -> dict:
Returns a dictionary with information about the current state of the convergence criteria.
"""
@classmethod
def GetDefaultParameters(cls):
return Kratos.Parameters("""{
Expand All @@ -108,6 +175,9 @@ def __init__(self, parameters: Kratos.Parameters, optimization_problem: Optimiza
self.__abs_value_change = []
self.value = None

def IsMaxIterationsReached(self):
return self.__optimization_problem.GetStep() >= self.__max_iter

@time_decorator()
def IsConverged(self) -> bool:
iter = self.__optimization_problem.GetStep()
Expand Down Expand Up @@ -147,6 +217,26 @@ def GetInfo(self) -> dict:
return info

class TargetValueCriterion:
"""
A class to check the convergence of an optimization problem based on a target value criterion.

Methods
-------
GetDefaultParameters():
Returns the default parameters for the criterion.

__init__(parameters: Kratos.Parameters, optimization_problem: OptimizationProblem):
Initializes the criterion with given parameters and optimization problem.

IsMaxIterationsReached() -> bool:
Checks if the maximum number of iterations has been reached.

IsConverged() -> bool:
Checks if the optimization problem has converged based on the target value.

GetInfo() -> dict:
Returns a dictionary with information about the current state of convergence.
"""
@classmethod
def GetDefaultParameters(cls):
return Kratos.Parameters("""{
Expand All @@ -161,6 +251,9 @@ def __init__(self, parameters: Kratos.Parameters, optimization_problem: Optimiza
self.__optimization_problem = optimization_problem
self.__target_value = parameters["target_value"].GetDouble()

def IsMaxIterationsReached(self):
return self.__optimization_problem.GetStep() >= self.__max_iter

@time_decorator()
def IsConverged(self) -> bool:
iter = self.__optimization_problem.GetStep()
Expand Down Expand Up @@ -202,6 +295,9 @@ def __init__(self, parameters: Kratos.Parameters, optimization_problem: Optimiza
self.__target_scaling_factor = parameters["target_scaling_factor"].GetDouble()
self.__machine_precision = parameters["machine_precision"].GetDouble()

def IsMaxIterationsReached(self):
return self.__optimization_problem.GetStep() >= self.__max_iter

@time_decorator()
def IsConverged(self) -> bool:
iter = self.__optimization_problem.GetStep()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
"DENSITY": 7.85000E+03,
"YOUNG_MODULUS": 2.06900E+11,
"POISSON_RATIO": 2.90000E-01,
"THICKNESS": 8.00000E-2
"THICKNESS": 7.00000E-2
Igarizza marked this conversation as resolved.
Show resolved Hide resolved
},
"Tables": {}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,28 +61,22 @@
"shell"
],
"filter_settings": {
"type": "implicit",
"radius": 0.2,
"linear_solver_settings": {
"solver_type": "amgcl",
"smoother_type": "ilu0",
"krylov_type": "gmres",
"coarsening_type": "aggregation",
"max_iteration": 200,
"provide_coordinates": false,
"gmres_krylov_space_dimension": 100,
"verbosity": 0,
"tolerance": 1e-7,
"scaling": false,
"block_size": 1,
"use_block_matrices_if_possible": true,
"coarse_enough": 5000
}
"filter_type": "implicit_filter",
"filter_radius": 0.2
},
"output_all_fields": false,
"beta_value": 25.0,
"initial_physical_thickness": 0.07,
"physical_thicknesses": [0.01,0.1]
"physical_thicknesses": [
0.01,
0.1
],
"thickness_projection_settings": {
"type": "adaptive_sigmoidal_projection",
"initial_value": 25,
"max_value": 30,
"increase_fac": 1.05,
"update_period": 50,
"penalty_factor": 1
}
}
}
],
Expand All @@ -93,7 +87,7 @@
"controls_lower_bound" : "0",
"controls_upper_bound" : "1",
"stopping_criteria" : {
"maximum_function_evalualtion": 2
"maximum_function_evalualtion": 5
Igarizza marked this conversation as resolved.
Show resolved Hide resolved
},
"algorithm_specific_settings" : {
"inner_maxeval" : 20
Expand All @@ -119,15 +113,8 @@
"module": "KratosMultiphysics.OptimizationApplication.processes",
"settings": {
"output_file_name": "summary.csv",
"write_kratos_version" : false,
"write_time_stamp" : false,
"list_of_output_components": ["all"],
"format_info": {
"int_length" : 7,
"float_precision": 9,
"bool_values" : ["no", "yes"],
"string_length" : 14
}
"write_kratos_version": false,
"write_time_stamp": false
}
}
]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@
"problem_data": {
"problem_name": "shell",
"parallel_type": "OpenMP",
"echo_level": 0
"echo_level": 0,
"start_time" : 0.0,
"end_time" : 1.0
},
"solver_settings": {
"solver_type": "static",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Optimization problem ascii output
# Kratos version: not_given
# Timestamp : not_specified
# -----------------------------------------------
# --------------- Initial values ----------------
# mass_shell:
# initial_value: 3.401453818e+03
# ------------ End of initial values ------------
# -----------------------------------------------
# ------------ Start of step values -------------
# Headers:
# STEP, mass_shell:value, mass_shell:rel_change [%], mass_shell:abs_change [%]
0, 3.401453818e+03, 0.000000000e+00, 0.000000000e+00
1, 4.902371672e+02, -8.558742252e+01, -8.558742252e+01
2, 4.901410945e+02, -1.959717609e-02, -8.559024697e+01
3, 4.900978469e+02, -8.823507807e-03, -8.559151842e+01
4, 4.900779556e+02, -4.058629529e-03, -8.559210321e+01
# End of file
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@
import KratosMultiphysics.KratosUnittest as kratos_unittest

from KratosMultiphysics.OptimizationApplication.optimization_analysis import OptimizationAnalysis
from KratosMultiphysics.compare_two_files_check_process import CompareTwoFilesCheckProcess
from KratosMultiphysics.kratos_utilities import DeleteFileIfExisting


import csv, os

try:
Expand All @@ -13,24 +17,25 @@
class TestNLOPTOptimizer(kratos_unittest.TestCase):
def test_MMA_optimizer(self):
with kratos_unittest.WorkFolderScope(".", __file__):
with open("optimization_parameters.json", "r") as file_input:
parameters = Kratos.Parameters(file_input.read())
model = Kratos.Model()
analysis = OptimizationAnalysis(model, parameters)
analysis.Run()
optimization_log_filename = "summary.csv"
# Testing
with open(optimization_log_filename, 'r') as csvfile:
reader = csv.reader(csvfile, delimiter=',')
last_line = None
for i, row in enumerate(reader):
if i == 13:
last_line = row

resulting_mass = float(last_line[1].strip())
self.assertAlmostEqual(resulting_mass, 542.0733237,2)

os.remove(optimization_log_filename)
with open("optimization_parameters.json", "r") as file_input:
parameters = Kratos.Parameters(file_input.read())

model = Kratos.Model()
analysis = OptimizationAnalysis(model, parameters)
analysis.Run()

CompareTwoFilesCheckProcess(Kratos.Parameters("""
{
"reference_file_name" : "summary_orig.csv",
"output_file_name" : "summary.csv",
"remove_output_file" : true,
"comparison_type" : "deterministic"
}""")).Execute()

@classmethod
def tearDownClass(cls) -> None:
with kratos_unittest.WorkFolderScope(".", __file__):
DeleteFileIfExisting("Structure.time")

if __name__ == "__main__":
kratos_unittest.main()
Loading