Esempio n. 1
0
def plot_twist(data, cases, live_plot=True, annotate_data={}):
    plt.figure()

    for idx, case in enumerate(cases):
        case_data = data[case]

        mesh = case_data['mesh'][-1]
        twist = case_data['twist'][-1][0]

        span = compute_span(mesh)

        if idx > 0:
            label = 'w/o ' + case_keys[case]
            plt.plot(span, twist, label=label, color=colors[idx])
        else:
            label = case_keys[case]
            plt.plot(span, twist, label=label, color=colors[idx], zorder=100)

        if not live_plot:
            plt.annotate(label, annotate_data[case], color=colors[idx])

    if live_plot:
        niceplots.draggable_legend()
    niceplots.adjust_spines()

    plt.xlabel('Normalized span')
    plt.ylabel('Twist [degrees]')

    if live_plot:
        plt.show()
    else:
        # plt.tight_layout()
        plt.savefig('twists.pdf')
Esempio n. 2
0
def plot_lifts(data, cases, live_plot=True, annotate_data={}):
    plt.figure()

    for idx, case in enumerate(cases):
        case_data = data[case]

        mesh = case_data['mesh'][-1]
        lift = case_data['lift'][-1]

        span = compute_span(mesh)

        span = (span[1:] + span[:-1]) / 2

        if idx > 0:
            label = 'w/o ' + case_keys[case]
            plt.plot(span, lift, label=label, color=colors[idx])
        else:
            label = case_keys[case]
            plt.plot(span, lift, label=label, color=colors[idx], zorder=100)
            plt.plot(case_data['lift_ell_span'][-1],
                     case_data['lift_ell'][-1],
                     '--',
                     color='gray',
                     label='Elliptical')

        if not live_plot:
            plt.annotate(label, annotate_data[case], color=colors[idx])
            if idx == 0:
                plt.annotate('Elliptical',
                             annotate_data['elliptical'],
                             color='gray')

    if live_plot:
        niceplots.draggable_legend()
    niceplots.adjust_spines()

    plt.xlabel('Normalized span')
    plt.ylabel('Normalized lift distribution')

    if live_plot:
        plt.show()
    else:
        # plt.tight_layout()
        plt.savefig('lifts.pdf')
Esempio n. 3
0
def plot_tc(data, cases, live_plot=True, annotate_data={}):
    plt.figure()

    for idx, case in enumerate(cases):
        case_data = data[case]

        mesh = case_data['mesh'][-1]
        t_over_c = case_data['t_over_c'][-1][0]

        span, t_over_c = get_flat_data(mesh, t_over_c)

        if idx > 0:
            label = 'w/o ' + case_keys[case]
            plt.plot(span, t_over_c, label=label, color=colors[idx])
        else:
            label = case_keys[case]
            plt.plot(span,
                     t_over_c,
                     label=label,
                     color=colors[idx],
                     zorder=100)

        if not live_plot:
            plt.annotate(label, annotate_data[case], color=colors[idx])

    if live_plot:
        niceplots.draggable_legend()
    niceplots.adjust_spines()

    plt.xlabel('Normalized span')
    plt.ylabel('Thickness-to-chord ratio')

    if live_plot:
        plt.show()
    else:
        # plt.tight_layout()
        plt.savefig('tc.pdf')
Esempio n. 4
0
    def test(self):
        import numpy as np
        import matplotlib.pylab as plt

        from ozone.tests.ode_function_library.simple_homogeneous_func import \
            SimpleHomogeneousODEFunction
        from ozone.utils.run_utils import compute_convergence_order, compute_ideal_error
        from ozone.methods_list import family_names, method_families

        num_times_vector = np.array([10, 15, 20])

        ode_function = SimpleHomogeneousODEFunction()

        initial_conditions = {'y': 1.}
        t0 = 0.
        t1 = 1.

        state_name = 'y'

        formulation = 'solver-based'

        colors = ['b', 'g', 'r', 'c', 'm', 'k', 'y']
        # plt.figure(figsize=(14, 17))
        plt.figure(figsize=(15, 9))

        nrow = 3
        ncol = 4

        for plot_index, family_name in enumerate(family_names):
            method_family = method_families[family_name]

            print(method_family)

            plt.subplot(nrow, ncol, plot_index + 1)

            legend_entries = []
            for j, method_name in enumerate(method_family):

                errors_vector, step_sizes_vector, orders_vector, ideal_order = compute_convergence_order(
                    num_times_vector, t0, t1, state_name, ode_function,
                    formulation, method_name, initial_conditions)

                ideal_step_sizes_vector, ideal_errors_vector = compute_ideal_error(
                    step_sizes_vector, errors_vector, ideal_order)

                plt.loglog(step_sizes_vector * 1e2, errors_vector,
                           colors[j] + 'o-')
                plt.loglog(ideal_step_sizes_vector * 1e2,
                           ideal_errors_vector,
                           colors[j] + ':',
                           label='_nolegend_')

                average_order = np.sum(orders_vector) / len(orders_vector)

                print('(Ideal, observed): ', ideal_order, average_order)

                legend_entries.append(method_name +
                                      ' ({})'.format(ideal_order))
                # legend_entries.append('order %s' % ideal_order)

            irow = int(np.floor(plot_index / ncol))
            icol = plot_index % ncol

            plt.title(family_name)
            if irow == nrow - 1:
                plt.xlabel('step size (x 1e-2)')
            if icol == 0:
                plt.ylabel('error')
            plt.legend(legend_entries)
            ax = plt.gca()
            ax.xaxis.set_minor_formatter(
                matplotlib.ticker.FormatStrFormatter("%.1f"))
            try:
                niceplots.adjust_spines(ax=plt.gca())
            except:
                pass

            print()

        plt.show()
Esempio n. 5
0
    va="bottom",
    ha="center",
)
q2ax.plot(
    -minimum[0],
    minimum[1],
    clip_on=False,
    marker="o",
    color=niceColors["Grey"],
    markeredgecolor="w",
    linestyle="",
    markersize=12,
)
q2ax.annotate(
    "Local Maximum",
    xy=(-minimum[0], 0),
    xytext=(0, -10),
    textcoords="offset points",
    va="top",
    ha="center",
    color=niceColors["Grey"],
)
niceplots.adjust_spines(q2ax, outward=True)
q2ax.set_xlabel("$x_1$")
q2ax.set_xticks([min(x1), -minimum[0], 0, minimum[0], max(x1)])
q2ax.set_xlim(left=min(x1), right=max(x1))
q2ax.set_ylim(bottom=min(x2), top=max(x2))
q2ax.set_yticks([min(x2), 0, minimum[-1], max(x2)])
q2ax.set_ylabel("$x_2$", rotation="horizontal", ha="right")
plt.savefig("ParulaContours.png", dpi=400)
Esempio n. 6
0
    def plot_functions(self):
        """
        Plot a 2D contour plot of the design space and optimizer progress.

        Saves figures to .png files.

        """

        if self.n_dims == 2:
            n_plot = 9
            x_plot = np.linspace(self.bounds[0, 0], self.bounds[0, 1], n_plot)
            y_plot = np.linspace(self.bounds[1, 0], self.bounds[1, 1], n_plot)
            X, Y = np.meshgrid(x_plot, y_plot)
            x_values = np.vstack((X.flatten(), Y.flatten())).T

            y_plot_high = self.model_high.run_vec(x_values)[self.objective].reshape(
                n_plot, n_plot
            )

            # surrogate = []
            # for x_value in x_values:
            #     surrogate.append(np.squeeze(self.approximation_functions['con'](x_value)))
            # surrogate = np.array(surrogate)
            # y_plot_high = surrogate.reshape(n_plot, n_plot)

            fig = plt.figure(figsize=(7.05, 5))
            contour = plt.contourf(X, Y, y_plot_high, levels=201)
            plt.scatter(
                self.design_vectors[:, 0], self.design_vectors[:, 1], color="white"
            )
            ax = plt.gca()
            ax.set_aspect("equal", "box")

            cbar = fig.colorbar(contour)
            cbar.ax.set_ylabel("CP")
            ticks = np.round(np.linspace(0.305, 0.48286, 6), 3)
            cbar.set_ticks(ticks)
            cbar.set_ticklabels(ticks)

            x = self.design_vectors[-1, 0]
            y = self.design_vectors[-1, 1]
            points = np.array(
                [
                    [x + self.trust_radius, y + self.trust_radius],
                    [x + self.trust_radius, y - self.trust_radius],
                    [x - self.trust_radius, y - self.trust_radius],
                    [x - self.trust_radius, y + self.trust_radius],
                    [x + self.trust_radius, y + self.trust_radius],
                ]
            )
            plt.plot(points[:, 0], points[:, 1], "w--")

            plt.xlim(self.bounds[0])
            plt.ylim(self.bounds[1])

            plt.xlabel("Chord DV #1")
            plt.ylabel("Chord DV #2")

            plt.tight_layout()

            num_iter = self.design_vectors.shape[0]
            num_offset = 10

            if num_iter <= 5:
                for i in range(num_offset):
                    plt.savefig(
                        f"image_{self.counter_plot}.png", dpi=300, bbox_inches="tight"
                    )
                    self.counter_plot += 1
            else:
                plt.savefig(
                    f"image_{self.counter_plot}.png", dpi=300, bbox_inches="tight"
                )
                self.counter_plot += 1

        else:
            import niceplots

            x_full = np.atleast_2d(np.linspace(0.0, 1.0, 101)).T
            squeezed_x = np.squeeze(x_full)
            y_full = squeezed_x.copy()
            for i, x_val in enumerate(squeezed_x):
                y_full[i] = self.approximation_functions[self.objective](
                    np.atleast_2d(x_val.T)
                )

            y_full_high = self.model_high.run_vec(x_full)[self.objective]
            y_full_low = self.model_low.run_vec(x_full)[self.objective]

            y_low = self.model_low.run_vec(self.design_vectors)[self.objective]
            y_high = self.model_high.run_vec(self.design_vectors)[self.objective]

            plt.figure()

            plt.plot(squeezed_x, y_full_low, label="low-fidelity", c="tab:green")
            plt.scatter(self.design_vectors, y_low, c="tab:green")

            plt.plot(squeezed_x, y_full_high, label="high-fidelity", c="tab:orange")
            plt.scatter(self.design_vectors, y_high, c="tab:orange")

            plt.plot(squeezed_x, np.squeeze(y_full), label="surrogate", c="tab:blue")

            x = self.design_vectors[-1, 0]
            y_plot = y_high[-1]
            y_diff = 0.5
            x_lb = max(x - self.trust_radius, self.bounds[0, 0])
            x_ub = min(x + self.trust_radius, self.bounds[0, 1])
            points = np.array(
                [
                    [x_lb, y_plot],
                    [x_ub, y_plot],
                ]
            )
            plt.plot(points[:, 0], points[:, 1], "-", color="gray", clip_on=False)

            points = np.array(
                [
                    [x_lb, y_plot - y_diff],
                    [x_lb, y_plot + y_diff],
                ]
            )
            plt.plot(points[:, 0], points[:, 1], "-", color="gray", clip_on=False)

            points = np.array(
                [
                    [x_ub, y_plot - y_diff],
                    [x_ub, y_plot + y_diff],
                ]
            )
            plt.plot(points[:, 0], points[:, 1], "-", color="gray", clip_on=False)

            plt.xlim(self.bounds[0])
            plt.ylim([-10, 10])

            plt.xlabel("x")
            plt.ylabel("y")

            ax = plt.gca()
            ax.text(s="Low-fidelity", x=0.1, y=0.5, c="tab:green", fontsize=12)
            ax.text(s="High-fidelity", x=0.26, y=-8.5, c="tab:orange", fontsize=12)
            ax.text(
                s="Augmented low-fidelity", x=0.6, y=-10.0, c="tab:blue", fontsize=12
            )

            niceplots.adjust_spines(outward=True)

            plt.tight_layout()

            plt.savefig(f"1d_{self.counter_plot}.png", dpi=300)
            self.counter_plot += 1
Esempio n. 7
0
    def test(self):
        import numpy as np
        import matplotlib.pylab as plt

        from ozone.tests.ode_function_library.simple_linear_func import \
            SimpleLinearODEFunction
        from ozone.tests.ode_function_library.simple_nonlinear_func import \
            SimpleNonlinearODEFunction
        from ozone.utils.run_utils import compute_runtimes, compute_ideal_runtimes
        from ozone.methods_list import family_names, method_families

        num_rep = 10

        num_times_vector = np.array([10, 15, 20])
        num_times_vector = np.array([21, 26, 31, 36])

        ode_function = SimpleLinearODEFunction()
        ode_function = SimpleNonlinearODEFunction()

        initial_conditions = {'y': 1.}
        t0 = 0.
        t1 = 1.

        state_name = 'y'

        formulations = ['time-marching', 'solver-based', 'optimizer-based']

        colors = ['b', 'g', 'r', 'c', 'm', 'k', 'y']
        # plt.figure(figsize=(14, 17))
        plt.figure(figsize=(15, 9))

        nrow = 3
        ncol = 4

        for plot_index, family_name in enumerate(family_names):
            method_family = method_families[family_name]
            method_name = method_family[1]

            print(method_family, method_name)

            plt.subplot(nrow, ncol, plot_index + 1)

            legend_entries = []

            for j, formulation in enumerate(formulations):

                avg_runtimes_vector = np.zeros(len(num_times_vector))

                for irep in range(num_rep):
                    step_sizes_vector, runtimes_vector = compute_runtimes(
                        num_times_vector, t0, t1, ode_function, formulation,
                        method_name, initial_conditions)

                    avg_runtimes_vector += runtimes_vector / num_rep

                ideal_step_sizes_vector, ideal_runtimes = compute_ideal_runtimes(
                    step_sizes_vector, avg_runtimes_vector)

                plt.loglog(step_sizes_vector * 1e2, avg_runtimes_vector,
                           colors[j] + 'o-')
                plt.loglog(ideal_step_sizes_vector * 1e2,
                           ideal_runtimes,
                           colors[j] + ':',
                           label='_nolegend_')

                print('({} time): '.format(formulation), avg_runtimes_vector)

                legend_entries.append(formulation)
                # legend_entries.append('linear')

            irow = int(np.floor(plot_index / ncol))
            icol = plot_index % ncol

            plt.title(family_name)
            if irow == nrow - 1:
                plt.xlabel('step size (x 1e-2)')
            if icol == 0:
                plt.ylabel('computation time (s)')
            plt.legend(legend_entries)
            try:
                niceplots.adjust_spines(ax=plt.gca())
            except:
                pass

            print()

        plt.show()
Esempio n. 8
0
        if i_col == 3:
            anchor = 6
            x_anchor = 0.4
            spacing = 0.22
            twist_labels = {
                'baseline': (x_anchor, anchor + spacing),
                'viscous': (x_anchor, anchor - 5 * spacing),
                'wave_drag': (x_anchor, anchor - 4 * spacing),
                'struct_weight': (x_anchor, anchor + 0),
                'fuel_weight': (x_anchor, anchor - 3 * spacing),
                'engine_mass': (x_anchor, anchor - 2 * spacing),
                'engine_thrust': (x_anchor, anchor - spacing),
            }

            ax_plot_twist(ax,
                          data,
                          folders,
                          live_plot=False,
                          annotate_data=twist_labels)

        niceplots.adjust_spines(ax)

        if i_row == 0:
            ax.set_title(labels[i_col], fontsize=24)
        if i_row == 2:
            ax.set_xlabel('Normalized span')
        if i_col == 0:
            ax.set_ylabel(wing_labels[i_row], fontsize=24)

plt.savefig('all_plots.pdf')