Temperature Analysis


In [ ]:
import pandas
import numpy

from bokeh.plotting import output_notebook, show, figure, ColumnDataSource
from bokeh.models import Span
from bokeh.io import push_notebook
output_notebook()

from ipywidgets import widgets, interactive
from IPython.display import display

from collections import OrderedDict

import datetime

# Get current sensors database from raspberry pi
df = pandas.read_csv('sensors.log',names = ["Level", "Sensor", "Time", "Value"],
                    parse_dates=['Time'])

df.index.name = 'ID'

# Get temperature values
temp = df.loc[df['Sensor'] == 'T']

# Draw temperature vs time
p = figure(width=850, height=350, x_axis_type="datetime")
p.line(temp['Time'],temp['Value'],line_width=2)
p.xaxis.axis_label = 'Time'
p.yaxis.axis_label = 'Temperature'

#Init threshold lines
minline = Span(dimension='width', line_color='blue', line_width=1)
maxline = Span(dimension='width', line_color='red', line_width=1)
p.add_layout(minline)
p.add_layout(maxline)

# Callback to get user limits
def Analysis(Tmin, Tmax):
    print('Safe range of temperatures (°C): [{}, {}] '.format(Tmin, Tmax))
    minline.location = Tmin
    maxline.location = Tmax
    temp.reset_index(inplace=True)
    temp_sel = temp[(temp['Value'] < Tmin) | (temp['Value'] > Tmax)].copy()
    temp_group = temp_sel.groupby(temp_sel.index - numpy.arange(temp_sel.shape[0]))
    results = []
    for _, group in temp_group:
        d = OrderedDict()
        d['Start_date'] = group.iloc[0]['Time']
        d['Stop_date'] = group.iloc[-1]['Time']
        d['Duration'] = d['Stop_date'] - d['Start_date']
        d['Max'] = group['Value'].max()
        d['Average'] = group['Value'].mean()
        results.append(d)
    df_group = pandas.DataFrame(results)
    df_group = df_group[df_group['Duration'] > datetime.timedelta(minutes=1)]
    push_notebook()
    return df_group

# Display description
w = interactive(Analysis, Tmin=(0.0,40.0), Tmax=(0.0,40.0),__manual=True)
display(w)

In [ ]:
show(p, notebook_handle=True)