def twi_fits(latitude, day, gen=False):

    np.random.seed(0)

    ES, td, tn, p = get_Eirr(latitude, day)
    params = [latitude]

    P = p[0][p[1] > 0]
    t = p[1][p[1] > 0]
    f = np.array([np.trapz(P[:i+1])*(t[0]-t[i])/i for i in
                  range(1, len(P)-1)])
    ends = np.array([P[i]*(t[0]-t[i]) for i in range(1, len(P))][:-1])
    Eday = np.array([P[i]*t[i] for i in range(1, len(P))][:-1])
    C = ends - f
    B = Eday + f

    x = np.log(P[1:-15])
    y = np.log(2*C[:-14])
    cn, err = fit(x, y, 1, "MA")
    rm = err
    print("RMS error: %.4f" % rm)
    dftw = cn.get_fitdata()
    if not gen:
        fig1, ax1 = plt.subplots()
        fig2, ax2 = plt.subplots()
        yfit = cn.evaluate(x)
        ax1.plot(P[1:-15], 2*C[:-14], "o", c="g", markerfacecolor="none",
                 mew=1.5)
        ax1.plot(P[1:-15], np.exp(yfit), c="g",
                 label="%dth Latitude" % latitude, lw=2)
        ax1.set_xlabel("Minimum Power $(P/S)_{\mathrm{min}}$ [W/m$^2$]",
                       fontsize=19)
        ax1.set_ylabel("Twilight Energy $(E/S)_{\mathrm{twilight}}}$ " +
                       "[Whr/m$^2$]", fontsize=19)
        ax1.grid()
        params.append(cn[0].right.c)
        params.append(cn[0].right.exp[list(cn[0].varkeys["u_fit_(0,)"])[0]])

    x = np.log(P[1:-15])
    y = np.log(2*B[:-14])
    cn, err = fit(x, y, 1, "MA")
    rm = err
    print("RMS error: %.4f" % rm)
    dfday = cn.get_fitdata()
    if not gen:
        yfit = cn.evaluate(x)
        ax2.plot(P[1:-15], 2*B[:-14], "o", c="g", markerfacecolor="none",
                 mew=1.5)
        ax2.plot(P[1:-15], np.exp(yfit), c="g",
                 label="%dth Latitude" % latitude, lw=2)
        ax2.grid()
        ax2.set_xlabel("Minimum Necessary Power $(P/S)_{\mathrm{min}}$ " +
                       "[W/m$^2$]", fontsize=19)
        ax2.set_ylabel("Daytime Energry $(E/S)_{\mathrm{day}}$ [Whr/m$^2$]",
                       fontsize=19)
        fig1.savefig(path + "Cenergy.pdf")
        fig2.savefig(path + "Benergy.pdf")
    return dftw, dfday
示例#2
0
def make_fit(naca_range, re_range, M_range):
    #call the fit setup function
    x, y = fit_setup(naca_range, re_range, M_range)

    cstrt, rms = fit(x, y, 4, 'SMA')
    print "RMS"
    print rms
示例#3
0
def arctanfit():
    u = np.linspace(1e-15, 0.7, 100)
    w = np.arctan(u)

    x = np.log(u)
    y = np.log(w)

    cn, err = fit(x, y, 1, "MA")
    rm = err
    print "RMS error: %.4f" % rm

    yfit = cn.evaluate(x)
    df = cn.get_dataframe()
    fig, ax = plt.subplots()
    ax.plot(u, w, lw=2)
    ax.plot(u, np.exp(yfit), "--", lw=2)
    ax.set_xlim([0, 0.7])
    ax.grid()
    ax.set_xlabel("$V_{\\mathrm{gust}}/V$")
    ax.set_ylabel("$\\alpha_{\\mathrm{gust}}$")
    ax.legend([
        "$\\arctan{(V_{\\mathrm{gust}}/V)}$",
        "$0.905 (V_{\\mathrm{gust}}/V)^{0.961}$"
    ],
              loc=2,
              fontsize=15)
    return df, fig, ax
示例#4
0
def plot_BSFCtoPower(power_csv, bsfc_csv):
    # Fitting BSFC vs. Power
    df = pd.read_csv(power_csv)
    p = df['P']
    rpm = df["RPM"]
    f = interpolate.interp1d(rpm, p)
    df = pd.read_csv(bsfc_csv)
    df = df[(df["RPM"] > min(rpm)) & (df["RPM"] < max(rpm))]
    rpmnew = df["RPM"]
    u = f(rpmnew) / max(p)
    w = df['BSFC'] / min(df["BSFC"])
    x = np.array(log(u))
    y = np.array(log(w))
    Type = 'SMA'
    K = 2

    cstrt, error = fit(x, y, K, Type)
    print "RMS error = %.4f" % error
    yfit = cstrt.evaluate(x)
    dfc = cstrt.get_dataframe()

    fig, ax = plt.subplots()
    ax.plot(u * 100, w * min(df["BSFC"]), "o", mfc="None", ms=7, mew=1.5)
    ax.plot(u * 100, np.exp(yfit) * min(df["BSFC"]), linewidth=2)
    ax.set_xlabel("Percent Power")
    ax.set_ylabel("$BSFC$ [kg/kW/hr]")
    ax.legend(["RCV Engine Ltd. Data", "GP approximation"], fontsize=15)
    ax.set_ylim([0, 1])
    ax.set_xlim([0, 100])
    ax.grid()
    return dfc, fig, ax
def make_fit(thick_range, re_range, M_range):
    #call the fit setup function
    x, y = fit_setup(thick_range, re_range, M_range)

    cstrt, rms = fit(x, y, 3, 'SMA')
    print("RMS")
    print(rms)
示例#6
0
文件: t_ex6_3.py 项目: hoburg/gpfit
    def test_rms_error(self):
        np.random.seed(SEED)
        Vdd = random_sample(1000,) + 1
        Vth = 0.2*random_sample(1000,) + 0.2
        P = Vdd**2 + 30*Vdd*exp(-(Vth-0.06*Vdd)/0.039)
        u = vstack((Vdd, Vth))
        x = log(u)
        y = log(P)
        K = 4

        _, rms_error = fit(x, y, K, "MA")

        self.assertTrue(rms_error < 1e-2)
示例#7
0
def make_fits(day, latrange, month, gen=False, path="", plot=False):

    for l in latrange:
        print "Fitting for %d latitude" % l
        altitudestart = range(43000, 50500, 500)
        for j, a in enumerate(altitudestart):
            print "Trying Altitude Range: %d-72000" % a
            X, Y = fit_setup(altitude=(a, 72000), latitude=l, day=day)
            rms_best = 1
            cn_best = None
            df_best = None
            yfit = None
            for K in range(2, 6):
                for ftype in ["MA", "SMA"]:
                    try:
                        cns, err = fit(X, Y, K, ftype)
                        print "Lat %d; K = %d; ftype = %s; RMS = %.4f" % (
                            l, K, ftype, err)
                    except ValueError:
                        print "Fit failed: Lat %d; K = %d; ftype = %s;" % (
                            l, K, ftype)
                        err = 0.9
                    if err < rms_best:
                        df = cns.get_dataframe()
                        if "0.0" in df.values or "inf" in df.values:
                            continue
                        rms_best = err
                        cn_best, df_best = cns, df

            if rms_best == 1:
                print "Nothing worked... trying new altitude range"
                continue
            elif rms_best < 0.05:
                print "success"
                if gen:
                    df_best.to_csv("windfits" + month +
                                   "/windaltfit_lat%d.csv" % l,
                                   index=False)
                if plot:
                    yfit = cn_best.evaluate(X)
                break
            else:
                print "Lowest RMS: %.3f, trying new altitude range" % rms_best
        if plot:
            if not yfit is None:
                fig, ax = plot_fits(X, Y, yfit, l, plot=plot)
                fig.savefig(path + "windfits" + month + "/windfitl%d.pdf" % l,
                            bbox_inches="tight")
                plt.close()
示例#8
0
文件: plot_fit.py 项目: hoburg/gpfit
def plot_fit_1d(udata, wdata, K=1, fitclass='MA', plotspace='log'):
    "Finds and plots a fit (MA or SMA) for 1D data"

    cstrt, _ = fit(np.log(udata), np.log(wdata), K, fitclass)
    uu = np.linspace(min(udata), max(udata), 1000)

    if fitclass == 'MA':
        uvarkey, = cstrt[0].left.varkeys
        A = [c.left.exps[0][uvarkey] for c in cstrt]
        B = np.log([c.left.cs[0] for c in cstrt])
        WW = []
        for k in range(K):
            WW += [np.exp(B[k])*uu**A[k]]
        stringlist = print_MA(A, B, 1, K)


    if fitclass == 'SMA':
        wexps, = cstrt.left.exps
        alpha, = wexps.values()
        uvarkey, = cstrt.right.varkeys
        A = [d[uvarkey]/alpha for d in cstrt.right.exps]
        B = np.log(cstrt.right.cs) / alpha

        ww = 0
        for k in range(K):
            ww += (np.exp(alpha*B[k])*uu**(alpha*A[k]))
        WW = [ww**(1./alpha)]

        print_str = print_SMA(A, B, alpha, 1, K)
        stringlist = [''.join(print_str)]

    f, ax = plt.subplots()
    if plotspace == 'log':
        ax.loglog(udata, wdata, '+r')
        for ww in WW:
            ax.loglog(uu, ww)
    elif plotspace == 'linear':
        ax.plot(udata, wdata, '+r')
        for ww in WW:
            ax.plot(uu, ww)
    ax.set_xlabel('u')
    ax.legend(['Data'] + stringlist, loc='best')

    plt.show()
    return f, ax
示例#9
0
def plot_powerlaw(csv):
    df = pd.read_csv(csv)
    u = np.array(df["lbs"] / WEIGHT)
    w = np.array(df["hp"] / POWER)

    x = np.log(u)
    y = np.log(w)

    np.random.seed(0)
    cn, err = fit(x, y, 1, "MA")
    print "RMS error: %.4f" % err
    weight = np.linspace(min(df["lbs"]), max(df["lbs"]), 100)
    yfit = cn.evaluate(np.log(weight / WEIGHT))
    df = cn.get_dataframe()

    fig, ax = plt.subplots()
    ax.plot(u * WEIGHT, w * POWER, "o", mfc="None", mew=1.5)
    ax.plot(weight, np.exp(yfit) * POWER, lw=2)
    ax.set_xlabel("Engine Weight [lbs]")
    ax.set_ylabel("Maximum SL Shaft Power [hp]")
    ax.legend(["UND Engine Data", "Power Law Fit"], loc=2)
    ax.grid()
    return df, fig, ax
示例#10
0
def plot_RPMtoPower():
    # Fitting Power vs. RPM
    df = pd.read_csv('Dataset_Power_Kw.csv')
    RPM = df['RPM']
    RPM_max = np.amax(RPM)
    P = df['P']
    P_max = np.amax(P)
    y = np.array(log(P / P_max))
    x = np.array(log(RPM / RPM_max))
    Type = 'SMA'
    K = 1
    cstrt, rmserror = fit(x, y, K, Type)
    print "RMS error = %.4f" % rmserror
    yfit = cstrt.evaluate(x)

    fig, ax = plt.subplots()
    ax.plot(RPM, P, "o", markerfacecolor="None")
    ax.plot(RPM, np.exp(yfit) * P_max)
    ax.set_xlabel("$RPM$")
    ax.set_ylabel("Shaft Power [kW]")
    ax.legend(["Manufacture Data", "GP approximation"])
    ax.grid()
    return fig, ax
示例#11
0
def plot_BSFCtoRPM():
    # Fitting BSFC vs. RPM
    df = pd.read_csv('Dataset_BSFC_kgKwh.csv')
    RPM = df['RPM']
    RPMmax = np.amax(RPM)
    BSFC = df['BSFC']
    BSFCmin = np.amin(BSFC)
    x = np.array(log(RPM / RPMmax))
    y = np.array(log(BSFC / BSFCmin))
    Type = 'SMA'
    K = 2

    cstrt, rmserror = fit(x, y, K, Type)
    print "RMS error = %.4f" % rmserror
    yfit = cstrt.evaluate(x)

    fig, ax = plt.subplots()
    ax.plot(RPM, BSFC, "o", markerfacecolor="None")
    ax.plot(RPM, np.exp(yfit) * BSFCmin)
    ax.set_xlabel("$RPM$")
    ax.set_ylabel("$BSFC$ [lb/hp/hr]")
    ax.legend(["Manufacture Data", "GP approximation"])
    ax.grid()
    return fig, ax
示例#12
0
            ax.plot(re, cd, "o", mec=colors[i], mfc="none", mew=1.5)
            ax.plot(re, fi, c=colors[i],
                    label="NACA" + naca_range[nacaint == na][0], lw=2)
            i += 1
    ax.legend(fontsize=15)
    ax.set_xlabel("$Re$")
    ax.set_ylabel("$c_{d_p}$")
    ax.grid()
    return fig, ax

if __name__ == "__main__":
    Re = [20, 35] + range(50, 1050, 50)
    NACA = np.array(["0005", "0008", "0009", "0010", "0015"])
    X, Y = fit_setup(NACA, Re) # call fit(X, Y, 4, "SMA") to get fit
    np.random.seed(0)
    cn, err = fit(X, Y, 5, "MA")
    print "RMS error: %.5f" % err
    df = cn.get_dataframe()
    if GENERATE:
        path = os.path.dirname(TailAero.__file__)
        df.to_csv(path + os.sep + "tail_dragfit.csv", index=False)
    else:
        df.to_csv("tail_dragfit.csv", index=False)

    F, A = plot_fits(NACA, cn, X, Y)
    if len(sys.argv) > 1:
        path = sys.argv[1]
        F.savefig(path + "taildragpolar.eps", bbox_inches="tight")
    else:
        F.savefig("taildragpolar.eps", bbox_inches="tight")
示例#13
0
文件: ex63.py 项目: hoburg/gpfit
import unittest
from numpy import log, exp, log10, vstack
from gpfit.fit import fit
from numpy.random import random_sample

Vdd = random_sample(1000,) + 1
Vth = 0.2*random_sample(1000,) + 0.2
P = Vdd**2 + 30*Vdd*exp(-(Vth-0.06*Vdd)/0.039)
u = vstack((Vdd,Vth))
x = log(u)
y = log(P)
K = 4

cstrt, rmsErr = fit(x,y,K,"ISMA")
示例#14
0
import numpy as np
from gpfit.fit import fit

N = 100
A = np.linspace(0.5, 10, 100)
B = np.array([0.01, 0.05, 0.4])

x, y = np.meshgrid(A, B)
z = np.log(x/(x-y))

u1 = np.array(list(A)*len(B))
u2 = np.hstack([[v]*len(A) for v in B])
u = [u1, u2]
w = np.hstack(z)

x = np.log(u)
y = np.log(w)

cn, er = fit(x, y, 3, "SMA")
print "RMS error: %.5f" % er
df = cn.get_dataframe()
df.to_csv("logfit.csv", index=False)
示例#15
0
cd0 = 0.020
cd1 = -0.004
cd2 = 0.020
cd8 = 1.0
cl0 = 0.8

cl_space = np.linspace(0, 1.5, 2)
cd = np.array([])
for cl in cl_space:
    cd = np.append(
        cd, cd0 + cd1 * (cl - cl0) + cd2 * (cl - cl0)**2 + cd8 * (cl - cl0)**8)

print(cl_space, cd)

K = 1

x = log(cl_space)

y = log(cd)

print len(x)
print len(y)
# plt.plot(mdot,delta_p)
# # plt.show()
cMA, errorMA = fit(x, y, K, "MA")
# cSMA, errorSMA = fit(x, y, K, "SMA")
# # cISMA, errorISMA = fit(x, y, K, "ISMA")

# print "MA RMS Error: %.5g" % errorMA
# print "SMA RMS Error: %.5g" % errorSMA
# # print "ISMA RMS Error: %.5g" % errorISMA
示例#16
0
import pandas as pd
import numpy as np
from numpy import logspace, log, log10
import matplotlib.pyplot as plt
from gpfit.fit import fit


# Fitting for etah, effectiveness parameter
df = pd.read_csv('etahFit.csv')

Re = np.array(df['Re'])
etah = np.array(df['etah'])
Remax = np.amax(Re)
etahmax = np.amax(etah)

logRe = log(Re/Remax)
logetah = log(etah/etahmax)

K=1
Type = 'SMA'
cstrt, rms_error = fit(logRe,logetah,K,Type)

plt.plot(log(Re), log((0.799*(Re/Remax)**-0.0296)**10*etahmax))
plt.plot(log(Re),log(etah))
plt.show()
示例#17
0
# Fitting BSFC vs. Power
df = pd.read_csv('Dataset_Power_Kw.csv')
p = df['P']
rpm = df["RPM"]
f = interpolate.interp1d(rpm, p)
df = pd.read_csv('Dataset_BSFC_kgKwh.csv')
df = df[(df["RPM"] > min(rpm)) & (df["RPM"] < max(rpm))]
rpmnew = df["RPM"]
u = f(rpmnew) / max(p)
w = df['BSFC'] / min(df["BSFC"])
x = np.array(log(u))
y = np.array(log(w))
Type = 'SMA'
K = 2

cstrt, rmserror = fit(x, y, K, Type)
print "RMS error = %.4f" % rmserror
yfit = cstrt.evaluate(x)

fig, ax = plt.subplots()
ax.plot(u, w * min(df["BSFC"]), "o", mfc="None", ms=7, mew=1.5)
ax.plot(u, np.exp(yfit) * min(df["BSFC"]), linewidth=2)
ax.set_xlabel("Percent Power")
ax.set_ylabel("$BSFC$ [kg/kW/hr]")
ax.legend(["RCV Engine Ltd. Data", "GP approximation"], fontsize=15)
ax.set_xlim([0, 1])
ax.set_ylim([0, 1])
ax.grid()
fig.savefig("powertobsfcfit.pdf", bbox_inches="tight")

# Fitting BSFC vs. RPM
示例#18
0
def return_fit(cl, re):
    "polar fit for the naca652 airfoil, K=3, SMA, RMS=0.0714"
    cd = (2.44337e-49 * (cl)**25.264 * (re)**2.09928
          + 1.15012e+56 * (cl)**92.7062 * (re)**-14.1311
          + 1.56299e-10 * (cl)**0.0617453 * (re)**-5.1536)**(1./18.3487)
    return cd

def plot_fits(re):
    "plot fit compared to data"
    colors = ["k", "m", "b", "g", "y"]
    assert len(re) == len(colors)
    fig, ax = plt.subplots()
    cls = np.linspace(0.2, 1.3, 20)
    for r, col in zip(re, colors):
        dataf = text_to_df("naca652.ncrit09.Re%dk.pol" % r)
        ax.plot(dataf["CL"], dataf["CD"], "o", c=col)
        cd = return_fit(cls, r*1000.)
        ax.plot(cls, cd, c=col, label="Re = %dk" % r)
    ax.legend(loc=2)
    ax.set_xlabel("$C_L$")
    ax.set_ylabel("$C_D$")
    ax.grid()
    return fig, ax

if __name__ == "__main__":
    Re = range(1000, 4500, 500)
    X, Y = fit_setup(Re)
    Cn, Rm = fit(X, Y, 3, "SMA")
    F, A = plot_fits([1500, 2000, 2500, 3000, 3500])
    F.savefig("naca652polarfit1.pdf")
示例#19
0
import unittest
from numpy import log, exp, log10, vstack
from numpy import arccos, arange
from gpfit.fit import fit
from numpy.random import random_sample
i = arange(0.0001, 3, .001)
j = arccos(exp(-i))
x = log(i)
y = log(j)
K = 1

cstrt, rmsErr = fit(x, y, K, "SMA")
print rmsErr
示例#20
0
def fit_friction_factor_data(x, y, k, method):
    c, error = fit(x, y, k, method)
    return c, error
        if roundre in re:
            ax.plot(cl, cd, "o", mec=colors[i], mfc="none", mew=1.5)
            ax.plot(cl, fi, c=colors[i], label="Re = %dk" % roundre, lw=2)
            i += 1
    ax.set_xlabel("$C_L$")
    ax.set_ylabel("$c_{d_p}$")
    ax.legend(loc=2)
    ax.grid()
    return fig, ax


if __name__ == "__main__":
    Re = np.arange(150, 750, 50)
    X, Y = fit_setup(Re)  # call fit(X, Y, 4, "SMA") to get fit
    np.random.seed(0)
    cn, err = fit(X, Y, 4, "SMA")
    print "RMS error: %.5f" % err
    df = cn.get_dataframe()
    if GENERATE:
        path = os.path.dirname(inspect.getfile(Wing))
        df.to_csv(path + os.sep + "jho_fitdata.csv", index=False)
    else:
        df.to_csv("jho_fitdata.csv", index=False)

    # replot = np.array([150, 200, 300, 350, 400])
    replot = np.array([300, 350, 400, 450, 500])
    F, A = plot_fits(replot, cn, X, Y)
    if len(sys.argv) > 1:
        path = sys.argv[1]
        F.savefig(path + "jho1polarfit1.eps", bbox_inches="tight")
    else:
示例#22
0
        if roundre in re:
            ax.plot(cl, cd, "o", mec=colors[i], mfc="none", mew=1.5)
            ax.plot(cl, fi, c=colors[i], label="Re = %dk" % roundre, lw=2)
            i += 1
    ax.set_xlabel("$C_L$")
    ax.set_ylabel("$c_{d_p}$")
    ax.legend(loc=2)
    ax.grid()
    return fig, ax


if __name__ == "__main__":
    Re = np.array([50, 75, 125, 150, 200, 300, 400, 500, 600, 700])
    X, Y = fit_setup(Re)  # call fit(X, Y, 4, "SMA") to get fit
    np.random.seed(0)
    cn, err = fit(X, Y, 3, "SMA")
    print "RMS error: %.5f" % err
    df = cn.get_dataframe()
    if GENERATE:
        path = os.path.dirname(inspect.getfile(ActuatorProp))
        df.to_csv(path + os.sep + "dae51_fitdata.csv", index=False)
    else:
        df.to_csv("dae51fitdata.csv", index=False)

    # replot = np.array([150, 200, 300, 350, 400])
    replot = np.array([300, 350, 400, 450, 500])
    F, A = plot_fits(replot, cn, X, Y)
    if len(sys.argv) > 1:
        path = sys.argv[1]
        F.savefig(path + "dae51polarfit1.eps", bbox_inches="tight")
    else:
示例#23
0
from gpfit.fit import fit
from numpy import logspace, log, log10

u = logspace(0, log10(3), 101)
w = (u**2 + 3) / (u + 1)**2
x = log(u)
y = log(w)
K = 3

cMA, errorMA = fit(x, y, K, "MA")
cSMA, errorSMA = fit(x, y, K, "SMA")
cISMA, errorISMA = fit(x, y, K, "ISMA")

print "MA RMS Error: ", errorMA
print "SMA RMS Error: ", errorSMA
print "ISMA RMS Error: ", errorISMA
示例#24
0
from gpfit.fit import fit
from numpy import logspace, log, log10, random
import numpy as np
import matplotlib.pyplot as plt
# fixed initial guess for fitting
# random.seed(33404)

mdot = np.array([0.001411400768, 0.04734265813, 0.1014552215])
delta_p_inv = np.array([1121.643023, 908.6306982, 29.95485818])
K = 1

x = log(mdot)
y = log(delta_p_inv)

# plt.plot(mdot,delta_p)
# plt.show()
cMA, errorMA = fit(x, y, K, "MA")
cSMA, errorSMA = fit(x, y, K, "SMA")
# cISMA, errorISMA = fit(x, y, K, "ISMA")

print "MA RMS Error: %.5g" % errorMA
print "SMA RMS Error: %.5g" % errorSMA
# print "ISMA RMS Error: %.5g" % errorISMA
示例#25
0
文件: t_ex6_1.py 项目: tonystao/gpfit
from gpfit.fit import fit
from numpy import logspace, log, log10

n = 501
u = logspace(0,log10(3),n)
w = (u**2+3)/(u+1)**2
x = log(u)
y = log(w)
K = 3
Type = "ISMA"

cstrt, rms_error = fit(x,y,K,Type)