Esempio n. 1
0
 def plot_theta_likelihood_r2(self, ax=None, pgf=False, opti_path=[]):
     """
     plot colormap of likelihood for theta1 and theta2
     :param ax: handle of the axis if this should be embedded in an existing plot
     :param pgf: store it as pgf file (for latex embedding)
     :param opti_path: show the path of the optimization as white crosses
     :return: the handle to the pcolor legend
     """
     if self._k != 2:
         print(
             'ERROR: plot_theta_likelihood_R2 only works with exactly 2 inputs'
         )
         return
     opt_theta = self._theta
     thetas = np.logspace(-5, 5, num=50)
     likely_thet = np.zeros((len(thetas), len(thetas)))
     for i1 in range(0, len(thetas)):
         for i2 in range(0, len(thetas)):
             self.update_param([thetas[i1], thetas[i2]], self._p)
             likely_thet[i2][i1] = self.calc_likelihood()
     # restore original thetas
     self._theta = opt_theta
     self.update_param(self._theta, self._p)
     # plot it
     plt_theta = PlotHelper([r'$\theta_{1}$', r'$\theta_{2}$'],
                            fancy=False,
                            ax=ax,
                            pgf=pgf)
     plt_theta.ax.set_xscale('log')
     plt_theta.ax.set_yscale('log')
     pcol = plt_theta.ax.pcolor(thetas,
                                thetas,
                                likely_thet,
                                cmap='YlOrRd_r')
     if len(opti_path) > 0:
         plt_theta.ax.plot(10**opti_path[:, 0],
                           10**opti_path[:, 1],
                           '+',
                           color='white',
                           markeredgewidth=0.5,
                           markersize=5,
                           label='Optimierer-Pfad')
     plt_theta.ax.plot(self._theta[0],
                       self._theta[1],
                       'x',
                       color='black',
                       label='Minimum',
                       markersize=8,
                       markeredgewidth=1.5)
     legend = plt_theta.finalize(width=6,
                                 height=5,
                                 legendLoc=4,
                                 show_legend=False)
     return pcol
Esempio n. 2
0
 def plot_p_likelihood_r2(self, ax=None, pgf=False, opti_path=[]):
     """
     plot colormap of likelihood for p1 and p2
     :param ax: handle of the axis if this should be embedded in an existing plot
     :param pgf: store it as pgf file (for latex embedding)
     :param opti_path: show the path of the optimization as white crosses
     :return:
     """
     if self._k != 2:
         print(
             'ERROR: plot_p_likelihood_R2 only works with exactly 2 inputs')
         return
     opt_p = self._p
     ps = np.linspace(1., 2., num=50)
     likely_p = np.zeros((len(ps), len(ps)))
     for i1 in range(0, len(ps)):
         for i2 in range(0, len(ps)):
             self.update_param(self._theta, [ps[i1], ps[i2]])
             likely_p[i2][i1] = self.calc_likelihood()
     # restore original ps
     self._p = opt_p
     self.update_param(self._theta, self._p)
     # plot it
     plt_P = PlotHelper(['$p_{1}$', '$p_{2}$'], fancy=False, ax=ax, pgf=pgf)
     pcol = plt_P.ax.pcolor(ps, ps, likely_p, cmap='YlOrRd_r')
     if len(opti_path) > 0:
         plt_P.ax.plot(opti_path[:, 0],
                       opti_path[:, 1],
                       '+',
                       color='white',
                       markeredgewidth=0.5,
                       markersize=5,
                       label='Optimierer-Pfad')
     plt_P.ax.plot(self._p[0],
                   self._p[1],
                   'x',
                   color='k',
                   label='Minimum',
                   markersize=8,
                   markeredgewidth=1.5)
     legend = plt_P.finalize(width=6,
                             height=5,
                             legendLoc=4,
                             show_legend=False)
     return pcol
Esempio n. 3
0
    def plot_likelihoods(self, fancy=False, pgf=False, opti_path=[]):
        """
        creates a plot that shows the likelihood over p1, p2, theta1, theta2 (only supports two inputs)
        two colormaps represent the likelihoods for p and theta
        :param fancy: use latex in plot
        :param pgf: store it as pgf file (for latex embedding)
        :param opti_path: show the path of the optimization as white crosses
        :return: pointer to PlotHelper instance (if no errors)
        """
        if self._k != 2:
            print(
                'ERROR: plot_p_likelihood_R2 only works with exactly 2 inputs')
            return
        path_p = []
        path_theta = []
        if len(opti_path) > 0:
            path_theta = np.array([opti_path[:, 0], opti_path[:, 1]]).T
            path_p = np.array([opti_path[:, 2], opti_path[:, 3]]).T

        plt_like = PlotHelper([], fancy=fancy, pgf=pgf)
        import matplotlib.pyplot as plt
        ax1 = plt_like.fig.add_subplot(121)
        ax2 = plt_like.fig.add_subplot(122)

        pcol1 = self.plot_p_likelihood_r2(ax=ax1, pgf=pgf, opti_path=path_p)
        pcol2 = self.plot_theta_likelihood_r2(ax=ax2,
                                              pgf=pgf,
                                              opti_path=path_theta)
        like_min = min(min(pcol1._A), min(pcol2._A))
        like_max = max(max(pcol1._A), max(pcol2._A))
        pcol1.set_clim(like_min, like_max)
        pcol2.set_clim(like_min, like_max)

        plt_like.fig.set_size_inches(6, 3)
        plt.tight_layout()

        plt_like.fig.subplots_adjust(right=0.85)
        plt_like.fig.subplots_adjust(bottom=0.3)
        cbar_ax = plt_like.fig.add_axes([0.88, 0.15, 0.02, 0.78])
        plt_like.fig.colorbar(pcol2, cax=cbar_ax)
        plt_like.fig.text(0.97,
                          0.7,
                          'neg. log. Likelihood',
                          size=plt_like.FONT_SIZE,
                          rotation=90.)
        handles, labels = ax1.get_legend_handles_labels()
        legend = plt_like.fig.legend(handles,
                                     labels,
                                     loc='lower center',
                                     bbox_to_anchor=(0.5, 0.01),
                                     ncol=2,
                                     fancybox=True)
        legend.get_frame().set_facecolor('#A3A3A3')
        for text in legend.get_texts():
            text.set_color('#000000')
        return plt_like
Esempio n. 4
0
 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
Esempio n. 5
0
from mylibs.halton import Halton

hal = Halton()
print(hal.halton(10, 2))

import matplotlib.pyplot as plt
samples = hal.generate_sample_plan(14, 2, [(5, 20), (0.01, 0.05)], base=[2,3])
for i in range(0, len(samples)):
    plt.plot([samples[i][0]], [samples[i][1]], 'bo')
plt.show()

from myutils.plot_helper import PlotHelper
plt_halton = PlotHelper([], fancy=True, pgf=False)
import matplotlib.pyplot as plt


ax1 = plt_halton.fig.add_subplot(121)
ax2 = plt_halton.fig.add_subplot(122)

for i in range(0, 100):
    point = [hal.halton(i, 11), hal.halton(i, 29)]
    ax1.plot([point[1]], [point[0]], 'bo', markersize=3)
ax1.xaxis.set_ticklabels([])
ax1.yaxis.set_ticklabels([])

for i in range(0, 100):
    point = [hal.halton(i, 2), hal.halton(i, 19)]
    ax2.plot([point[1]], [point[0]], 'bo', markersize=3)
ax2.xaxis.set_ticklabels([])
ax2.yaxis.set_ticklabels([])
Esempio n. 6
0
    def plot_it(self, display_plots=True):
        """
        plots the results
        :param display_plots: display it or only save it
        :return: None
        """
        ##################################################
        # plot it
        # convert all to np arrays
        # shell = np.array(self.shell)
        # opti_shell = np.array(opti_shell)
        # known_shell = np.array(known_shell)

        if False:
            plot3dw = PlotHelper(
                ['Rippen', 'Blechdicke in mm', 'Gewicht in kg'],
                fancy=False,
                pgf=pgf)
            plotX, plotY = np.meshgrid(self.ribs, self.shell * 1000)
            surf = plot3dw.ax.plot_wireframe(plotX,
                                             plotY,
                                             self.weights,
                                             color='blue',
                                             label='weight',
                                             rcount=20,
                                             ccount=20,
                                             linewidths=1,
                                             alpha=0.5)
            samplePoints = plot3dw.ax.plot(self.known_params[:, 0],
                                           self.known_params[:, 1] * 1000.,
                                           'bo',
                                           label='Stützstellen')
            plot3dw.finalize(show_legend=True)

        plot3d = PlotHelper([r'Rippen', r'Blechdicke in mm', r'Mises in Pa'],
                            fancy=FANCY_PLOT,
                            pgf=self.pgf)
        # plot FEM data as lines
        for i in range(0, len(self.ribs)):
            if i == 0:
                plot3d.ax.plot(np.ones((len(self.shell))) * self.ribs[i],
                               self.shell * 1000.,
                               self.stress[:, i],
                               'g-',
                               lw=3.,
                               label=u'FEM Daten')
            else:
                plot3d.ax.plot(np.ones((len(self.shell))) * self.ribs[i],
                               self.shell * 1000.,
                               self.stress[:, i],
                               'g-',
                               lw=3.)
        # plot surrogate model as wireframe
        ribs_sample = np.linspace(min(self.ribs_s), max(self.ribs_s), 200)
        shell_sample = np.linspace(min(self.shell_s), max(self.shell_s), 200)
        surro_short_name = SURRO_NAMES[self.surro_type][:3]
        if len(SURRO_NAMES[self.surro_type]) > 3:
            surro_short_name += '.'
        surro_plot = plot3d.plot_function_3d(
            self.surro.predict,
            ribs_sample,
            shell_sample,
            r'$\widehat{f}_{' + surro_short_name + '}$',
            color='b',
            scale=[self.scale_rib, self.scale_shell * 1000., 1.],
            offset=[self.offset_rib, self.offset_shell * 1000, 0.])
        samplePoints = plot3d.ax.plot(self.known_params[:, 0],
                                      self.known_params[:, 1] * 1000.,
                                      self.known_stress,
                                      'bo',
                                      label=u'Stützstellen')

        if self.results.opti_curve != []:
            # plot limit load line
            plot3d.ax.plot(self.results.opti_curve[0],
                           np.array(self.results.opti_curve[1]) * 1000.,
                           self.results.opti_curve[2],
                           'k--',
                           lw=3.,
                           label=u'max. Mises Stress')
            # plot optimal point
            plot3d.ax.plot([self.results.optimum_rib],
                           [self.results.optimum_shell * 1000.],
                           [self.results.optimum_stress],
                           'rx',
                           markersize=12,
                           markeredgewidth=5,
                           label='glob. Optimum')
            plot3d.ax.plot([17], [2.565], [max_shear_strength], 'kx')
        plot3d.ax.locator_params(nbins=7, axis='x')
        plot3d.ax.locator_params(nbins=5, axis='y')

        plot3d.ax.set_zlim3d(np.min(np.array(self.stress)),
                             max_shear_strength * 1.2)
        plot3d.ax.set_ylim3d(
            np.min(np.array(self.shell)) * 1000.,
            np.max(np.array(self.shell)) * 1000.)

        plot3d.finalize(height=4,
                        width=6,
                        legendLoc=8,
                        legendNcol=3,
                        bbox_to_anchor=(0.5, -0.33))
        plot3d.ax.view_init(18, 105)
        plot3d.ax.invert_xaxis()
        # plot3d.ax.zaxis.offsetText.set_visible(True)
        # offset_z = plot3d.ax.zaxis.get_major_formatter().get_offset()
        offset_z = '1e8'
        plot3d.ax.set_zlabel('Mises in Pa x ' + offset_z,
                             fontdict=plot3d.font,
                             labelpad=plot3d.labelpad)
        plot3d.ax.zaxis.offsetText.set_visible(False)
        plot3d.save(Constants().PLOT_PATH + 'wingSurro_{:s}_{:s}.pdf'.format(
            SAMPLE_NAMES[self.sampling_type], SURRO_NAMES[self.surro_type]))
        if display_plots:
            plot3d.show()
Esempio n. 7
0
 def optimize(self):
     """
     runs optimizaiton on the surrogate model
     :return: None
     """
     ##################################################
     # optimize
     opti_ribs = []
     opti_shell = []
     opti_stress = []
     opti_weights = []
     used_ribs = np.array(range(range_rib[0], range_rib[1] + 1))
     used_ribs_s = (used_ribs - self.offset_rib) / self.scale_rib
     for i in range(0, len(used_ribs_s)):
         # SLSQP: proplem; find local min not glob. depending on init-vals
         init_guess = (min(self.known_params_s[:, 1]) +
                       max(self.known_params_s[:, 1])) / 2
         # bnds = [(min(known_shell), max(known_shell))]
         # res = minimize(shell_predict, init_guess, args=[krig, ribs[i]], method='SLSQP', tol=1e-6, options={'disp': True, 'maxiter': 99999}, bounds=bnds)
         # opti_shell.append(res.x[0])
         try:
             root_s = optimize.newton(self.shell_predict,
                                      init_guess,
                                      args=[self.surro, used_ribs_s[i]])
             root = (root_s * self.scale_shell) + self.offset_shell
             root_stress = self.surro.predict([used_ribs_s[i], root_s])
             if root_stress < max_shear_strength * 1.05:  #this check is needed if the surrogate does not cross the max stress at all at this ribnumber
                 opti_ribs.append(used_ribs[i])
                 opti_shell.append(root)
                 opti_stress.append(root_stress)
                 weight = WingConstruction.calc_weight_stat(
                     wing_length, chord_length * 0.4, chord_height,
                     used_ribs[i], root, density)
                 opti_weights.append(weight)
         except Exception as e:
             print(e)
     # exclude model edges from opti vals
     opti_ribs = opti_ribs[:-1]
     opti_ribs = opti_ribs[1:]
     opti_shell = opti_shell[:-1]
     opti_shell = opti_shell[1:]
     opti_stress = opti_stress[:-1]
     opti_stress = opti_stress[1:]
     opti_weights = opti_weights[:-1]
     opti_weights = opti_weights[1:]
     if len(opti_weights) > 0:
         best_i = opti_weights.index(min(opti_weights))
         if self.show_plots:
             optWeightPlot = PlotHelper(['ribs', 'weight'], pgf=self.pgf)
             optWeightPlot.ax.plot(opti_ribs,
                                   opti_weights,
                                   '-',
                                   color='dodgerblue')
             optWeightPlot.ax.plot([opti_ribs[best_i]],
                                   opti_weights[best_i],
                                   'rx',
                                   label='minimum')
             import matplotlib.ticker as ticker
             optWeightPlot.ax.xaxis.set_major_locator(
                 ticker.IndexLocator(base=2, offset=0))
             optWeightPlot.finalize(height=2)
         self.results.optimum_rib = opti_ribs[best_i]
         self.results.optimum_shell = opti_shell[best_i]
         self.results.optimum_weight = opti_weights[best_i]
         self.results.optimum_stress = opti_stress[best_i]
         self.results.opti_curve = [
             opti_ribs, opti_shell, opti_stress, opti_weights
         ]
Esempio n. 8
0
 def run_validation(self, full_validation=False):
     """
     does the validation of the surrogate model
     :param full_validation: if True does everything, if False only rmse and mae
     :return: None
     """
     ##################################################
     # validate
     vali = Validation()
     if full_validation:
         p_x, p_y = np.meshgrid(self.ribs, self.shell)
         params = np.array([p_x.flatten(), p_y.flatten()]).T
         params_s = np.zeros(params.shape)
         params_s[:, 0] = (params[:, 0] - self.offset_rib) / self.scale_rib
         params_s[:,
                  1] = (params[:, 1] - self.offset_shell) / self.scale_shell
         values = self.stress.flatten()
         vali_r = vali.run_full_analysis(params_s,
                                         values,
                                         self.known_params_s,
                                         self.known_stress,
                                         self.vali_params_s,
                                         self.vali_values,
                                         self.surro.predict,
                                         self.surro_class,
                                         update_params=self.update_params)
         self.results.vali_results = vali_r
     else:
         rmse = vali.calc_rmse(self.vali_params_s, self.vali_values,
                               self.surro.predict)
         self.results.vali_results.rmse = rmse
         self.results.vali_results.mae = vali.calc_mae(
             self.vali_params_s, self.vali_values, self.surro.predict)
     if self.show_plots and full_validation:
         deri_plot = PlotHelper(['Rippen', 'Blechdicke in mm'],
                                fancy=FANCY_PLOT,
                                pgf=self.pgf)
         dev = np.zeros(self.stress.shape)
         for xi in range(0, len(self.ribs_s)):
             for yi in range(0, len(self.shell_s)):
                 devi = (abs(self.stress[yi][xi] - self.surro.predict(
                     [self.ribs_s[xi], self.shell_s[yi]])) /
                         np.array(self.stress).mean()) * 100.
                 dev[yi][xi] = devi
         pcol = deri_plot.ax.pcolor(self.ribs,
                                    np.array(self.shell) * 1000,
                                    dev,
                                    cmap='YlOrRd',
                                    alpha=0.7)
         pcol.set_clim(0, 5.)
         cbar = deri_plot.fig.colorbar(pcol)
         deri_plot.ax.plot(self.known_params[:, 0],
                           self.known_params[:, 1] * 1000,
                           'bo',
                           label='Stützstellen')
         deri_plot.ax.plot(self.vali_params[:, 0],
                           self.vali_params[:, 1] * 1000,
                           'o',
                           color='fuchsia',
                           label='Vali.-Punkte')
         # deri_plot.ax.plot([opti_ribs[best_i]], [opti_shell[best_i] * 1000.], 'rx',
         #                  markersize=12, markeredgewidth=5, label='glob. Optimum')
         deri_plot.ax.invert_yaxis()
         deri_plot.finalize(width=6.,
                            height=4.,
                            legendLoc=8,
                            legendNcol=3,
                            bbox_to_anchor=(0.5, -0.38),
                            tighten_layout=True)
         deri_plot.save(Constants().PLOT_PATH +
                        'wingSurro_deri_{:s}_{:s}.pdf'.format(
                            SAMPLE_NAMES[self.sampling_type], SURRO_NAMES[
                                self.surro_type]))
Esempio n. 9
0
                                POINTS,
                                SURRO_KRIGING,
                                run_validation=VALIDATION)

        print('POLY------------------------')
        surP.print_results()
        print('RBF gaus------------------------')
        surRg.print_results()
        print('RBF mq------------------------')
        surRm.print_results()
        print('KRIGING------------------------')
        surK.print_results()

        #plot opti-lines
        opti_lines = PlotHelper(['Rippen', 'opt. Gewicht'],
                                pgf=PGF,
                                fancy=True)
        l0 = opti_lines.ax.plot(resP.opti_curve[0],
                                resP.opti_curve[3],
                                '-',
                                label='Polynom')  #, color='dodgerblue')
        opti_lines.ax.plot([resP.optimum_rib], [resP.optimum_weight],
                           'o',
                           color=l0[0].get_color())

        l1 = opti_lines.ax.plot(resRg.opti_curve[0],
                                resRg.opti_curve[3],
                                '-',
                                label='RBF-gauß')  #, color='orange')
        opti_lines.ax.plot([resRg.optimum_rib], [resRg.optimum_weight],
                           'o',
import numpy as np

from mylibs.polynomial import Polynomial
from myutils.plot_helper import PlotHelper
from myutils.samples import *
from mylibs.validation import Validation
from mylibs.validation import ValidationResults
from mylibs.latin_hyper_cube import LatinHyperCube
from mylibs.halton import Halton
from mylibs.structured_sample import StructuredSample

if __name__ == '__main__':
    polyPlot = PlotHelper(['Eingang', 'Ausgang'], fancy=True, pgf=False)

    # the smooth whole function
    fx = np.linspace(0, 10, 1001)
    fy = list(map(f_2d, fx))

    polyPlot.ax.plot(fx, fy, 'r-', label=r'$f_{original}$')

    # validate points
    valiParams = np.array([1., 5., 9.])
    valiValues = np.array(list(map(f_2d, valiParams)))
    valiParams = valiParams.reshape((len(valiParams), 1))

    fx = fx.reshape((len(fx), 1))

    vali_res = []
    poly_plot_points = [2, 3, 4, 5, 6, 7]
    sampling_points = [2, 3, 4, 5, 6, 7, 8, 9, 10]  # [2, 3, 4, 5, 6, 7]
    plot_styles = [
Esempio n. 11
0
def plot_iter(file_path=None):
    if file_path == None:
        file_path = LOG_FILE_PATH
    data = np.genfromtxt(file_path, delimiter=',', skip_header=1)
    iter = data[:, 0]
    time = data[:, 1]
    ribs = data[:, 2]
    shell = data[:, 4]
    stress = data[:, 5]
    weight = data[:, 6]
    #print some info:
    print('number of iterations: {:d}'.format(int(iter[-1])+1))
    print('total time: {:f}'.format(time[-1] - time[0]))
    iter_plot = PlotHelper([], fancy=True, pgf=PGF)
    ax1 = iter_plot.fig.add_subplot(211)
    ax2 = iter_plot.fig.add_subplot(212)
    # param plot
    iter_param = PlotHelper(['', 'Rippen'], fancy=True, ax=ax1, pgf=PGF)
    iter_param.ax.plot(iter, ribs, color='teal')
    iter_param.ax.yaxis.label.set_color('teal')
    ax_shell = iter_param.ax.twinx()
    ax_shell.set_ylabel('Blechd. in mm')
    ax_shell.yaxis.label.set_color('orange')
    ax_shell.plot(iter, shell * 1000, color='orange')
    iter_param.ax.set_ylim(range_rib)
    ax_shell.set_ylim(tuple(1000*x for x in range_shell))
    iter_param.finalize(show_legend=False)
    from matplotlib.ticker import MaxNLocator
    iter_param.ax.xaxis.set_major_locator(MaxNLocator(integer=True))
    # results plot
    iter_res = PlotHelper(['Iteration', 'Mises in Pa'], fancy=True, ax=ax2, pgf=PGF)
    iter_res.ax.plot(iter, stress, color='tomato')
    iter_res.ax.plot([min(iter), max(iter)], [max_shear_strength, max_shear_strength], '--', color='tomato', label='max. Spannung')
    iter_res.ax.yaxis.label.set_color('tomato')
    ax_weight = iter_res.ax.twinx()
    ax_weight.set_ylabel('Gewicht in kg')
    ax_weight.yaxis.label.set_color('royalblue')
    ax_weight.plot(iter, weight, color='royalblue')
    iter_res.ax.xaxis.set_major_locator(MaxNLocator(integer=True))
    #leg = iter_res.finalize(legendLoc='upper right', show_legend=True, bbox_to_anchor=(.95, 1.25))
    iter_plot.finalize(width=6, height=3, tighten_layout=True)
    handles, labels = iter_res.ax.get_legend_handles_labels()
    leg = iter_plot.fig.legend(handles, labels, loc='lower center', bbox_to_anchor=(0.65, 0.42), ncol=2, fancybox=True)
    leg.get_frame().set_facecolor('#FFFFFF')
    leg.get_frame().set_alpha(1.)
    import matplotlib.pyplot as plt
    plt.subplots_adjust(wspace=0.025, hspace=0.55, bottom=0.18, top=.98)
    #iter_param.ax.text(7.5, 25, 'Eingägne')
    #iter_res.ax.text(7.5, 6.5e+8, 'Ausgägne')
    iter_plot.save('../data_out/plot/openMDAOconv_ALPSO.pdf', transparent=False)
    iter_plot.show()
Esempio n. 12
0
import numpy as np

from mylibs.rbf import RBF
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, pgf=False)

    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, pz = generate_sample_data(f_3d, pxEdge, pyEdge)
    knownParams = np.array([px, py]).T

    scat1 = plt1.ax.scatter(px, py, pz, c='r', marker='o', s=10, label=r'St\"utzstellen')

    rbf = RBF(knownParams, pz)
    a = 0.17
    rbf.update_param(a, 'lin')

    plt1.plot_function_3d(rbf.predict, fx, fy, r'$\widehat{f}_{RBF}$', color='b')
    t1.toc()
Esempio n. 13
0
        ax.set_xscale('log')
        pcol = ax.pcolor(thetas, ps, likely, cmap='YlOrRd_r')
        fig.colorbar(pcol)
        ax.plot(krig._theta[0], krig._p[0], 'rx')
        ax.set_xlabel('$\theta$')
        ax.set_ylabel('p')

    krig.optimize(opti_algo='grid')
    #krig1.update_param(krig1._theta, krig1._p)

    minLike = krig.calc_likelihood()
    print('minLike = ' + str(minLike))
    print('@theta = ' + str(krig._theta[0]))
    print('@p = ' + str(krig._p[0]))

    plt0 = PlotHelper([r'$\theta$', r'Likelihood'], fancy=True, pgf=PGF)
    plt0.ax.semilogx(thetas, likely[-1])
    plt0.ax.semilogx(krig._theta[0],
                     minLike,
                     'r+',
                     markersize=8,
                     label='Minimum')
    plt0.finalize(width=4,
                  height=1.8,
                  legendLoc='upper right',
                  legendNcol=1,
                  tighten_layout=True)
    plt.subplots_adjust(bottom=0.26, top=.98)
    plt0.save('../data_out/plot/krigingR2likelihood.pdf')
    #plt0.show()
Esempio n. 14
0
import numpy as np

from mylibs.rbf import RBF
from mylibs.structured_sample import StructuredSample
from mylibs.validation import Validation
from myutils.plot_helper import PlotHelper
from myutils.samples import *

if __name__ == '__main__':
    plt1 = PlotHelper(['Eingang', 'Ausgang'], fancy=True, pgf=False)

    # the smooth whole function
    fx = np.linspace(0, 10, 1001)
    fy = np.array(list(map(f_2d, fx)))

    plt1.ax.plot(fx, fy, 'r-', label=r'$f_{original}$')

    # now we pretend we only know a view points
    sample = StructuredSample()
    knwonParams = sample.generate_sample_plan(6, 1, [(0., 10.)])
    knownParams = np.array(knwonParams).flatten()
    knownValues = np.array(list(map(f_2d, knownParams)))

    fx = fx.reshape((len(fx), 1))

    aas = [1., 0.24, 1., 0.24]
    rbfs = ['gaus', 'gaus', 'imq', 'imq']
    plot_styles = ['b--', 'b:', 'c--', 'c:']

    for i in range(0, len(aas)):
        print('##############')
Esempio n. 15
0
d2.corellation()
d2.print_res_table(ref=max_shear_strength)

#d3 = DoE(input_names, ranges, runner.calc_stress, level_count=3)
#d3.corellation()
#d3.print_res_table()

if True:
    FANCY = True
    PGF = True

    avg = 0.5 * (d2._results[0].res + d2._results[3].res) - 0.5 * (
        d2._results[1].res + d2._results[2].res)
    print('interaction: {:f}'.format(avg))

    pl = PlotHelper([], fancy=FANCY, pgf=PGF)
    import matplotlib.pyplot as plt

    ax1 = pl.fig.add_subplot(221)
    ax2 = pl.fig.add_subplot(223)
    ax3 = pl.fig.add_subplot(224)

    pl1 = PlotHelper(['Level', 'Ausgang'], fancy=FANCY, pgf=PGF, ax=ax1)
    line_b = pl1.ax.plot([-1, 1], [d2._results[0].res, d2._results[1].res],
                         '-',
                         label='Blech-Einfl.(Rippen-L.: $-$)')
    line_r = pl1.ax.plot([-1, 1], [d2._results[0].res, d2._results[2].res],
                         '-',
                         label='Rippen-Einfl.(Blech-L.: $-$)')
    pl1.ax.xaxis.set_ticks([-1, 1])
    pl1.finalize(show_legend=False,
Esempio n. 16
0
from mylibs.structured_sample import StructuredSample
from myutils.plot_helper import PlotHelper

sam = StructuredSample()

str_plt = PlotHelper(['', ''], fancy=True, pgf=False)
import matplotlib.pyplot as plt

samples = sam.generate_sample_plan(30, 2, [(0, 30), (0, 30)])
for i in range(0, len(samples)):
    str_plt.ax.plot([samples[i][0]], [samples[i][1]], 'bo')

str_plt.ax.xaxis.set_ticklabels([])
str_plt.ax.yaxis.set_ticklabels([])
#str_plt.ax.set_xticks(range(0, 31), minor=False)
#str_plt.ax.set_yticks(range(0, 31), minor=False)
str_plt.ax.locator_params(nbins=4, axis='x')
str_plt.ax.locator_params(nbins=4, axis='y')
str_plt.ax.grid(True)

str_plt.finalize(width=1.5, height=1.5, show_legend=False)
str_plt.save('../data_out/plot/structuredSamp.pdf')
str_plt.show()
Esempio n. 17
0
# 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,
                            py,
Esempio n. 18
0
import numpy as np

from mylibs.polynomial import Polynomial
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,
                      pgf=False)

    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, pz = generate_sample_data(f_3d, pxEdge, pyEdge)
    knownParams = np.array([px, py]).T

    scat1 = plt1.ax.scatter(px,
                            py,
                            pz,
                            c='r',
                            marker='o',
                            s=10,
                            label=r'St\"utzstellen')
Esempio n. 19
0
    def plot_results(self, file_name):
        import matplotlib.pyplot as plt
        ribs, shell_thick, max_stress, max_disp, weight = self.read_data_file(
            file_name, use_abaqus=True)
        # max_stress = max_stress_fixed
        n_rib = len(ribs)
        n_thick = len(shell_thick)
        opti_ribs = []
        opti_shell = []
        opti_weight = []
        rib_mat, shell_mat = np.meshgrid(ribs, shell_thick)
        # interpol weight
        f_weight = interpolate.interp2d(rib_mat,
                                        shell_mat,
                                        weight,
                                        kind='linear')

        plot1 = PlotHelper(['ribs', 'max stress'])
        for i in range(0, len(shell_thick)):
            stress = max_stress[i]
            # if np.min(stress) < max_shear_strength and np.max(stress) > max_shear_strength:
            #   optRibs = np.interp(max_shear_strength, stress, ribs)
            #   f = interp1d(stress, ribs, kind='linear')
            #   plot1.ax.plot([f(max_shear_strength)], [max_shear_strength], 'go')
            #   opti_ribs.append(f(max_shear_strength))
            #   opti_shell.append(shellThick[i])
            plot1.ax.plot(ribs,
                          max_stress[i],
                          label='shell= {:03f}'.format(shell_thick[i]))
        plot1.ax.plot(ribs,
                      np.full((len(ribs), 1), max_shear_strength),
                      'r--',
                      label='Limit-Load')
        plot1.finalize(legendNcol=2, tighten_layout=False)
        # plot1.show()

        plot2 = PlotHelper(['shellthickness in mm', 'max stress'])
        for i in range(0, len(ribs)):
            stress = max_stress[:, i]
            plot2.ax.plot(shell_thick,
                          stress,
                          label='ribs= {:f}'.format(ribs[i]))
            if np.min(stress) < max_shear_strength and np.max(
                    stress) > max_shear_strength:
                # optRibs = np.interp(max_shear_strength, stress, ribs)
                f = interp1d(stress, shell_thick, kind='linear')
                plot2.ax.plot([f(max_shear_strength)], [max_shear_strength],
                              'go')
                opti_ribs.append(ribs[i])
                opti_shell.append(f(max_shear_strength))
                opti_weight.append(f_weight(ribs[i], f(max_shear_strength))[0])
        plot2.ax.plot(shell_thick,
                      np.full((len(shell_thick), 1), max_shear_strength),
                      'r--',
                      label='Limit-Load')
        # plot2.ax.set_xlim((min([x * 1000 for x in shellThick]), max([x * 1000 for x in shellThick])))

        plot2.finalize(legendNcol=2)
        plot2.show()

        opti_min_index = opti_weight.index(min(opti_weight))
        print('opt wight {:03f}'.format(opti_weight[opti_min_index]))
        print('@ {:00f} ribs'.format(opti_ribs[opti_min_index]))
        print('@ {:05f} shell-thickness'.format(opti_shell[opti_min_index]))

        plot3d = PlotHelper(['ribs', 'shell thickness in m', 'mises stress'])
        max_stress[max_stress > 1.2 * max_shear_strength] = np.nan
        color_map = plt.cm.jet(weight / np.max(weight))
        surf = plot3d.ax.plot_surface(rib_mat,
                                      shell_mat,
                                      max_stress,
                                      facecolors=color_map,
                                      cstride=1,
                                      rstride=1)
        optiLine = plot3d.ax.plot(opti_ribs,
                                  opti_shell,
                                  max_shear_strength,
                                  'k--',
                                  label='Limit-Load')
        optiPoint = plot3d.ax.plot([opti_ribs[opti_min_index]],
                                   [opti_shell[opti_min_index]],
                                   max_shear_strength,
                                   'ro',
                                   label='glob. optimum')
        m = cm.ScalarMappable(cmap=cm.jet)
        m.set_array(weight)
        cbar = plt.colorbar(m)
        cbar.set_label('structure weight in kg', rotation=270)
        limit = np.full((n_thick, n_rib), max_shear_strength)
        plot3d.ax.plot_wireframe(rib_mat,
                                 shell_mat,
                                 limit,
                                 color='r',
                                 alpha=0.1)
        plot3d.ax.set_zlim3d(0, max_shear_strength)
        plot3d.finalize()
        plot3d.show()
Esempio n. 20
0
                           width=6,
                           legendLoc=legend_loc,
                           show_legend=show_legend,
                           bbox_to_anchor=(1., 0.5))
        #samp_plot.show()
    return samp_plot


if __name__ == '__main__':
    #file = run_analysis()
    #plot_sample_point_analysis(file)
    #order_plot = plot_sample_point_analysis('analysis_PolyV002.csv', data_i=13)
    #order_plot.save(Constants().PLOT_PATH + 'polymOrderComp.pdf')
    #order_plot.show()

    plt_comp = PlotHelper([], fancy=True, pgf=False)
    import matplotlib.pyplot as plt
    ax1 = plt_comp.fig.add_subplot(322)
    ax2 = plt_comp.fig.add_subplot(324)
    ax3 = plt_comp.fig.add_subplot(326)

    poly_file = 'analysis_PolyV002.csv'
    rbf_file = 'analysis_RbfV001.csv'
    krig_file = 'analysis_KrigV001.csv'

    plot_sample_point_analysis(poly_file, ax=ax1, title='Polynom', data_i=8)
    labels = [item.get_text() for item in ax1.get_xticklabels()]
    empty_string_labels = [''] * len(labels)
    ax1.set_xticklabels(empty_string_labels)
    ax1.set_xlabel('')
    ax1.set_ylabel('')
Esempio n. 21
0
def plot_sample_point_analysis(file_name, ax=None, title='', data_i=8):
    DEVIATION = 5  # $\O$ -Abweichung in $\%$
    RMSE = 6  # RMSE in $\%$
    MAE = 7
    PRESS = 8
    RIBS = 9
    SHELL = 10
    WEIGHT = 11
    STRESS = 12
    OPTI_PARAM = 13
    #data_i = RMSE
    file_path = Constants().WORKING_DIR + '/' + file_name
    data = np.genfromtxt(file_path, delimiter=',', skip_header=1)
    sampling_plan_id = data[:, 1]
    sampling_point_count = data[:, 2]
    deviation = data[:, data_i]
    sampling_data = {}
    for samp in SAMPLE_NAMES[:-1]:
        sampling_data[samp] = []
    for i in range(0, len(sampling_plan_id)):
        sampling_data[SAMPLE_NAMES[int(sampling_plan_id[i])]].append(
            (sampling_point_count[i], deviation[i]))
    samp_plot = PlotHelper([
        'Anzahl der Stützstellen', 'RMSE in $\%$ von der max. Mises Spannung'
    ],
                           fancy=True,
                           pgf=False,
                           ax=ax)
    # plot one % line
    if data_i == DEVIATION or data_i == RMSE or data_i == PRESS:
        samp_plot.ax.plot([0, max(sampling_point_count)], [1., 1.],
                          '--',
                          color='lightgray',
                          label='1\%-Linie')
    for key in sampling_data:
        x = [x for x, y in sampling_data[key]]
        y = [y for x, y in sampling_data[key]]
        if data_i == DEVIATION:
            y = np.array(y) * 100.  # make it percent
        if data_i == RMSE or data_i == PRESS:
            y = np.array(y) * (100. / max_shear_strength)
        samp_plot.ax.plot(x, y, 'x-', label=key)
    legend_loc = 'upper right'
    if data_i == DEVIATION:
        samp_plot.ax.set_ylim([0, 3.])
    elif data_i == RMSE:
        samp_plot.ax.set_ylim([0, 3.])
    elif data_i == MAE:
        samp_plot.ax.set_ylim([0, 5e+7])
    elif data_i == PRESS:
        samp_plot.ax.set_ylabel('PRESS in $\%$ von der max. Mises Spannung')
        samp_plot.ax.set_ylim([0, 5])
    elif data_i == OPTI_PARAM:
        legend_loc = 'center left'
        samp_plot.ax.set_ylabel('Polynom-Grad')
    samp_plot.ax.set_xlim([5, 30])  #max(sampling_point_count)])

    if title != '':
        height = (samp_plot.ax.get_ylim()[1] -
                  samp_plot.ax.get_ylim()[0]) * 0.75
        samp_plot.ax.text(22, height, title, fontdict=samp_plot.font)
    show_legend = True
    if ax != None:
        show_legend = False
    samp_plot.ax.locator_params(nbins=4, axis='y')
    samp_plot.ax.locator_params(nbins=7, axis='x')

    #samp_plot.save(Constants().PLOT_PATH + file_name.replace('csv', 'pdf'))
    if ax == None:
        samp_plot.ax.locator_params(nbins=5, axis='y')
        samp_plot.finalize(height=2,
                           width=6,
                           legendLoc=legend_loc,
                           show_legend=show_legend,
                           bbox_to_anchor=(1., 0.5))
        #samp_plot.show()
    return samp_plot
Esempio n. 22
0
import numpy as np

from mylibs.polynomial import Polynomial
from myutils.plot_helper import PlotHelper
from myutils.samples import *
from mylibs.validation import Validation
from mylibs.validation import ValidationResults
from mylibs.latin_hyper_cube import LatinHyperCube
from mylibs.halton import Halton
from mylibs.structured_sample import StructuredSample

if __name__ == '__main__':
    polyPlot = PlotHelper(['Eingang', 'Ausgang'], fancy=True, pgf=False)

    # the smooth whole function
    fx = np.linspace(0, 10, 1001)
    fy = list(map(f_2d, fx))

    polyPlot.ax.plot(fx, fy, 'r-', label=r'$f_{original}$')

    # now we pretend we only know a view points
    sample = StructuredSample()
    knwonParams = sample.generate_sample_plan(6, 1, [(0., 10.)])
    knownParams = np.array(knwonParams).flatten()
    #knownParams = np.array([0., 2., 4., 6., 8., 10.])
    knownValues = np.array(list(map(f_2d, knownParams)))

    # validate points
    valiParams = np.array([1., 5., 9.])
    valiValues = np.array(list(map(f_2d, valiParams)))
    valiParams = valiParams.reshape((len(valiParams), 1))
import numpy as np
from mylibs.latin_hyper_cube import LatinHyperCube

sam = LatinHyperCube()

import matplotlib.pyplot as plt
samples = sam.generate_sample_plan(14, 2, [(5, 20), (0.01, 0.05), (1, 5)])
#samples = sam.enhanced_latin_hypercube_2_pow_x(16)
for i in range(0, len(samples)):
    plt.plot([samples[i][0]], [samples[i][1]], 'bo')
plt.show()

from myutils.plot_helper import PlotHelper
plt_latin = PlotHelper([], fancy=True, pgf=False)
import matplotlib.pyplot as plt

ax1 = plt_latin.fig.add_subplot(121)
ax2 = plt_latin.fig.add_subplot(122)

sample_mat_full = sam.enhanced_latin_hypercube(2, 16)
xy_full = sam.bool_mat_to_list(sample_mat_full)
plotXY_full = np.array(xy_full).T.tolist()
ax1.plot(plotXY_full[0], plotXY_full[1], 'bo', markersize=5)

deleteX = [0, 15, 4, 1]
deleteY = [0, 15, 1, 4]
for i in range(0, len(deleteX)):
    #ax1.plot([deleteX[i]], [deleteY[i]], 'rx', mew=2, ms=10)
    ax1.plot([-1, 16], [deleteY[i], deleteY[i]], 'r-', linewidth=2)
    ax1.plot([deleteX[i], deleteX[i]], [-1, 16], 'r-', linewidth=2)
    ax1.text(deleteX[i] - 0.3,