import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

from opengrid import config
c = config.Config()

%matplotlib inline
plt.rcParams['figure.figsize'] = 16,8

from opengrid.library.houseprint import houseprint

"""
Explanation: This script shows how to use the existing code in opengrid to create a water consumption benchmark.
End of explanation
"""


hp = houseprint.Houseprint()

hp.sync_tmpos()

"""
Explanation: Load the Houseprint and sync all data
End of explanation
"""


df = hp.get_data(sensortype='water', head=pd.Timestamp('now') - pd.Timedelta(days=365))
#retain only positive values (sometimes there are meter resets)
df = df[df > 0]

"""
Explanation: Create a dataframe containing a column for each water sensor with data of exactly one year (up till now)
End of explanation
"""


for sensor in df.columns:
    plt.figure()
    ts = df[sensor].dropna()
    ax1=plt.subplot(121)
    plt.plot_date(ts.index, ts, '-', label=sensor)
    plt.ylabel('water consumption [l/min]')
    plt.legend()
    
    ax2=plt.subplot(122)
    plt.plot(np.sort(ts)[::-1], label=sensor)
    plt.ylabel('water JBDC [l/min]')
    plt.legend()

"""
Explanation: Plot results
Plot timeseries and load duration for each retained sensor
End of explanation
"""


for sensor in df.columns:
    plt.figure()
    ts = df[sensor]
    ts=ts[ts>1]
    ts=ts[ts<30]
    ts.hist(bins=100)
    plt.title(hp.find_sensor(sensor).device.key + ' - ' + hp.find_sensor(sensor).description + ' - ' + sensor)

for sensor in df.columns:
        
    plt.figure()
    ts = df[sensor]
    ts=ts[ts>0.1]
    ts=ts[ts<30]
    
    hst, edges = np.histogram(ts, np.arange(0,20,0.5))
    hst_weighted = hst * edges[1:]
    plt.plot(np.arange(0,20,0.5)[1:], hst_weighted)
    #plt.plot(np.arange(0,20,0.25)[1:], hst)
    plt.title(hp.find_sensor(sensor).device.key + ' - ' + sensor)
    plt.ylabel('Water consumption (liter)')
    

"""
Explanation: Let's refine the load duration into a histogram
End of explanation
"""


