/
weather.py
173 lines (135 loc) · 5.72 KB
/
weather.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
from typing import Dict, Tuple
import math
import timely_beliefs as tb
from sqlalchemy.orm import Query
from sqlalchemy.ext.hybrid import hybrid_method, hybrid_property
from sqlalchemy.sql.expression import func
from sqlalchemy.schema import UniqueConstraint
from flexmeasures.data.config import db
from flexmeasures.data.models.time_series import TimedValue
from flexmeasures.utils.geo_utils import parse_lat_lng
from flexmeasures.utils.flexmeasures_inflection import humanize
class WeatherSensorType(db.Model):
""" "
TODO: Add useful attributes like ...?
"""
name = db.Column(db.String(80), primary_key=True)
display_name = db.Column(db.String(80), default="", unique=True)
daily_seasonality = True
weekly_seasonality = False
yearly_seasonality = True
def __init__(self, **kwargs):
super(WeatherSensorType, self).__init__(**kwargs)
self.name = self.name.replace(" ", "_").lower()
if "display_name" not in kwargs:
self.display_name = humanize(self.name)
def __repr__(self):
return "<WeatherSensorType %r>" % self.name
class WeatherSensor(db.Model, tb.SensorDBMixin):
"""A weather sensor has a location on Earth and measures weather values of a certain weather sensor type, such as
temperature, wind speed and radiation."""
name = db.Column(db.String(80), unique=True)
display_name = db.Column(db.String(80), default="", unique=False)
weather_sensor_type_name = db.Column(
db.String(80), db.ForeignKey("weather_sensor_type.name"), nullable=False
)
# latitude is the North/South coordinate
latitude = db.Column(db.Float, nullable=False)
# longitude is the East/West coordinate
longitude = db.Column(db.Float, nullable=False)
# only one sensor of any type is needed at one location
__table_args__ = (
UniqueConstraint(
"weather_sensor_type_name",
"latitude",
"longitude",
name="weather_sensor_type_name_latitude_longitude_key",
),
)
def __init__(self, **kwargs):
super(WeatherSensor, self).__init__(**kwargs)
self.name = self.name.replace(" ", "_").lower()
@property
def weather_unit(self) -> float:
"""Return the 'unit' property of the generic asset, just with a more insightful name."""
return self.unit
@property
def location(self) -> Tuple[float, float]:
return self.latitude, self.longitude
@hybrid_property
def cos_rad_lat(self):
return math.cos(math.radians(self.latitude))
@hybrid_property
def sin_rad_lat(self):
return math.sin(math.radians(self.latitude))
@hybrid_property
def rad_lng(self):
return math.radians(self.longitude)
@hybrid_method
def great_circle_distance(self, **kwargs):
"""Query great circle distance (in km).
Can be called with an object that has latitude and longitude properties, for example:
great_circle_distance(object=asset)
Can also be called with latitude and longitude parameters, for example:
great_circle_distance(latitude=32, longitude=54)
great_circle_distance(lat=32, lng=54)
"""
r = 6371 # Radius of Earth in kilometers
other_latitude, other_longitude = parse_lat_lng(kwargs)
if other_latitude is None or other_longitude is None:
return None
other_cos_rad_lat = math.cos(math.radians(other_latitude))
other_sin_rad_lat = math.sin(math.radians(other_latitude))
other_rad_lng = math.radians(other_longitude)
return (
math.acos(
self.cos_rad_lat
* other_cos_rad_lat
* math.cos(self.rad_lng - other_rad_lng)
+ self.sin_rad_lat * other_sin_rad_lat
)
* r
)
@great_circle_distance.expression
def great_circle_distance(self, **kwargs):
"""Query great circle distance (unclear if in km or in miles).
Can be called with an object that has latitude and longitude properties, for example:
great_circle_distance(object=asset)
Can also be called with latitude and longitude parameters, for example:
great_circle_distance(latitude=32, longitude=54)
great_circle_distance(lat=32, lng=54)
"""
other_latitude, other_longitude = parse_lat_lng(kwargs)
if other_latitude is None or other_longitude is None:
return None
return func.earth_distance(
func.ll_to_earth(self.latitude, self.longitude),
func.ll_to_earth(other_latitude, other_longitude),
)
sensor_type = db.relationship(
"WeatherSensorType", backref=db.backref("sensors", lazy=True)
)
def __repr__(self):
return "<WeatherSensor %s:%r (%r), res.:%s>" % (
self.id,
self.name,
self.weather_sensor_type_name,
self.event_resolution,
)
def to_dict(self) -> Dict[str, str]:
return dict(name=self.name, sensor_type=self.weather_sensor_type_name)
class Weather(TimedValue, db.Model):
"""
All weather measurements are stored in one slim table.
TODO: datetime objects take up most of the space (12 bytes each)). One way out is to normalise them out to a table.
"""
sensor_id = db.Column(
db.Integer(), db.ForeignKey("weather_sensor.id"), primary_key=True, index=True
)
sensor = db.relationship("WeatherSensor", backref=db.backref("weather", lazy=True))
@classmethod
def make_query(cls, **kwargs) -> Query:
"""Construct the database query."""
return super().make_query(asset_class=WeatherSensor, **kwargs)
def __init__(self, **kwargs):
super(Weather, self).__init__(**kwargs)