Algorithmically Scoring Your Sleep.

Recently I ran into a problem my digital personal assistant PAL couldn’t wrap his head around. I had slept 5.5 hours, but my deep sleep was off the charts, and I felt very well rested. When I woke up, PAL had the nerve to tell me that I had a poor night’s sleep although this was far from the truth. I knew that there was a better way, and I set out to find that. The four most important data points I could think of (and that I already have collected) were: total time in bed, total time sleeping, total time in deep sleep, and resting heart rate during the night. With all of these things, too little can be harmful, but if one factor is too little, but the others are higher than normal, it can balance out.

I had to decide upon a scoring system and decided to go with a score of 1 to 100 due to our cultural infatuation with base 10. I’ll likely move to a logarithmic interval soon but decided this was good enough to start with.

With the goal of having a score of 50 be normal sleep, I decided to start out by assigning the variable that holds the score a value of 50. Then the algorithm would recursively go over each of the data points, adding or subtracting based on their deviation.

def sleepScoreCalc(duration, actualSleep, restfulSleep, restingHr):  
# Score range 0 to 100
# score 70 is exceptional
score = 50
score += 0.25 * (actualSleep - (6.6 * 60))
score -= 1 * (actualSleep/restfulSleep) - 0.9
score -= 5 * (restingHr - 50)
return score

There is nothing fancy about the algorithm, but it didn’t need to be complex. The only requirement was to accurately detect if my sleep was truly bad, good, or exceptional. With all the test cases it performed admirably, and my sleep this past night had a score of 63.65, which lined up perfectly with how I was feeling and my general assessment of my sleep data. And the neat thing is that one can’t figure out any of my sleep data from the score because there are so many ways to reach the same value.

I hope to write similar algorithms to analyze my runs, bikes, steps taken during a day (total, hourly distribution, heart rate impact), etc. And it would also be great to add in even more variables, which I plan to do soon, as well as some more advanced math.

Source: Noah Codes