-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
202 lines (167 loc) · 7.33 KB
/
Copy pathmain.py
File metadata and controls
202 lines (167 loc) · 7.33 KB
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
import json
import requests
import time
import argparse
from typing import Optional
from geo import Table
from geo import createGeoJSON
# class Table:
# cellSize = 0
# ncols = 0
# nrows = 0
# @staticmethod
# def fromCityIO(data):
# print("data", data)
# ret = Table()
# ret.cellSize = data["spatial"]["cellSize"]
# ret.ncols = data["spatial"]["ncols"]
# ret.nrows = data["spatial"]["nrows"]
# ret.mapping = data["mapping"]["type"]
# ret.typeidx = data["block"].index("type")
# return ret
def getFromCfg(key: str) -> str:
# import os#os.path.dirname(os.path.realpath(__file__)+
with open("config.json") as file:
js = json.load(file)
return js[key]
def getCurrentState(topic="", endpoint=-1, token=None):
if endpoint == -1 or endpoint == None:
get_address = getFromCfg("input_url") + topic
else:
get_address = getFromCfg("input_urls")[endpoint] + topic
try:
if token is None:
r = requests.get(get_address, headers={'Content-Type': 'application/json'})
else:
r = requests.get(get_address, headers={'Content-Type': 'application/json',
'Authorization': 'Bearer {}'.format(token).rstrip()})
if not r.status_code == 200:
print("could not get from cityIO")
print("Error code", r.status_code)
return {}
return r.json()
except requests.exceptions.RequestException as e:
print("CityIO error while GETting!" + str(e))
return {}
def sendToCityIO(data, endpoint=-1, token=None):
if endpoint == -1 or endpoint == None:
post_address = getFromCfg("output_url")
else:
post_address = getFromCfg("output_urls")[endpoint]
try:
if token is None:
r = requests.post(post_address, json=data, headers={'Content-Type': 'application/json'})
else:
r = requests.post(post_address, json=data,
headers={'Content-Type': 'application/json',
'Authorization': 'Bearer {}'.format(token).rstrip()})
print(r)
if not r.status_code == 200:
print("could not post result to cityIO", post_address)
print("Error code", r.status_code)
else:
print("Successfully posted to cityIO", post_address, r.status_code)
except requests.exceptions.RequestException as e:
print("CityIO error while POSTing!" + str(e))
return
def run(endpoint=-1, token=None):
gridDef = Table.fromCityIO(getCurrentState("header", endpoint, token))
if not gridDef:
print("couldn't load input_url!")
exit()
gridData = getCurrentState("grid", endpoint, token)
gridHash = getCurrentState("meta/hashes/grid", endpoint, token)
# dictionary of type(/openspace_type) : [["grey","white"], [0,1]], i.e. first index, wether it creates grey or white water, second index, drainage coefficient
coefficients = {}
with open("drainagecoefficients.json") as file:
coefficients = json.load(file)
expectedRain = getFromCfg("expectedAnnualRain") # in m³/m²a
numWhiteCells = 0
numGreyCells = 0
numUnknownCells = 0
numStreetCells = 0
numBuildingCells = 0
numOpenCells = 0
specificVolumes = {}
filledGrid = []
for cell in gridData:
if (cell is None or not "type" in gridDef.mapping[cell[gridDef.typeidx]]):
filledGrid.append({})
continue
curtype = gridDef.mapping[cell[gridDef.typeidx]]["type"]
if curtype == "street":
# handle promenade
if gridDef.mapping[cell[gridDef.typeidx]]["str_numLanes"] == 0:
curtype = "promenade"
if curtype == "open_space":
if gridDef.mapping[cell[gridDef.typeidx]]["os_type"] is None:
numUnknownCells += 1
print(curtype, "unknown")
filledGrid.append({})
continue
curtype += "/" + gridDef.mapping[cell[gridDef.typeidx]]["os_type"]
if not curtype in coefficients:
numUnknownCells += 1
print(curtype, "unknown")
filledGrid.append({})
continue
if curtype in specificVolumes:
specificVolumes[curtype] += coefficients[curtype][1]
else:
specificVolumes[curtype] = coefficients[curtype][1]
if coefficients[curtype][0] == "white":
numWhiteCells += coefficients[curtype][1]
elif coefficients[curtype][0] == "grey":
numGreyCells += coefficients[curtype][1]
elif coefficients[curtype][0] == "street":
numStreetCells += coefficients[curtype][1]
elif coefficients[curtype][0] == "building":
numBuildingCells += coefficients[curtype][1]
elif coefficients[curtype][0] == "open":
numOpenCells += coefficients[curtype][1]
else:
numUnknownCells += 1
filledGrid.append({})
# print(curtype, "unknown")
continue
filledGrid.append({"type":curtype, "amount": (coefficients[curtype][1] * gridDef.cellSize * gridDef.cellSize * expectedRain) } )
whitewater_m3 = int(numWhiteCells * gridDef.cellSize * gridDef.cellSize * expectedRain)
graywater_m3 = int(numGreyCells * gridDef.cellSize * gridDef.cellSize * expectedRain)
unknown_m3 = int(numUnknownCells * gridDef.cellSize * gridDef.cellSize * expectedRain)
streetwater_m3 = int(numStreetCells * gridDef.cellSize * gridDef.cellSize * expectedRain)
buildingwater_m3 = int(numBuildingCells * gridDef.cellSize * gridDef.cellSize * expectedRain)
open_m3 = int(numOpenCells * gridDef.cellSize * gridDef.cellSize * expectedRain)
for key in specificVolumes:
specificVolumes[key] = int(specificVolumes[key] * gridDef.cellSize * gridDef.cellSize * expectedRain)
# print("m³ white water to be handled: ", whitewater_m3)
# print("m³ grey water to be handled: ", graywater_m3)
# print("m³ unknown water to be handled: ", unknown_m3)
data = {"unit": "cubic meters per annum", "white": whitewater_m3, "grey": graywater_m3, "unknown": unknown_m3,
"street_total": streetwater_m3, "building_total": buildingwater_m3, "open_total": open_m3,
"grid_hash": gridHash}
data.update(specificVolumes)
geojsonstring = createGeoJSON(filledGrid, gridDef)
# print(geojsonstring)
data["geojson"] = json.loads(geojsonstring)
# print(data)
sendToCityIO(data, endpoint, token)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='calculate storm water amounts from cityIO.')
parser.add_argument('--endpoint', type=int, default=-1, help="endpoint url to choose from config.ini/input_urls")
args = parser.parse_args()
print("endpoint", args.endpoint)
try:
with open("token.txt") as f:
token = f.readline()
if token == "": token = None # happens with empty file
except IOError:
token = None
oldHash = ""
while True:
gridHash = getCurrentState("meta/hashes/grid", int(args.endpoint), token)
if gridHash != {} and gridHash != oldHash:
run(int(args.endpoint), token)
oldHash = gridHash
else:
print("waiting for grid change")
time.sleep(5)