# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

# # Analysis of Building America 2015 Study

# +
import pandas as pd
import numpy as np
# import matplotlib pyplot commands
from matplotlib.pyplot import *
from IPython.display import Image, Markdown
 
# Show Plots in the Notebook
# %matplotlib inline
 
# 'style' the plot like fivethirtyeight.com website
style.use('bmh')
# -

rcParams['figure.figsize']= (10, 6)   # set Chart Size
rcParams['font.size'] = 14            # set Font size in Chart

sheet_names = ('Site1', 'Site2', 'Site4', 'Site5', 'Site8', 'Site9', 'Site10')
ix = 3
dfp = pd.read_excel('COP_vs_temp_plots.xlsx', sheet_name=sheet_names[ix])
dfp.plot(x='temperature', y='cop', kind='scatter')
xlim(-15, 60)
ylim(0, 4.5)
title(sheet_names[ix])
gca().set_xticks(np.arange(-15, 61, 5));


def bin_averages(df, bin_width = 5.0):
    """For DataFrame df, calculate average temperatures and COPs for bins
    of outdoor temperature of width 'bin_width' deg F.  Return a DataFrame
    with the averaged values.
    """
    dfc = df.copy()
    # calculate the bin for each row
    dfc['temp_bin'] = dfc['temperature'] // bin_width
    
    # average by bins
    dfa = dfc.groupby('temp_bin').mean()
    dfa = dfa[['temperature', 'cop']]
    return dfa


# Determines width of averaging bins
BIN_WIDTH = 10./3.

# Plot all the curves, but also create one DataFrame containing
# all the binned data
figure(figsize=(10,8))
df_all = None
for sht_nm in sheet_names:
    dfp = pd.read_excel('COP_vs_temp_plots.xlsx', sheet_name=sht_nm)
    dfa = bin_averages(dfp, bin_width=BIN_WIDTH)
    dfa.reset_index(inplace=True)
    dfa.drop(columns=['temp_bin'], inplace=True)
    dfa['site'] = sht_nm
    plot(dfa.temperature, dfa.cop, label=sht_nm)
    if df_all is None:
        df_all = dfa
    else:
        df_all = pd.concat([df_all, dfa])
xlabel('Outdoor Temperature, deg F')
ylabel('COP')
legend()

df_all.head()

# There is good data coverage from 10 - 50 deg F outdoors.  Except, Site 5 only has data up through about 35 deg F.  So, we will drop Site 5. 

# Drop Site 5
df_all.query("site != 'Site5'", inplace=True)

df_all.query('site == "Site4"')

# The other problem is that Site 4 has no data in the 46.67 deg F to 50 deg F bin, as shown in the above table.  So if we use the bin_averages() function, it will ignore Site 4 in the calculation of the average for that bin, causing a large distortion since Site 4 has a high COP.  So, instead of using the bin_averages() function to combine all this data, we should just use interpolated values at the midpoint temperatures of the bin.

# Midpoints of the temperature bins we are interested in
temp_midpoints = np.arange(10.0 + BIN_WIDTH / 2.0, 50.0, BIN_WIDTH)
temp_midpoints

# +
# Make a DataFrame with the temperature midpoints as the index
# and each column being the COP values from a particular site.
df_mids = pd.DataFrame(index=temp_midpoints)
for site_str in df_all.site.unique():
    df_site = df_all.query('site==@site_str')
    cop_values = np.interp(temp_midpoints, df_site.temperature, df_site.cop)
    df_mids[site_str] = cop_values
        
df_mids
# -

series_mean = df_mids.mean(axis=1)
series_mean

# turn Series into a DataFrame
df_all_avg = pd.DataFrame({'temperature': series_mean.index, 'cop': series_mean.values})
df_all_avg

df_all_avg.plot(x='temperature', y='cop')

# Redo the plot showing all the lines, but superimpose this line on it
figure(figsize=(10,8))
df_all = None
for sht_nm in sheet_names:
    dfp = pd.read_excel('COP_vs_temp_plots.xlsx', sheet_name=sht_nm)
    dfa = bin_averages(dfp, bin_width=BIN_WIDTH)
    dfa.reset_index(inplace=True)
    dfa.drop(columns=['temp_bin'], inplace=True)
    dfa['site'] = sht_nm
    plot(dfa.temperature, dfa.cop, label=sht_nm, linewidth=0.5)
    if df_all is None:
        df_all = dfa
    else:
        df_all = pd.concat([df_all, dfa])
plot(df_all_avg.temperature, df_all_avg.cop, 'r-', linewidth=2.0, label='Average')
xlabel('Outdoor Temperature, deg F')
ylabel('COP')
legend()

# Calculate weighted average of HSPF values for the studied 
# units.  I dropped Site 5, which was the one Fujit 15RLS2 studied.
# So:  3 Mitsu FE18 + 3 Mitsu FE12
(3 * 10.3 + 3 * 10.5) / 6.0

df_all_avg['source'] = '<NAME>'
df_all_avg['field_study'] = True
df_all_avg['hspf'] = 10.4   # Estimate at this point
df_all_avg.to_pickle('temp_cop_swinter.pkl')

StarcoderdataJupyterScriptsDedupFiltered