예제 #1
0
 def optimize(self, init_guess=None, opti_algo='grid', record_data=False):
     """
     runs automatic optimization of thetas and ps
     :param init_guess: list of input values for an initial guess
     :param opti_algo: string for the algorithm to use 'grid' (self implemented LikeliOptimizer) or 'basin' (using scipy.optimize.basin-hopping)
     :param record_data: if True the test points of the optimizer gets recorded (this is needed for plot of optimizer path in plot_likelihoods)
     :return: None
     """
     timer = TimeTrack('optiTimer')
     self.records = None
     if record_data:
         self.records = []
     if 'basin' in opti_algo:
         # basinhopping:
         if init_guess is None:
             init_guess = []
             for t in self._theta:
                 init_guess.append(t)
             for p in self._p:
                 init_guess.append(p)
         bnds = []
         for i in range(0, self._k):
             bnds.append((-5., +5.))
         for i in range(0, self._k):
             bnds.append((1., 2.))
         bounds = BasinHoppingBounds(xmax=list(zip(*bnds))[1],
                                     xmin=list(zip(*bnds))[0])
         step = BasinHoppingStep()
         minimizer_kwargs = dict(method='SLSQP',
                                 bounds=bnds,
                                 options={
                                     'disp': False,
                                     'maxiter': 5e3
                                 },
                                 tol=1e-4)
         timer.tic()
         res = basinhopping(self._calc_likelihood_opti_exp,
                            init_guess,
                            minimizer_kwargs=minimizer_kwargs,
                            accept_test=bounds,
                            take_step=step,
                            niter=1000,
                            niter_success=100)
         timer.toc(print_it=True)
     elif 'grid' in opti_algo:
         skipper = LikeliOptimizer(debug=True)
         timer.tic()
         res = skipper.find(self._calc_likelihood_opti_exp, self._k)
         timer.toc(print_it=True)
     else:
         raise Exception('ERROR: unknown optimizer selected')
     exps = res.x[0:self._k]
     thetas = []
     for e in exps:
         thetas.append(10.**e)
     if record_data:
         print('Kriging Likelihood optimization evaluations: {:d}'.format(
             len(self.records)))
     self.update_param(thetas, res.x[self._k:])
예제 #2
0
    def auto_run(self,
                 sampling_type,
                 sample_point_count,
                 surro_type,
                 run_validation=True,
                 auto_fit=True,
                 params=[],
                 sequential_runs=0):
        """
        runs whole surrogate process
        :param sampling_type: index of the sampling type (definition in defines.py)
        :param sample_point_count: number of sampling points
        :param surro_type: index of the surrogate type (definition in defines.py)
        :param run_validation: run all validations (rmse, mae, press, avg-deviation)
        :param auto_fit: auto fit RBF and polynom surrogate by using validation
        :param params: adiational parameters to pass to the surrogate algorithm
        :param sequential_runs: number of sequential runs (add found optimum to sampling plan and build a new surrogate including the prev. optimum)
        :return: results as instance of SurroResults, pointer to the surrogate model instance
        """
        suc = self.generate_sampling_plan(sampling_type, sample_point_count)
        if not suc:
            return self.results, None
        self.run_validation_points()
        for i in range(0, sequential_runs + 1):
            if self.results.optimum_weight > 0.:
                self.known_params = np.append(
                    self.known_params,
                    [[self.results.optimum_rib, self.results.optimum_shell]],
                    axis=0)
                self._generate_scaled_sampling_points()

            self.run_fem_calculation()

            fit_time = TimeTrack('FitTime')
            fit_time.tic()
            if surro_type == SURRO_POLYNOM and auto_fit:
                suc = self.auto_fit_poly()
            elif surro_type == SURRO_RBF and auto_fit:
                suc = self.auto_fit_rbf(params=params)
            else:
                suc = self.train_model(surro_type, params=params)
            self.results.runtime = fit_time.toc()
            if not suc:
                return self.results, None
            self.optimize()

        if run_validation:
            self.run_validation_points(flip_points=True)
            self.run_validation(full_validation=True)

        self.print_results()
        if self.show_plots:
            self.plot_it()
        return self.results, self.surro
예제 #3
0
    def opti_it(self, rib_range=range(10, 23)):
        ######################
        ### needed Objects ###
        self.runner = MultiRun(use_calcu=not USE_ABA,
                               use_aba=USE_ABA,
                               non_liner=False,
                               project_name_prefix=PROJECT_NAME_PREFIX,
                               force_recalc=False)
        self.executionCounter = 0
        self.write_newton_log('iter,time,ribs,shell,stress,weight')
        self.timer = TimeTrack()

        opti_ribs = []
        opti_shell = []
        opti_stress = []
        opti_weights = []
        for r in rib_range:
            r = int(r)
            init_guess = (range_shell[0] + range_shell[1]) / 2.
            self.executionCounter = 0
            root = optimize.newton(self.shell_predict,
                                   init_guess,
                                   args=[r],
                                   tol=1.48e-08,
                                   maxiter=50)
            opti_ribs.append(r)
            opti_shell.append(root)
            stress, weight = self.calc_stress_weight(root, r)
            opti_stress.append(stress)
            opti_weights.append(weight)
            print('execution count: {:d}'.format(self.executionCounter))
            self.write_newton_log(
                str(self.executionCounter) + ',' + str(self.timer.get_time()) +
                ',' + str(r) + ',' + str(root) + ',' + str(stress) + ',' +
                str(weight))
        print('DONE')
        print(opti_ribs)
        print(opti_shell)
        print(opti_stress)
        print(opti_weights)
        best_i = opti_weights.index(min(opti_weights))
        print('BEST:')
        print('ribs:' + str(opti_ribs[best_i]))
        print('shell:' + str(opti_shell[best_i]))
        print('stress:' + str(opti_stress[best_i]))
        print('weight:' + str(opti_weights[best_i]))
예제 #4
0
    def setup(self):
        ######################
        ### needed Objects ###
        self.runner = MultiRun(use_calcu=not USE_ABA, use_aba=USE_ABA, non_liner=False, project_name_prefix=PROJECT_NAME_PREFIX, force_recalc=False)

        #####################
        ### openMDAO init ###
        ### INPUTS
        self.add_input('ribs', val=int((22 - offset_rib) / scale_rib), desc='number of ribs')
        self.add_input('shell', val=(0.003 - offset_shell) / scale_shell, desc='thickness of the shell')

        ### OUTPUTS
        self.add_output('stress', val=1e8)#, ref=1e8)
        self.add_output('weight', val=100.)#, ref=100)

        self.declare_partials('*', '*', method='fd')
        self.executionCounter = 0
        self.timer = TimeTrack()
예제 #5
0
    def setup(self):
        ######################
        ### needed Objects ###
        self.runner = MultiRun(use_calcu=not USE_ABA, use_aba=USE_ABA, non_liner=False, project_name_prefix=PROJECT_NAME_PREFIX, force_recalc=False)

        sur = Surrogate(use_abaqus=USE_ABA, pgf=False, show_plots=False, scale_it=False)
        res, sur_handel = sur.auto_run(SAMPLE_HALTON, 17, SURRO_POLYNOM, run_validation=False)
        self.surro = sur_handel

        #####################
        ### openMDAO init ###
        ### INPUTS
        self.add_input('ribs', val=int((22 - offset_rib) / scale_rib), desc='number of ribs')
        self.add_input('shell', val=(0.003 - offset_shell) / scale_shell, desc='thickness of the shell')

        ### OUTPUTS
        self.add_output('stress', val=1e8)#, ref=1e8)
        self.add_output('weight', val=100.)#, ref=100)

        self.declare_partials('*', '*', method='fd')
        self.executionCounter = 0
        self.timer = TimeTrack()
예제 #6
0
class WingStructureSurro(ExplicitComponent):

    def setup(self):
        ######################
        ### needed Objects ###
        self.runner = MultiRun(use_calcu=not USE_ABA, use_aba=USE_ABA, non_liner=False, project_name_prefix=PROJECT_NAME_PREFIX, force_recalc=False)

        sur = Surrogate(use_abaqus=USE_ABA, pgf=False, show_plots=False, scale_it=False)
        res, sur_handel = sur.auto_run(SAMPLE_HALTON, 17, SURRO_POLYNOM, run_validation=False)
        self.surro = sur_handel

        #####################
        ### openMDAO init ###
        ### INPUTS
        self.add_input('ribs', val=int((22 - offset_rib) / scale_rib), desc='number of ribs')
        self.add_input('shell', val=(0.003 - offset_shell) / scale_shell, desc='thickness of the shell')

        ### OUTPUTS
        self.add_output('stress', val=1e8)#, ref=1e8)
        self.add_output('weight', val=100.)#, ref=100)

        self.declare_partials('*', '*', method='fd')
        self.executionCounter = 0
        self.timer = TimeTrack()

    def compute(self, inputs, outputs):
        ribs = (inputs['ribs'][0] * scale_rib) + offset_rib
        ribs_int = int(round(ribs))

        rib0 = int(math.floor(ribs))
        rib1 = int(math.ceil(ribs))

        shell = (inputs['shell'][0] * scale_shell) + offset_shell

        pro0 = self.runner.new_project_r_t(rib0, shell)
        pro1 = self.runner.new_project_r_t(rib1, shell)
        if rib1 - rib0 < 0.000000001:
            weight = pro0.calc_wight()
        else:
            weight = (pro0.calc_wight() + ((ribs) - rib0)
                  * ((pro1.calc_wight() - pro0.calc_wight()) / (rib1 - rib0)))

        stress = self.surro.predict([ribs, shell])

        outputs['stress'] = (stress - offset_stress) / scale_stress
        outputs['weight'] = (weight - offset_weight) / scale_weight

        if WEIGHT_PANALTY_FAC > 0:
            weight_panalty = ((ribs) % 1)
            if weight_panalty >= 0.5:
                weight_panalty = 1. - weight_panalty
            outputs['weight'] = (weight + (weight_panalty * WEIGHT_PANALTY_FAC) - offset_weight) / scale_weight

        write_mdao_log(str(self.executionCounter) + ','
                     + str(self.timer.get_time()) + ','
                     + str(ribs) + ','
                     + str(ribs_int) + ','
                     + str(shell) + ','
                     + str(stress) + ','
                     + str(weight))
        self.executionCounter += 1
        print('#{:d}: {:0.10f}({:d}), {:0.10f} -> {:0.10f}, {:0.10f}'.format(self.executionCounter, ribs, ribs_int, shell, stress, weight))
        print('#{:d}: {:0.10f}, {:0.10f} -> {:0.10f}, {:0.10f}'.format(self.executionCounter, inputs['ribs'][0], inputs['shell'][0], outputs['stress'][0], outputs['weight'][0]))
예제 #7
0
class WingStructure(ExplicitComponent):

    def setup(self):
        ######################
        ### needed Objects ###
        self.runner = MultiRun(use_calcu=not USE_ABA, use_aba=USE_ABA, non_liner=False, project_name_prefix=PROJECT_NAME_PREFIX, force_recalc=False)

        #####################
        ### openMDAO init ###
        ### INPUTS
        self.add_input('ribs', val=int((22 - offset_rib) / scale_rib), desc='number of ribs')
        self.add_input('shell', val=(0.003 - offset_shell) / scale_shell, desc='thickness of the shell')

        ### OUTPUTS
        self.add_output('stress', val=1e8)#, ref=1e8)
        self.add_output('weight', val=100.)#, ref=100)

        self.declare_partials('*', '*', method='fd')
        self.executionCounter = 0
        self.timer = TimeTrack()

    def compute(self, inputs, outputs):
        ribs = (inputs['ribs'][0] * scale_rib) + offset_rib
        rib0 = int(math.floor(ribs))
        rib1 = int(math.ceil(ribs))

        ribs_int = int(round(ribs))

        shell = (inputs['shell'][0] * scale_shell) + offset_shell
        self.runner.project_name_prefix = PROJECT_NAME_PREFIX + '_{:05d}'.format(self.executionCounter)

        pro0 = self.runner.new_project_r_t(rib0, shell)
        pro0 = self.runner.run_project(pro0, used_cpus=1)
        res0 = pro0.resultsCalcu
        pro1 = self.runner.new_project_r_t(rib1, shell)
        pro1 = self.runner.run_project(pro1, used_cpus=1)
        res1 = pro1.resultsCalcu

        if USE_ABA:
            res0 = pro0.resultsAba
            res1 = pro1.resultsAba

        if rib1 - rib0 < 0.000000001:
            stress = res0.stressMisesMax
            weight = pro0.calc_wight()
        else:
            stress = (res0.stressMisesMax + ((ribs) - rib0)
                      * ((res1.stressMisesMax - res0.stressMisesMax) / (rib1 - rib0)))
            weight = (pro0.calc_wight() + ((ribs) - rib0)
                      * ((pro1.calc_wight() - pro0.calc_wight()) / (rib1 - rib0)))

        outputs['stress'] = (stress - offset_stress) / scale_stress
        outputs['weight'] = (weight - offset_weight) / scale_weight

        if WEIGHT_PANALTY_FAC > 0:
            weight_panalty = ((ribs) % 1)
            if weight_panalty >= 0.5:
                weight_panalty = 1. - weight_panalty
            outputs['weight'] = weight + ((weight_panalty * WEIGHT_PANALTY_FAC) * WEIGHT_FAC)

        write_mdao_log(str(self.executionCounter) + ','
                     + str(self.timer.get_time()) + ','
                     + str(ribs) + ','
                     + str(ribs_int) + ','
                     + str(shell) + ','
                     + str(stress) + ','
                     + str(weight))
        self.executionCounter += 1
        print(
            '#{:d}: {:0.10f}({:d}), {:0.10f} -> {:0.10f}, {:0.10f}'.format(self.executionCounter, ribs, ribs_int, shell,
                                                                           stress, weight))
        print('#{:d}: {:0.10f}, {:0.10f} -> {:0.10f}, {:0.10f}'.format(self.executionCounter, inputs['ribs'][0],
                                                                       inputs['shell'][0], outputs['stress'][0],
                                                                       outputs['weight'][0]))
예제 #8
0
class NewtonOpt:
    def __init__(self):
        pass

    def opti_it(self, rib_range=range(10, 23)):
        ######################
        ### needed Objects ###
        self.runner = MultiRun(use_calcu=not USE_ABA,
                               use_aba=USE_ABA,
                               non_liner=False,
                               project_name_prefix=PROJECT_NAME_PREFIX,
                               force_recalc=False)
        self.executionCounter = 0
        self.write_newton_log('iter,time,ribs,shell,stress,weight')
        self.timer = TimeTrack()

        opti_ribs = []
        opti_shell = []
        opti_stress = []
        opti_weights = []
        for r in rib_range:
            r = int(r)
            init_guess = (range_shell[0] + range_shell[1]) / 2.
            self.executionCounter = 0
            root = optimize.newton(self.shell_predict,
                                   init_guess,
                                   args=[r],
                                   tol=1.48e-08,
                                   maxiter=50)
            opti_ribs.append(r)
            opti_shell.append(root)
            stress, weight = self.calc_stress_weight(root, r)
            opti_stress.append(stress)
            opti_weights.append(weight)
            print('execution count: {:d}'.format(self.executionCounter))
            self.write_newton_log(
                str(self.executionCounter) + ',' + str(self.timer.get_time()) +
                ',' + str(r) + ',' + str(root) + ',' + str(stress) + ',' +
                str(weight))
        print('DONE')
        print(opti_ribs)
        print(opti_shell)
        print(opti_stress)
        print(opti_weights)
        best_i = opti_weights.index(min(opti_weights))
        print('BEST:')
        print('ribs:' + str(opti_ribs[best_i]))
        print('shell:' + str(opti_shell[best_i]))
        print('stress:' + str(opti_stress[best_i]))
        print('weight:' + str(opti_weights[best_i]))

    def shell_predict(self, shell_thick, rib_num):
        if shell_thick > range_shell[1]:
            shell_thick = range_shell[1]
        if shell_thick < range_shell[0]:
            shell_thick = range_shell[0]
        stress, _ = self.calc_stress_weight(shell_thick, rib_num)
        self.executionCounter += 1
        return stress - max_shear_strength

    def calc_stress_weight(self, shell_thick, rib_num):
        self.runner.project_name_prefix = PROJECT_NAME_PREFIX + '_{:05d}'.format(
            self.executionCounter)
        pro = self.runner.new_project_r_t(rib_num, shell_thick)
        pro = self.runner.run_project(pro, used_cpus=1)
        res = pro.resultsCalcu
        if USE_ABA:
            res = pro.resultsAba
        stress = res.stressMisesMax
        weight = pro.calc_wight()
        return stress, weight

    def write_newton_log(self, out_str):
        out_str = out_str.replace('[', '')
        out_str = out_str.replace(']', '')
        output_f = open(LOG_FILE_PATH, 'a')  # 'a' so we append the file
        output_f.write(out_str + '\n')
        output_f.close()

    def plot_it(self, file_path=None, plot_handle=None, marker='-'):
        if file_path == None:
            file_path = LOG_FILE_PATH
        data = np.genfromtxt(file_path, delimiter=',', skip_header=1)
        plot = plot_handle
        if plot_handle == None:
            plot = PlotHelper(['Rippenanzahl', 'Gewicht in kg'],
                              fancy=True,
                              pgf=False)
        plot.ax.plot(data[:, 2], data[:, 5], marker, color='dodgerblue')
        import matplotlib.ticker as ticker
        plot.ax.xaxis.set_major_locator(ticker.IndexLocator(base=2, offset=0))
        plot.ax.yaxis.label.set_color('dodgerblue')
        ax_shell = plot.ax.twinx()
        ax_shell.set_ylabel('Blechdicke in mm')
        ax_shell.yaxis.label.set_color('orange')
        ax_shell.plot(data[:, 2], data[:, 3] * 1000, marker, color='orange')
        ax_shell.set_ylim(tuple(1000 * x for x in range_shell))
        plot.ax.set_xlim((1, 30))
        plot.finalize(height=2, show_legend=False)
        #plot.save(Constants().PLOT_PATH + 'newtonOptiPlot.pdf')
        #plot.show()
        return plot
예제 #9
0
# description     :kriging in Rn
# author          :Juri Bieler
# date            :2018-07-13
# notes           :
# python_version  :3.6
# ==============================================================================

import numpy as np

from mylibs.kriging import Kriging
from myutils.plot_helper import PlotHelper
from myutils.time_track import TimeTrack
from myutils.samples import *

if __name__ == '__main__':
    t1 = TimeTrack('OverAllTimer')
    plt1 = PlotHelper(['Eingang 1', 'Eingang 2', 'Ausgang'], fancy=False)

    # now we pretend we only know a view points
    fx = np.linspace(-2, 12, 101)
    fy = np.linspace(-2, 12, 101)
    plt1.plot_function_3d(f_3d, fx, fy, r'$f_{original}$', color='r')
    # the smooth whole function

    # now we pretend we only know a view points
    pxEdge = [0., 2., 4., 6., 8., 10.]
    pyEdge = [0., 2., 4., 6., 8., 10.]
    px, py, knownValues = generate_sample_data(f_3d, pxEdge, pyEdge)
    knownParams = np.array([px, py]).T

    scat1 = plt1.ax.scatter(px,
예제 #10
0
# description     :file for testing a single fem-calculation
# author          :Juri Bieler
# date            :2018-07-13
# notes           :
# python_version  :3.6
# ==============================================================================

import numpy as np
import sys
from datetime import datetime
from wingconstruction.wingutils.constants import Constants
from wingconstruction.project import Project
from myutils.time_track import TimeTrack
from wingconstruction.wingutils.defines import *

t = TimeTrack()
t.tic()
projectName = 'testSolver'
pro1 = Project(projectName)
pro1.halfSpan = wing_length
pro1.boxDepth = chord_length * 0.4
pro1.boxHeight = chord_height
pro1.ribs = 19
pro1.enginePos = engine_pos_y
pro1.engineWeight = engine_weight
pro1.boxOverhang = 0.
pro1.forceTop = -(2. / 3.) * wing_load
pro1.forceBot = -(1. / 3.) * wing_load
pro1.elementSize = .1
#pro1.elementSize = 0.05
pro1.elemType = 'qu4'