Fa0713/Demand_Prediction
1
1import folium2import math3import numpy as np4import pandas as pd5from sklearn.preprocessing import StandardScaler6from sklearn.ensemble import RandomForestClassifier7import gradio as gr8 9# Load data files10regions_df = pd.read_csv("delhi_region_landmark_distances_corrected.csv")11train_df = pd.read_csv("delhi_region_demand_dataset_(USE).csv")12 13features = ['day_of_week', 'month', 'holiday', 'temperature', 'humidity',14 'wind_speed', 'rainfall', 'dist_city', 'dist_airport', 'dist_railway']15weather_features = ['temperature', 'humidity', 'wind_speed', 'rainfall']16target = 'demand'17 18def get_calendar_features(date_str):19 dt = pd.to_datetime(date_str)20 return {'day_of_week': dt.weekday(), 'month': dt.month, 'holiday': int(dt.weekday() == 6)}21 22def generate_random_weather():23 return {24 'temperature': np.random.uniform(15, 35),25 'humidity': np.random.uniform(20, 80),26 'wind_speed': np.random.uniform(0, 10),27 'rainfall': np.random.choice([0.0, 0.5, 1.0, 5.0])28 }29 30def destination_point(lat, lon, distance_m, bearing_deg):31 R = 637100032 bearing = math.radians(bearing_deg)33 lat1, lon1 = math.radians(lat), math.radians(lon)34 lat2 = math.asin(math.sin(lat1)*math.cos(distance_m/R) + math.cos(lat1)*math.sin(distance_m/R)*math.cos(bearing))35 lon2 = lon1 + math.atan2(math.sin(bearing)*math.sin(distance_m/R)*math.cos(lat1),36 math.cos(distance_m/R) - math.sin(lat1)*math.sin(lat2))37 return math.degrees(lat2), math.degrees(lon2)38 39def create_map_for_date(date_str, predictions_df):40 delhi_center = (28.6139, 77.2090)41 R = 3000042 R1 = R / math.sqrt(31)43 ring_radii = [R1 * math.sqrt(2**k - 1) for k in range(1, 6)]44 sectors_per_ring = [4 * 2**(k - 1) for k in range(1, 6)]45 46 m = folium.Map(location=delhi_center, zoom_start=11)47 region_num = 148 49 for i, r_outer in enumerate(ring_radii):50 r_inner = 0 if i == 0 else ring_radii[i - 1]51 sectors = sectors_per_ring[i]52 sector_angle = 360 / sectors53 54 for sector in range(sectors):55 start_angle = sector * sector_angle56 end_angle = (sector + 1) * sector_angle57 points = []58 59 for angle in np.linspace(start_angle, end_angle, 10):60 lat, lon = destination_point(delhi_center[0], delhi_center[1], r_inner, angle)61 points.append((lat, lon))62 for angle in np.linspace(end_angle, start_angle, 10):63 lat, lon = destination_point(delhi_center[0], delhi_center[1], r_outer, angle)64 points.append((lat, lon))65 66 demand_val = predictions_df.loc[predictions_df['region'] == region_num, 'predicted_demand'].values67 demand_val = demand_val[0] if len(demand_val) > 0 else 068 color = 'red' if demand_val == 1 else 'blue'69 70 folium.Polygon(71 locations=points,72 color=color,73 fill=True,74 fill_color=color,75 fill_opacity=0.4,76 weight=1,77 tooltip=f'Region {region_num}: Demand={"High" if demand_val == 1 else "Low"} - Date: {date_str}'78 ).add_to(m)79 80 region_num += 181 82 return m._repr_html_()83 84def predict_and_map(dates_input):85 dates_to_predict = [d.strip() for d in dates_input.split(",") if d.strip()]86 output_maps = []87 88 X = train_df[features].copy()89 y = train_df[target]90 if X['holiday'].dtype == bool:91 X['holiday'] = X['holiday'].astype(int)92 93 scaler = StandardScaler()94 X[weather_features] = scaler.fit_transform(X[weather_features])95 96 model = RandomForestClassifier(n_estimators=100, random_state=42)97 model.fit(X, y)98 99 for date_str in dates_to_predict:100 records = []101 calendar_features = get_calendar_features(date_str)102 weather_vals = generate_random_weather()103 104 for _, region in regions_df.iterrows():105 record = {106 'region': region['region'],107 'dist_city': region['dist_city'],108 'dist_airport': region['dist_airport'],109 'dist_railway': region['dist_railway'],110 **calendar_features,111 **weather_vals112 }113 records.append(record)114 115 df_pred = pd.DataFrame(records)116 df_pred[weather_features] = scaler.transform(df_pred[weather_features])117 X_pred = df_pred[features]118 preds = model.predict(X_pred)119 df_pred['predicted_demand'] = preds120 121 m_html = create_map_for_date(date_str, df_pred)122 output_maps.append(m_html)123 124 return output_maps[0] if output_maps else "No valid dates provided."125 126interface = gr.Interface(127 fn=predict_and_map,128 inputs=gr.Textbox(label="Enter date(s) (comma-separated, format: YYYY-MM-DD)"),129 outputs=gr.HTML(label="Predicted Demand Map"),130 title="Delhi Region Demand Forecast Map",131 description="Enter one or more dates to predict demand and visualize it on the Delhi region map."132)133 134if __name__ == "__main__":135 interface.launch()136 