2017-11-04 03:03:24 +00:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
from collections import OrderedDict
|
|
|
|
|
2021-08-28 20:42:22 +00:00
|
|
|
from django.utils import timezone, formats
|
2019-04-14 20:32:46 +00:00
|
|
|
from django.utils.translation import gettext as _
|
2017-11-04 03:03:24 +00:00
|
|
|
|
|
|
|
import plotly.offline as plotly
|
|
|
|
import plotly.graph_objs as go
|
|
|
|
|
|
|
|
from core.utils import duration_string
|
|
|
|
|
|
|
|
from reports import utils
|
|
|
|
|
2021-12-31 15:17:21 +00:00
|
|
|
from datetime import timedelta
|
|
|
|
|
2022-02-10 00:00:30 +00:00
|
|
|
ASLEEP_COLOR = "rgb(35, 110, 150)"
|
|
|
|
AWAKE_COLOR = "rgba(255, 255, 255, 0)"
|
2017-11-04 03:03:24 +00:00
|
|
|
|
2021-10-30 13:20:41 +00:00
|
|
|
|
|
|
|
def sleep_pattern(sleeps):
|
2017-11-04 03:03:24 +00:00
|
|
|
"""
|
|
|
|
Create a graph showing blocked out periods of sleep during each day.
|
2021-10-30 13:20:41 +00:00
|
|
|
:param sleeps: a QuerySet of Sleep instances.
|
2017-11-04 03:03:24 +00:00
|
|
|
:returns: a tuple of the the graph's html and javascript.
|
|
|
|
"""
|
|
|
|
last_end_time = None
|
|
|
|
adjustment = None
|
2021-12-31 15:17:21 +00:00
|
|
|
|
|
|
|
days = _init_days(sleeps.first().start, sleeps.last().end)
|
|
|
|
|
2021-10-30 13:20:41 +00:00
|
|
|
for sleep in sleeps:
|
|
|
|
start_time = timezone.localtime(sleep.start)
|
|
|
|
end_time = timezone.localtime(sleep.end)
|
2017-11-04 03:03:24 +00:00
|
|
|
start_date = start_time.date().isoformat()
|
2021-08-28 03:06:18 +00:00
|
|
|
end_date = end_time.date().isoformat()
|
2021-10-30 13:20:41 +00:00
|
|
|
duration = sleep.duration
|
2017-11-04 03:03:24 +00:00
|
|
|
|
|
|
|
# Check if the previous entry crossed midnight (see below).
|
|
|
|
if adjustment:
|
2021-10-30 13:29:21 +00:00
|
|
|
_add_adjustment(adjustment, days)
|
2022-02-10 00:00:30 +00:00
|
|
|
last_end_time = timezone.localtime(adjustment["end_time"])
|
2017-11-04 03:03:24 +00:00
|
|
|
adjustment = None
|
|
|
|
|
|
|
|
# If the dates do not match, set up an adjustment for the next day.
|
|
|
|
if end_time.date() != start_time.date():
|
|
|
|
adj_start_time = end_time.replace(hour=0, minute=0, second=0)
|
|
|
|
adjustment = {
|
2022-02-10 00:00:30 +00:00
|
|
|
"column": end_date,
|
|
|
|
"start_time": adj_start_time,
|
|
|
|
"end_time": end_time,
|
|
|
|
"duration": end_time - adj_start_time,
|
2017-11-04 03:03:24 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
# Adjust end_time for the current entry.
|
|
|
|
end_time = end_time.replace(
|
2022-02-10 00:00:30 +00:00
|
|
|
year=start_time.year,
|
|
|
|
month=start_time.month,
|
|
|
|
day=start_time.day,
|
|
|
|
hour=23,
|
|
|
|
minute=59,
|
|
|
|
second=0,
|
|
|
|
)
|
2017-11-04 03:03:24 +00:00
|
|
|
duration = end_time - start_time
|
|
|
|
|
2020-12-03 04:15:22 +00:00
|
|
|
if not last_end_time:
|
2017-11-04 03:03:24 +00:00
|
|
|
last_end_time = start_time.replace(hour=0, minute=0, second=0)
|
|
|
|
|
|
|
|
# Awake time.
|
2022-02-10 00:00:30 +00:00
|
|
|
days[start_date].append(
|
|
|
|
{"time": (start_time - last_end_time).seconds / 60, "label": None}
|
|
|
|
)
|
2017-11-04 03:03:24 +00:00
|
|
|
|
|
|
|
# Asleep time.
|
2022-02-10 00:00:30 +00:00
|
|
|
days[start_date].append(
|
|
|
|
{
|
|
|
|
"time": duration.seconds / 60,
|
|
|
|
"label": _format_label(duration, start_time, end_time),
|
|
|
|
}
|
2021-10-30 13:29:21 +00:00
|
|
|
)
|
2017-11-04 03:03:24 +00:00
|
|
|
|
2017-11-07 11:23:19 +00:00
|
|
|
# Update the previous entry duration if an offset change occurred.
|
|
|
|
# This can happen when an entry crosses a daylight savings time change.
|
|
|
|
if start_time.utcoffset() != end_time.utcoffset():
|
|
|
|
diff = start_time.utcoffset() - end_time.utcoffset()
|
|
|
|
duration -= timezone.timedelta(seconds=diff.seconds)
|
2022-02-10 00:00:30 +00:00
|
|
|
yesterday = end_time - timezone.timedelta(days=1)
|
2021-04-11 20:56:40 +00:00
|
|
|
yesterday = yesterday.date().isoformat()
|
2021-10-30 13:29:21 +00:00
|
|
|
days[yesterday][len(days[yesterday]) - 1] = {
|
2022-02-10 00:00:30 +00:00
|
|
|
"time": duration.seconds / 60,
|
|
|
|
"label": _format_label(duration, start_time, end_time),
|
2021-10-30 13:29:21 +00:00
|
|
|
}
|
2017-11-07 11:23:19 +00:00
|
|
|
|
2017-11-04 03:03:24 +00:00
|
|
|
last_end_time = end_time
|
|
|
|
|
2021-08-28 03:06:18 +00:00
|
|
|
# Handle any left over adjustment (if the last entry crossed midnight).
|
|
|
|
if adjustment:
|
2021-10-30 13:29:21 +00:00
|
|
|
_add_adjustment(adjustment, days)
|
2021-08-28 03:06:18 +00:00
|
|
|
|
2021-08-28 03:47:52 +00:00
|
|
|
# Create dates for x-axis using a 12:00:00 time to ensure correct
|
|
|
|
# positioning of bars (covering entire day).
|
|
|
|
dates = []
|
2021-10-30 13:29:21 +00:00
|
|
|
for time in list(days.keys()):
|
2022-02-10 00:00:30 +00:00
|
|
|
dates.append("{} 12:00:00".format(time))
|
2021-08-28 03:47:52 +00:00
|
|
|
|
2017-11-04 03:03:24 +00:00
|
|
|
traces = []
|
2021-10-30 13:20:41 +00:00
|
|
|
color = AWAKE_COLOR
|
2020-12-03 04:15:22 +00:00
|
|
|
|
|
|
|
# Set iterator and determine maximum iteration for dates.
|
|
|
|
i = 0
|
|
|
|
max_i = 0
|
2021-10-30 13:29:21 +00:00
|
|
|
for date_times in days.values():
|
2020-12-03 04:15:22 +00:00
|
|
|
max_i = max(len(date_times), max_i)
|
|
|
|
while i < max_i:
|
|
|
|
y = {}
|
|
|
|
text = {}
|
2021-10-30 13:29:21 +00:00
|
|
|
for date in days.keys():
|
2020-12-03 04:15:22 +00:00
|
|
|
try:
|
2022-02-10 00:00:30 +00:00
|
|
|
y[date] = days[date][i]["time"]
|
|
|
|
text[date] = days[date][i]["label"]
|
2020-12-03 04:15:22 +00:00
|
|
|
except IndexError:
|
|
|
|
y[date] = None
|
|
|
|
text[date] = None
|
|
|
|
i += 1
|
2022-02-10 00:00:30 +00:00
|
|
|
traces.append(
|
|
|
|
go.Bar(
|
|
|
|
x=dates,
|
|
|
|
y=list(y.values()),
|
|
|
|
hovertext=list(text.values()),
|
|
|
|
# `hoverinfo` is deprecated but if we use the new `hovertemplate`
|
|
|
|
# the "filler" areas for awake time get a hover that says "null"
|
|
|
|
# and there is no way to prevent this currently with Plotly.
|
|
|
|
hoverinfo="text",
|
|
|
|
marker={"color": color},
|
|
|
|
showlegend=False,
|
|
|
|
)
|
|
|
|
)
|
2021-10-30 13:20:41 +00:00
|
|
|
if color == AWAKE_COLOR:
|
|
|
|
color = ASLEEP_COLOR
|
2017-11-04 03:03:24 +00:00
|
|
|
else:
|
2021-10-30 13:20:41 +00:00
|
|
|
color = AWAKE_COLOR
|
2017-11-04 03:03:24 +00:00
|
|
|
|
|
|
|
layout_args = utils.default_graph_layout_options()
|
2022-02-10 00:00:30 +00:00
|
|
|
layout_args["margin"]["b"] = 100
|
2017-11-04 03:03:24 +00:00
|
|
|
|
2022-02-10 00:00:30 +00:00
|
|
|
layout_args["barmode"] = "stack"
|
|
|
|
layout_args["bargap"] = 0
|
|
|
|
layout_args["hovermode"] = "closest"
|
|
|
|
layout_args["title"] = _("<b>Sleep Pattern</b>")
|
|
|
|
layout_args["height"] = 800
|
2017-11-04 03:03:24 +00:00
|
|
|
|
2022-02-10 00:00:30 +00:00
|
|
|
layout_args["xaxis"]["title"] = _("Date")
|
|
|
|
layout_args["xaxis"]["tickangle"] = -65
|
|
|
|
layout_args["xaxis"]["tickformat"] = "%b %e\n%Y"
|
|
|
|
layout_args["xaxis"]["ticklabelmode"] = "period"
|
|
|
|
layout_args["xaxis"]["rangeselector"] = utils.rangeselector_date()
|
2017-11-04 03:03:24 +00:00
|
|
|
|
2022-02-10 00:00:30 +00:00
|
|
|
start = timezone.localtime().strptime("12:00 AM", "%I:%M %p")
|
2017-11-04 03:03:24 +00:00
|
|
|
ticks = OrderedDict()
|
2022-02-10 00:00:30 +00:00
|
|
|
ticks[0] = start.strftime("%I:%M %p")
|
|
|
|
for i in range(0, 60 * 24, 30):
|
|
|
|
ticks[i] = formats.time_format(
|
|
|
|
start + timezone.timedelta(minutes=i), "TIME_FORMAT"
|
|
|
|
)
|
|
|
|
|
|
|
|
layout_args["yaxis"]["title"] = _("Time of day")
|
|
|
|
layout_args["yaxis"]["range"] = [24 * 60, 0]
|
|
|
|
layout_args["yaxis"]["tickmode"] = "array"
|
|
|
|
layout_args["yaxis"]["tickvals"] = list(ticks.keys())
|
|
|
|
layout_args["yaxis"]["ticktext"] = list(ticks.values())
|
|
|
|
layout_args["yaxis"]["tickfont"] = {"size": 10}
|
|
|
|
|
|
|
|
fig = go.Figure({"data": traces, "layout": go.Layout(**layout_args)})
|
|
|
|
output = plotly.plot(fig, output_type="div", include_plotlyjs=False)
|
2017-11-04 03:03:24 +00:00
|
|
|
return utils.split_graph_output(output)
|
|
|
|
|
|
|
|
|
2021-12-31 15:17:21 +00:00
|
|
|
def _init_days(first_day, last_day):
|
|
|
|
period = (last_day.date() - first_day.date()).days + 1
|
2022-02-10 00:00:30 +00:00
|
|
|
|
|
|
|
def new_day(d):
|
|
|
|
return (first_day + timedelta(days=d)).date().isoformat()
|
|
|
|
|
2021-12-31 15:17:21 +00:00
|
|
|
return {new_day(day): [] for day in range(period)}
|
|
|
|
|
|
|
|
|
2021-10-30 13:29:21 +00:00
|
|
|
def _add_adjustment(adjustment, days):
|
2021-08-28 03:06:18 +00:00
|
|
|
"""
|
|
|
|
Adds "adjustment" data for entries that cross midnight.
|
|
|
|
:param adjustment: Column, start time, end time, and duration of entry.
|
2021-10-30 13:29:21 +00:00
|
|
|
:param blocks: List of days
|
2021-08-28 03:06:18 +00:00
|
|
|
"""
|
2022-02-10 00:00:30 +00:00
|
|
|
column = adjustment.pop("column")
|
2022-04-18 03:03:46 +00:00
|
|
|
if not column in days:
|
|
|
|
days[column] = []
|
2021-08-28 03:06:18 +00:00
|
|
|
# Fake (0) entry to keep the color switching logic working.
|
2022-02-10 00:00:30 +00:00
|
|
|
days[column].append({"time": 0, "label": 0})
|
2021-08-28 03:06:18 +00:00
|
|
|
|
|
|
|
# Real adjustment entry.
|
2022-02-10 00:00:30 +00:00
|
|
|
days[column].append(
|
|
|
|
{
|
|
|
|
"time": adjustment["duration"].seconds / 60,
|
|
|
|
"label": _format_label(**adjustment),
|
|
|
|
}
|
|
|
|
)
|
2021-08-28 03:06:18 +00:00
|
|
|
|
|
|
|
|
2020-12-03 04:15:22 +00:00
|
|
|
def _format_label(duration, start_time, end_time):
|
2017-11-04 03:03:24 +00:00
|
|
|
"""
|
2020-12-03 04:15:22 +00:00
|
|
|
Formats a time block label.
|
|
|
|
:param duration: Duration.
|
|
|
|
:param start_time: Start time.
|
|
|
|
:param end_time: End time.
|
|
|
|
:return: Formatted string with duration, start, and end time.
|
2017-11-04 03:03:24 +00:00
|
|
|
"""
|
2022-02-10 00:00:30 +00:00
|
|
|
return "Asleep {} ({} to {})".format(
|
|
|
|
duration_string(duration),
|
|
|
|
formats.time_format(start_time, "TIME_FORMAT"),
|
|
|
|
formats.time_format(end_time, "TIME_FORMAT"),
|
|
|
|
)
|