dmarr commited on
Commit
4162c33
·
1 Parent(s): a14e226
Files changed (1) hide show
  1. app_all.py +725 -0
app_all.py ADDED
@@ -0,0 +1,725 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import requests
3
+ import pandas as pd
4
+ import json
5
+ import io
6
+ import datetime
7
+ import pandas as pd
8
+ import numpy as np
9
+ import requests
10
+ import base64
11
+ import json
12
+ from calendar import monthrange
13
+ import pymongo
14
+ from mongoengine import StringField, ListField, DateTimeField, DictField
15
+ import matplotlib.pyplot as plt
16
+ from matplotlib.dates import MonthLocator
17
+
18
+
19
+
20
+ def mongo_unavs_call(user_input_start_date, user_input_end_date, user_input_past_date):
21
+ print("Starting mongo_unavs_call")
22
+ # Connect to the MongoDB database
23
+ user = "dmarroquin"
24
+ passw = "tN9XpCCQM2MtYDme"
25
+ host = "nucmonitordata.xxcwx9k.mongodb.net"
26
+ client = pymongo.MongoClient(
27
+ f"mongodb+srv://{user}:{passw}@{host}/?retryWrites=true&w=majority&connectTimeoutMS=5000"
28
+ )
29
+
30
+ db = client["data"]
31
+ collection_past_unavs = db["unavs"]
32
+ collection_unavs =db["unavs_update"]
33
+
34
+ start_date = f"{user_input_start_date}T00:00:00"
35
+ end_date = f"{user_input_end_date}T23:59:59"
36
+ past_date = f"{user_input_past_date}T23:59:59"
37
+
38
+ pipeline = [
39
+ {
40
+ "$unwind": "$results"
41
+ },
42
+ {
43
+ "$unwind": "$results.generation_unavailabilities"
44
+ },
45
+ {
46
+ "$match": {
47
+ "results.generation_unavailabilities.production_type": "NUCLEAR",
48
+ # "results.generation_unavailabilities.start_date": {"$lte": end_date},
49
+ # "results.generation_unavailabilities.end_date": {"$gte": start_date},
50
+ # "results.generation_unavailabilities.updated_date": {"$lte": end_date}
51
+ "results.generation_unavailabilities.updated_date": {"$lte": past_date}
52
+ }
53
+ },
54
+ {
55
+ "$project": {
56
+ "_id": 0,
57
+ "generation_unavailabilities": "$results.generation_unavailabilities"
58
+ }
59
+ }
60
+ ]
61
+
62
+ result1 = list(collection_past_unavs.aggregate(pipeline))
63
+ result2 = list(collection_unavs.aggregate(pipeline))
64
+
65
+ # Merge the two lists of JSON results
66
+ merged_result = result1 + result2
67
+
68
+ return merged_result
69
+
70
+ # --------------------------------------------------------------------------------------- #
71
+
72
+ # Convert the dictionary of dictionaries to JSON
73
+ def convert_to_json(item):
74
+ if isinstance(item, dict):
75
+ return {str(k): convert_to_json(v) for k, v in item.items()}
76
+ elif isinstance(item, list):
77
+ return [convert_to_json(i) for i in item]
78
+ elif isinstance(item, ObjectId):
79
+ return str(item)
80
+ else:
81
+ return item
82
+ # --------------------------------------------------------------------------------------- #
83
+
84
+ # Function gives the total of the data. When printed as dataframe/excel,
85
+ # Will give a final row with the total for each plant and the total overall
86
+ def add_total(data):
87
+ total_values = {}
88
+ for key in data:
89
+ daily_values = data[key]
90
+ total = sum(daily_values.values())
91
+ daily_values["Total"] = total
92
+ for date, value in daily_values.items():
93
+ if date not in total_values:
94
+ total_values[date] = value
95
+ else:
96
+ total_values[date] += value
97
+
98
+ data["Total"] = total_values
99
+
100
+ # --------------------------------------------------------------------------------------- #
101
+
102
+ def nuc_monitor(usr_start_date, usr_end_date, past_date, mongo_db_data):
103
+ # # Slightly changed metadata to fit the data from the RTE API: ST-LAURENT B 2 --> ST LAURENT 2, ....
104
+
105
+ plants_metadata = {"BELLEVILLE 1": 1310.0, "BELLEVILLE 2": 1310.0, "BLAYAIS 1": 910.0, "BLAYAIS 2": 910.0,
106
+ "BLAYAIS 3": 910.0, "BLAYAIS 4": 910.0, "BUGEY 2": 910.0, "BUGEY 3": 910.0, "BUGEY 4": 880.0,
107
+ "BUGEY 5": 880.0, "CATTENOM 1": 1300.0, "CATTENOM 2": 1300.0, "CATTENOM 3": 1300.0,
108
+ "CATTENOM 4": 1300.0, "CHINON 1": 905.0, "CHINON 2": 905.0, "CHINON 3": 905.0,
109
+ "CHINON 4": 905.0, "CHOOZ 1": 1500.0, "CHOOZ 2": 1500.0, "CIVAUX 1": 1495.0,
110
+ "CIVAUX 2": 1495.0, "CRUAS 1": 915.0, "CRUAS 2": 915.0, "CRUAS 3": 915.0, "CRUAS 4": 915.0,
111
+ "DAMPIERRE 1": 890.0, "DAMPIERRE 2": 890.0, "DAMPIERRE 3": 890.0, "DAMPIERRE 4": 890.0,
112
+ "FLAMANVILLE 1": 1330.0, "FLAMANVILLE 2": 1330.0, "GOLFECH 1": 1310.0, "GOLFECH 2": 1310.0,
113
+ "GRAVELINES 1": 910.0, "GRAVELINES 2": 910.0, "GRAVELINES 3": 910.0, "GRAVELINES 4": 910.0,
114
+ "GRAVELINES 5": 910.0, "GRAVELINES 6": 910.0, "NOGENT 1": 1310.0, "NOGENT 2": 1310.0,
115
+ "PALUEL 1": 1330.0, "PALUEL 2": 1330.0, "PALUEL 3": 1330.0, "PALUEL 4": 1330.0, "PENLY 1": 1330.0,
116
+ "PENLY 2": 1330.0, "ST ALBAN 1": 1335.0, "ST ALBAN 2": 1335.0, "ST LAURENT 1": 915.0,
117
+ "ST LAURENT 2": 915.0, "TRICASTIN 1": 915.0, "TRICASTIN 2": 915.0, "TRICASTIN 3": 915.0,
118
+ "TRICASTIN 4": 915.0, "FESSENHEIM 1": 880.0, "FESSENHEIM 2": 880.0}
119
+
120
+ # --------------------- INITIAL DATA CLEANING FOR MONGO DATA ------------------------ #
121
+
122
+ # # Create a DataFrame
123
+ # mongo_data = mongo_unavs_call(usr_start_date, usr_end_date, past_date)
124
+ # mongo_data = get_mongodb_data(usr_start_date, usr_end_date, past_date)
125
+ # print(mongo_db_data)
126
+ mongo_df = pd.DataFrame(mongo_db_data)
127
+
128
+ # print(mongo_df)
129
+ # Unpack the dictionaries into separate columns
130
+ mongo_df_unpacked = pd.json_normalize(mongo_df['generation_unavailabilities'])
131
+
132
+ # Concatenate the unpacked columns with the original DataFrame
133
+ mongo_df_result = pd.concat([mongo_df, mongo_df_unpacked], axis=1)
134
+
135
+ # Drop the original column
136
+ mongo_df_result.drop(columns=['generation_unavailabilities'], inplace=True)
137
+
138
+ mongo_df_result['start_date'] = mongo_df_result['values'].apply(lambda x: x[0]['start_date'])
139
+ mongo_df_result['end_date'] = mongo_df_result['values'].apply(lambda x: x[0]['end_date'])
140
+ mongo_df_result['available_capacity'] = mongo_df_result['values'].apply(lambda x: x[0]['available_capacity'])
141
+ mongo_df_result['unavailable_capacity'] = mongo_df_result['values'].apply(lambda x: x[0]['unavailable_capacity'])
142
+ # print(mongo_df_result)
143
+ # print(mongo_df_result.columns)
144
+ # Drop the original 'values' column
145
+ mongo_df_result.drop('values', axis=1, inplace=True)
146
+ mongo_df2 = mongo_df_result
147
+ mongo_df2.rename(columns=lambda col: col.replace('unit.', ''), inplace=True)
148
+
149
+ # --------------------- INITIAL DATA CLEANING FOR MONGO DATA ------------------------ #
150
+
151
+ # Make the two dataframes have the same columns
152
+ mongo_unavs = mongo_df2.copy()
153
+ mongo_unavs.drop(columns="type", inplace=True)
154
+
155
+ # merged_df['updated_date'] = merged_df['updated_date'].astype(str)
156
+
157
+ # --------------------------- HERE IS THE CHANGE TO GET ONLY ACTIVE OR ACTIVE AND INACTIVE --------------------------- #
158
+ # start_date_str = usr_start_date.strftime("%Y-%m-%d")
159
+ start_date_str = str(usr_start_date)
160
+ # end_date_str = usr_end_date.strftime("%Y-%m-%d")
161
+ end_date_str = str(usr_end_date)
162
+ current_datetime = datetime.datetime.now()
163
+ past_date_str = str(past_date.strftime("%Y-%m-%dT%H:%M:%S%z"))
164
+ current_datetime_str = current_datetime.strftime("%Y-%m-%d")
165
+
166
+ # nuclear_unav = mongo_unavs.copy()[(mongo_unavs.copy()["production_type"] == "NUCLEAR") & (mongo_unavs.copy()["updated_date"] <= past_date_str)]
167
+ # print(past_date_str)
168
+ # Sort by updated date
169
+ sorted_df = mongo_unavs.copy().sort_values(by='updated_date')
170
+
171
+ sorted_df = sorted_df.copy().reset_index(drop=True)
172
+
173
+ # cruas_2 = sorted_df.copy()[(sorted_df.copy()["name"] == "ST ALBAN 2") & (sorted_df.copy()["end_date"] >= start_date_str)]
174
+ # print(cruas_2[['updated_date', 'end_date', 'available_capacity']])
175
+
176
+ # Filter to get identifiers
177
+ filtered_id_df = sorted_df.copy()
178
+
179
+ # I commented this out
180
+ filtered_id_df = filtered_id_df.drop_duplicates(subset='identifier', keep='last')
181
+
182
+ # cruas_2 = filtered_id_df.copy()[(filtered_id_df.copy()["name"] == "ST ALBAN 2") & (filtered_id_df.copy()["end_date"] >= start_date_str)]
183
+ # print(cruas_2[['updated_date', 'end_date', 'available_capacity']])
184
+
185
+ filtered_id_df = filtered_id_df.copy().reset_index(drop=True)
186
+
187
+ filtered_df = filtered_id_df[
188
+ (filtered_id_df["production_type"] == "NUCLEAR") &
189
+ # (mongo_unavs["updated_date"] <= past_date_str) &
190
+ (filtered_id_df["status"] != "DISMISSED")]
191
+
192
+ # if photo_date == True:
193
+ # nuclear_unav = merged_df.copy()[(merged_df.copy()["production_type"] == "NUCLEAR") & (merged_df.copy()["updated_date"] <= past_date_str)]
194
+ # photo_date = True
195
+ # else: # need to add updated_date as a conditional to get the newest for that day
196
+ # nuclear_unav = merged_df.copy()[(merged_df.copy()["production_type"] == "NUCLEAR") & (merged_df.copy()["updated_date"] <= end_date_str)]
197
+
198
+ # --------------------------- HERE IS THE CHANGE TO GET ONLY ACTIVE OR ACTIVE AND INACTIVE --------------------------- #
199
+
200
+ # --------------------- SECOND DATA CLEANING ------------------------ #
201
+ # This filter should take only the most recent id and discard the rest
202
+
203
+
204
+
205
+ # This filter should take all the dates with unavs that include days with unavs in the range of the start and end date
206
+
207
+
208
+ # This filter might take out the most recent identifiers (Message ID) that change the dates of unavailability of a plant.
209
+ # This means that the actual unavailability is something else
210
+ # filtered_df = filtered_id_df.copy()[(filtered_id_df.copy()['start_date'] <= end_date_str) & (filtered_id_df.copy()['end_date'] >= start_date_str)]
211
+
212
+ # Need to eventually do a filter that takes the most restrictive updated identifier instead of the most recent when there
213
+ # is an overlap
214
+
215
+ # Update available_capacity where the condition is True
216
+
217
+ # Standardize datetime in dataframe
218
+ filtered_df2 = filtered_df.copy() # This code will just standardize datetime stuff
219
+ filtered_df2['creation_date'] = pd.to_datetime(filtered_df2['creation_date'], utc=True)
220
+ filtered_df2['updated_date'] = pd.to_datetime(filtered_df2['updated_date'], utc=True)
221
+ filtered_df2['start_date'] = pd.to_datetime(filtered_df2['start_date'], utc=True)
222
+ filtered_df2['end_date'] = pd.to_datetime(filtered_df2['end_date'], utc=True)
223
+
224
+ # Drop the duplicates
225
+ filtered_df3 = filtered_df2.copy().drop_duplicates()
226
+
227
+ # start_date_datetime = pd.to_datetime(start_date_str, utc=True) # Remove timezone info
228
+ start_date_datetime = pd.Timestamp(start_date_str, tz='UTC')
229
+ # end_date_datetime = pd.to_datetime(end_date_str, utc=True)
230
+ end_date_datetime = pd.Timestamp(end_date_str, tz='UTC')
231
+
232
+ # Turn df into dict for json processing
233
+ filtered_unavs = filtered_df3.copy().to_dict(orient='records')
234
+
235
+ results = {}
236
+
237
+ for unav in filtered_unavs:
238
+ plant_name = unav['name']
239
+ if plant_name in results:
240
+ # If the key is already in the dictionary, append unavailability to the list
241
+ results[plant_name].append({'status': unav['status'],
242
+ 'id': unav['message_id'],
243
+ 'creation_date': unav['creation_date'],
244
+ 'updated_date': unav['updated_date'],
245
+ 'start_date': unav['start_date'],
246
+ 'end_date': unav['end_date'],
247
+ 'available_capacity': unav['available_capacity']})
248
+ else:
249
+ # if the key of the plant is not there yet, create a new element of the dictionary
250
+
251
+ # Get message_id instead of identifier, easier to identify stuff with it
252
+ results[plant_name] = [{'status': unav['status'],
253
+ 'id': unav['message_id'],
254
+ 'creation_date': unav['creation_date'],
255
+ 'updated_date': unav['updated_date'],
256
+ 'start_date': unav['start_date'],
257
+ 'end_date': unav['end_date'],
258
+ 'available_capacity': unav['available_capacity']}]
259
+
260
+ # Custom encoder to handle datetime objects
261
+ class DateTimeEncoder(json.JSONEncoder):
262
+ def default(self, o):
263
+ if isinstance(o, datetime.datetime):
264
+ return o.isoformat()
265
+ return super().default(o)
266
+
267
+ results_holder = results
268
+
269
+ # Create new dict with each plant only having start_date less than user_end_date and an end_date greater than user_start_date
270
+ # should just be doing the same as above in the df for filtering only dates that inclued the start and end date
271
+ start_date = start_date_datetime.date()
272
+ end_date = end_date_datetime.date()
273
+ results_filtered = results_holder
274
+ for key, value in results_filtered.items():
275
+ filtered_values = []
276
+ for item in value:
277
+ item_start_date = item['start_date'].date()
278
+ item_end_date = item['end_date'].date()
279
+ identifier = item['id']
280
+ if item_start_date < end_date and item_end_date > start_date and identifier not in filtered_values:
281
+ filtered_values.append(item)
282
+ results_filtered[key] = filtered_values
283
+
284
+
285
+ sorted_results = results_filtered
286
+ # --------------------- SECOND DATA CLEANING ------------------------ #
287
+
288
+ # --------------------------- HERE IS THE FINAL PROCESS --------------------------- #
289
+
290
+ for key, value in sorted_results.items():
291
+ sorted_results[key] = sorted(value, key=lambda x: x['updated_date'])
292
+
293
+ results_sorted = sorted_results
294
+
295
+ dates_of_interest = [start_date] # We are creating a list of dates ranging from user specified start and end dates
296
+ date_plus_one = start_date
297
+
298
+ while date_plus_one < end_date:
299
+ date_plus_one = date_plus_one + datetime.timedelta(days=1)
300
+ dates_of_interest.append(date_plus_one)
301
+
302
+ # This is to standardize the datetimes. Without this, the datetime calculations for each power plant will not work
303
+ # This is just getting the plant metadata and giving it updated_date????? With an amount of items based on the length of the
304
+ # date range????
305
+ results_plants = {plant_name: {date: {"available_capacity": power, "updated_date": pd.to_datetime("1970-01-01", utc=True)} for date in dates_of_interest}
306
+ for plant_name, power in plants_metadata.items()}
307
+
308
+ # print(results_sorted)
309
+ for plant, unavailabilities in results_sorted.items():
310
+ # Get the full power of a given plant according to the sorted results
311
+ original_power = plants_metadata[plant]
312
+ # Get all the unavailabilities scheduled for the plant.
313
+ # This is actually apparently just getting the metadata though???
314
+ results_current_plant = results_plants[plant]
315
+
316
+ for unavailability in unavailabilities:
317
+ # For each unavailability, the resulting power, start and end datetime are collected. Need to collect updated_date
318
+ power_unavailability = unavailability["available_capacity"]
319
+ updated_date_unav = unavailability["updated_date"]
320
+ # The date comes as a string
321
+ start_datetime_unav = unavailability["start_date"]
322
+ end_datetime_unav = unavailability["end_date"]
323
+ start_date_unav = start_datetime_unav.date() # Extract date part
324
+ end_date_unav = end_datetime_unav.date() # Extract date part
325
+
326
+ # For the current unavailability, we want to find which days it affects
327
+ for day in dates_of_interest:
328
+
329
+ start_hour = start_datetime_unav.hour
330
+ start_minute = start_datetime_unav.minute
331
+ end_hour = end_datetime_unav.hour
332
+ end_minute = end_datetime_unav.minute
333
+
334
+ if start_date_unav <= day <= end_date_unav:
335
+ # Check if the day is already updated with a later update_date
336
+
337
+ if day in results_current_plant and updated_date_unav <= results_current_plant[day]["updated_date"]:
338
+ # Here is likely where we can do the filter for worst case scenario
339
+ # --------------------------- !!!!!!CREATE NEW FILTER THAT KEEPS ONLY MOST RESTRICTIVE OVERLAP!!!!!! --------------------------- #
340
+ # if power_unavailability < results_current_plant[day]['available_capacity']:
341
+
342
+ # # Calculate the % of the day that the plant is under maintenance
343
+ # if start_date_unav == day and day == end_date_unav:
344
+ # # The unavailability starts and ends on the same day
345
+ # percentage_of_day = (end_hour * 60 + end_minute - start_hour * 60 - start_minute) / (24 * 60)
346
+ # elif start_date_unav == day:
347
+ # # The unavailability starts on the current day but ends on a later day
348
+ # percentage_of_day = (24 * 60 - (start_hour * 60 + start_minute)) / (24 * 60)
349
+ # elif day == end_date_unav:
350
+ # # The unavailability starts on a previous day and ends on the current day
351
+ # percentage_of_day = (end_hour * 60 + end_minute) / (24 * 60)
352
+ # else:
353
+ # # The unavailability covers the entire day
354
+ # percentage_of_day = 1
355
+
356
+ # --------------------------- !!!!!!CREATE NEW FILTER THAT KEEPS ONLY MOST RESTRICTIVE OVERLAP!!!!!! --------------------------- #
357
+ # else:
358
+
359
+ continue # Skip to the next loop if there is already information for a later update_date
360
+
361
+ # Calculate the % of the day that the plant is under maintenance
362
+ if start_date_unav == day and day == end_date_unav:
363
+ # The unavailability starts and ends on the same day
364
+ percentage_of_day = (end_hour * 60 + end_minute - start_hour * 60 - start_minute) / (24 * 60)
365
+ elif start_date_unav == day:
366
+ # The unavailability starts on the current day but ends on a later day
367
+ percentage_of_day = (24 * 60 - (start_hour * 60 + start_minute)) / (24 * 60)
368
+ elif day == end_date_unav:
369
+ # The unavailability starts on a previous day and ends on the current day
370
+ percentage_of_day = (end_hour * 60 + end_minute) / (24 * 60)
371
+ else:
372
+ # The unavailability covers the entire day
373
+ percentage_of_day = 1
374
+
375
+ # The average power of the day is calculated
376
+ power_of_day = percentage_of_day * power_unavailability + (1 - percentage_of_day) * original_power
377
+
378
+ # Update the available_capacity for the day only if it's not already updated with a later update_date
379
+ if (day not in results_current_plant):
380
+ results_current_plant[day] = {"available_capacity": power_of_day, "updated_date": updated_date_unav}
381
+
382
+ elif (day in results_current_plant) and (updated_date_unav > results_current_plant[day]["updated_date"]) and (power_of_day < results_current_plant[day]['available_capacity']):
383
+ results_current_plant[day] = {"available_capacity": power_of_day, "updated_date": updated_date_unav}
384
+
385
+ else:
386
+ continue
387
+
388
+
389
+
390
+ output_results = {}
391
+ for plant, plant_data in results_plants.items():
392
+ available_capacity_per_day = {str(date): data["available_capacity"] for date, data in plant_data.items()}
393
+ output_results[plant] = available_capacity_per_day
394
+
395
+ # print(output_results)
396
+ add_total(output_results)
397
+ # print("Done")
398
+ # print(results_plants)
399
+ # Convert datetime key to string to store in mongodb
400
+ output_results = {plant: {str(date): power for date, power in plant_data.items()} for plant, plant_data in output_results.items()}
401
+ output_results = pd.DataFrame(output_results)
402
+ print(output_results)
403
+
404
+ # -------------------------------------------------
405
+ # Calculate the average of each column excluding the last row
406
+ averages = output_results.iloc[:-1, :].mean()
407
+
408
+ # Replace the last row with the calculated averages
409
+ output_results.iloc[-1, :] = averages
410
+
411
+ output_results = output_results.to_dict()
412
+
413
+ def turn_total_row_to_avg(data):
414
+ # Replace the last key of each dictionary with 'Averages'
415
+ for key, value in data.items():
416
+ last_key = list(value.keys())[-1]
417
+ value['Averages'] = value.pop(last_key)
418
+
419
+ turn_total_row_to_avg(output_results)
420
+
421
+ # print(output_results)
422
+
423
+ json_data = json.dumps(output_results)
424
+ # print(json_data)
425
+ return json_data
426
+ # -------------------------------------------------
427
+
428
+
429
+ # @st.cache_data
430
+ def get_mongodb_data(start_date, end_date, past_date):
431
+ database_data = mongo_unavs_call(start_date, end_date, past_date)
432
+ return database_data
433
+
434
+ # @st.cache_data
435
+ def get_nucmonitor_data(start_date, end_date, past_date):
436
+ mongo = get_mongodb_data(start_date, end_date, past_date)
437
+ response_nucmonitor = nuc_monitor(start_date, end_date, past_date, mongo)
438
+ # nucmonitor_data = response_nucmonitor.json()
439
+ # nucmonitor_json = json.loads(nucmonitor_data)
440
+ # print(response_nucmonitor)
441
+ df = pd.read_json(response_nucmonitor)
442
+ return df
443
+
444
+ # @st.cache_data
445
+ def get_photodate_data(start_date, end_date, past_date):
446
+ mongo = get_mongodb_data(start_date, end_date, past_date)
447
+ response_nucmonitor = nuc_monitor(start_date, end_date, past_date, mongo)
448
+ # nucmonitor_data = response_nucmonitor.json()
449
+ # nucmonitor_json = json.loads(nucmonitor_data)
450
+ # print(response_nucmonitor)
451
+ df = pd.read_json(response_nucmonitor)
452
+ return df
453
+
454
+ def run_app():
455
+
456
+ st.title("Nucmonitor App")
457
+
458
+ # Get user input (e.g., dates)
459
+ start_date = st.date_input("Start Date")
460
+ end_date = st.date_input("End Date")
461
+ past_date = st.date_input("Cutoff Date")
462
+ # winter_date = st.date_input("Winter Cutoff Date")
463
+
464
+ current_date = datetime.datetime.now()
465
+
466
+ with st.form("nucmonitor_form"):
467
+ submitted = st.form_submit_button("Get Nucmonitor")
468
+
469
+ if not submitted:
470
+ st.write("Form not submitted")
471
+
472
+ else:
473
+ st.write("Data received from Flask:")
474
+ df_nucmonitor = get_nucmonitor_data(start_date, end_date, current_date)
475
+ df_photo_date = get_photodate_data(start_date, end_date, past_date)
476
+ # df_winter_date = get_nucmonitor_data(start_date, end_date, winter_date)
477
+ current_date_str = str(current_date.strftime('%Y-%m-%d'))
478
+ past_date_str = str(past_date.strftime('%Y-%m-%d'))
479
+ st.write(f"Current View Forecast at {current_date_str} (MW)")
480
+ st.write(df_nucmonitor) # Display DataFrame
481
+
482
+ st.write(f"Past View Forecast at {past_date_str}")
483
+ st.write(df_photo_date)
484
+
485
+ # Get info on current forecast Nucmonitor
486
+ st.write(f"Total Energy per Day at Current View Forecast {current_date_str} (MW)")
487
+
488
+ # Remove the final row 'Total'
489
+ df_nucmonitor_2 = df_nucmonitor.iloc[:-1, :]
490
+ # Get the last column
491
+ df_nucmonitor_2 = df_nucmonitor_2.iloc[:, -1]
492
+
493
+ # print(df_nucmonitor_2)
494
+
495
+ st.write(df_nucmonitor_2)
496
+
497
+ # Get info on past date forecast Nucmonitor
498
+ st.write(f"Total Energy per Day at Past View Forecast {past_date_str} (MW)")
499
+
500
+ # Remove the final row 'Total'
501
+ df_photo_date_2 = df_photo_date.iloc[:-1, :]
502
+ # Get the last column
503
+ df_photo_date_2 = df_photo_date_2.iloc[:, -1]
504
+
505
+ # print(df_photo_date_2)
506
+
507
+ st.write(df_photo_date_2)
508
+
509
+ # --------------------------------- AVERAGE EXPECTED AVAILABILITY M-1 M M+1 M+2 PIPELINE --------------------------------- #
510
+
511
+ # Create a Table that displays the forecast of each dataframe total for two months before date and two months after
512
+ # Filter dates for two months before and after the current date
513
+ # Define date ranges
514
+ # I am under the impression that I will need to use past_date for the offset
515
+ # two_months_before = (current_date - pd.DateOffset(months=2)).strftime('%Y-%m')
516
+ # one_month_before = (current_date - pd.DateOffset(months=1)).strftime('%Y-%m')
517
+ # one_month_after = (current_date + pd.DateOffset(months=1)).strftime('%Y-%m')
518
+ # two_months_after = (current_date + pd.DateOffset(months=2)).strftime('%Y-%m')
519
+
520
+ two_months_before = (current_date - pd.DateOffset(months=2)).strftime('%Y-%m')
521
+ one_month_before = (current_date - pd.DateOffset(months=1)).strftime('%Y-%m')
522
+ one_month_after = (current_date + pd.DateOffset(months=1)).strftime('%Y-%m')
523
+ two_months_after = (current_date + pd.DateOffset(months=2)).strftime('%Y-%m')
524
+
525
+ # Assuming df is the DataFrame containing the date index and the 'Total' column
526
+
527
+ # # Convert the index to datetime if it's not already
528
+ # df_nucmonitor_2.index = pd.to_datetime(df_nucmonitor_2.index)
529
+ # df_photo_date_2.index = pd.to_datetime(df_photo_date_2.index)
530
+
531
+ # # Calculate monthly averages with date in yyyy-mm format
532
+ # monthly_average_nucmonitor = df_nucmonitor_2.resample('M').mean()
533
+ # monthly_average_photo_date = df_photo_date_2.resample('M').mean()
534
+
535
+ # Convert the index to datetime if it's not already
536
+ df_nucmonitor_2.index = pd.to_datetime(df_nucmonitor_2.index)
537
+ df_photo_date_2.index = pd.to_datetime(df_photo_date_2.index)
538
+
539
+ # Calculate monthly averages with date in yyyy-mm format
540
+ monthly_average_nucmonitor = df_nucmonitor_2.resample('M').mean()
541
+ monthly_average_nucmonitor.index = monthly_average_nucmonitor.index.strftime('%Y-%m')
542
+
543
+ monthly_average_photo_date = df_photo_date_2.resample('M').mean()
544
+ monthly_average_photo_date.index = monthly_average_photo_date.index.strftime('%Y-%m')
545
+
546
+
547
+ # print(monthly_average_nucmonitor)
548
+ # print(monthly_average_nucmonitor.index)
549
+ # print(len(monthly_average_nucmonitor.index) < 5)
550
+ if (len(monthly_average_nucmonitor.index) < 5) or (two_months_before not in monthly_average_nucmonitor.index or two_months_after not in monthly_average_nucmonitor.index):
551
+ df_display_normal_bool = False
552
+
553
+ else:
554
+ # print(two_months_before, one_month_before, current_date.strftime('%Y-%m'), one_month_after, two_months_after)
555
+ # Filter DataFrames based on date ranges
556
+ df_nucmonitor_filtered = monthly_average_nucmonitor[
557
+ (monthly_average_nucmonitor.index == two_months_before) |
558
+ (monthly_average_nucmonitor.index == one_month_before) |
559
+ (monthly_average_nucmonitor.index == current_date.strftime('%Y-%m')) |
560
+ (monthly_average_nucmonitor.index == one_month_after) |
561
+ (monthly_average_nucmonitor.index == two_months_after)
562
+ ]
563
+
564
+ df_photo_date_filtered = monthly_average_photo_date[
565
+ (monthly_average_photo_date.index == two_months_before) |
566
+ (monthly_average_photo_date.index == one_month_before) |
567
+ (monthly_average_photo_date.index == current_date.strftime('%Y-%m')) |
568
+ (monthly_average_photo_date.index == one_month_after) |
569
+ (monthly_average_photo_date.index == two_months_after)
570
+ ]
571
+
572
+ # Display the filtered DataFrames
573
+ st.write(f"Forecast at {current_date_str} (MW)")
574
+ st.write(df_nucmonitor_filtered)
575
+ st.write(f"Forecast at {past_date_str} (MW)")
576
+ st.write(df_photo_date_filtered)
577
+
578
+ current_forecast_update = df_nucmonitor_filtered.tolist()
579
+ past_forecast_update = df_photo_date_filtered.tolist()
580
+ delta = [current - past for current, past in zip(current_forecast_update, past_forecast_update)]
581
+
582
+ # print('Dates:', [two_months_before, one_month_before, current_date.strftime('%Y-%m'), one_month_after, two_months_after])
583
+ # print(f"Forecast update {current_date_str}", current_forecast_update)
584
+ # print(f"Forecast update {past_date_str}", past_forecast_update,)
585
+ # print('Delta', delta)
586
+
587
+ # Create a DataFrame for display
588
+ data_avg_expected_normal = {
589
+ 'Dates': [two_months_before, one_month_before, current_date.strftime('%Y-%m'), one_month_after, two_months_after],
590
+ f"Forecast update {current_date_str} (MW)": current_forecast_update,
591
+ f"Forecast update {past_date_str} (MW)": past_forecast_update,
592
+ 'Delta': delta
593
+ }
594
+ df_display_normal_bool = True
595
+
596
+ # --------------------------------- AVERAGE EXPECTED AVAILABILITY M-1 M M+1 M+2 PIPELINE --------------------------------- #
597
+
598
+ # --------------------------------- AVERAGE EXPECTED AVAILABILITY WINTER PIPELINE --------------------------------- #
599
+ # Create a Table that displays the forecast of each dataframe for the Winter months (Nov, Dec, Jan, Feb, Mar)
600
+
601
+ # Create a table that gets the forecast for winter. This involves creating a new dataframe with
602
+ # only the winter months with the total of each day, and another dataframe with the average of each month. Each month
603
+ # included will only be 20xx-11, 12, and 20xx+1-01, 02, 03
604
+
605
+ # Define date ranges for winter months
606
+ # winter_start_date = current_date.replace(month=11, day=1)
607
+ # winter_end_date = (current_date.replace(year=current_date.year+1, month=3, day=31))
608
+ winter_start = f"{current_date.year}-11"
609
+ winter_end = f"{current_date.year+1}-03"
610
+ winter_start_str = str(winter_start)
611
+ winter_end_str = str(winter_end)
612
+ # print("winter_start_str", winter_start)
613
+ # print("winter_end_str", winter_end)
614
+ # print("monthly_average_nucmonitor.index", monthly_average_nucmonitor.index)
615
+ # print(monthly_average_nucmonitor.index == winter_start)
616
+ # print(monthly_average_nucmonitor.index == winter_end)
617
+ if monthly_average_nucmonitor.index.any() != winter_start or monthly_average_nucmonitor.index.any() != winter_end:
618
+ df_display_winter_bool = False
619
+
620
+ else:
621
+ # Filter DataFrames based on winter date range
622
+ df_nucmonitor_winter = monthly_average_nucmonitor[(monthly_average_nucmonitor.index >= winter_start_str) & (monthly_average_nucmonitor.index <= winter_end_str)]
623
+
624
+ df_photo_date_winter = monthly_average_photo_date[(monthly_average_photo_date.index >= winter_start_str) & (monthly_average_photo_date.index <= winter_end_str)]
625
+
626
+ # Display the forecast DataFrames for winter
627
+ st.title("Forecast for Winter Months")
628
+ st.write(f"Forecast for {current_date.year}-{current_date.year+1} (Nov, Dec, Jan, Feb, Mar)")
629
+ st.write("Nucmonitor Forecast:")
630
+ st.write(df_nucmonitor_winter)
631
+ st.write("Photo Date Forecast:")
632
+ st.write(df_photo_date_winter)
633
+
634
+ current_winter_forecast_update = df_nucmonitor_winter.tolist()
635
+ past_winter_forecast_update = df_photo_date_winter.tolist()
636
+ winter_delta = [current - past for current, past in zip(current_winter_forecast_update, past_winter_forecast_update)]
637
+ # print("current_winter_forecast_update:", current_winter_forecast_update)
638
+ # print("past_winter_forecast_update:", past_winter_forecast_update)
639
+
640
+ # Create a DataFrame for display
641
+ data_avg_expected_winter = {
642
+ 'Dates': [f'Nov-{current_date.year}', f'Dec-{current_date.year}', f'Jan-{current_date.year+1}', f'Feb-{current_date.year+1}', f'Mar-{current_date.year+1}'],
643
+ f"Forecast update {current_date_str}": current_winter_forecast_update,
644
+ f"Forecast update {past_date_str}": past_winter_forecast_update,
645
+ 'Delta': winter_delta
646
+ }
647
+ # print(data_avg_expected_winter)
648
+ df_display_winter_bool = True
649
+
650
+ # --------------------------------- AVERAGE EXPECTED AVAILABILITY WINTER PIPELINE --------------------------------- #
651
+
652
+ # --------------------------------- VISUALIZE --------------------------------- #
653
+ if df_display_normal_bool:
654
+ df_display_normal = pd.DataFrame(data_avg_expected_normal)
655
+ # Display the DataFrame as a horizontal table
656
+ st.write("Table 1. Average expected availability on the French nuclear fleet (MW) - M-1, M, M+1, M+2, M+3")
657
+ st.table(df_display_normal)
658
+
659
+ if df_display_winter_bool:
660
+ df_display_winter = pd.DataFrame(data_avg_expected_winter)
661
+ st.write(f"Table 2. Average expected availability on the French nuclear fleet (MW) - Winter {winter_start}/{winter_end}")
662
+ st.table(df_display_winter)
663
+
664
+ # Line charts of the forecasts (need to combine them so they appear in the same chart)
665
+ st.write("Current forecast (MW)")
666
+ st.line_chart(df_nucmonitor_2)
667
+
668
+ st.write("Previous forecast (MW)")
669
+ st.line_chart(df_photo_date_2)
670
+ # Create a new dataframe out of df_nucmonitor_2 call real_avail that contains df_nucmonitor_2 up until current_date
671
+
672
+ # Slice the DataFrame to include data up until current_date
673
+ real_avail = df_nucmonitor_2.loc[df_nucmonitor_2.index <= current_date_str]
674
+
675
+ # Winter forecast still not the correct one, this is just a placeholder
676
+ # winter_forecast = df_nucmonitor_2.loc[(df_nucmonitor_2.index >= winter_start_date) & (df_nucmonitor_2.index <= winter_end_date)]
677
+
678
+ # Optionally, if you want to reset the index
679
+ # real_avail = real_avail.reset_index()
680
+ # print(real_avail)
681
+ st.write("Observed Historical Availability (MW)")
682
+ st.line_chart(real_avail)
683
+
684
+ # Combine dataframes
685
+ # combined_df = pd.concat([df_nucmonitor_2, df_photo_date_2, real_avail, winter_forecast], axis=1)
686
+ combined_df = pd.concat([df_nucmonitor_2, df_photo_date_2, real_avail], axis=1)
687
+
688
+ # combined_df.columns = [f'Forecast {current_date_str}', f'Forecast {past_date_str}', 'Observed Historical Availability', f'Winter forecast {winter_start}/{winter_end}']
689
+ combined_df.columns = [f'Forecast {current_date_str} (MW)', f'Forecast {past_date_str} (MW)', 'Observed Historical Availability (MW)']
690
+
691
+ # print(combined_df)
692
+ st.write(f"Graph 1. {start_date} to {end_date} (MW)")
693
+ st.line_chart(combined_df)
694
+
695
+ # Add a download button
696
+ # Create a BytesIO object to hold the Excel data
697
+
698
+ excel_buffer = io.BytesIO()
699
+
700
+
701
+ current_datetime = datetime.datetime.now()
702
+ current_year = current_datetime.strftime('%Y')
703
+ current_month = current_datetime.strftime('%m')
704
+ current_day = current_datetime.strftime('%d')
705
+ current_hour = current_datetime.strftime('%H')
706
+ current_minute = current_datetime.strftime('%M')
707
+ current_second = current_datetime.strftime('%S')
708
+
709
+
710
+ # Save the DataFrame to the BytesIO object as an Excel file
711
+ df_nucmonitor.to_excel(excel_buffer, index=True)
712
+ # Set the cursor position to the beginning of the BytesIO object
713
+ excel_buffer.seek(0)
714
+
715
+ # Provide the BytesIO object to the download button
716
+ download_button = st.download_button(
717
+ label="Download Excel",
718
+ data=excel_buffer,
719
+ file_name=f"nucmonitor_data_{current_year}-{current_month}-{current_day}-h{current_hour}m{current_minute}s{current_second}.xlsx",
720
+ mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
721
+ )
722
+
723
+
724
+ if __name__ == '__main__':
725
+ run_app()