def test_rosenbrock_constrained(plot=False):
    opti = asb.Opti()

    x = opti.variable(init_guess=0)
    y = opti.variable(init_guess=0)
    r = opti.parameter()

    f = (1 - x)**2 + (y - x**2)**2
    opti.minimize(f)
    con = x**2 + y**2 <= r
    dual = opti.subject_to(con)

    r_values = np.linspace(1, 3)

    sols = [opti.solve({r: r_value}) for r_value in r_values]
    fs = [sol.value(f) for sol in sols]
    duals = [
        sol.value(dual)  # Ensure the dual can be evaluated
        for sol in sols
    ]

    if plot:
        fig, ax = plt.subplots(1, 1, figsize=(6.4, 4.8), dpi=200)
        plt.plot(r_values, fs, label="$f$")
        plt.plot(r_values, duals, label=r"Dual var. ($\frac{df}{dr}$)")
        plt.legend()
        plt.xlabel("$r$")
        plt.show()

    assert dual is not None  # The dual should be a real value
    assert r_values[0] == pytest.approx(1)
    assert duals[0] == pytest.approx(0.10898760051521068, abs=1e-6)
Beispiel #2
0
    def plot_tropopause_altitude():
        fig, ax = plt.subplots()

        day_of_years = np.linspace(0, 365, 250)
        latitudes = np.linspace(-80, 80, 200)
        Day_of_years, Latitudes = np.meshgrid(day_of_years, latitudes)

        trop_alt = tropopause_altitude(
            Latitudes.flatten(),
            Day_of_years.flatten()
        ).reshape(Latitudes.shape)

        args = [
            day_of_years,
            latitudes,
            trop_alt / 1e3
        ]

        levels = np.arange(10, 20.1, 1)
        CS = plt.contour(*args, levels=levels, linewidths=0.5, colors="k", alpha=0.7)
        CF = plt.contourf(*args, levels=levels, cmap='viridis_r', alpha=0.7, extend="both")
        cbar = plt.colorbar(label="Tropopause Altitude [km]", extendrect=True)
        ax.clabel(CS, inline=1, fontsize=9, fmt="%.0f km")

        plt.xticks(
            np.linspace(0, 365, 13)[:-1],
            (
                "Jan. 1",
                "Feb. 1",
                "Mar. 1",
                "Apr. 1",
                "May 1",
                "June 1",
                "July 1",
                "Aug. 1",
                "Sep. 1",
                "Oct. 1",
                "Nov. 1",
                "Dec. 1"
            ),
            rotation=40
        )

        lat_label_vals = np.arange(-80, 80.1, 20)
        lat_labels = []
        for lat in lat_label_vals:
            if lat >= 0:
                lat_labels.append(f"{lat:.0f}N")
            else:
                lat_labels.append(f"{-lat:.0f}S")
        plt.yticks(
            lat_label_vals,
            lat_labels
        )

        show_plot(
            f"Tropopause Altitude by Season and Latitude",
            xlabel="Day of Year",
            ylabel="Latitude",
        )
Beispiel #3
0
    def plot_winds_at_tropopause_altitude():
        fig, ax = plt.subplots()

        day_of_years = np.linspace(0, 365, 150)
        latitudes = np.linspace(-80, 80, 120)
        Day_of_years, Latitudes = np.meshgrid(day_of_years, latitudes)

        winds = wind_speed_world_95(
            altitude=tropopause_altitude(Latitudes.flatten(),
                                         Day_of_years.flatten()),
            latitude=Latitudes.flatten(),
            day_of_year=Day_of_years.flatten(),
        ).reshape(Latitudes.shape)

        args = [day_of_years, latitudes, winds]

        levels = np.arange(0, 80.1, 5)
        CS = plt.contour(*args,
                         levels=levels,
                         linewidths=0.5,
                         colors="k",
                         alpha=0.7)
        CF = plt.contourf(*args,
                          levels=levels,
                          cmap='viridis_r',
                          alpha=0.7,
                          extend="max")
        cbar = plt.colorbar(label="Wind Speed [m/s]", extendrect=True)
        ax.clabel(CS, inline=1, fontsize=9, fmt="%.0f m/s")

        plt.xticks(
            np.linspace(0, 365, 13)[:-1],
            ("Jan. 1", "Feb. 1", "Mar. 1", "Apr. 1", "May 1", "June 1",
             "July 1", "Aug. 1", "Sep. 1", "Oct. 1", "Nov. 1", "Dec. 1"),
            rotation=40)

        lat_label_vals = np.arange(-80, 80.1, 20)
        lat_labels = []
        for lat in lat_label_vals:
            if lat >= 0:
                lat_labels.append(f"{lat:.0f}N")
            else:
                lat_labels.append(f"{-lat:.0f}S")
        plt.yticks(lat_label_vals, lat_labels)

        show_plot(
            f"95th-Percentile Wind Speeds at Tropopause Altitude",
            xlabel="Day of Year",
            ylabel="Latitude",
        )
Beispiel #4
0
    def plot_winds_at_day(day_of_year=0):
        fig, ax = plt.subplots()

        altitudes = np.linspace(0, 30000, 150)
        latitudes = np.linspace(-80, 80, 120)
        Altitudes, Latitudes = np.meshgrid(altitudes, latitudes)

        winds = wind_speed_world_95(
            altitude=Altitudes.flatten(),
            latitude=Latitudes.flatten(),
            day_of_year=day_of_year * np.ones_like(Altitudes.flatten()),
        ).reshape(Altitudes.shape)

        args = [altitudes / 1e3, latitudes, winds]

        levels = np.arange(0, 80.1, 5)
        CS = plt.contour(*args,
                         levels=levels,
                         linewidths=0.5,
                         colors="k",
                         alpha=0.7)
        CF = plt.contourf(*args,
                          levels=levels,
                          cmap='viridis_r',
                          alpha=0.7,
                          extend="max")
        cbar = plt.colorbar(label="Wind Speed [m/s]", extendrect=True)
        ax.clabel(CS, inline=1, fontsize=9, fmt="%.0f m/s")

        lat_label_vals = np.arange(-80, 80.1, 20)
        lat_labels = []
        for lat in lat_label_vals:
            if lat >= 0:
                lat_labels.append(f"{lat:.0f}N")
            else:
                lat_labels.append(f"{-lat:.0f}S")
        plt.yticks(lat_label_vals, lat_labels)

        show_plot(
            f"95th-Percentile Wind Speeds at Day {day_of_year:.0f}",
            xlabel="Altitude [km]",
            ylabel="Latitude",
        )
import aerosandbox.numpy as np

np.random.seed(0)  # Fix a seed for reproducibility

### Create some data (some fictional system where temperature is a function of time, and we're measuring it)
n = 20

time = 100 * np.random.rand(n)

actual_temperature = 2 * time + 20  # True physics of the system

noise = 10 * np.random.randn(n)
measured_temperature = actual_temperature + noise  # Measured temperature of the system

### Add in a dropout measurement (say, the sensor wire randomly came loose and gave us a 0 reading)
time = np.hstack((time, 90))
measured_temperature = np.hstack((measured_temperature, 0))

if __name__ == '__main__':
    from aerosandbox.tools.pretty_plots import plt, sns, mpl, show_plot
    fig, ax = plt.subplots()
    plt.plot(time, measured_temperature, ".")
    show_plot(xlabel="Time", ylabel="Measured Temperature")
    af = asb.Airfoil("dae11")
    af.generate_polars()

    alpha = np.linspace(-40, 40, 300)
    re = np.geomspace(1e4, 1e12, 100)
    Alpha, Re = np.meshgrid(alpha, re)
    af.CL_function(alpha=0, Re=1e6)

    CL = af.CL_function(Alpha.flatten(), Re.flatten()).reshape(Alpha.shape)
    CD = af.CD_function(Alpha.flatten(), Re.flatten()).reshape(Alpha.shape)
    CM = af.CM_function(Alpha.flatten(), Re.flatten()).reshape(Alpha.shape)

    ##### Plot alpha-Re contours
    from aerosandbox.tools.pretty_plots import plt, show_plot, contour

    fig, ax = plt.subplots()
    contour(Alpha, Re, CL, levels=30, colorbar_label=r"$C_L$")
    plt.scatter(af.xfoil_data["alpha"],
                af.xfoil_data["Re"],
                color="k",
                alpha=0.2)
    plt.yscale('log')
    show_plot(
        f"Auto-generated Polar for {af.name} Airfoil",
        "Angle of Attack [deg]",
        "Reynolds Number [-]",
    )

    fig, ax = plt.subplots()
    contour(Alpha,
            Re,
Beispiel #7
0
    ##### Tangential force calculation
    CT = (pt1_star + pt2_star * cosa + pt3_star * cosa**3) * sina**2

    ##### Conversion to wind axes
    CL = CN * cosa + CT * sina
    CD = CN * sina - CT * cosa
    CM = np.zeros_like(CL)  # TODO

    return CL, CD, CM


if __name__ == '__main__':
    af = Airfoil("naca0012")
    alpha = np.linspace(0, 360, 721)
    CL, CD, CM = airfoil_coefficients_post_stall(af, alpha)
    from aerosandbox.tools.pretty_plots import plt, show_plot, set_ticks

    fig, ax = plt.subplots(1, 2, figsize=(8, 5))
    plt.sca(ax[0])
    plt.plot(alpha, CL)
    plt.xlabel("AoA")
    plt.ylabel("CL")
    set_ticks(45, 15, 0.5, 0.1)
    plt.sca(ax[1])
    plt.plot(alpha, CD)
    plt.xlabel("AoA")
    plt.ylabel("CD")
    set_ticks(45, 15, 0.5, 0.1)
    show_plot()
Beispiel #8
0
from aerosandbox.tools.pretty_plots import plt, show_plot, equal

vars_to_plot = {
    **dyn.state,
    "alpha"   : dyn.alpha,
    "beta"    : dyn.beta,
    "speed"   : dyn.speed,
    "altitude": dyn.altitude,
    "CL"      : aero["CL"],
    "CY"      : aero["CY"],
    "CD"      : aero["CD"],
    "Cl"      : aero["Cl"],
    "Cm"      : aero["Cm"],
    "Cn"      : aero["Cn"],
}
fig, axes = plt.subplots(6, 4, figsize=(15, 10), sharex=True)
for var_to_plot, ax in zip(vars_to_plot.items(), axes.flatten(order="F")):
    plt.sca(ax)
    k, v = var_to_plot
    plt.plot(dyn.time, v)
    plt.ylabel(k)
show_plot()

fig, ax = plt.subplots()
plt.plot(dyn.xe, dyn.altitude, "k")
sc = plt.scatter(dyn.xe, dyn.altitude, c=dyn.speed, cmap=plt.get_cmap("rainbow"), zorder=4)
plt.axis('equal')
plt.colorbar(label="Airspeed [m/s]")
show_plot("Trajectory using `asb.AeroBuildup` Flight Dynamics", "$x_e$", "$-z_e$")
Beispiel #9
0
            "m_b": M_b[1],
            "n_b": M_b[2]
        }


if __name__ == '__main__':
    from aerosandbox.aerodynamics.aero_3D.test_aero_3D.geometries.conventional import airplane

    aero = AeroBuildup(
        airplane=airplane,
        op_point=OperatingPoint(alpha=0, beta=1),
    ).run()

    from aerosandbox.tools.pretty_plots import plt, show_plot, contour, equal, set_ticks

    fig, ax = plt.subplots(2, 2)
    alpha = np.linspace(-10, 10, 1000)
    aero = AeroBuildup(
        airplane=airplane,
        op_point=OperatingPoint(velocity=100, alpha=alpha, beta=0),
    ).run()

    plt.sca(ax[0, 0])
    plt.plot(alpha, aero["CL"])
    plt.xlabel(r"$\alpha$ [deg]")
    plt.ylabel(r"$C_L$")
    set_ticks(5, 1, 0.5, 0.1)

    plt.sca(ax[0, 1])
    plt.plot(alpha, aero["CD"])
    plt.xlabel(r"$\alpha$ [deg]")