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)
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")
    )

    ##### Plot Polars
    fig, ax = plt.subplots(2, 2, figsize=(8, 8))
    Re = 1e6
    alpha_lowres = np.linspace(-15, 15, 31)
    ma = alpha
    mCL = af.CL_function(alpha, Re)
    mCD = af.CD_function(alpha, Re)
    xf_run = asb.XFoil(af, Re=Re, max_iter=20).alpha(alpha_lowres)
    xa = xf_run["alpha"]
    xCL = xf_run["CL"]
    xCD = xf_run["CD"]

    plt.sca(ax[0, 0])
    plt.plot(ma, mCL)
    plt.plot(xa, xCL, ".")
    plt.xlabel("Angle of Attack [deg]")
    plt.ylabel("Lift Coefficient $C_L$ [-]")

    plt.sca(ax[0, 1])
    plt.plot(ma, mCD)
    plt.plot(xa, xCD, ".")
    plt.ylim(0, 0.05)
    plt.xlabel("Angle of Attack [deg]")
    plt.ylabel("Drag Coefficient $C_D$ [-]")

    plt.sca(ax[1, 0])
    plt.plot(mCD, mCL)
    plt.plot(xCD, xCL, ".")
    plt.xlim(0, 0.05)
Example #4
0
        return self.mean_free_path() / length


if __name__ == "__main__":
    # Make AeroSandbox Atmosphere
    altitude = np.linspace(-5e3, 100e3, 1000)
    atmo_diff = Atmosphere(altitude=altitude)
    atmo_isa = Atmosphere(altitude=altitude, method="isa")

    from aerosandbox.tools.pretty_plots import plt, sns, mpl, show_plot, set_ticks

    fig, ax = plt.subplots()

    plt.plot(
        ((atmo_diff.pressure() - atmo_isa.pressure()) / atmo_isa.pressure()) *
        100,
        altitude / 1e3,
    )
    set_ticks(0.2, 0.1, 20, 10)
    plt.xlim(-1, 1)
    show_plot("AeroSandbox Atmosphere vs. ISA Atmosphere",
              "Pressure, Relative Error [%]", "Altitude [km]")

    fig, ax = plt.subplots()
    plt.plot(
        atmo_diff.temperature() - atmo_isa.temperature(),
        altitude / 1e3,
    )
    set_ticks(1, 0.5, 20, 10)
    plt.xlim(-5, 5)
    show_plot("AeroSandbox Atmosphere vs. ISA Atmosphere",
from scipy import optimize

fig, ax = plt.subplots()
speeds = np.linspace(0, 30, 500)


def get_mileage(speed):
    bike = Bike()
    try:
        perf = bike.steady_state_performance(speed=speed, )
    except ValueError:
        return np.NaN

    motor = perf['motor state']
    power = motor['voltage'] * motor['current']

    return power / speed


mileage = np.array([get_mileage(speed) for speed in speeds])  # J/m

mileage_Wh_per_mile = mileage / 3600 * 1000 * 1.609

plt.plot(speeds * 2.24, mileage_Wh_per_mile)
plt.xlim(left=0)
plt.ylim(bottom=0, top=50)
set_ticks(x_major=5, x_minor=1, y_major=5, y_minor=1)
show_plot(f"Electric Bike: Mileage vs. Speed",
          xlabel="Speed [mph]",
          ylabel=f"Energy Mileage [Wh per mile]")
Example #6
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()
Example #7
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$")
Example #8
0
def model(x, p):
    return 1 - p["1scl"] / (x - p["1cen"]) - (p["2scl"] / (x - p["2cen"]))**2


fit = asb.FittedModel(model=model,
                      x_data=fineness,
                      y_data=eta,
                      parameter_guesses={
                          "1scl": 1,
                          "1cen": -25,
                          "2scl": -1,
                          "2cen": -25,
                      },
                      parameter_bounds={
                          "1scl": (0, None),
                          "1cen": (None, 0),
                          "2scl": (0, None),
                          "2cen": (None, 0),
                      },
                      residual_norm_type="L2",
                      verbose=False)
print(fit.parameters)

from aerosandbox.tools.pretty_plots import plt, show_plot

fig, ax = plt.subplots()
plt.plot(fineness, eta, ".k")
fineness_plot = np.linspace(0, 40, 500)
plt.plot(fineness_plot, fit(fineness_plot), "-")
show_plot(r"$\eta$ Fitting", "Fineness Ratio", r"$\eta$")
Example #9
0
    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]")
    plt.ylabel(r"$C_D$")
    set_ticks(5, 1, 0.05, 0.01)
    plt.ylim(bottom=0)

    plt.sca(ax[1, 0])
    plt.plot(alpha, aero["Cm"])
    plt.xlabel(r"$\alpha$ [deg]")
    plt.ylabel(r"$C_m$")
    ) * d_ue_dx,  # From AVF Eq. 4.51
)
opti.subject_to(
    logint(theta / H_star) * d_H_star_dx ==
    int(2 * c_D / H_star - c_f / 2) +
    logint(
        (H - 1) * theta / ue
    ) * d_ue_dx
)

### Add initial conditions
opti.subject_to([
    theta[0] == theta_0,
    H[0] == H_0  # Equilibrium value
])

### Solve
sol = opti.solve()
theta = sol.value(theta)
H = sol.value(H)

### Plot
from aerosandbox.tools.pretty_plots import plt, show_plot

fig, ax = plt.subplots()
plt.plot(x, theta)
show_plot(r"$\theta$", "$x$", r"$\theta$")
fig, ax = plt.subplots()
plt.plot(x, H)
show_plot("$H$", "$x$", "$H$")
Example #11
0
    def simulate(
            self,
            t_eval,
            t_span=(0, 60),
            initial_position=0,
            initial_velocity=0,
    ):
        res = integrate.solve_ivp(
            fun=self.equations_of_motion,
            t_span=t_span,
            y0=np.array([initial_position, initial_velocity]),
            t_eval=t_eval,
        )
        return res.y


if __name__ == '__main__':

    bike = Bike()

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

    fig, ax = plt.subplots()
    t = np.linspace(0, 60, 500)
    pos, vel = bike.simulate(t)
    plt.plot(t, vel * 2.24)
    set_ticks(2, 1, 4, 2)
    plt.xlim(0, 20)
    plt.ylim(0, 36)
    show_plot("Electric Bike", xlabel="Time [s]", ylabel="Speed [mph]")
Example #12
0
from scipy import optimize

speed = 24 / 2.24

fig, ax = plt.subplots()
t = np.linspace(0, 10, 500)

gear_ratios = np.geomspace(0.020 / 0.700, 0.700 / 0.700, 300)


def get_efficiency(gear_ratio):
    bike = Bike(gear_ratio=gear_ratio)
    try:
        perf = bike.steady_state_performance(speed=speed)
    except ValueError:
        return np.NaN

    return perf['motor state']['efficiency']


eff = np.array([get_efficiency(gear_ratio) for gear_ratio in gear_ratios])

plt.plot(gear_ratios, eff * 100)
plt.xlim(gear_ratios[0], gear_ratios[-1])
plt.ylim(0, 100)
# plt.xscale('log')
set_ticks(x_major=0.1, x_minor=0.025, y_major=10, y_minor=2.5)
show_plot(f"Electric Bike: Gear Ratios at {speed * 2.24:.0f} mph",
          xlabel="Gear Ratio",
          ylabel=f"Efficiency [%]")
import os, sys
from pathlib import Path

this_dir = Path(__file__).parent
sys.path.insert(0, str(this_dir.parent))
from bike import Bike
import aerosandbox.numpy as np
from aerosandbox.tools.pretty_plots import plt, show_plot, set_ticks

fig, ax = plt.subplots()
t = np.linspace(0, 10, 500)

gear_ratios = np.geomspace(0.020 / 0.700, 0.700 / 0.700, 10)

colors = plt.cm.get_cmap('rainbow')(np.linspace(0, 1, len(gear_ratios)))

for i, gear_ratio in enumerate(gear_ratios):
    pos, vel = Bike(gear_ratio=gear_ratio).simulate(t)
    plt.plot(
        t,
        vel * 2.24,
        label=f"{gear_ratio:.2f}",
        color=colors[i],
    )
set_ticks(1, 0.5, 5, 1)
show_plot("Electric Bike: Gear Ratios",
          xlabel="Time [s]",
          ylabel="Speed [mph]")