-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsustainability.py
More file actions
390 lines (323 loc) · 12.3 KB
/
sustainability.py
File metadata and controls
390 lines (323 loc) · 12.3 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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
from enum import Enum
import logging
from fastapi import Query, HTTPException, APIRouter, Body
from dotenv import load_dotenv
from .Database_class import DataBase
router = APIRouter()
class VehicleEnum(Enum):
Bus = "bus"
Car = "car"
Luas = "luas"
Train = "train"
Bike = "bike"
Walk = "walk"
class Sustainability:
def __init__(self, api, logger: logging.Logger):
self.app = api
self.logger = logger
self.vehicle_types = ["bus", "car", "luas", "train", "bike", "walk"]
load_dotenv()
# Register Endpoints
self.api_get_sus_stats()
self.api_update_sus_stats()
def db_initialise_sustainability(self, username):
db = DataBase()
db.connect_db()
# Monthly distances table
current_month_distances_dict = {
"username": username,
"bike": 0,
"car": 0,
"luas": 0,
"train": 0,
"bus": 0,
"walk": 0,
"total": 0,
}
db.add_entry("monthly_distance", current_month_distances_dict)
self.logger.info("User entry added to current month distances")
# Current year emissions table
year_emissions_dict = {
"username": username,
"month_1": 0,
"month_2": 0,
"month_3": 0,
"month_4": 0,
"month_5": 0,
"month_6": 0,
"month_7": 0,
"month_8": 0,
"month_9": 0,
"month_10": 0,
"month_11": 0,
"month_12": 0,
}
db.add_entry("monthly_emissions_2025", year_emissions_dict)
self.logger.info("User entry added to monthly emissions table")
db.close_con()
def api_get_sus_stats(self):
@self.app.get("/get_sus_stats")
async def get_sus_stats(user: str = Query(..., alias="sender")):
self.logger.info(
f"Received request for sustainability statistics from {user}"
)
emissions_savings = self.db_fetch_month_sus_stats(user)
current_year_emissions = self.db_fetch_year_sus_stats(user)
raw_distances = self.db_fetch_raw_distances(user)
friends_sus_scores = self.db_get_friends_sust_scores(user)
self.logger.info(f"Emissions savings: {emissions_savings}")
self.logger.info(f"Year emissions: {current_year_emissions}")
self.logger.info(f"Raw distances: {raw_distances}")
self.logger.info(
f"Sustainability scores of friends: {friends_sus_scores}"
)
if emissions_savings is None or current_year_emissions is None:
raise HTTPException(
status_code=404, detail=f"User '{user}' not found"
)
self.logger.info("Sustainability stats retrieved")
# Return emissions_savings as JSON
return {
"emissions_savings": emissions_savings,
"current_year_emissions": current_year_emissions,
"raw_distances": raw_distances,
"friends_sus_scores": friends_sus_scores,
}
def api_update_sus_stats(self):
@self.app.post("/update_sus_stats")
async def update_sus_stats(
username: str = Body(...),
flag: bool = Body(...),
modeDistances: dict = Body(...),
):
journeyData = {
"bike": modeDistances["BICYCLING"],
"car": modeDistances["DRIVING"],
"luas": modeDistances["Tram"],
"train": modeDistances["Train"],
"bus": modeDistances["Bus"],
"walk": modeDistances["WALKING"],
}
if flag:
self.db_update_monthly_distances(username, journeyData)
self.logger.info("Monthly distances updated")
self.update_user_sus_score(username)
journeyData.pop("car", None)
return self.calc_scores_from_route(journeyData)
def db_fetch_month_sus_stats(self, user):
table_name = "monthly_distance"
db = DataBase()
db.connect_db()
if db.search_user(table_name, user):
monthly_distances = db.return_user_row(table_name, user)
db.close_con()
return self.calc_emissions_savings(monthly_distances)
else:
db.close_con()
return None
def db_fetch_year_sus_stats(self, user):
table_name = "monthly_emissions_2025"
db = DataBase()
db.connect_db()
# If user found
if db.search_user(table_name, user):
self.logger.info("Found user")
current_year_emissions = db.return_user_row(table_name, user)
current_year_emissions.pop(
"username", None
) # Remove the username key if it exists
self.logger.info("Current year emissions retrieved")
self.logger.info(
f"Current year emissions: {current_year_emissions}"
)
db.close_con()
return current_year_emissions
else:
db.close_con()
print("Year stats not found")
return None
def db_update_monthly_distances(self, user, journey_data):
table_name = "monthly_distance"
db = DataBase()
db.connect_db()
# If user found
if db.search_user(table_name, user):
self.logger.info("Found user")
for transport_mode in journey_data:
if transport_mode not in self.vehicle_types:
self.logger.error(
f"Invalid transport mode: {transport_mode}"
)
continue
# Get distance for each transport mode
raw_distances = db.return_user_row(table_name, user)
self.logger.info(f"Raw distances: {raw_distances}")
# Add new distances to the existing ones
journey_data[transport_mode] += raw_distances[transport_mode]
self.logger.info(
f"Updated distances: {journey_data[transport_mode]}"
)
# Update the database with new distances
db.update_entry(
table_name,
user,
transport_mode,
journey_data[transport_mode],
)
db.close_con()
return True
else:
db.close_con()
print("Monthly distances not found")
return False
def db_fetch_raw_distances(self, user):
table_name = "monthly_distance"
db = DataBase()
db.connect_db()
# If user found
if db.search_user(table_name, user):
self.logger.info("Found user")
monthly_distances = db.return_user_row(table_name, user)
self.logger.info(f"monthly distances: {monthly_distances}")
db.close_con()
return monthly_distances
else:
db.close_con()
print("Year stats not found")
return None
def db_fetch_all_sust_friends(self, user):
table_name = "user_table"
db = DataBase()
db.connect_db()
friends_list = db.search_entry(table_name, user, "friends_list")
db.close_con()
return friends_list
def db_get_friends_sust_scores(self, user):
table_name = "user_table"
db = DataBase()
db.connect_db()
friends_list = self.db_fetch_all_sust_friends(user)
if isinstance(friends_list, tuple):
friends_list = list(friends_list)
# Check for no friends
if not friends_list: # This handles both None and empty lists
self.logger.info(f"Friends list empty for: {user}")
friends_list = [
user
] # Create a list with the user as the only entry
else:
friends_list.append(user) # Append the user to the existing list
friend_scores = {}
for friend in friends_list:
query = f"SELECT sus_score FROM {table_name} WHERE username = '{friend}';" # noqa: E501
cursor = db.connection.cursor()
try:
cursor.execute(query)
result = cursor.fetchone()
if result:
friend_scores[friend] = result[0]
else:
friend_scores[friend] = None
except Exception as e:
self.logger.error(
f"Error fetching sustainability score for {friend}: {e}"
)
friend_scores[friend] = None
finally:
cursor.close()
db.close_con()
return friend_scores
def calc_emissions(self, distance: float, vehicle_type: str) -> float:
"""
EF = E/A # EF => E = A * EF = emmisiions factor, E = total emissions,
A = activity level (km travelled)
Args:
distance (float): distance travelled by vehicle in question
vehicle_type (VehicleEnum): type of vehicle in question
Returns:
float: g of CO2 emitted
"""
emission_factor = 0
if distance < 0:
return -1
elif vehicle_type == "bus":
emission_factor = 25
elif vehicle_type == "car":
emission_factor = 102
elif vehicle_type == "luas":
emission_factor = 5
elif vehicle_type == "train":
emission_factor = 28
elif vehicle_type == "bike":
emission_factor = 0
elif vehicle_type == "walk":
emission_factor = 0
else:
return -1
emissions = distance * emission_factor
return emissions
def calc_scores(self, emissions_difference: float) -> float:
if emissions_difference < 0:
return -1
return round(emissions_difference / 1000, 2)
def calc_scores_from_route(self, journey_data):
calc_emissions_savings = self.calc_emissions_savings(journey_data)
transport_score = 0
for transport_mode in journey_data:
if transport_mode not in self.vehicle_types:
self.logger.error(
f"Invalid transport mode: {transport_mode}"
)
continue
transport_score += self.calc_scores(
calc_emissions_savings[transport_mode]
)
return transport_score
def update_user_sus_score(self, user: str) -> float:
db = DataBase()
db.connect_db()
monthly_data = db.return_user_row("monthly_distance", user)
if not monthly_data:
self.logger.warning(f"No monthly distance data found for {user}")
db.close_con()
return 0
emissions_savings = self.calc_emissions_savings(monthly_data)
total_score = 0
for mode in emissions_savings:
total_score += self.calc_scores(emissions_savings[mode])
db.update_entry("user_table", user, "sus_score", total_score)
self.logger.info(
f"Updated sustainability score for {user}: {total_score}"
)
db.close_con()
return total_score
def calc_emissions_savings(self, monthly_distances):
emissions_dif = {
"bike": 0,
"luas": 0,
"train": 0,
"bus": 0,
"walk": 0,
}
for vehicle_type in self.vehicle_types:
if (
vehicle_type == "car"
or vehicle_type == "total"
or vehicle_type == "username"
):
continue
if vehicle_type not in monthly_distances:
self.logger.error(
f"Key '{vehicle_type}' not found in monthly_distances"
)
continue
# self.logger.log(msg=f"current vehicle type: {vehicle_type}")
print(f"current vehicle type: {vehicle_type}")
car_emissions = self.calc_emissions(
monthly_distances[vehicle_type], "car"
)
transport_emissions = self.calc_emissions(
monthly_distances[vehicle_type], vehicle_type
)
emissions_dif[vehicle_type] = car_emissions - transport_emissions
return emissions_dif