Esempio n. 1
0
def mtow_plot(model):
    model.cost = model["MTOW"]
    fig, ax = plt.subplots()
    x = np.linspace(1, 15, 500)
    tol = 0.05
    time = 0.0
    nsolves = 0
    ws = []
    xs = []
    for p in [85, 90, 95]:
        wind = get_windspeed(38, p, 15000, 355)
        cwind = get_windspeed(38, p, np.linspace(0, 15000, 11)[1:], 355)
        for vk in model.varkeys["V_{wind}"]:
            if "Climb" in vk.models:
                model.substitutions.update({vk: cwind[vk.idx[0]]})
            else:
                model.substitutions.update({vk: wind})

        model.substitutions.update({"MTOW": 1000})
        model.cost = 1/model["t_Mission/Loiter"]
        sol = model.solve("mosek")
        time += sol["soltime"]
        nsolves += 1
        upper = sol("t_Mission/Loiter").magnitude
        xmin_ = x[x < upper + 0.03]
        xs.append(xmin_)

        del model.substitutions["MTOW"]
        model.cost = model["MTOW"]
        bst = autosweep_1d(model, tol, model["t_Mission/Loiter"],
                           [1, xmin_[-1]], solver="mosek")
        bsts = find_sols([bst])
        sols = np.hstack([b.sols for b in bsts])
        time += sum(np.unique([s["soltime"] for s in sols]))
        nsolves += bst.nsols
        ws.append(bst.sample_at(xmin_)["cost"])

    print "%d solves in %.4f seconds" % (nsolves, time)
    ax.fill_between(xs[0], ws[0],
                    np.append(ws[2], [1000]*(len(xs[0])-len(xs[2]))),
                    facecolor="r", edgecolor="None", alpha=0.3)
    ax.plot(xs[0], ws[0], "r")
    ax.plot(xs[1], ws[1], "r", lw=2)
    ax.plot(xs[2], ws[2], "r")
    for i, p in enumerate(["80%", "90%", "95%"]):
        weight = ws[i].magnitude
        we = 500 + min(abs(weight-500))
        if we not in weight:
            we = 500 - min(abs(weight-500))
        end = xs[i][weight == we][0]
        ax.annotate(p, xy=(end, we), xytext=(end+0.3, we+0.01),
                    arrowprops=dict(arrowstyle="-"), fontsize=12)
    ax.grid()
    ax.set_ylim([0, 1000])
    ax.set_xlabel("Endurance [days]")
    ax.set_ylabel("Max Take Off Weight [lbf]")
    return fig, ax
Esempio n. 2
0
"Show autosweep_1d functionality"
import cPickle as pickle
import numpy as np
import gpkit
from gpkit import units, Variable, Model
from gpkit.tools.autosweep import autosweep_1d
from gpkit.small_scripts import mag

A = Variable("A", "m**2")
l = Variable("l", "m")

m1 = Model(A**2, [A >= l**2 + units.m**2])
tol1 = 1e-3
bst1 = autosweep_1d(m1, tol1, l, [1, 10], verbosity=0)
print "Solved after %2i passes, cost logtol +/-%.3g" % (bst1.nsols, bst1.tol)
# autosweep solution accessing
l_vals = np.linspace(1, 10, 10)
sol1 = bst1.sample_at(l_vals)
print "values of l:", l_vals
print "values of A:", sol1("A")
cost_estimate = sol1["cost"]
cost_lb, cost_ub = sol1.cost_lb(), sol1.cost_ub()
print "cost lower bound:", cost_lb
print "cost estimate:   ", cost_estimate
print "cost upper bound:", cost_ub
# you can evaluate arbitrary posynomials
np.testing.assert_allclose(mag(2*sol1(A)), mag(sol1(2*A)))
assert (sol1["cost"] == sol1(A**2)).all()
# the cost estimate is the logspace mean of its upper and lower bounds
np.testing.assert_allclose((np.log(mag(cost_lb)) + np.log(mag(cost_ub)))/2,
                           np.log(mag(cost_estimate)))
Esempio n. 3
0
"Show autosweep_1d functionality"
import cPickle as pickle
import numpy as np
import gpkit
from gpkit import units, Variable, Model
from gpkit.tools.autosweep import autosweep_1d
from gpkit.small_scripts import mag

A = Variable("A", "m**2")
l = Variable("l", "m")

m1 = Model(A**2, [A >= l**2 + units.m**2])
tol1 = 1e-3
bst1 = autosweep_1d(m1, tol1, l, [1, 10], verbosity=0)
print "Solved after %2i passes, cost logtol +/-%.3g" % (bst1.nsols, bst1.tol)
# autosweep solution accessing
l_vals = np.linspace(1, 10, 10)
sol1 = bst1.sample_at(l_vals)
print "values of l:", l_vals
print "values of A:", sol1("A")
cost_estimate = sol1["cost"]
cost_lb, cost_ub = sol1.cost_lb(), sol1.cost_ub()
print "cost lower bound:", cost_lb
print "cost estimate:   ", cost_estimate
print "cost upper bound:", cost_ub
# you can evaluate arbitrary posynomials
np.testing.assert_allclose(mag(2*sol1(A)), mag(sol1(2*A)))
assert (sol1["cost"] == sol1(A**2)).all()
# the cost estimate is the logspace mean of its upper and lower bounds
np.testing.assert_allclose((np.log(mag(cost_lb)) + np.log(mag(cost_ub)))/2,
                           np.log(mag(cost_estimate)))
Esempio n. 4
0
def plot_wrange(model, sto, Nr, plot=True):
    " plot weight vs range "
    model.cost = model.aircraft.topvar("W")
    model.substitutions["V_{min}"] = 100

    Rmin = 25

    if plot:
        fig, ax = plt.subplots()
        figs, axs = plt.subplots()
        figv, axv = plt.subplots()

    clrs = ["#084081", "#0868ac", "#2b8cbe", "#4eb3d3", "#7bccc4"]*5

    i = 0
    Rknee = []

    for s in sto:
        model.substitutions.update({"S_{runway}": s})
        model.cost = 1/model["R"]
        sol = model.solve("mosek")
        Rmax = sol("R").magnitude - 10
        model.cost = model[model.aircraft.topvar("W")]
        bst = autosweep_1d(model, 0.1, model["R"], [Rmin, Rmax])
        solR = bst.solarray("R")
        stosens = bst.solarray["sensitivities"]["constants"]["R"]
        fbatt = bst.solarray("W_{batt}")/bst.solarray(
            model.aircraft.topvar("W"))
        wair = bst.solarray(model.aircraft.topvar("W"))
        lands = bst.solarray["sensitivities"]["constants"][
            "m_{fac}_Mission/GLanding"]

        f = interp1d(stosens, solR, "cubic")
        fw = interp1d(stosens, wair, "cubic")
        fwf = interp1d(stosens, fbatt, "cubic")
        if 1.0 > max(stosens):
            Rknee.extend([np.nan])
            wint = np.nan
            wbint = np.nan
        else:
            Rknee.extend([f(1.0)])
            wint = fw(1.0)
            wbint = fwf(1.0)

        if plot:
            axs.plot(solR, lands, color=clrs[i],
                     label="$S_{runway} = %d [ft]$" % s)
            x = np.linspace(Rmin, Rmax, 100)
            solR = bst.sample_at(x)["R"]
            fbatt = bst.sample_at(x)["W_{batt}"]/bst.sample_at(x)[
                model.aircraft.topvar("W")]
            wair = bst.sample_at(x)[model.aircraft.topvar("W")]
            ax.plot(solR, wair, color=clrs[i],
                    label="$S_{\\mathrm{runwawy}} = %d [ft]$" % s)
            axv.plot(solR, fbatt, color=clrs[i],
                     label="$S_{\\mathrm{runway}} = %d [ft]$" % s)
            # ax.plot(Rknee[-1], wint, marker='o', color="k", markersize=5)
            axv.plot(Rknee[-1], wbint, marker='o', color="k", markersize=5)
            i += 1

    if plot:
        ax.set_ylabel("Max Takeoff Weight [lbf]")
        ax.set_xlabel("Range [nmi]")
        ax.legend(loc=4, fontsize=12)
        ax.grid()
        ax.set_ylim([0, 10000])
        axs.set_ylabel("Landing Sensitivity")
        axs.set_xlabel("Range [nmi]")
        axs.legend(loc=2, fontsize=12)
        axs.grid()
        axs.set_ylim([-0.1, 1])

    if plot:
        ret = [fig, figs, figv]
    else:
        ret = Rknee

    return ret
Esempio n. 5
0
def plot_contours(path=None):
    N = 100
    stime = 0.0
    numsolves = 0
    plt.rcParams.update({'font.size': 19})
    hmin = 250.0
    hmax = 400.0
    for av in [80, 85, 90]:
        for lat in [25, 30, 35]:
            zo = 10
            if lat == 25:
                bs = range(30, 80, 5)
            elif lat == 30:
                bs = range(35, 80, 5)
                if av == 90:
                    del bs[0]
            else:
                bs = range(45, 80, 5)
                if av == 90:
                    del bs[0]
            fig, ax = plt.subplots()
            M = Mission(latitude=lat)
            M.substitutions.update({"W_{pay}": 10})
            for vk in M.varkeys["\\eta_{prop}"]:
                M.substitutions.update({vk: 0.75})
            for vk in M.varkeys["p_{wind}"]:
                M.substitutions.update({vk: av / 100.0})
            del M.substitutions["\\eta_Mission/Aircraft/SolarCells"]
            del M.substitutions["h_{batt}"]
            M.cost = M["h_{batt}"]
            lines = []
            midx = []
            for b in bs:
                etamax = 0.4
                etamin = 0.15
                M.substitutions.update({"b_Mission/Aircraft/Wing": b})
                M.substitutions.update(
                    {"\\eta_Mission/Aircraft/SolarCells": etamax})
                sol = M.solve("mosek")
                stime += sol["soltime"]
                numsolves += 1
                del M.substitutions["\\eta_Mission/Aircraft/SolarCells"]
                if sol("h_{batt}").magnitude < hmin:
                    M.substitutions.update({"h_{batt}": hmin})
                    M.cost = M["\\eta_Mission/Aircraft/SolarCells"]
                    sol = M.solve("mosek")
                    stime += sol["soltime"]
                    numsolves += sol["soltime"]
                    etamax = sol("\\eta_Mission/Aircraft/SolarCells")

                M.substitutions.update({"h_{batt}": hmax})
                M.cost = M["\\eta_Mission/Aircraft/SolarCells"]
                sol = M.solve("mosek")
                stime += sol["soltime"]
                numsolves += 1
                etamin = sol("\\eta_Mission/Aircraft/SolarCells")

                if etamin > etamax:
                    continue

                del M.substitutions["h_{batt}"]
                M.cost = M["h_{batt}"]
                xmin_ = np.linspace(etamin, etamax, 100)
                tol = 0.01
                bst = autosweep_1d(M,
                                   tol,
                                   M["\\eta_Mission/Aircraft/SolarCells"],
                                   [etamin, etamax],
                                   solver="mosek")
                bsts = find_sols([bst])
                sols = np.hstack([bs.sols for bs in bsts])
                stime += sum(np.unique([s["soltime"] for s in sols]))
                numsolves += bst.nsols

                if b % 10 == 0:
                    l = ax.plot(xmin_,
                                bst.sample_at(xmin_)["cost"],
                                "k",
                                label="%d [ft]" % b,
                                zorder=zo)
                    zo += 2
                    lines.append(l[0])
                    midx.append(np.median(xmin_))
                else:
                    ax.plot(xmin_,
                            bst.sample_at(xmin_)["cost"],
                            "--",
                            c="0.5",
                            zorder=100)

            # parato fontier
            del M.substitutions["b_Mission/Aircraft/Wing"]
            M.substitutions.update(
                {"\\eta_Mission/Aircraft/SolarCells": etamax})
            M.cost = M["h_{batt}"]
            sol = M.solve("mosek")
            etamax = 0.4
            stime += sol["soltime"]
            numsolves += 1
            del M.substitutions["\\eta_Mission/Aircraft/SolarCells"]
            if sol("h_{batt}").magnitude < hmin:
                M.substitutions.update({"h_{batt}": hmin})
                M.cost = M["\\eta_Mission/Aircraft/SolarCells"]
                sol = M.solve("mosek")
                stime += sol["soltime"]
                numsolves += sol["soltime"]
                etamax = sol("\\eta_Mission/Aircraft/SolarCells")

            M.substitutions.update({"h_{batt}": hmax})
            M.cost = M["\\eta_Mission/Aircraft/SolarCells"]
            sol = M.solve("mosek")
            stime += sol["soltime"]
            numsolves += 1
            etamin = sol("\\eta_Mission/Aircraft/SolarCells")

            if etamin > etamax:
                break
            del M.substitutions["h_{batt}"]
            M.cost = M["h_{batt}"]
            xmin_ = np.linspace(etamin, etamax, 100)
            tol = 0.01
            bst = autosweep_1d(M,
                               tol,
                               M["\\eta_Mission/Aircraft/SolarCells"],
                               [etamin, etamax],
                               solver="mosek")
            bsts = find_sols([bst])
            sols = np.hstack([b.sols for b in bsts])
            stime += sum(np.unique([s["soltime"] for s in sols]))
            numsolves += bst.nsols

            ax.set_xlabel("Solar Cell Efficiency")
            ax.set_ylabel("Battery Specific Energy [Whr/kg]")
            labelLines(lines[:-1],
                       align=True,
                       xvals=midx,
                       zorder=[11, 13, 15, 17])
            ax.fill_between(np.hstack([0.15, xmin_]),
                            0,
                            np.hstack([hmax,
                                       bst.sample_at(xmin_)["cost"]]),
                            edgecolor="r",
                            lw=2,
                            hatch="/",
                            facecolor="None",
                            zorder=100)
            ax.text(0.17, 260, "Infeasible", fontsize=19)
            ax.set_xlim([0.15, 0.4])
            ax.set_ylim([250, 400])
            if path:
                fig.savefig(path + "bcontourl%da%d.pdf" % (lat, av),
                            bbox_inches="tight")
            else:
                fig.savefig("bcontourl%da%d.pdf" % (lat, av))

    print "%d solves in %.4f seconds" % (numsolves, stime)
Esempio n. 6
0
bmax = []
lines = []
for lat in range(20, 31, 2):
    hmax = 500
    M = Mission(latitude=lat)
    M.substitutions.update({"W_{pay}": 10})
    for vk in M.varkeys["\\eta_{prop}"]:
        M.substitutions.update({vk: 0.75})
    for vk in M.varkeys["p_{wind}"]:
        M.substitutions.update({vk: 90/100.0})
    del M.substitutions["h_{batt}"]
    M.cost = M["h_{batt}"]
    sol = M.solve("mosek")
    hmin = sol["cost"].magnitude + 1e-3
    M.cost = M["b_Mission/Aircraft/Wing"]
    xmin_ = np.linspace(hmin, hmax, 100)
    tol = 0.01
    bst = autosweep_1d(M, tol, M["h_{batt}"], [hmin, hmax], solver="mosek")
    l = ax.plot(xmin_, bst.sample_at(xmin_)["cost"], "k", label="%d" % lat)
    lines.append(l[0])
    bmax.append(max(bst.sample_at(xmin_)["cost"].magnitude))

labelLines(lines, align=False, xvals=[270, 290, 310, 330, 360, 390],
           zorder=[10]*len(lines))
ax.set_ylabel("Span [ft]")
ax.set_xlabel("Battery Specific Energy [Whr/kg]")
ax.set_xlim([250, 400])
ax.set_ylim([20, max(bmax)-5])
ax.grid()
fig.savefig("test.pdf", bbox_inches="tight")
Esempio n. 7
0
def plot_battsolarcon():
    fig, ax = plt.subplots()
    time = 0
    numsolves = 0
    etamax = []
    lines = []
    midx = []
    passing = True
    for lat in range(20, 44, 1):
        if passing:
            hmax = 500
            M = Mission(latitude=lat)
            M.substitutions.update({"W_{pay}": 10})
            for vk in M.varkeys["\\eta_{prop}"]:
                M.substitutions.update({vk: 0.75})
            for vk in M.varkeys["p_{wind}"]:
                M.substitutions.update({vk: 90 / 100.0})
            del M.substitutions["h_{batt}"]
            M.substitutions.update({"\\eta_Mission/Aircraft/SolarCells": 0.4})
            M.cost = M["h_{batt}"]
            sol = M.solve("mosek")
            time += sol["soltime"]
            numsolves += 1
            hmin = sol["cost"].magnitude + 1e-3
            if hmin >= hmax:
                break
            del M.substitutions["\\eta_Mission/Aircraft/SolarCells"]
            M.cost = M["\\eta_Mission/Aircraft/SolarCells"]
            xmin_ = np.linspace(hmin, hmax, 100)
            tol = 0.01
            notpassing = True
            try:
                bst = autosweep_1d(M,
                                   tol,
                                   M["h_{batt}"], [hmin, hmax],
                                   solver="mosek")
                bsts = find_sols([bst])
                sols = np.hstack([b.sols for b in bsts])
                time += sum(np.unique([s["soltime"] for s in sols]))
                numsolves += bst.nsols
                if lat % 4 == 0:
                    l = ax.plot(xmin_,
                                bst.sample_at(xmin_)["cost"],
                                "k",
                                label="%d$^{\\circ}$ Lat" % lat)
                    lines.append(l[0])
                    etamax.append(max(bst.sample_at(xmin_)["cost"].magnitude))
                    midx.append(np.median(xmin_))
                elif lat % 2 == 0:
                    l = ax.plot(xmin_,
                                bst.sample_at(xmin_)["cost"],
                                "--",
                                c="0.5",
                                label="%d$^{\\circ}$ Lat" % lat)
            except RuntimeWarning:
                passing = False

    # ax.fill_between(xmin_, bst.sample_at(xmin_)["cost"], max(etamax),
    #                 edgecolor="r", lw=2, hatch="/", facecolor="None", zorder=100)
    print "%d solves in %.4f seconds" % (numsolves, time)
    labelLines(lines, align=False, xvals=midx, zorder=[10] * len(lines))
    # ax.text(425, 0.36, "Infeasible")
    ax.set_ylabel("Solar Cell Efficiency")
    ax.set_xlabel("Battery Specific Energy [Whr/kg]")
    ax.set_xlim([250, 500])
    ax.set_ylim([0.1, max(etamax)])
    ax.grid()
    return fig, ax