nightr/server/nightr/strategies/tide_strat.py

86 lines
3.2 KiB
Python

import calendar
from datetime import datetime, timedelta
import json
import requests
from .strat_utils import determine_month
from ..util import Context, Prediction
def is_tide(context: Context) -> Prediction:
"""
Determine whether or not it is night in Aarhus based on the current water level and which month we are in, based
on number of cars driving across The Storbæltsbro.
"""
p = Prediction()
month, cur_year_total_cars, last_year_total_cars = determine_month()
month = int(month)
p.reasons.append(f"The number of cars having driven on the Storbæltsbro is {cur_year_total_cars}, in the current year")
p.reasons.append(f"The number of cars having driven over it in the last year is {last_year_total_cars}, thus the frequency is: {last_year_total_cars / cur_year_total_cars:.2f}")
p.reasons.append(f"The month is therefore {calendar.month_name[month]}")
tide_data = requests.get('https://www.dmi.dk/fileadmin/user_upload/Bruger_upload/Tidevand/2019/Aarhus.t.txt')
lines = tide_data.text[570:].split('\n')
tuples = [x.split('\t') for x in lines]
lel = [[datetime.strptime(x[0], '%Y%m%d%H%M'), x[1]] for x in tuples[:-1]]
matches = [[x[0], int(x[1])] for x in lel if x[0].month == month]
all_the_data = requests.get('https://www.dmi.dk/NinJo2DmiDk/ninjo2dmidk?cmd=odj&stations=22331&datatype=obs')
current_water_level = int(json.loads(all_the_data.content)[0]['values'][-1]['value'])
# Generate average of when the water is high
last_match = matches[0]
moments = []
for idx, water_level in enumerate(matches[1:]):
#print(last_match[1], water_level[1])
diff = abs(last_match[1]) + abs(water_level[1])
time_diff = (water_level[0] - last_match[0]).seconds
average_inc = time_diff/diff
average_delta = timedelta(seconds=average_inc)
if last_match[1] < 0 and last_match[1] <= current_water_level: # Increasing
time = last_match
while time[1] != current_water_level:
time[0] += average_delta
time[1] += 1
elif last_match[1] < 0 and last_match[1] >= current_water_level:
time = last_match
while time[1] != current_water_level:
time[0] += average_delta
time[1] -= 1
elif last_match[1] > 0 and last_match[1] >= current_water_level: # Decreasing
time = last_match
while time[1] != current_water_level:
time[0] += average_delta
time[1] -= 1
elif last_match[1] > 0 and last_match[1] <= current_water_level:
time = last_match
while time[1] != current_water_level:
time[0] += average_delta
time[1] += 1
last_match = water_level
moments.append(time[0])
night = sum([1 for x in moments if 6 >= x.hour or x.hour >= 22])
p.reasons.append(f"The water level is currently at {current_water_level} in the Aarhus Bay")
p.reasons.append(f"The number of times the water is at the current level at nighttime is: {night}, compared to the total amount of times in {calendar.month_name[month]}, being {len(moments)}")
p.probability = 1 - (night / len(moments))
return p