Example #1
0
# Making KratosMultiphysics backward compatible with python 2.6 and 2.7
from __future__ import print_function, absolute_import, division

# Import Kratos core and apps
from KratosMultiphysics import *
from KratosMultiphysics.ShapeOptimizationApplication import *

# Read parameters
with open("optimization_parameters.json", 'r') as parameter_file:
    parameters = Parameters(parameter_file.read())

model = Model()

# Create optimizer and perform optimization
import optimizer_factory
optimizer = optimizer_factory.CreateOptimizer(
    parameters["optimization_settings"], model)
optimizer.Optimize()
Example #2
0
# Read parameters
with open("parameters.json", 'r') as parameter_file:
    parameters = Parameters(parameter_file.read())

# Defining the model_part
optimization_model_part = ModelPart(
    parameters["optimization_settings"]["design_variables"]
    ["optimization_model_part_name"].GetString())
optimization_model_part.ProcessInfo.SetValue(
    DOMAIN_SIZE, parameters["optimization_settings"]["design_variables"]
    ["domain_size"].GetInt())

# Create optimizer and perform optimization
import optimizer_factory
optimizer = optimizer_factory.CreateOptimizer(parameters,
                                              optimization_model_part)
optimizer.Optimize()

# =======================================================================================================
# Test results and clean directory
# =======================================================================================================

# Testing is done using the "json_output_process" & "json_check_process" within the structural analysis

# Cleaning
original_directory = os.getcwd()
output_directory = parameters["optimization_settings"]["output"][
    "output_directory"].GetString()
optimization_model_part_name = parameters["optimization_settings"][
    "design_variables"]["optimization_model_part_name"].GetString()
try:
Example #3
0
        elif x <= 25.0:
            return 1.0 - (x - 20.0) / 5.0
        else:
            return 0.0

# =======================================================================================================
# Perform optimization
# =======================================================================================================

with open("parameters.json",'r') as parameter_file:
    parameters = Parameters(parameter_file.read())

model = Model()

import optimizer_factory
optimizer = optimizer_factory.CreateOptimizer(parameters["optimization_settings"], model, CustomAnalyzer())
optimizer.Optimize()

# =======================================================================================================
# Test results and clean directory
# =======================================================================================================
output_directory = parameters["optimization_settings"]["output"]["output_directory"].GetString()
optimization_log_filename = parameters["optimization_settings"]["output"]["optimization_log_filename"].GetString() + ".csv"
optimization_model_part_name = parameters["optimization_settings"]["model_settings"]["model_part_name"].GetString()

# Testing
original_directory = os.getcwd()
os.chdir(output_directory)

with open(optimization_log_filename, 'r') as csvfile:
    reader = csv.reader(csvfile, delimiter=',')
Example #4
0

def ObjectiveGradient(X, opt_iter):
    """ Returns the gradient of the objective function """
    sensitivity = dict()
    for node in design_surface.Nodes:
        delta = node.Y - TentFunction(node.X)
        if abs(delta) == 0.0:
            sy = 0.0
        else:
            sy = delta / abs(delta)
        sensitivity[node.Id] = [0.0, sy, 0.0]
    return sensitivity


def Analyzer(X, controls, iterator, response):
    """ Performs the analysis in the optimization loop """
    if controls["1"]["calc_func"]:
        response["1"]["func"] = ObjectiveFunction(X, iterator)
    if controls["1"]["calc_grad"]:
        response["1"]["grad"] = ObjectiveGradient(X, iterator)


import optimizer_factory

optimizer = optimizer_factory.CreateOptimizer(design_surface,
                                              settings.KratosShapeSettings,
                                              Analyzer)

optimizer.optimize()
Example #5
0
                local_gradient[1] = 0.0
                local_gradient[2] = 0.0

            response_gradient[node.Id] = local_gradient

        return response_gradient


# =======================================================================================================
# Perform optimization
# =======================================================================================================

# Create optimizer and perform optimization
import optimizer_factory
optimizer = optimizer_factory.CreateOptimizer(parameters,
                                              optimization_model_part,
                                              CustomAnalyzer())
optimizer.Optimize()

# =======================================================================================================
# Test results and clean directory
# =======================================================================================================
output_directory = parameters["optimization_settings"]["output"][
    "output_directory"].GetString()
response_log_filename = parameters["optimization_settings"]["output"][
    "response_log_filename"].GetString() + ".csv"
optimization_model_part_name = parameters["optimization_settings"][
    "design_variables"]["optimization_model_part_name"].GetString()

# Testing
original_directory = os.getcwd()
Example #6
0
def analyzer(X,controls,iterator,response):
    
    # ------------------------------------------------------------------------------------------------------
    # Input format:
    # ------------------------------------------------------------------------------------------------------
    #
    # X = { unique_node_id: [x,y,z],
    #       unique_node_id: [x,y,z],
    #       ... }
    #
    # controls = { "unique_func_id": {"calc_func": 1/0, "calc_grad": 1/0},
    #              "unique_func_id": {"calc_func": 1/0, "calc_grad": 1/0},
    #              ... }
    #
    # iterator = "mayor_itr.sub_itr" (Initial design iterator = "1.0" or "1.1")
    #
    # ------------------------------------------------------------------------------------------------------
    # Output format:
    # ------------------------------------------------------------------------------------------------------
    #
    # response = { "unique_func_id": {"func": xxx, "grad": {unique_node_id: [dx,dy,dz], ... }},
    #              "unique_func_id": {"func": xxx, "grad": {unique_node_id: [dx,dy,dz], ... }},
    #              ... }
    #
    # response may contain only those entries which were called through the controller in the input
    #
    # ------------------------------------------------------------------------------------------------------

    if( iterator=="1.0" or iterator=="1.1" ):

        # Some initialization for the disciplinary solvers might go here
        
    # ------------------------------------------------------------------------------------------------------

    # Compute some primal field 
    # - Note that objective and constraint values may be computed within the same solve
    # - Note also that through the controls, we can make sure that whenever an adjoint gradient is to be 
    #   calculated, the primal field is computed first. At the same time though, additional unnecessary primal 
    #   function calls may be avoided in case different adjoint solutions need to be caluclated based on the 
    #   same primal field. This is possible since through the controls we know from the beginning all 
    #   the function calls that the optimizer asks for in this step, so we may optimize the workflow for each
    #   combination.
    if( controls["some_objective_name"]["calc_func"] or 
        controls["some_objective_name"]["calc_grad"] or 
        controls["some_constraint_name"]["calc_func"] or
        controls["some_constraint_name"]["calc_grad"] ):
        
        # Run e.g. some CFD or CSM code
        # ...-> objective_value, constraint_value
      
        # Store objective value in response container
        response["some_objective_name"]["func"] = objective_value

        # Compute and store constraint
        response["some_constraint_name"]["func"] = constraint_value

    # ------------------------------------------------------------------------------------------------------

    # Compute adjoint field and ojbective gradient if required
    if( controls["some_objective_name"]["calc_grad"] ):

        # Call disciplinary solver to compute objective gradients
        # ... -> dFdX

        # Store gradients in response container
        response["some_objective_name"]["grad"] = dFdX

    # ------------------------------------------------------------------------------------------------------   
    
    # Compute adjoint field and constraint gradient if required
    if( controls["some_constraint_name"]["calc_grad"] ):

        # Call disciplinary solver to compute constraint gradients

        # Store gradients in response container
        response["some_constraint_name"]["grad"] = dFdX

    # ------------------------------------------------------------------------------------------------------ 

# Initalize model_part here to have it available for further use in this main script
design_surface = ModelPart("design_surface")

# Create an optimizer object 
optimizer = optimizer_factory.CreateOptimizer(design_surface,settings.KratosShapeSettings,analyzer)

print("\n> ==============================================================================================================")
print("> Starting optimization")
print("> ==============================================================================================================\n")

# Call the optimize function of the optimizer
optimizer.optimize()

print("\n> ==============================================================================================================")
print("> Finished shape optimization!")
print("> ==============================================================================================================\n")