-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
2263 lines (1924 loc) · 87.4 KB
/
main.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
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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# main.py
"""
WeatherAI Script
This script handles the ingestion, preprocessing, and modeling of weather and space event data.
It continuously monitors specified directories for new or modified CSV files, processes the data,
trains a machine learning model, and makes predictions based on the updated data.
It also includes functionalities for generating forecasts, evaluating model accuracy, and updating the model incrementally.
Author: Simon
Date: 2024-11-30
"""
import re
import os
import sys
import time
import json
import joblib
import numbers
import logging
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from utilities import update_data
from datetime import datetime, timedelta
from sklearn.impute import SimpleImputer
from sklearn.compose import ColumnTransformer
from logging.handlers import RotatingFileHandler
from watchdog.events import FileSystemEventHandler
from sklearn.multioutput import MultiOutputRegressor
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.linear_model import SGDRegressor, LinearRegression
from sklearn.metrics import mean_squared_error, r2_score, roc_curve, auc
# ============================
# Configuration and Setup
# ============================
# Define the base directory paths
BASE_DIR = "/Users/simon/Desktop/Areas/TKS/Focus1Rep2/WeatherAI"
KNOWLEDGE_PATH = os.path.join(BASE_DIR, 'Databases', 'Knowledge') # Central location for logs and models
# Ensure the knowledge directory exists
try:
os.makedirs(KNOWLEDGE_PATH, exist_ok=True)
except Exception as e:
print(f"Failed to create knowledge directory: {e}")
sys.exit(1)
# Configure logging
log_file = os.path.join(KNOWLEDGE_PATH, 'weather_ai.log')
try:
handler = RotatingFileHandler(log_file, maxBytes=10*1024*1024, backupCount=5) # 10MB per log file
logging.basicConfig(
level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
handler,
logging.StreamHandler(sys.stdout)
]
)
logging.info("Logging configured successfully.")
except Exception as e:
print(f"Failed to configure logging: {e}")
sys.exit(1)
# Define Paths
REAL_TIME_DATA_PATH = os.path.join(BASE_DIR, 'Databases', 'Data', 'Hourly Data')
SPACE_DATA_PATH = os.path.join(BASE_DIR, 'Databases', 'Data', 'Space Data')
NEAR_EARTH_SPACE_DATA_PATH = os.path.join(BASE_DIR, 'Databases', 'Data', 'Near Earth Space Data')
# Verify that data directories exist
DATA_DIRECTORIES = [
REAL_TIME_DATA_PATH,
SPACE_DATA_PATH,
NEAR_EARTH_SPACE_DATA_PATH
]
for directory in DATA_DIRECTORIES:
if not os.path.exists(directory):
logging.warning(f"Data directory does not exist: {directory}")
else:
logging.info(f"Data directory exists: {directory}")
# Initialize global variables
model = None
preprocessor = None
# Define target variables
POSSIBLE_TARGETS = {
'WIND_SPEED', 'VISIBILITY', 'STATION_PRESSURE', 'TEMP', 'RELATIVE_HUMIDITY',
'WINDCHILL', 'HUMIDEX', 'PRECIP_AMOUNT', 'DEW_POINT_TEMP'
}
TARGET_VARIABLES = set()
FEATURE_COLUMNS = set()
NUMERICAL_FEATURES = set()
CATEGORICAL_FEATURES = set()
# Define minimum target data points required
MIN_TARGET_DATA_POINTS = 100 # Adjust based on dataset size and requirements
# ============================
# File System Event Handler
# ============================
class RealTimeDataHandler(FileSystemEventHandler):
"""
Handles file system events for real-time data ingestion.
"""
def on_created(self, event):
"""
Called when a file or directory is created.
"""
if not event.is_directory and event.src_path.endswith('.csv'):
logging.info(f'New file detected: {event.src_path}')
process_new_data(event.src_path)
def on_modified(self, event):
"""
Called when a file or directory is modified.
"""
if not event.is_directory and event.src_path.endswith('.csv'):
logging.info(f'File modified: {event.src_path}')
process_new_data(event.src_path)
# ============================
# Data Collection and Loading
# ============================
def collect_all_columns():
"""
Collects all possible columns from specified data sources and categorizes them into
target variables, numerical features, and categorical features.
This function performs the following steps:
1. Collects columns from all data directories specified in `data_directories`.
2. Identifies target variables by intersecting all collected columns with `POSSIBLE_TARGETS`.
3. Defines feature columns as the set difference between all collected columns and target variables.
4. Automatically detects categorical and numerical features based on sample data types.
5. Excludes 'UTC_DATE' from numerical features.
6. Logs the identified target variables, categorical features, and numerical features.
Global Variables:
- FEATURE_COLUMNS: Set of feature columns identified from the data sources.
- TARGET_VARIABLES: Set of target variables identified from the data sources.
- NUMERICAL_FEATURES: Set of numerical feature columns identified from the data sources.
- CATEGORICAL_FEATURES: Set of categorical feature columns identified from the data sources.
Logs:
- Logs the process of collecting columns from data sources.
- Logs warnings if no sample data is available for a column.
- Logs the identified target variables, categorical features, and numerical features.
"""
global FEATURE_COLUMNS, TARGET_VARIABLES, NUMERICAL_FEATURES, CATEGORICAL_FEATURES
logging.info('Collecting all possible columns from data sources...')
# Collect columns from all data directories
data_directories = [
REAL_TIME_DATA_PATH,
SPACE_DATA_PATH,
NEAR_EARTH_SPACE_DATA_PATH
]
all_columns = set()
column_samples = {}
for directory in data_directories:
data_frames = load_data_from_directory(directory)
for df in data_frames.values():
all_columns.update(df.columns)
for col in df.columns:
if col not in column_samples:
# Get a sample value for the column
sample_series = df[col].dropna()
sample_value = sample_series.iloc[0] if not sample_series.empty else None
column_samples[col] = sample_value
logging.info(f'All columns found: {all_columns}')
# Define target variables and feature columns
TARGET_VARIABLES = all_columns.intersection(POSSIBLE_TARGETS)
FEATURE_COLUMNS = all_columns - TARGET_VARIABLES
# Automatically detect categorical features based on data types
CATEGORICAL_FEATURES = set()
NUMERICAL_FEATURES = set()
for col in FEATURE_COLUMNS:
sample_value = column_samples.get(col, None)
if sample_value is not None:
if isinstance(sample_value, numbers.Number):
NUMERICAL_FEATURES.add(col)
else:
CATEGORICAL_FEATURES.add(col)
else:
logging.warning(f'No sample data for column "{col}". Cannot determine data type.')
# Exclude 'UTC_DATE' from numerical features
NUMERICAL_FEATURES.discard('UTC_DATE')
# Log the identified features
logging.info(f'Identified TARGET_VARIABLES: {TARGET_VARIABLES}')
logging.info(f'Identified CATEGORICAL_FEATURES: {CATEGORICAL_FEATURES}')
logging.info(f'Identified NUMERICAL_FEATURES: {NUMERICAL_FEATURES}')
def get_columns_from_directory(directory_path):
"""
Retrieves column names from all CSV files within a directory.
Parameters:
directory_path (str): Path to the data directory.
Returns:
set: Set of column names found in the directory.
"""
columns = set()
data_frames = load_data_from_directory(directory_path)
for df in data_frames:
columns.update(df.columns)
return columns
def get_unique_value_counts(column, directories):
"""
Calculates the total number of unique values for a given column across multiple directories.
Parameters:
column (str): Column name.
directories (list): List of directory paths.
Returns:
int: Total number of unique values.
"""
unique_values = set()
for directory in directories:
data_frames = load_data_from_directory(directory)
for df in data_frames:
if column in df.columns:
unique_values.update(df[column].dropna().unique())
return len(unique_values)
def load_data_from_directory(directory_path, expected_pattern=None):
"""
Loads CSV files from a directory with varying filename patterns and parses them accordingly.
Parameters:
directory_path (str): Path to the parent directory containing CSV files in subdirectories.
Returns:
dict: A dictionary with keys as (category, year) tuples and values as DataFrames.
"""
data_frames = {}
if not os.path.exists(directory_path):
logging.warning(f'Directory "{directory_path}" does not exist.')
return data_frames
for root, _, files in os.walk(directory_path):
parent_dir = os.path.basename(root)
for file in files:
if not file.endswith('.csv'):
continue
if parent_dir == 'Hourly Data':
pattern = r'^(?P<year>\d{4})\.csv$'
elif parent_dir == 'Space Data':
pattern = r'^space_events_(?P<year>\d{4})\.csv$'
elif parent_dir == 'Near Earth Space Data':
pattern = r'^(?P<category>\w+)-(?P<year>\d{4})\.csv$'
else:
logging.warning(f'Unrecognized directory "{parent_dir}". Skipping file "{file}".')
continue
regex = re.compile(pattern)
match = regex.match(file)
if not match:
logging.warning(f'File "{file}" does not match the pattern in directory "{parent_dir}".')
continue
category = match.group('category') if 'category' in match.groupdict() else None
year = int(match.group('year'))
file_path = os.path.join(root, file)
try:
df = pd.read_csv(file_path)
data_frames[(category, year)] = df
logging.info(f'Loaded file "{file}" with shape {df.shape}.')
except Exception as e:
logging.warning(f'Failed to read file "{file_path}": {e}')
logging.info(f'Total files loaded from "{directory_path}": {len(data_frames)}')
return data_frames
def apply_column_mappings(df):
"""
Standardizes column names using predefined mappings.
Parameters:
df (pd.DataFrame): DataFrame to apply column mappings to.
Returns:
pd.DataFrame: DataFrame with standardized column names.
"""
COLUMN_MAPPING = {
'UTC_DATE': 'UTC_DATE',
'LOCAL_DATE': 'LOCAL_DATE',
'UTC_YEAR': 'UTC_YEAR',
'UTC_MONTH': 'UTC_MONTH',
'UTC_DAY': 'UTC_DAY',
'LOCAL_YEAR': 'LOCAL_YEAR',
'LOCAL_MONTH': 'LOCAL_MONTH',
'LOCAL_DAY': 'LOCAL_DAY',
'LOCAL_HOUR': 'LOCAL_HOUR',
'date': 'UTC_DATE',
'startTime': 'UTC_DATE',
'eventTime': 'UTC_DATE',
'beginTime': 'UTC_DATE',
'peakTime': 'UTC_DATE',
'endTime': 'UTC_DATE',
'submissionTime': 'UTC_DATE',
'time21_5': 'UTC_DATE',
'messageIssueTime': 'UTC_DATE',
'modelCompletionTime': 'UTC_DATE',
'temperature_average': 'temperature_average',
'temperature_min': 'temperature_min',
'temperature_max': 'temperature_max',
'temp': 'temperature_average',
'temperature': 'temperature_average',
'Temperature': 'temperature_average',
'Temp (°C)': 'temperature_average',
'DEW_POINT_TEMP': 'dew_point_temp',
'dew_point_temp': 'dew_point_temp',
'dew_point_temp_flag': 'dew_point_temp_flag',
'wind_speed_average': 'wind_speed_average',
'wind_speed_min': 'wind_speed_min',
'wind_speed_max': 'wind_speed_max',
'wind_speed': 'wind_speed_average',
'Wind Speed': 'wind_speed_average',
'Wind Speed (km/h)': 'wind_speed_average',
'WIND_SPEED': 'wind_speed_average',
'WINDCHILL': 'windchill',
'WINDCHILL_FLAG': 'windchill_flag',
'STATION_PRESSURE': 'station_pressure',
'station_pressure': 'station_pressure',
'STATION_PRESSURE_FLAG': 'station_pressure_flag',
'pressure_average': 'pressure_average',
'pressure_min': 'pressure_min',
'pressure_max': 'pressure_max',
'RELATIVE_HUMIDITY': 'relative_humidity',
'RELATIVE_HUMIDITY_FLAG': 'relative_humidity_flag',
'HUMIDEX': 'humidex',
'HUMIDEX_FLAG': 'humidex_flag',
'VISIBILITY': 'visibility',
'VISIBILITY_FLAG': 'visibility_flag',
'PRECIP_AMOUNT': 'precip_amount',
'PRECIP_AMOUNT_FLAG': 'precip_amount_flag',
'WIND_DIRECTION': 'wind_direction',
'WIND_DIRECTION_FLAG': 'wind_direction_flag',
'STATION_NAME': 'station_name',
'PROVINCE_CODE': 'province_code',
'sourceLocation': 'source_location',
'location': 'location',
'ID': 'id',
'activityID': 'activity_id',
'CME_ID': 'cme_id',
'flrID': 'flr_id',
'gstID': 'gst_id',
'hssID': 'hss_id',
'mpcID': 'mpc_id',
'rbeID': 'rbe_id',
'sepID': 'sep_id',
'simulationID': 'simulation_id',
'messageID': 'message_id',
'messageType': 'message_type',
'messageURL': 'message_url',
'sol': 'sol',
'catalog': 'catalog',
'cmeAnalyses': 'cme_analyses',
'linkedEvents': 'linked_events',
'note': 'note',
'versionId': 'version_id',
'link': 'link',
'isMostAccurate': 'is_most_accurate',
'associatedCMEID': 'associated_cme_id',
'featureCode': 'feature_code',
'dataLevel': 'data_level',
'measurementTechnique': 'measurement_technique',
'imageType': 'image_type',
'tilt': 'tilt',
'minorHalfWidth': 'minor_half_width',
'speedMeasuredAtHeight': 'speed_measured_at_height',
'latitude': 'latitude',
'longitude': 'longitude',
'halfAngle': 'half_angle',
'speed': 'speed',
'type': 'type',
'au': 'au',
'cmeInputs': 'cme_inputs',
'estimatedShockArrivalTime': 'estimated_shock_arrival_time',
'estimatedDuration': 'estimated_duration',
'rmin_re': 'rmin_re',
'kp_18': 'kp_18',
'kp_90': 'kp_90',
'kp_135': 'kp_135',
'kp_180': 'kp_180',
'isEarthGB': 'is_earth_gb',
'impactList': 'impact_list',
}
df.rename(columns=COLUMN_MAPPING, inplace=True)
logging.debug(f'Renamed columns: {df.columns.tolist()}')
return df
def verify_numerical_features(df):
"""
Verifies that all numerical features contain numeric data.
Excludes any columns that contain non-numeric data from NUMERICAL_FEATURES.
Parameters:
df (pd.DataFrame): DataFrame to verify numerical features in.
"""
global NUMERICAL_FEATURES, FEATURE_COLUMNS
for col in list(NUMERICAL_FEATURES):
if col not in df.columns:
logging.warning(f'Column "{col}" not found in DataFrame and will be excluded from numerical features.')
NUMERICAL_FEATURES.discard(col)
FEATURE_COLUMNS.discard(col)
continue
missing_percentage = df[col].isnull().mean() * 100
if missing_percentage > 50: # Threshold can be adjusted
logging.warning(f'Column "{col}" has {missing_percentage:.2f}% missing values and will be excluded from numerical features.')
NUMERICAL_FEATURES.discard(col)
FEATURE_COLUMNS.discard(col)
continue
if not pd.api.types.is_numeric_dtype(df[col]):
# Attempt to convert to numeric, coercing errors to NaN
df[col] = pd.to_numeric(df[col], errors='coerce')
if df[col].isnull().all():
logging.warning(f'Column "{col}" cannot be converted to numeric and will be excluded from numerical features.')
NUMERICAL_FEATURES.discard(col)
FEATURE_COLUMNS.discard(col)
else:
num_nans = df[col].isnull().sum()
logging.info(f'Column "{col}" converted to numeric with {num_nans} NaN values.')
def check_missing_columns(df, required_columns):
"""
Checks if the required columns are present in the DataFrame.
Parameters:
df (pd.DataFrame): The input DataFrame.
required_columns (set): A set of required column names.
Returns:
set: A set of missing column names.
"""
missing_columns = required_columns - set(df.columns)
if missing_columns:
logging.warning(f"Missing columns in DataFrame: {missing_columns}")
return missing_columns
def log_target_statistics(df):
"""
Logs the count of non-null values and basic statistics for each target variable.
Excludes target variables with insufficient data.
Parameters:
df (pd.DataFrame): DataFrame to analyze target variables in.
"""
global TARGET_VARIABLES, FEATURE_COLUMNS
targets_to_exclude = set()
for target in TARGET_VARIABLES.copy():
if target in df.columns:
non_null = df[target].notnull().sum()
logging.info(f'Target "{target}" has {non_null} non-null entries.')
if non_null < MIN_TARGET_DATA_POINTS:
logging.warning(f'Target "{target}" has insufficient data ({non_null} entries) and will be excluded.')
targets_to_exclude.add(target)
else:
logging.info(f'Target "{target}" statistics:\n{df[target].describe()}')
else:
logging.warning(f'Target "{target}" not found in DataFrame.')
if targets_to_exclude:
TARGET_VARIABLES -= targets_to_exclude
FEATURE_COLUMNS -= targets_to_exclude
logging.info(f'Excluded targets due to insufficient data: {targets_to_exclude}')
def analyze_correlations(df):
"""
Analyzes and logs the correlation between features and target variables.
Parameters:
df (pd.DataFrame): DataFrame to perform correlation analysis on.
"""
global TARGET_VARIABLES, NUMERICAL_FEATURES
if TARGET_VARIABLES and NUMERICAL_FEATURES:
# Select only numerical features and target variables
relevant_cols = list(TARGET_VARIABLES) + list(NUMERICAL_FEATURES)
available_cols = df.columns.intersection(relevant_cols)
if len(available_cols) < 2:
logging.warning('Not enough columns to perform correlation analysis.')
return
# Exclude non-numeric columns
non_numeric_cols = df[available_cols].select_dtypes(exclude=[np.number]).columns.tolist()
if non_numeric_cols:
logging.warning(f'Non-numeric columns excluded from correlation analysis: {non_numeric_cols}')
available_cols = [col for col in available_cols if col not in non_numeric_cols]
if len(available_cols) < 2:
logging.warning('No numeric columns available for correlation analysis after excluding non-numeric columns.')
return
# Compute correlation matrix
correlation_matrix = df[available_cols].corr()
for target in TARGET_VARIABLES:
if target in correlation_matrix:
correlations = correlation_matrix[target].sort_values(ascending=False)
logging.info(f'Correlations with target "{target}":\n{correlations}')
else:
logging.warning('Cannot perform correlation analysis without target and numerical feature variables.')
def load_and_combine_data():
logging.info('Starting to load and combine data from all sources.')
# Load Hourly Weather Data
hourly_data = load_data_from_directory(
REAL_TIME_DATA_PATH, expected_pattern='{year}.csv'
)
if hourly_data:
logging.info('Loaded Hourly Weather Data.')
hourly_df = pd.concat(hourly_data.values(), ignore_index=True).copy()
logging.info(f'Hourly DataFrame shape: {hourly_df.shape}')
logging.debug(f'Hourly DataFrame type: {type(hourly_df)}')
else:
logging.warning('No Hourly Weather Data found.')
hourly_df = pd.DataFrame()
# Load and aggregate Space Data
space_data = load_data_from_directory(
SPACE_DATA_PATH, expected_pattern='{prefix}_events_{year}.csv'
)
if space_data:
logging.info('Loaded Space Data.')
space_df = pd.concat(space_data.values(), ignore_index=True).copy()
space_df = apply_column_mappings(space_df)
logging.info(f'Space DataFrame shape after mapping: {space_df.shape}')
logging.debug(f'Space DataFrame type: {type(space_df)}')
else:
logging.warning('No Space Data found.')
space_df = pd.DataFrame()
# Load and aggregate Near Earth Space Data
near_earth_data = load_data_from_directory(
NEAR_EARTH_SPACE_DATA_PATH, expected_pattern='{category}-{year}.csv'
)
if near_earth_data:
logging.info('Loaded Near Earth Space Data.')
# Combine data by categories
aggregated_near_earth_dataframes = []
for (category, year), df in near_earth_data.items():
if category is None:
logging.warning(f'Category is None for file loaded for year {year}. Skipping.')
continue
df['Category'] = category # Add category column for clarity
df = apply_column_mappings(df)
aggregated_df = aggregate_near_earth_space_data(df, category)
if not aggregated_df.empty:
aggregated_near_earth_dataframes.append(aggregated_df)
logging.info(f'Aggregated {category}-{year} DataFrame with shape: {aggregated_df.shape}')
logging.debug(f'Aggregated DataFrame type: {type(aggregated_df)}')
else:
logging.warning(f'Aggregated DataFrame for {category}-{year} is empty.')
# Combine all categories into one DataFrame
if aggregated_near_earth_dataframes:
aggregated_near_earth_df = pd.concat(aggregated_near_earth_dataframes, ignore_index=True)
logging.info(f'Combined Near Earth Space DataFrame shape: {aggregated_near_earth_df.shape}')
logging.debug(f'Combined Near Earth Space DataFrame type: {type(aggregated_near_earth_df)}')
else:
logging.warning('No valid Near Earth Space Data found after aggregation.')
aggregated_near_earth_df = pd.DataFrame()
else:
logging.warning('No Near Earth Space Data found.')
aggregated_near_earth_df = pd.DataFrame()
# Ensure 'UTC_DATE' is consistent across all DataFrames
data_frames_to_process = {
'hourly_df': hourly_df,
'space_df': space_df,
'aggregated_near_earth_df': aggregated_near_earth_df
}
for df_name, df in data_frames_to_process.items():
if not df.empty and 'UTC_DATE' in df.columns:
df['UTC_DATE'] = pd.to_datetime(df['UTC_DATE'], errors='coerce')
df['UTC_DATE'] = df['UTC_DATE'].dt.tz_localize(None)
logging.info(f'Processed "UTC_DATE" column in {df_name}.')
logging.debug(f'{df_name} "UTC_DATE" column type: {df["UTC_DATE"].dtype}')
else:
logging.warning(f'"UTC_DATE" column missing or empty in {df_name}.')
# Merge all DataFrames on 'UTC_DATE'
if not hourly_df.empty and 'UTC_DATE' in hourly_df.columns:
combined_data = hourly_df.copy()
logging.debug(f'Combined DataFrame initial type: {type(combined_data)}')
for df_name, df in data_frames_to_process.items():
if df_name != 'hourly_df' and not df.empty and 'UTC_DATE' in df.columns:
combined_data = pd.merge(combined_data, df, on='UTC_DATE', how='left')
logging.info(f'Merged {df_name} into combined DataFrame. Current shape: {combined_data.shape}')
logging.debug(f'Combined DataFrame type after merging {df_name}: {type(combined_data)}')
else:
logging.warning('No Hourly Data available to merge or "UTC_DATE" missing. Returning an empty DataFrame.')
combined_data = pd.DataFrame()
# Verify numerical features
verify_numerical_features(combined_data)
# Log target statistics and exclude insufficient targets
log_target_statistics(combined_data)
# Perform correlation analysis
analyze_correlations(combined_data)
logging.info('Data loading and combination process completed.')
logging.debug(f'Final combined_data type: {type(combined_data)}')
return combined_data
def aggregate_space_data(space_df):
"""
Aggregates space data to a daily level.
Parameters:
space_df (pd.DataFrame): Space data DataFrame.
Returns:
pd.DataFrame: Aggregated space data with 'UTC_DATE' as the date key.
"""
if space_df.empty:
logging.warning("Input space_df is empty. Returning empty DataFrame.")
return pd.DataFrame()
# Make a copy to avoid SettingWithCopyWarning
space_df = space_df.copy()
# Ensure 'UTC_DATE' is in datetime format
space_df['UTC_DATE'] = pd.to_datetime(space_df['UTC_DATE'], errors='coerce')
# Drop rows with invalid dates
space_df = space_df.dropna(subset=['UTC_DATE'])
# Remove timezone information
space_df['UTC_DATE'] = space_df['UTC_DATE'].dt.tz_localize(None)
# Set 'UTC_DATE' as the index
space_df.set_index('UTC_DATE', inplace=True)
# Drop non-numeric columns before aggregation
numeric_cols = space_df.select_dtypes(include=[np.number]).columns
space_df = space_df[numeric_cols]
if space_df.empty:
logging.warning("No numeric data available for aggregation after processing 'UTC_DATE'.")
return pd.DataFrame()
# Resample to daily frequency and aggregate
aggregated_space_df = space_df.resample('D').mean().reset_index()
return aggregated_space_df
def aggregate_near_earth_space_data(space_df, category):
"""
Aggregates space data to align with Earth weather data.
Uses specific time keepers for each type of space data.
Parameters:
space_df (pd.DataFrame): Space data DataFrame.
category (str): Category of the space event (e.g., 'FLR', 'CME').
Returns:
pd.DataFrame: Aggregated space data with 'UTC_DATE' as the date key.
"""
if space_df.empty:
logging.warning("Input space_df is empty. Returning empty DataFrame.")
return pd.DataFrame()
time_keepers = {
"CME": "UTC_DATE",
"CMEAnalysis": "UTC_DATE",
"FLR": "UTC_DATE",
"GST": "UTC_DATE",
"HSS": "UTC_DATE",
"IPS": "UTC_DATE",
"MPC": "UTC_DATE",
"notifications": "UTC_DATE",
"RBE": "UTC_DATE",
"SEP": "UTC_DATE",
"WSAEnlilSimulations": "UTC_DATE",
}
# Make a copy to avoid SettingWithCopyWarning
space_df = space_df.copy()
if category in time_keepers:
time_col = time_keepers[category]
if time_col in space_df.columns:
# Drop the existing 'UTC_DATE' column to prevent duplication
if 'UTC_DATE' in space_df.columns and time_col != 'UTC_DATE':
space_df = space_df.drop(columns=['UTC_DATE'])
logging.info(f"Dropped existing 'UTC_DATE' column to prevent duplication.")
# Rename the time column to 'UTC_DATE'
space_df = space_df.rename(columns={time_col: 'UTC_DATE'})
logging.info(f"Renamed '{time_col}' to 'UTC_DATE' for category '{category}'.")
else:
logging.warning(f"Time column '{time_col}' not found in data for category '{category}'.")
return pd.DataFrame() # Return empty DataFrame to avoid further errors
else:
logging.warning(f"Category '{category}' not found in time keepers.")
return pd.DataFrame()
# Remove duplicate columns
space_df = space_df.loc[:, ~space_df.columns.duplicated()]
# Ensure 'UTC_DATE' is in datetime format
space_df['UTC_DATE'] = pd.to_datetime(space_df['UTC_DATE'], errors='coerce')
# Drop rows with invalid dates
space_df = space_df.dropna(subset=['UTC_DATE'])
# Remove timezone information
space_df['UTC_DATE'] = space_df['UTC_DATE'].dt.tz_localize(None)
# Set 'UTC_DATE' as the index
space_df.set_index('UTC_DATE', inplace=True)
# Drop non-numeric columns before aggregation
numeric_cols = space_df.select_dtypes(include=[np.number]).columns
space_df = space_df[numeric_cols]
if space_df.empty:
logging.warning("No numeric data available for aggregation after processing 'UTC_DATE'.")
return pd.DataFrame()
# Resample to daily frequency and aggregate
aggregated_space_df = space_df.resample('D').mean().reset_index()
# Verify 'UTC_DATE' exists
if 'UTC_DATE' not in aggregated_space_df.columns:
logging.error("'UTC_DATE' column is missing after aggregation.")
return pd.DataFrame()
else:
logging.info(f"'UTC_DATE' column is present after aggregation with {aggregated_space_df.shape[0]} records.")
return aggregated_space_df
def generate_forecasts():
"""
Generates weather forecasts using historical weather and space data.
Saves the forecasts in distinct logs for each prediction period and returns them.
"""
global model, preprocessor
logging.info('Starting forecast generation...')
# Load the model if not loaded
if model is None:
model_path = os.path.join(KNOWLEDGE_PATH, 'model.joblib')
if os.path.exists(model_path):
try:
model = joblib.load(model_path)
logging.info('Model loaded successfully from model.joblib.')
except Exception as e:
logging.error(f'Failed to load model: {e}')
print(f'Failed to load model: {e}')
return {}
else:
logging.error('Model file model.joblib does not exist. Please train the model first.')
print('Model file model.joblib does not exist. Please train the model first.')
return {}
# Load the preprocessor if not loaded
if preprocessor is None:
preprocessor_path = os.path.join(KNOWLEDGE_PATH, 'preprocessor.joblib')
if os.path.exists(preprocessor_path):
try:
preprocessor = joblib.load(preprocessor_path)
logging.info('Preprocessor loaded successfully from preprocessor.joblib.')
except Exception as e:
logging.error(f'Failed to load preprocessor: {e}')
print(f'Failed to load preprocessor: {e}')
return {}
else:
logging.error('Preprocessor file preprocessor.joblib does not exist. Please train the model first.')
print('Preprocessor file preprocessor.joblib does not exist. Please train the model first.')
return {}
combined_data = load_and_prepare_data()
# Define forecast periods
forecast_periods = {
"monthly": 30,
"daily": 1,
"weekly": 7,
"yearly": 365
}
predictions_collection = {}
# Iterate through forecast periods
for period_name, days_ahead in forecast_periods.items():
# Define the target prediction start date
today = datetime.now()
prediction_start_date = (today + timedelta(days=days_ahead)).replace(hour=0, minute=0, second=0, microsecond=0)
logging.info(f"Preparing data for {period_name} forecast starting from {prediction_start_date.date()}...")
# Load and combine data up to the prediction date
combined_data = load_and_combine_data()
if combined_data.empty:
logging.warning(f"No data available for {period_name} forecast. Skipping...")
continue
# Filter data up to one month before the prediction date
combined_data = combined_data[combined_data['UTC_DATE'] < prediction_start_date]
# Preprocess data
X_data, _ = preprocess_data(combined_data, is_training=False)
if X_data is None:
logging.error(f"Failed to preprocess data for {period_name} forecast.")
continue
# **Debugging Statements:**
logging.debug(f"Type of X_data: {type(X_data)}")
logging.debug(f"Shape of X_data: {X_data.shape if hasattr(X_data, 'shape') else 'No shape'}")
if hasattr(X_data, 'dtype'):
logging.debug(f"Data type of X_data: {X_data.dtype}")
else:
logging.debug("X_data does not have 'dtype' attribute.")
# Perform predictions
logging.info(f"Generating predictions for {period_name} forecast...")
try:
predictions = model.predict(X_data)
logging.debug(f"Predictions shape: {predictions.shape}")
logging.debug(f"Predictions type: {type(predictions)}")
predictions_df = pd.DataFrame(
predictions, columns=list(TARGET_VARIABLES)
)
predictions_df['forecast_period'] = period_name
predictions_df['timestamp'] = datetime.now()
predictions_df['forecast_date'] = prediction_start_date
# Collect predictions for this forecast period
predictions_collection[period_name] = predictions_df
# Save predictions to a log file
forecast_log_path = os.path.join(
KNOWLEDGE_PATH, f"{period_name}_forecast_log.csv"
)
predictions_df.to_csv(
forecast_log_path, mode='a', header=not os.path.exists(forecast_log_path), index=False
)
logging.info(f"Saved {period_name} forecast predictions to {forecast_log_path}.")
except Exception as e:
logging.error(f"Failed to generate predictions for {period_name} forecast: {e}")
print(f"Failed to generate predictions for {period_name} forecast: {e}")
# Return predictions as a dictionary of DataFrames
return predictions_collection
# ============================
# Data Preprocessing
# ============================
def validate_numeric_columns(df):
"""
Validates that numeric columns in the DataFrame contain only numeric data.
Parameters:
df (pd.DataFrame): DataFrame to validate.
Returns:
pd.DataFrame: Cleaned DataFrame with invalid rows dropped or coerced.
"""
for col in df.select_dtypes(include='object').columns:
try:
df[col] = pd.to_numeric(df[col], errors='coerce')
logging.info(f"Column '{col}' successfully coerced to numeric.")
except Exception as e:
logging.warning(f"Column '{col}' contains non-numeric data: {e}")
handle_non_numeric_columns(df)
return df
def handle_non_numeric_columns(df):
"""
Handles non-numeric columns by dropping or converting them to numeric through .
Input DataFrame is modified in place.
Output: DataFrame with non-numeric columns dropped or converted to numeric.
"""
return df
def parse_json(value):
"""
Attempts to parse a JSON-like string into a Python object.
Parameters:
value (str): The string to parse.
Returns:
list or dict or None: Parsed object or None if parsing fails.
"""
if pd.isnull(value):
return None
try:
# Clean up the string
value = str(value).strip()
# Replace single quotes with double quotes
value = value.replace("'", '"')
# Fix common issues with brackets and braces
if not (value.startswith('[') or value.startswith('{')):
value = '[' + value + ']'
if not (value.endswith(']') or value.endswith('}')):
value = value + ']'
# Remove any trailing commas
value = value.rstrip(',').rstrip(';')
# Parse the JSON string
return json.loads(value)
except json.JSONDecodeError as e:
logging.warning(f"JSON decoding failed for value: {value} with error: {e}")
return None
def clean_utc_date(date_series):
def clean_single_date(date_str):
if pd.isnull(date_str):
return pd.NaT
try:
# Remove any trailing non-datetime information (e.g., '-CME-001')
clean_str = str(date_str).split('-')[0]
# Handle cases where time is missing
if 'T' not in clean_str:
clean_str += 'T00:00:00'
return pd.to_datetime(clean_str)
except Exception as e:
logging.warning(f"Failed to parse date '{date_str}': {e}")
return pd.NaT
return date_series.apply(clean_single_date)
def process_text_features(df):
"""
Identifies text columns and processes them using TF-IDF vectorization.
Parameters:
df (pd.DataFrame): The input DataFrame.
Returns:
pd.DataFrame: DataFrame with text features processed.
"""
# Identify text columns
text_columns = df.select_dtypes(include=['object']).columns
for col in text_columns:
df[col] = df[col].astype(str).fillna('')
tfidf = TfidfVectorizer()
tfidf_matrix = tfidf.fit_transform(df[col])
tfidf_df = pd.DataFrame(tfidf_matrix.toarray(), columns=[f"{col}_{word}" for word in tfidf.get_feature_names_out()], index=df.index)
df = pd.concat([df.drop(col, axis=1), tfidf_df], axis=1)
return df
def preprocess_data(df, is_training=False):
global preprocessor, num_imputer, cat_imputer, FEATURE_COLUMNS, TARGET_VARIABLES, CATEGORICAL_FEATURES, NUMERICAL_FEATURES
logging.info('Preprocessing data...')
# Make a copy to prevent errors
df = df.copy()
# Return none if data is empty
if df.empty:
logging.error('Input DataFrame is empty.')
return None, None
# Apply column mappings
df = apply_column_mappings(df) # Good: No issues
# Integrate the text processing into the preprocessing pipeline
df = process_text_features(df)
# Step 1: Validate 'UTC_DATE' and extract time-based features
df = validate_and_extract_time_features(df)
if df is None:
return None, None
# Step 2: Parse JSON-like strings into actual lists/dicts
df = parse_json_columns(df)