-
Notifications
You must be signed in to change notification settings - Fork 902
/
BR.py
207 lines (162 loc) · 5.6 KB
/
BR.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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
from collections import defaultdict
from datetime import datetime
from logging import Logger, getLogger
from typing import Any, Dict, Optional, Union
import arrow
from requests import Session
from .lib.validation import validate
URL = "http://tr.ons.org.br/Content/GetBalancoEnergetico/null"
SOURCE = "ons.org.br"
GENERATION_MAPPING = {
"nuclear": "nuclear",
"eolica": "wind",
"termica": "unknown",
"solar": "solar",
"hydro": "hydro",
}
REGIONS = {
"BR-NE": "nordeste",
"BR-N": "norte",
"BR-CS": "sudesteECentroOeste",
"BR-S": "sul",
}
REGION_EXCHANGES = {
"BR-CS->BR-S": "sul_sudeste",
"BR-CS->BR-NE": "sudeste_nordeste",
"BR-CS->BR-N": "sudeste_norteFic",
"BR-N->BR-NE": "norteFic_nordeste",
}
REGION_EXCHANGES_DIRECTIONS = {
"BR-CS->BR-S": -1,
"BR-CS->BR-NE": 1,
"BR-CS->BR-N": 1,
"BR-N->BR-NE": 1,
}
COUNTRIES_EXCHANGE = {
"UY": {"name": "uruguai", "flow": 1},
"AR": {"name": "argentina", "flow": -1},
"PY": {"name": "paraguai", "flow": -1},
}
def get_data(session: Optional[Session]):
"""Requests generation data in json format."""
s = session or Session()
json_data = s.get(URL).json()
return json_data
def production_processor(json_data, zone_key: str) -> tuple:
"""Extracts data timestamp and sums regional data into totals by key."""
dt = arrow.get(json_data["Data"])
totals = defaultdict(lambda: 0.0)
region = REGIONS[zone_key]
breakdown = json_data[region]["geracao"]
for generation, val in breakdown.items():
totals[generation] += val
# BR_CS contains the Itaipu Dam.
# We merge the hydro keys into one, then remove unnecessary keys.
totals["hydro"] = (
totals.get("hidraulica", 0.0)
+ totals.get("itaipu50HzBrasil", 0.0)
+ totals.get("itaipu60Hz", 0.0)
)
entries_to_remove = {"hidraulica", "itaipu50HzBrasil", "itaipu60Hz", "total"}
mapped_totals = {
GENERATION_MAPPING.get(name, "unknown"): val
for name, val in totals.items()
if name not in entries_to_remove
}
return dt, mapped_totals
def fetch_production(
zone_key: str,
session: Optional[Session] = None,
target_datetime: Optional[datetime] = None,
logger: Logger = getLogger(__name__),
) -> Dict[str, Any]:
"""Requests the last known production mix (in MW) of a given country."""
if target_datetime:
raise NotImplementedError("This parser is not yet able to parse past dates")
data = get_data(session)
timestamp, production = production_processor(data, zone_key)
datapoint = {
"zoneKey": zone_key,
"datetime": timestamp.datetime,
"production": production,
"storage": {
"hydro": None,
},
"source": SOURCE,
}
datapoint = validate(
datapoint, logger, remove_negative=True, required=["hydro"], floor=1000
)
return datapoint
def fetch_exchange(
zone_key1: str,
zone_key2: str,
session: Optional[Session] = None,
target_datetime: Optional[datetime] = None,
logger: Logger = getLogger(__name__),
) -> dict:
"""Requests the last known power exchange (in MW) between two regions."""
if target_datetime:
raise NotImplementedError("This parser is not yet able to parse past dates")
data = get_data(session)
dt = arrow.get(data["Data"]).datetime
sorted_zone_keys = "->".join(sorted([zone_key1, zone_key2]))
country_exchange = COUNTRIES_EXCHANGE.get(zone_key1) or COUNTRIES_EXCHANGE.get(
zone_key2
)
net_flow: Union[float, None] = None
if country_exchange:
net_flow = (
data["internacional"][country_exchange["name"]] * country_exchange["flow"]
)
return {
"datetime": dt,
"sortedZoneKeys": sorted_zone_keys,
"netFlow": net_flow,
"source": SOURCE,
}
def fetch_region_exchange(
zone_key1: str,
zone_key2: str,
session: Optional[Session] = None,
target_datetime: Optional[datetime] = None,
logger: Logger = getLogger(__name__),
) -> dict:
"""Requests the last known power exchange (in MW) between two Brazilian regions."""
if target_datetime:
raise NotImplementedError("This parser is not yet able to parse past dates")
data = get_data(session)
dt = arrow.get(data["Data"]).datetime
sorted_regions = "->".join(sorted([zone_key1, zone_key2]))
exchange = REGION_EXCHANGES[sorted_regions]
net_flow = (
data["intercambio"][exchange] * REGION_EXCHANGES_DIRECTIONS[sorted_regions]
)
return {
"datetime": dt,
"sortedZoneKeys": sorted_regions,
"netFlow": net_flow,
"source": SOURCE,
}
if __name__ == "__main__":
"""Main method, never used by the Electricity Map backend, but handy for testing."""
print("fetch_production(BR-NE) ->")
print(fetch_production("BR-NE"))
print("fetch_production(BR-N) ->")
print(fetch_production("BR-N"))
print("fetch_production(BR-CS) ->")
print(fetch_production("BR-CS"))
print("fetch_production(BR-S) ->")
print(fetch_production("BR-S"))
print("fetch_exchange(BR-S, UY) ->")
print(fetch_exchange("BR-S", "UY"))
print("fetch_exchange(BR-S, AR) ->")
print(fetch_exchange("BR-S", "AR"))
print("fetch_region_exchange(BR-CS->BR-S)")
print(fetch_region_exchange("BR-CS", "BR-S"))
print("fetch_region_exchange(BR-CS->BR-NE)")
print(fetch_region_exchange("BR-CS", "BR-NE"))
print("fetch_region_exchange(BR-CS->BR-N)")
print(fetch_region_exchange("BR-CS", "BR-N"))
print("fetch_region_exchange(BR-N->BR-NE)")
print(fetch_region_exchange("BR-N", "BR-NE"))