Пример #1
0
def make_colormap(colors):
    """
    Define a new color map based on values specified in the dictionary
    colors, where colors[z] is the color that value z should be mapped to,
    with linear interpolation between the given values of z.

    The z values (dictionary keys) are real numbers and the values
    colors[z] can be either an RGB list, e.g. [1,0,0] for red, or an
    html hex string, e.g. "#ff0000" for red.
    """

    from matplotlib.colors import LinearSegmentedColormap, ColorConverter
    from numpy import sort

    z = sort(colors.keys())
    n = len(z)
    z1 = min(z)
    zn = max(z)
    x0 = (z - z1) / ((zn - z1)*1.)

    CC = ColorConverter()
    R = []
    G = []
    B = []
    for i in arange(n):
        #i'th color at level z[i]:
        Ci = colors[z[i]]
        if type(Ci) == str:
            # a hex string of form '#ff0000' for example (for red)
            RGB = CC.to_rgb(Ci)
        else:
            # assume it's an RGB triple already:
            RGB = Ci
        R.append(RGB[0])
        G.append(RGB[1])
        B.append(RGB[2])

    cmap_dict = {}
    cmap_dict['red'] = [(x0[i],R[i],R[i]) for i in arange(len(R))]
    cmap_dict['green'] = [(x0[i],G[i],G[i]) for i in arange(len(G))]
    cmap_dict['blue'] = [(x0[i],B[i],B[i]) for i in arange(len(B))]
    mymap = LinearSegmentedColormap('mymap',cmap_dict)
    return mymap
Пример #2
0
def make_colormap(colors):
    """
    Define a new color map based on values specified in the dictionary
    colors, where colors[z] is the color that value z should be mapped to,
    with linear interpolation between the given values of z.

    The z values (dictionary keys) are real numbers and the values
    colors[z] can be either an RGB list, e.g. [1,0,0] for red, or an
    html hex string, e.g. "#ff0000" for red.
    """

    from matplotlib.colors import LinearSegmentedColormap, ColorConverter

    z = np.sort(colors.keys())
    n = len(z)
    z1 = min(z)
    zn = max(z)
    x0 = (z - z1) / ((zn - z1) * 1.)

    CC = ColorConverter()
    R = []
    G = []
    B = []
    for i in xrange(n):
        # i'th color at level z[i]:
        Ci = colors[z[i]]
        if isinstance(Ci, str):
            # a hex string of form '#ff0000' for example (for red)
            RGB = CC.to_rgb(Ci)
        else:
            # assume it's an RGB triple already:
            RGB = Ci
        R.append(RGB[0])
        G.append(RGB[1])
        B.append(RGB[2])

    cmap_dict = {}
    cmap_dict['red'] = [(x0[i], R[i], R[i]) for i in xrange(len(R))]
    cmap_dict['green'] = [(x0[i], G[i], G[i]) for i in xrange(len(G))]
    cmap_dict['blue'] = [(x0[i], B[i], B[i]) for i in xrange(len(B))]
    mymap = LinearSegmentedColormap('mymap', cmap_dict)
    return mymap
Пример #3
0
def make_colormap(colors):
    """
    Define a new color map based on values specified in the dictionary
    colors, where colors[z] is the color that value z should be mapped to,
    with linear interpolation between the given values of z.

    The z values (dictionary keys) are real numbers and the values
    colors[z] can be either an RGB list, e.g. [1,0,0] for red, or an
    html hex string, e.g. "#ff0000" for red.
    """
    from matplotlib import colors as mc

    z = np.sort(list(colors.keys()))
    min_z = min(z)
    x0 = (z - min_z) / (max(z) - min_z)
    rgb = [mc.to_rgb(colors[zi]) for zi in z]
    cmap_dict = dict(
        red=[(x0[i], c[0], c[0]) for i, c in enumerate(rgb)],
        green=[(x0[i], c[1], c[1]) for i, c in enumerate(rgb)],
        blue=[(x0[i], c[2], c[2]) for i, c in enumerate(rgb)],
    )
    mymap = mc.LinearSegmentedColormap("mymap", cmap_dict)
    return mymap
Пример #4
0
def analysis(dataFrame_agg_t, xdata_new):
    dataFrame_agg = dataFrame_agg_t[dataFrame_agg_t["Set Type"] == "Measurement"]

    newWalls = ["Wall Position " + str(ii) for ii in np.round(xdata_new, 2)]

    print(dataFrame_agg.columns.tolist())
    dataFrame_agg["HTC Mixed Predicted"] = np.divide(np.multiply(dataFrame_agg["Nu Mixed"], dataFrame_agg["k nf"]),
                                                     dataFrame_agg["D h"])
    dataFrame_agg["Nu laminar"] = np.multiply(np.power(dataFrame_agg["Re"], .6) * .128, dataFrame_agg["Pr"] ** .4)
    dataFrame_agg["HTC Laminar Predicted"] = np.divide(np.multiply(dataFrame_agg["Nu laminar"], dataFrame_agg["k nf"]),
                                                       dataFrame_agg["D h"])
    uniqueFluids = pd.unique(dataFrame_agg["Fluid"])
    print(uniqueFluids)

    # sns.scatterplot('Re', 'HTC', data=dataFrame_agg, hue='Fluid')
    if 1 == 1:
        plt.figure()

    if 1 == 1:
        fig, (ax1) = plt.subplots(1, 1, gridspec_kw={'height_ratios': [3]})
        fig11b, (ax1b) = plt.subplots(1, 1, gridspec_kw={'height_ratios': [3]})
        fig11, (ax11) = plt.subplots(1, 1, gridspec_kw={'height_ratios': [3]})
        import matplotlib.colors
        colors = {}
        for iic, ic in enumerate(uniqueFluids):
            colors[ic] = plt.cm.tab10(iic)
        popt_ReHTC_s = []
        laminaryvals = []
        for i in range(len(uniqueFluids)):
            dataFrame_agg_f = dataFrame_agg[dataFrame_agg["Fluid"] == uniqueFluids[i]]

            # interpolate HTC vs Reynolds
            def funcHTC(x, a, b):
                return np.exp(a * np.log(x) + b)

            popt_ReHTC, pcov = curve_fit(funcHTC, dataFrame_agg_f['Re'], dataFrame_agg_f['HTC'],
                                         # bounds=([0,-np.inf], [np.inf,np.inf])
                                         )
            popt_ReHTC_s.append(popt_ReHTC)
            ax1.errorbar(dataFrame_agg_f['Re'], dataFrame_agg_f['HTC'], xerr=0,
                         yerr=dataFrame_agg_f['HTC err'], ls='none', c=colors[uniqueFluids[i]], alpha=1, lw=.5,
                         label=uniqueFluids[i])
            ax1b.scatter(dataFrame_agg_f['Re'], dataFrame_agg_f['Nu'],  c=colors[uniqueFluids[i]], alpha=1,
                         label=uniqueFluids[i])

            xrange_re = np.power(10,np.linspace(0, 5, 100))
            # ax1.plot(dataFrame_agg_f['Re'].sort_values(), (
            #             dataFrame_agg_f['Re'] ** .6 * dataFrame_agg_f['Pr'] ** .4 * .128 * dataFrame_agg_f['k nf'] *
            #             dataFrame_agg_f['D h'] ** -1).sort_values()
            #          , c=colors[uniqueFluids[i]], linestyle="--", label=uniqueFluids[i] + " Laminar")

            yvals = xrange_re ** .6 * np.mean(dataFrame_agg_f['Pr']) ** .4 * .128 * np.mean(
                dataFrame_agg_f['k nf']) * np.mean(dataFrame_agg_f['D h']) ** -1

            laminaryvals.append(yvals)
            ax1.plot(xrange_re, yvals, c=colors[uniqueFluids[i]], linestyle="--", label=uniqueFluids[i] + " Laminar Hewitt")
            ax1b.plot(xrange_re, xrange_re ** .6 * np.mean(dataFrame_agg_f['Pr']) ** .4 * .128, c=colors[uniqueFluids[i]], linestyle="--", label=uniqueFluids[i] + " Laminar Hewitt")

            # Perkins et al from Shah text for 4 sided heated square channel in thermally developing hydrodynamically
            # developed flow
            Prandtl = np.mean(dataFrame_agg_f['Pr'])
            print('------------ ', np.mean(dataFrame_agg_f['Pr']))
            xrange_xstar = ((4 / .651) * xrange_re ** -1 * Prandtl ** -1)
            yvals_Perkins = np.divide(1, .277 - .152 *
                                      np.power(2.71828, -38.6 * xrange_xstar))
            ax1.plot(xrange_re, yvals_Perkins* np.mean(
                dataFrame_agg_f['k nf']) * np.mean(dataFrame_agg_f['D h']) ** -1, c=colors[uniqueFluids[i]], linestyle="-.",
                     label=uniqueFluids[i] + " Laminar Perkins")


            ax1b.plot(xrange_re,yvals_Perkins, c=colors[uniqueFluids[i]], linestyle="-.",
                     label=uniqueFluids[i] + " Laminar Perkins")

            yvals_Churchill = np.power(1+np.power(220/np.pi*xrange_xstar,-10/9),3/10)*5.365-1
            ax1.plot(xrange_re, yvals_Churchill * np.mean(
                dataFrame_agg_f['k nf']) * np.mean(dataFrame_agg_f['D h']) ** -1, c=colors[uniqueFluids[i]],
                     linestyle="-.",
                     label=uniqueFluids[i] + " Laminar Churchill")
            ax1b.plot(xrange_re,yvals_Churchill, c=colors[uniqueFluids[i]], linestyle=":",
                     label=uniqueFluids[i] + " Laminar Churchill") # churchill oand Ozoe from Shah p128 for thermally developing hydrodynamically developed specified heat flux in cirucular tube
            # ax1.plot(dataFrame_agg_f['Re'].sort_values(), dataFrame_agg_f['HTC Mixed Predicted'].sort_values(),
            # c=colors[uniqueFluids[i]],
            #          linestyle=":", label=uniqueFluids[i] + " Mixed")

            print('_____________________ FLUID HTC vs Re fit ____ ', uniqueFluids[i])
            print(popt_ReHTC)
            ax1.plot(xrange_re, funcHTC(xrange_re, *popt_ReHTC), c=colors[uniqueFluids[i]],
                     label=uniqueFluids[i] + ' Fit: a=%5.3f, b=%5.3f' % tuple(popt_ReHTC))

            ax1.set_ylim([100, 10000])

            targetReynolds = 200
            print()
            interpHTC = funcHTC(targetReynolds, *popt_ReHTC)
            print(f"HTC at ", targetReynolds, ": ", interpHTC)

        ax1.set_xlabel('Re')
        ax1.set_ylabel('HTC $[W/m^2K]$')
        ax1.set_title("HTC Estimates")
        ax1.set_xscale('log')
        ax1.set_yscale('log')
        ax1b.set_xlabel('Re')
        ax1b.set_ylabel('Nu')
        ax1b.set_title("Nu")
        ax1b.set_xscale('log')
        ax1b.set_yscale('log')
        fig11b.subplots_adjust(left=.15, bottom=.1, right=.7, top=.95, wspace=0, hspace=0)
        fig11b.legend(loc='center right', borderaxespad=0.2, fontsize=8, frameon=False)
        fig.subplots_adjust(left=.15, bottom=.1, right=.7, top=.95, wspace=0, hspace=0)
        fig.legend(loc='center right', borderaxespad=0.2, fontsize=8, frameon=False)

        idx_compare = 1
        for i in range(len(uniqueFluids)):
            yvals = np.divide(funcHTC(xrange_re, *popt_ReHTC_s[i]), funcHTC(xrange_re, *popt_ReHTC_s[idx_compare]))
            ax11.plot(xrange_re, yvals, c=colors[uniqueFluids[i]],
                      label=uniqueFluids[i] + " Meas. Data Fit")
            ax11.plot(xrange_re, np.divide(laminaryvals[i], laminaryvals[idx_compare]), c=colors[uniqueFluids[i]],
                      label=uniqueFluids[i] + " Laminar Meas. Prop.", linestyle='--')

        ax11.set_xlabel('Re')
        ax11.set_ylabel('Normalized HTC')
        ax11.set_title("HTC Estimates Normalized to Basefluid")
        plt.xscale('log')
        # plt.yscale('log')
        ax11.legend()
        fig11.savefig(pjoin(dir_path,"06_HTC_Re_fits.png"))
        fig.savefig(pjoin(dir_path,"06_HTC_Re.png"))
        fig11b.savefig(pjoin(dir_path,"06_Nu_Re.png"))

    if 1 == 1:
        fig4, (ax4) = plt.subplots(1, 1, gridspec_kw={'height_ratios': [3]})
        dtemp_t = dataFrame_agg_t[dataFrame_agg_t["Wall Position"] == newWalls[-1]]
        temp_names = ['T1 PreHeat', 'T3 TS In', 'T2 TS Out', 'T4 HX In', 'T5 HX Out']
        idvars = ["Fluid", "Mass Flow Rate (kg/s)", "Set Type", 'T wall Midpoint', "HTC", "HTC knownQ", "Re",
                  "$\dot{Q} corrected$",
                  "Pumping Power (DP)[W]", "Pumping Power (corr)[W]"]

        dtemp_t = pd.melt(dtemp_t, id_vars=idvars, var_name="Temp Type", value_vars=temp_names,
                          value_name="Temp [°C]")
        # 'T1 PreHeat', 'T2 TS Out',
        #        'T3 TS In', 'T2B TS Out', 'T4 HX In', 'T5 HX Out'
        sns.violinplot(x="Temp [°C]", y="Temp Type", hue="Set Type", data=dtemp_t, inner=None, color=".8", height=6,
                       split=True)

        sns.stripplot(x="Temp [°C]", y="Temp Type", hue="Fluid", data=dtemp_t, dodge=True)
        plt.title('Loop Temperatures')
        fig4.savefig(pjoin(dir_path,"06_loopTemps.png"))

    if 1 == 1:
        fig2, (ax2) = plt.subplots(1, 1, gridspec_kw={'height_ratios': [3]})
        dtemp = dataFrame_agg_t[dataFrame_agg_t["Wall Position"] == newWalls[-1]]
        # dataFrame_i["mu_nf"]
        dtemp["Pressure Drop Correrlation"] = dtemp["Pumping Power (corr)[W]"] / np.max(
            dataFrame_agg["Pumping Power (corr)[W]"])
        dtemp["Measured Pressure Drop"] = dtemp["Pumping Power (DP)[W]"] / np.max(dtemp["Pumping Power (DP)[W]"])
        dtemp = pd.melt(dtemp, id_vars=["Fluid", "Mass Flow Rate (kg/s)", "Set Type", 'T wall Midpoint'],
                        var_name="Pumping Power Estimate",
                        value_vars=["Pressure Drop Correrlation", "Measured Pressure Drop"],
                        value_name="Pumping Power [W]")
        sns.scatterplot('T wall Midpoint', "Pumping Power [W]",
                        data=dtemp, hue='Fluid', style="Pumping Power Estimate")

        # plt.xscale('log')
        plt.yscale('log')
        plt.title("Pumping Power Estimate Comparison")
        fig2.savefig(pjoin(dir_path,"06_pumpingPowers2.png"))

    if 1 == 1:
        height = 1  # m

        fig5, (ax5) = plt.subplots(1, 1, gridspec_kw={'height_ratios': [3]})
        dtemp = dataFrame_agg[dataFrame_agg["Wall Position"] == newWalls[-1]]
        dtemp["$\Delta P_{fric}$"] = dtemp["Pumping Power (corr)[W]"] * 10 / dtemp["Mass Flow Rate (kg/s)"] * dtemp[
            "rho nf"]
        # 'T1 PreHeat', 'T2 TS ut', 'T3 TS In',
        dtemp["$\Delta P_{grav}$"] = -height * 9.81 * np.multiply(dtemp["T1 PreHeat"] - dtemp["T2 TS Out"],
                                                                  np.multiply(dtemp["CTE"], dtemp["rho nf"]))
        dtemp["$\Delta P_{measure}$"] = dtemp["DPTS [inH20]"] * 249.09
        press_names = ['$\Delta P_{fric}$', '$\Delta P_{grav}$', '$\Delta P_{measure}$']
        dtemp1 = pd.melt(dtemp, id_vars=idvars, var_name="Pressure Type",
                         value_vars=press_names,
                         value_name="Pressure [Pa]")
        sns.violinplot(x="Pressure [Pa]", y="Pressure Type", data=dtemp1, inner=None, color=".8", height=6)

        sns.stripplot(x="Pressure [Pa]", y="Pressure Type", hue="Fluid", data=dtemp1, dodge=True)

        plt.title('Pressure Drop Estimates')
        fig5.savefig(pjoin(dir_path,"06_delPs.png"))

        fig6, (ax6) = plt.subplots(1, 1, gridspec_kw={'height_ratios': [3]})
        fig6.subplots_adjust(bottom=.2)
        dtemp["$\Delta P_{grav} / \Delta P_{measure}$"] = np.divide(dtemp["$\Delta P_{grav}$"],
                                                                    dtemp['$\Delta P_{measure}$'])
        sns.scatterplot('T wall Midpoint', "$\Delta P_{grav} / \Delta P_{measure}$", hue="Fluid", data=dtemp, ax=ax6)
        plt.yscale('log')
        plt.title('Calculated Pressure Drop Components')
        secax1 = ax6.secondary_xaxis('bottom', functions=(forward, inverse))
        secax1.set_frame_on(True)
        secax1.patch.set_visible(False)
        secax1.xaxis.set_label_position('bottom')
        secax1.spines['bottom'].set_position(('outward', 40))
        secax1.set_xlabel('HTC $[W/m^2K]$')
        fig6.savefig(pjoin(dir_path,"06_delPs_ratioTwall.png"))

        fig7, (ax7) = plt.subplots(1, 1, gridspec_kw={'height_ratios': [3]})
        fig7.subplots_adjust(bottom=.2)
        dtemp["$\Delta T_{outlet-inlet}$"] = dtemp['T2 TS Out'] - dtemp['T3 TS In']
        sns.scatterplot('T wall Midpoint', "$\Delta T_{outlet-inlet}$", hue="Fluid", data=dtemp, ax=ax7)
        plt.yscale('log')
        plt.title('$\Delta T_{outlet-inlet}$')
        secax1 = ax7.secondary_xaxis('bottom', functions=(forward, inverse))
        secax1.set_frame_on(True)
        secax1.patch.set_visible(False)
        secax1.xaxis.set_label_position('bottom')
        secax1.spines['bottom'].set_position(('outward', 40))
        secax1.set_xlabel('HTC $[W/m^2K]$')
        fig7.savefig(pjoin(dir_path,"06_delTs_Twall.png"))

        plt.figure()
        sns.scatterplot('Re', "$\Delta P_{grav} / \Delta P_{measure}$", hue="Fluid", data=dtemp)
        plt.yscale('log')
        plt.xscale('log')
        plt.title('Calculated Pressure Drop Components')
        plt.savefig(pjoin(dir_path,"06_delPs_ratioRe.png"))

        plt.figure()
        sns.scatterplot('HTC knownQ', "$\Delta P_{grav} / \Delta P_{measure}$", hue="Fluid", data=dtemp)
        plt.yscale('log')
        # plt.xscale('log')
        plt.xlabel("HTC $[W/m^2K]$")
        plt.title('Calculated Pressure Drop Components')
        plt.savefig(pjoin(dir_path,"06_delPs_ratioHTC.png"))

        plt.figure()
        sns.scatterplot('Re', "$\dot{Q} corrected$", hue="Fluid", data=dtemp)
        # plt.yscale('log')
        plt.xscale('log')
        plt.axhline(y=5, c='r', linestyle='--')
        plt.title('Bulk $\dot{Q}$ [W]')
        plt.ylabel('$\dot{Q}$ [W]')
        plt.savefig(pjoin(dir_path,"06_QCorrectedRe.png"))

        plt.figure()
        sns.scatterplot('Pumping Power (DP)[W]', "Pumping Power (corr)[W]", hue="Fluid", data=dtemp)
        # plt.yscale('log')
        # plt.xscale('log')
        plt.title('')

        plt.savefig(pjoin(dir_path,"06_pumpingpowerEstimates.png"))

    if 1 == 1:
        fig3 = plt.figure()
        import matplotlib.colors
        colors = {}
        for iic, ic in enumerate(uniqueFluids):
            colors[ic] = plt.cm.tab10(iic)

        labels = list(colors.keys())
        ax = fig3.gca(projection='3d')
        for i in range(len(uniqueFluids)):
            dataFrame_agg_f = dataFrame_agg[dataFrame_agg["Fluid"] == uniqueFluids[i]]
            idvars = dataFrame_agg_f.columns
            idvars = [f for f in idvars if not f in newWalls]

            ax.scatter3D(dataFrame_agg_f['Wall Position [cm]'], dataFrame_agg_f['Pumping Power (DP)[W]'],
                         dataFrame_agg_f['HTC Local'],
                         color=colors[uniqueFluids[i]], linewidth=0.01, label=uniqueFluids[i])

            ax.legend()

        ax.set_xlabel('Wall Position [cm]')
        ax.set_ylabel('Pumping Power [W]')
        ax.set_zlabel('HTC Local $[W/m^2K]$')

    return
Пример #5
0
def analysis(name="median", idx_ref=1):
    sets = [datapaths1, datapaths2, datapaths3, datapaths4, datapaths5]
    compiled_pumpingPower3Points = []
    fluids = []

    pumping_power_est_type = "Pumping Power (DP)[W]"
    if 1 == 1:  # plot pumping power versus wall temperature
        colors_a = plt.cm.tab10(range(len(sets)))
        print(colors_a)
        # colors_a = ['r', 'b', 'g','k','orange']
        linestyle = {"Midpoint": '-', "Outlet": "--", "Inlet": "-.-"}

        fig1, (ax1) = plt.subplots(1, 1, gridspec_kw={'height_ratios': [3]})

        fig8, (ax8) = plt.subplots(1, 1, gridspec_kw={'height_ratios': [3]})
        fig6, (ax6, ax7) = plt.subplots(1,
                                        2,
                                        figsize=(12, 4),
                                        gridspec_kw={'width_ratios': [3, 3]})
        fig6.subplots_adjust(left=.08,
                             bottom=.2,
                             right=.92,
                             top=.88,
                             wspace=0,
                             hspace=0)
        fig4.subplots_adjust(bottom=.2)
        fig1.subplots_adjust(bottom=.2)

        fig5, ax5 = plt.subplots(1,
                                 1,
                                 gridspec_kw={'height_ratios': [3]},
                                 figsize=(5, 5))
        fig5.subplots_adjust(left=.08,
                             bottom=.2,
                             right=.92,
                             top=.88,
                             wspace=0,
                             hspace=0)

        fig2, (ax2_1, ax2_2,
               ax2_3) = plt.subplots(1,
                                     3,
                                     figsize=(12, 4),
                                     gridspec_kw={'width_ratios': [3, 3, 3]})
        fig2.subplots_adjust(left=.08,
                             bottom=.2,
                             right=.92,
                             top=.88,
                             wspace=0,
                             hspace=0)

        sets_len = [len(f) for f in sets]
        print(sets_len)
        fig3, (ax3_0) = plt.subplots(1,
                                     len(sets),
                                     figsize=(12, 4),
                                     gridspec_kw={'width_ratios': sets_len})
        fig3.subplots_adjust(left=.08, bottom=.2, right=.92, top=.88)
        fig3B, (ax3B) = plt.subplots(1,
                                     1,
                                     figsize=(12, 4),
                                     gridspec_kw={'width_ratios': [1]})
        fig3B.subplots_adjust(left=.08, bottom=.2, right=.92, top=.88)
        c = []
        interpolatePumpingPower_agg = []
        interpolatePumpingPowerErr_agg = []
        fluids_agg = []

        popt_fluids = []
        for iset, datapaths in enumerate(sets):
            dataSamples = len(sets)
            fluid_T_wall_agg = []
            fluid_HTC_wall_agg = []
            fluid_HTC_wallErr_agg = []
            fluid_Re_agg = []
            fluid_volFlow_agg = []
            fluid_pumpPower_agg = []
            fluid_pumpPowerErr_agg = []
            fluid_heatingAggNoSaph = []
            fluid_Richard = []
            fluid_heatingAggSaph = []
            dates = []
            pump_powerMidpoint = []
            pump_powerMidpointErr = []
            fluid_HTC_wall = []
            for i, datapath in enumerate(datapaths):
                print(datapath)
                test_name = datapath.split('/Lubrizol Loop/')[1]
                date = datapath.split('/Lubrizol Loop/')[1].split('_')[0]
                dates.append(date)
                fluid_name = datapath.split('_')[1]
                fluid_power = datapath.split('_')[2]
                fluids.append(fluid_name + ' ' + str(i))
                print(fluid_name)
                pumpingPower3Points = np.load(
                    pjoin(datapath, "pumpingPower3Points.npy"))
                pumpingPower3Points_err = np.load(
                    pjoin(datapath, "pumpingPower3Points_err.npy"))
                data_measurement = pd.read_pickle(
                    pjoin(datapath, 'd_meas.pkl_a03'))
                data_calibration_flow = pd.read_pickle(
                    pjoin(datapath, 'd_cal_flow_a03.pkl'))
                positions_wall = np.load(
                    pjoin(datapath, 'positions_wall.pkl.npy'))

                colnames = [f + "HTC" for f in positions_wall[:, 0]]

                # wall position, Re, HTC or Nu
                for i, mass_flow_rate in enumerate(data_measurement["Re"]):
                    d_local = data_measurement[
                        data_measurement["Mass Flow Rate (kg/s)"] ==
                        mass_flow_rate]
                    np.asarray(list(positions_wall[:, 1][::-1])).astype(
                        float), d_local[colnames].values.ravel()

                fluid_HTC_wall = []
                fluid_T_wall_agg.append(data_measurement["T_wall " +
                                                         name].values)
                fluid_HTC_wall_agg.append(data_measurement["HTC " +
                                                           name].values)
                fluid_HTC_wallErr_agg.append(
                    data_measurement["HTC_err"].values)
                fluid_Re_agg.append(data_measurement["Re"].values)
                fluid_heatingAggNoSaph.append(
                    data_measurement["PreHeat Power"].values)
                fluid_Richard.append(data_measurement["Ri"].values)
                fluid_heatingAggSaph.append(
                    data_calibration_flow["PreHeat Power"].values)
                fluid_pumpPower_agg.append(
                    data_measurement[pumping_power_est_type].values)
                fluid_volFlow_agg.append(
                    data_measurement["Volume Flow Rate (L/min)"].values)
                fluid_pumpPowerErr_agg.append(
                    data_measurement['Pumping Power (DP)[W]' + '_err'].values)
                compiled_pumpingPower3Points.append([
                    date, fluid_name,
                    float(pumpingPower3Points[0]),
                    float(pumpingPower3Points[1]),
                    float(pumpingPower3Points[2]),
                    float(pumpingPower3Points_err[1])
                ])
                pump_powerMidpoint.append(pumpingPower3Points[1])
                pump_powerMidpointErr.append(pumpingPower3Points_err[1])
            dates = np.hstack(dates)
            pump_powerMidpoint = np.hstack(pump_powerMidpoint)
            fluid_heatingAggNoSaph = np.hstack(fluid_heatingAggNoSaph)
            fluid_Richard = np.hstack(fluid_Richard)
            fluid_heatingAggSaph = np.hstack(fluid_heatingAggSaph)
            pump_powerMidpointErr = np.hstack(pump_powerMidpointErr)
            fluid_T_wall_agg = np.hstack(fluid_T_wall_agg)
            fluid_HTC_wall_agg = np.hstack(fluid_HTC_wall_agg)
            fluid_HTC_wallErr_agg = np.hstack(fluid_HTC_wallErr_agg)
            fluid_Re_agg = np.hstack(fluid_Re_agg)
            fluid_volFlow_agg = np.hstack(fluid_pumpPower_agg)
            fluid_pumpPower_agg = np.hstack(fluid_pumpPower_agg)
            fluid_pumpPowerErr_agg = np.hstack(fluid_pumpPowerErr_agg)

            # plot for looking at the midpoint FOM for each data capture.
            if 1 == 1 and name == "Midpoint":
                x_pos = np.arange(len(dates))

                FOMs = 5 / pump_powerMidpoint  # 5W
                ax3 = ax3_0[iset]
                ax3.bar(
                    x_pos,
                    FOMs,
                    yerr=np.divide(pump_powerMidpointErr, pump_powerMidpoint) *
                    FOMs,
                    align='center',
                    ecolor='blue',
                    capsize=10,
                    color="grey")

                ax3_0[0].set_ylabel('FOM at ' + name)
                ax3.set_xticks(x_pos)
                ax3.set_xticklabels(dates, rotation=45)
                ax3.set_title(fluid_name)
                ax3.yaxis.grid(True)
                ax3.xaxis.grid(False)

            # interpolate to all the data collected

            def funcLine(x, a, b, c):

                return a * x**2 + b * x + c

            def funcLinear(x, a, b, c):

                return b * np.log(x) + c

            def funcLineExp(x, a, b, c):
                return np.exp(a * x**2 + b * x + c)

            def funcLineExpDerivative(x, a, b, c):
                return np.multiply((2 * a * x + b),
                                   np.exp(a * x**2 + b * x + c))

            def funcPupmingPowerEr(x, b, c, d, a):
                return b * x**.5 + c * x**2 + d * x + a

            def funcInterpError(xdata_span, popt, popt_err, IRCAMERA_ERR,
                                samples):
                return np.power(
                    (funcPupmingPowerEr(funcLineExp(xdata_span, *popt), *
                                        popt_err)**2 + IRCAMERA_ERR *
                     funcLineExpDerivative(xdata_span, *popt)**2),
                    .5) / np.sqrt(samples)

            bounds = (-np.inf, np.inf)

            # fit the T vs pump power data
            popt, pcov = curve_fit(funcLine,
                                   fluid_T_wall_agg,
                                   np.log(fluid_pumpPower_agg),
                                   bounds=bounds)
            # fit the pump power vs pump power error data
            popt_err, pcov_err = curve_fit(funcPupmingPowerEr,
                                           fluid_pumpPower_agg,
                                           fluid_pumpPowerErr_agg,
                                           bounds=bounds)
            popt_fluids.append(popt)
            xdata_span = np.linspace(np.min(fluid_T_wall_agg),
                                     np.max(fluid_T_wall_agg), 300)
            y_data = funcLineExp(xdata_span, *popt)
            ax1.plot(xdata_span,
                     y_data,
                     c=colors_a[iset],
                     label=fluid_name + ' ' + fluid_power +
                     ' Fit: a=%5.3f, b=%5.3f, c=%5.3f' % tuple(popt))
            ax1.errorbar(fluid_T_wall_agg,
                         fluid_pumpPower_agg,
                         xerr=.5,
                         yerr=fluid_pumpPowerErr_agg,
                         ls='none',
                         alpha=1,
                         lw=1,
                         label='_nolegend_',
                         c=colors_a[iset])
            secax1 = ax1.secondary_xaxis('bottom',
                                         functions=(forward, inverse))
            secax1.set_frame_on(True)
            secax1.patch.set_visible(False)
            secax1.xaxis.set_label_position('bottom')
            secax1.spines['bottom'].set_position(('outward', 40))
            secax1.set_xlabel('HTC $[W/m^2K]$')

            ydata_heat = fluid_Richard
            # popt_preheat, pcov_preheat = curve_fit(funcLinear, fluid_pumpPower_agg,ydata_heat)
            xdata_pspan = np.linspace(np.min(fluid_pumpPower_agg),
                                      np.max(fluid_pumpPower_agg), 300)
            # ax6.plot(xdata_pspan, funcLinear(xdata_pspan,*popt_preheat), c=colors_a[iset],label=fluid_name)
            ax6.scatter(fluid_T_wall_agg,
                        ydata_heat,
                        s=15,
                        c=colors_a[iset],
                        label=fluid_name)
            # label=fluid_name + " Mean: %5.2f , std: %5.2f" % tuple([np.mean(ydata_heat),np.std(ydata_heat)]))

            ax7.scatter(fluid_pumpPower_agg,
                        ydata_heat,
                        s=15,
                        c=colors_a[iset],
                        label=fluid_name)
            ax7.set_xlabel('Pumping Power $\dot{W}$ [W]')
            # ax7.set_ylabel('Richardson Number')
            ax7.set_xscale('log')
            # ax7.set_title('Richardson Number')
            ax7.legend(fontsize=10)

            IRCAMERA_ERR = .5  # deg C
            interpErrorTotal = funcInterpError(xdata_span, popt, popt_err,
                                               IRCAMERA_ERR, dataSamples)
            ax1.fill_between(xdata_span,
                             y_data - interpErrorTotal,
                             y_data + interpErrorTotal,
                             facecolor='lightgrey',
                             alpha=.3)

            if name == "Midpoint":
                dataframe_fluid = pd.DataFrame({
                    "Wall Temp":
                    xdata_span,
                    "Pumping Power":
                    y_data,
                    "Pumping Power Error":
                    interpErrorTotal
                })
                dataframe_fluid.to_csv(
                    '/Users/hanscastorp/Dropbox/MIT-LUBRIZOL/LabData/Lubrizol Loop/04_Compiled_data_temp_pumpingpower'
                    + fluid_name + '.csv')

            ax2_1.errorbar(fluid_pumpPower_agg,
                           fluid_HTC_wall_agg,
                           xerr=fluid_pumpPowerErr_agg,
                           yerr=fluid_HTC_wallErr_agg,
                           ls='none',
                           alpha=1,
                           lw=.5,
                           label=fluid_name)
            ax2_2.errorbar(fluid_volFlow_agg,
                           fluid_HTC_wall_agg,
                           xerr=0,
                           yerr=fluid_HTC_wallErr_agg,
                           ls='none',
                           alpha=1,
                           lw=.5,
                           label=fluid_name)
            ax2_3.errorbar(fluid_Re_agg,
                           fluid_HTC_wall_agg,
                           xerr=0,
                           yerr=fluid_HTC_wallErr_agg,
                           ls='none',
                           alpha=1,
                           lw=.5,
                           label=fluid_name)

            # interpolate HTC vs Reynolds
            def funcHTC(x, a, b):
                return np.exp(a * np.log(x) + b)

            popt_ReHTC, pcov = curve_fit(
                funcHTC,
                fluid_Re_agg,
                fluid_HTC_wall_agg,
                # bounds=([0,-np.inf], [np.inf,np.inf])
            )
            ax8.errorbar(fluid_Re_agg,
                         fluid_HTC_wall_agg,
                         xerr=0,
                         yerr=fluid_HTC_wallErr_agg,
                         ls='none',
                         c=colors_a[iset],
                         alpha=1,
                         lw=.5,
                         label=fluid_name)
            xrange_re = np.linspace(1, 1000, 1000)
            print('_____________________ FLUID HTC vs Re fit ____ ',
                  fluid_name)
            print(popt_ReHTC)

            ax8.plot(fluid_Re_agg,
                     funcHTC(fluid_Re_agg, *popt_ReHTC),
                     c=colors_a[iset],
                     label=fluid_name +
                     ' Fit: a=%5.3f, b=%5.3f' % tuple(popt_ReHTC))
            targetReynolds = 200
            interpHTC = funcHTC(targetReynolds, *popt_ReHTC)
            print(f"HTC at ", targetReynolds, ": ", interpHTC)

            targetTemp = 55

            interpolatePumpingPower = funcLineExp(targetTemp, *popt)
            interpolatePumpingPowerErr = funcInterpError(
                targetTemp, popt, popt_err, IRCAMERA_ERR, dataSamples)
            interpolatePumpingPower_agg.append(interpolatePumpingPower)
            interpolatePumpingPowerErr_agg.append(interpolatePumpingPowerErr)
            fluids_agg.append(fluid_name)
            ax1.axhline(y=interpolatePumpingPower, color='r', linestyle='--')

        uniqueFluids = np.unique(fluids_agg)
        colors = {}
        for iic, ic in enumerate(uniqueFluids):
            colors[ic] = plt.cm.tab10(iic)

        labels = list(colors.keys())

        ax1.axvline(x=targetTemp, color='r', linestyle='--')

        interpolatePumpingPower_agg = np.hstack(interpolatePumpingPower_agg)
        interpolatePumpingPowerErr_agg = np.hstack(
            interpolatePumpingPowerErr_agg)
        interpolatePumpingPowerErr_agg = np.divide(
            interpolatePumpingPowerErr_agg, interpolatePumpingPower_agg)
        FOM = interpolatePumpingPower_agg**-1
        FOM_normed = FOM / FOM[idx_ref]
        FOM_normed_err = np.multiply(FOM_normed,
                                     interpolatePumpingPowerErr_agg)
        i = 0
        left, right = ax1.get_xlim()
        # xdata_span = np.linspace(45, 65 , 300)

        for datapaths in sets:
            # ax1.text(x=60,y=interpolatePumpingPower_agg[i],s=fluids_agg[i]+ " FOM: %10.1E" %FOM_normed[i])

            ax1.text(x=60,
                     y=interpolatePumpingPower_agg[i],
                     s=fluids_agg[i] + " FOM: %10.1f $\pm$%10.1f" %
                     (FOM_normed[i], FOM_normed_err[i]))
            ax1.text(x=right + (right - left) * .01,
                     y=interpolatePumpingPower_agg[i],
                     c="r",
                     s="%10.2E W" % interpolatePumpingPower_agg[i],
                     fontsize=10)

            i += 1

        if 1 == 1:
            x_pos = np.arange(len(fluids_agg))
            p1 = ax5.bar(x_pos,
                         np.round(FOM_normed, 1),
                         yerr=FOM_normed_err,
                         align='center',
                         ecolor='blue',
                         capsize=10,
                         facecolor="white",
                         edgecolor="black",
                         fill=True)

            ax5.set_ylabel('FOM')
            ax5.set_xlabel('Fluid')
            ax5.set_xticks(x_pos)
            ax5.set_xticklabels(fluids_agg, rotation=45)
            ax5.set_title("Midpoint FOM Norm to Basefluid")
            ax5.yaxis.grid(True)
            ax5.xaxis.grid(False)
            ax5.bar_label(p1, label_type='center', padding=-5)
            ax5.bar_label(p1,
                          labels=['±%.1f' % e for e in FOM_normed_err],
                          padding=2,
                          color='b')

        i = 0
        if name != "Inlet":
            for datapaths in sets:
                scale_factor = np.divide(
                    funcLineExp(xdata_span, *popt_fluids[i])**-1,
                    funcLineExp(xdata_span, *popt_fluids[idx_ref])**-1)
                ax4.plot(xdata_span,
                         scale_factor,
                         c=colors_a[i],
                         linestyle=linestyle[name],
                         label=fluids_agg[i] + ' at Wall ' + name)

                i += 1
            ax4.set_ylabel('Normalized FOM ')
            ax4.set_xlabel('$T_{wall}$ [°C]')
            # ax4.set_yscale('log')
            ax4.set_title('FOM Sensitivity Normaalzing to ' +
                          fluids_agg[idx_ref])

            secax = ax4.secondary_xaxis('bottom', functions=(forward, inverse))
            secax.set_frame_on(True)
            secax.patch.set_visible(False)
            secax.xaxis.set_label_position('bottom')
            secax.spines['bottom'].set_position(('outward', 40))
            secax.set_xlabel('HTC $[W/m^2K]$')
            ax4.legend(fontsize=10)

        ax1.text(x=48,
                 y=.002,
                 s="$y = e^{a x^2 + b x +c}$",
                 fontsize=18,
                 bbox=dict(
                     boxstyle="square",
                     ec=(0, 0, 0),
                     fc=(1., 1, 1),
                 ))

        ax1.set_ylabel('Pumping Power $\dot{W}$ [W]')
        ax1.set_xlabel('$T_{wall}$ [°C]')
        ax1.set_yscale('log')
        ax1.set_ylim([10**-5, 1.1])
        ax1.set_title('Pumping Power vs Wall Temp at: ' + name)

        ax8.set_ylabel('HTC $[W/m^2K]$')
        ax8.set_xlabel('Re')
        ax8.yaxis.grid(True)
        ax8.xaxis.grid(True)

        ax8.set_yscale('log')
        ax8.set_xscale('log')
        ax8.set_title('Reynolds vs HTC at: ' + name)
        ax8.legend(fontsize=10)

        ax6.set_xlabel('$T_{wall}$ [°C]')
        ax6.set_ylabel('Richardson Number')
        # ax6.set_yscale('log')
        # ax6.set_title('Richardson Number')
        ax6.legend(fontsize=10)
        ax7.tick_params(labelleft=False, labelright=True)

        ax2_1.set_xlabel('Test Section Pumping Power $\dot{W}$ [W]')
        ax2_1.set_ylabel('HTC $[W/m^2K]$')
        ax2_1.set_xscale('log')
        # ax2_2.set_xscale('log')
        # ax2_3.set_xscale('log')
        ax2_1.set_title('Pumping Power')
        ax2_2.set_title('$Volume Flow Rate $')
        ax2_3.set_title('Re')
        ax2_2.tick_params(labelleft=False)
        ax2_3.tick_params(labelleft=False)
        ax2_3.tick_params(labelright=True)
        ax2_1.set_xlabel('Pumping Power $\dot{W}$ [W]')
        ax2_2.set_xlabel('Volume Flow Rate [L/min]')
        # ax2_2.set_xlabel('$T_{wall}$ [C]')
        ax2_3.set_xlabel('Reynolds')
        ax2_1.legend(fontsize=10)

        fig2.suptitle('Wall Location: ' + name, fontsize=16)
        fig6.suptitle('Richardson at Wall Location: ' + name, fontsize=16)
        compiled_pumpingPower3Points = np.vstack(compiled_pumpingPower3Points)
        dataframe = pd.DataFrame(compiled_pumpingPower3Points,
                                 index=fluids,
                                 columns=[
                                     "Date", "Fluid", "Pumping Power Inlet",
                                     "Pumping Power Midpoint",
                                     "Pumping Power Outlet",
                                     "Pumping Power Midpoint Error"
                                 ])
        for ffff in [
                "Pumping Power Inlet", "Pumping Power Midpoint",
                "Pumping Power Outlet", "Pumping Power Midpoint Error"
        ]:
            dataframe[ffff] = pd.to_numeric(dataframe[ffff], downcast="float")

        dataframe = dataframe.sort_values("Date")
        dataframe["Fluid"] = [f.split(' ')[0] for f in dataframe["Fluid"]]

        if 1 == 1:

            x_pos = np.arange(len(dataframe["Date"]))
            # with pd.option_context('display.max_rows', None, 'display.max_columns',
            #                        None):  # more options can be specified also
            #     print(dataframe)
            FOMs = 5 / dataframe["Pumping Power Midpoint"].values  # 5W
            bars = ax3B.bar(
                x_pos,
                FOMs,
                yerr=np.divide(dataframe["Pumping Power Midpoint Error"],
                               dataframe["Pumping Power Midpoint"]) * FOMs,
                align='center',
                ecolor='blue',
                capsize=10,
                color="grey")

            ax3B.set_ylabel('FOM at ' + name)
            ax3B.set_xticks(x_pos)
            ax3B.set_xticklabels(dataframe["Date"], rotation=45)
            ax3B.set_title("FOM Measurements")
            ax3B.yaxis.grid(True)
            ax3B.xaxis.grid(False)
            for it, test in enumerate(dataframe["Fluid"]):
                bars[it].set_color(colors[test])

            handles = [
                plt.Rectangle((0, 0), 1, 1, color=colors[label])
                for label in labels
            ]
            ax3B.legend(handles, labels)

        dataframe.to_csv(
            '/Users/hanscastorp/Dropbox/MIT-LUBRIZOL/LabData/Lubrizol Loop/20210827_Compiled_data.csv'
        )
        fig1.savefig(
            '/Users/hanscastorp/Dropbox/MIT-LUBRIZOL/LabData/Lubrizol Loop/4_pumppower_vs_Twall_'
            + name + '.png')
        fig8.savefig(
            '/Users/hanscastorp/Dropbox/MIT-LUBRIZOL/LabData/Lubrizol Loop/4_Rey_vs_HTC_'
            + name + '.png')
        fig6.savefig(
            '/Users/hanscastorp/Dropbox/MIT-LUBRIZOL/LabData/Lubrizol Loop/4_Ri_vs_WallTemp'
            + '_' + name + '.png')
        fig5.savefig(
            '/Users/hanscastorp/Dropbox/MIT-LUBRIZOL/LabData/Lubrizol Loop/4_fluids_comp_'
            + name + '.png')
        fig2.savefig(
            '/Users/hanscastorp/Dropbox/MIT-LUBRIZOL/LabData/Lubrizol Loop/4_pumppower_vs_HTC_'
            + name + '.png')
        fig3.savefig(
            '/Users/hanscastorp/Dropbox/MIT-LUBRIZOL/LabData/Lubrizol Loop/4_fluid_Time'
            + '_' + fluid_name + '_' + name + '.png')
        fig3B.savefig(
            '/Users/hanscastorp/Dropbox/MIT-LUBRIZOL/LabData/Lubrizol Loop/4_fluid_TimeB'
            + '_' + fluid_name + '_' + name + '.png')
Пример #6
0
Файл: pca.py Проект: ufwt/TraFix
            csvf.writerow([words[i], types[i].name,
                           str(pca[i]), ''] + list(pca[i]))

if args.plot:
    if args.f > 3:
        print 'Plotting is only supported for final vector size at most 3. Skipping plot\n'
    else:
        if len(set(types)) < len(mcolors.BASE_COLORS):
            mcolors = mcolors.BASE_COLORS
            avoid = ['w']
        else:
            mcolors = mcolors.CSS4_COLORS
            avoid = ['white']
        mcolors = sorted(
            map(lambda y: mcolors[y],
                filter(lambda x: x not in avoid, mcolors.keys())))
        stride = max(1, len(mcolors) / len(Types))
        colorsMap = {}

        def mapColorToType(t):
            if t.value not in colorsMap.keys():
                colorsMap[t.value] = mcolors[len(colorsMap.keys()) * stride]
            return colorsMap[t.value]

        colors = map(mapColorToType, types)
        if args.f == 1:
            p = plt.scatter(pca, [0 for i in range(len(pca))], c=colors)
        if args.f == 2:
            p = plt.scatter(pca[:, 0], pca[:, 1], c=colors)
        if args.f == 3:
            p = Axes3D(plt.figure()).scatter(pca[:, 0],
Пример #7
0
def parallel(
    df,
    components=None,
    classes=None,
    rescale=True,
    legend=False,
    ax=None,
    label_rotate=60,
    **kwargs,
):
    """
    Create a parallel coordinate plot across dataframe columns, with
    individual lines for each row.

    Parameters
    -----------
    df : :class:`pandas.DataFrame`
        Dataframe to create a plot from.
    components : :class:`list`
        Subset of dataframe columns to use as indexes along the x-axis.
    rescale : :class:`bool`
        Whether to rescale values to [-1, 1].
    legend : :class:`bool`, :code:`False`
        Whether to include or suppress the legend.
    ax : :class:`matplotlib.axes.Axes`
        Axis to plot on (optional).

    Todo
    ------
    * A multi-axis version would be more compatible with independent rescaling and zoom
    * Enable passing a list of colors

        Rather than just a list of numbers to be converted to colors.
    """
    samples = df.copy()
    ax = init_axes(ax=ax, **kwargs)

    target = samples.index.name or "index"
    samples = samples.reset_index()  # to access the index to use as a 'class'

    if components is None:
        components = samples.columns.tolist()

    non_target = [i for i in components if i != target]
    if rescale:
        samples[non_target] = samples.loc[:, non_target].apply(
            lambda x: (x - x.mean()) / x.std())

    colors = process_color(**kwargs)

    [kwargs.pop(x, None)
     for x in colors.keys()]  # so colors aren't added twice

    parallel_coordinates(
        samples.loc[:, [target] + non_target],
        target,
        ax=ax,
        color=colors.get("color", None),
        **subkwargs(kwargs, parallel_coordinates),
    )
    ax.spines["bottom"].set_color("none")
    ax.spines["top"].set_color("none")
    if not legend:
        ax.get_legend().remove()

    if label_rotate is not None:
        [i.set_rotation(label_rotate) for i in ax.get_xticklabels()]

    return ax