Temperature against space use#

We are currently testing an experimental feature showing when the venue is in use. To see it, choose venue 99.

# Imports 
import ipywidgets as widgets
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go   
import os
from IPython.display import display

# Get the possible data venues
venuekeysfile = "venue-keys.csv"
dfVenueKeys = pd.read_csv(venuekeysfile)
dfVenueKeys = dfVenueKeys.dropna(subset=['channel_id'])




#give user option to select their venue
venueDropdown = widgets.Dropdown(
    options=dfVenueKeys['venue_id'],
    value=dfVenueKeys['venue_id'][0],
    description='Venue ID:',
    disabled=False,
)


container = widgets.HBox(children=[venueDropdown])

#print(venueDropdown.value)

#Retrieve the venue and begin graphing
dfCollatedDataSet = pd.DataFrame(columns=['timestamp', 'entry_id', 'temperature', 'rh', 'voltage', 'venue_id'])
dfCollatedUseDiaries = pd.DataFrame(columns=['start', 'end', 'entry_id', 'venue_id'])
for index, venueSensorDetails in dfVenueKeys.iterrows():
    
    sensorMacOfSelection = venueSensorDetails['sensor_MAC']
    venueOfSelection = str(venueSensorDetails['venue_id'])
    dfTempDataSet = pd.read_csv('deviceData/'+ "venue_" + venueOfSelection + "_with_device_" + sensorMacOfSelection + '.csv' )
    dfTempDataSet = dfTempDataSet.dropna()
    dfTempDataSet['timestamp'] = pd.to_datetime(dfTempDataSet['timestamp'])
    dfTempDataSet['venue_id'] = venueSensorDetails['venue_id']

    #dfCollatedDataSet = dfCollatedDataSet.append(dfTempDataSet, ignore_index=True)
    dfCollatedDataSet = pd.concat([dfCollatedDataSet, dfTempDataSet]) 
    #should already be datetimes - why is this here?
    dfCollatedDataSet['timestamp'] = pd.to_datetime(dfCollatedDataSet['timestamp'])
    
    if os.path.exists('useDiaries/'+ "venue_" + venueOfSelection + "_with_device_" + sensorMacOfSelection + '.csv'):
        dfUseDiary = pd.read_csv('useDiaries/'+ "venue_" + venueOfSelection + "_with_device_" + sensorMacOfSelection + '.csv' )
        dfUseDiary = dfUseDiary.fillna('')
        dfUseDiary['start'] = pd.to_datetime(dfUseDiary['startUse'])
        dfUseDiary['end'] = pd.to_datetime(dfUseDiary['endUse'])
        dfUseDiary['venue_id'] = venueSensorDetails['venue_id']
        

        #dfCollatedUseDiaries = dfCollatedUseDiaries.append(dfUseDiary, ignore_index=True)
        dfCollatedUseDiaries = pd.concat([dfCollatedUseDiaries, dfUseDiary])
        #should already be datetimes - why is this here?
        dfCollatedUseDiaries['start'] = pd.to_datetime(dfUseDiary['start'])
        dfCollatedUseDiaries['end'] = pd.to_datetime(dfUseDiary['end'])
    
    #print('Loading data for venue: ', venueSensorDetails['venue_id']) 

    
#print('Check')
#dfCollatedDataSet.sample(6)




# Assign an empty figure widget with two traces
trace0 = go.Scatter(customdata=dfCollatedDataSet[dfCollatedDataSet['venue_id'] == 0], 
                    y=dfCollatedDataSet['temperature'], 
                    x = dfCollatedDataSet['timestamp'], 
                    mode='lines', 
                    hoverinfo='all', 
                    name='Temperature',
                    )

# trace1 = go.Scatter(customdata=dfCollatedDataSet[dfCollatedDataSet['venue_id'] == 0], 
#                     y=dfCollatedDataSet['rh'], 
#                     x = dfCollatedDataSet['timestamp'], 
#                     mode='lines', 
#                     hoverinfo='all', 
#                     name='Relative Humidity',
#)


g = go.FigureWidget(data=[trace0], #, trace1],
                    layout = go.Layout(
                        yaxis=dict(range=[0,0])           
                    ))


#print("Job Done")
updatemenu = []
buttons = []

# button with one option for each dataframe
for index, venue in dfVenueKeys.iterrows():
    buttons.append(dict(method='update',
                        label='Venue ' + str(venue['venue_id']),
                        visible=True,
                        args=[{'y':[dfCollatedDataSet[dfCollatedDataSet['venue_id']==venue['venue_id']]['temperature'].values], #, 
                                    #dfCollatedDataSet[dfCollatedDataSet['venue_id']==venue['venue_id']]['rh'].values],
                               'x':[dfCollatedDataSet[dfCollatedDataSet['venue_id']==venue['venue_id']]['timestamp'].values],
                               'type':'scatter',   
                            #  'name': 'Temperature',
                                                          
                               },
                               {
                                   'title.text': 'Temperature for Venue = ' + str(venue['venue_id']),
                                   'title.font.color': 'green',
                                    #'yaxis.range': [-5,dfCollatedDataSet[dfCollatedDataSet['venue_id']==venue['venue_id']][['temperature', 'rh']].max().max()+5], 
                                    'yaxis.range': [dfCollatedDataSet[dfCollatedDataSet['venue_id']==venue['venue_id']]['temperature'].min()-10,dfCollatedDataSet[dfCollatedDataSet['venue_id']==venue['venue_id']]['temperature'].max()+5], 
                                   'yaxis.title.text': 'Temperature',
                                   'xaxis.title.text': 'Timestamp'

                               },
                               ],
                        )
                  )

# some adjustments to the updatemenus
updatemenu = []
your_menu = dict()
updatemenu.append(your_menu)

updatemenu[0]['buttons'] = buttons
updatemenu[0]['direction'] = 'down'
updatemenu[0]['showactive'] = True
# updatemenu[0]['active'] = 0

 

fig = go.Figure(g)
# add dropdown menus to the figure
fig.update_layout(showlegend=True, 
              updatemenus=updatemenu, 
              autosize = True, 
              title= "Please select a venue to see your data.",
              width=1500,
              height=700,
)

fig.update_layout(
    hovermode='x unified',
    hoverlabel=dict(
        bgcolor="white",
        # font_size=16,
        font_family="Rockwell"
    )
)

# Add range slider

fig.update_layout(
    xaxis=dict(
        rangeselector=dict(
            buttons=list([
                dict(
                     label="All",
                     step="all"
                     ),
                                dict(count=1,
                     label="Hour",
                     step="hour",
                     stepmode="todate"),
                dict(count=1,
                     label="Day",
                     step="day",
                     stepmode="backward"),
                dict(count=7,
                     label="Week",
                     step="day",
                     stepmode="backward"),
                dict(count=1,
                     label="Year",
                     step="year",
                     stepmode="backward")
            ])
        ),
        rangeslider=dict(
            visible=True
        ),
        type="date"
    )
)


#fig.update_yaxes(range=[50, 60])  


fig.add_hline(y=16, annotation_text='16C - usual minimum for children', annotation_font_color="blue", line_color='red', layer='above', line_dash='dash')
# fig.update_yaxes(range = [-5, dfCollatedDataSet['temperature'].max()+5])

for ind in dfCollatedUseDiaries.index:
    #print(dfCollatedUseDiaries['start'][ind])
    #print(dfCollatedUseDiaries['end'][ind])

    fig.add_vrect(x0=dfCollatedUseDiaries['start'][ind], x1=dfCollatedUseDiaries['end'][ind],
                annotation_text=dfCollatedUseDiaries['label'][ind], 
                annotation_position="top left",
                annotation=dict(font_size=14, 
                font_family="Times New Roman"),
                fillcolor="green", 
                opacity=0.25, 
                line_width=0)
                
fig.show()