safiaa02 commited on
Commit
49ac943
·
verified ·
1 Parent(s): a26cc1f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +59 -13
app.py CHANGED
@@ -5,11 +5,16 @@ import plotly.express as px
5
  from datetime import datetime, timedelta
6
  from prophet import Prophet
7
  import networkx as nx
 
 
 
 
 
8
 
9
  # Generate synthetic data
10
  def generate_data():
11
- schools = [f"School_{i}" for i in range(1, 11)]
12
- time_range = [datetime.now() - timedelta(hours=i) for i in range(24)]
13
 
14
  data = []
15
  for school in schools:
@@ -24,14 +29,19 @@ def generate_data():
24
  # Load or generate data
25
  df = generate_data()
26
 
 
 
 
 
 
27
  def train_prophet(df):
28
- df["Timestamp"] = pd.to_datetime(df["Timestamp"])
29
  df_numeric = df[["Timestamp", "Bandwidth_Usage"]] # Select only numeric columns
30
- df_prophet = df_numeric.groupby("Timestamp").mean().reset_index()
31
- df_prophet.columns = ["ds", "y"]
32
 
33
  model = Prophet()
34
- model.fit(df_prophet)
35
 
36
  future = model.make_future_dataframe(periods=5, freq="H") # Predict next 5 hours
37
  forecast = model.predict(future)
@@ -39,17 +49,46 @@ def train_prophet(df):
39
  return forecast
40
 
41
  def allocate_bandwidth(demand_predictions, total_bandwidth=500):
42
- total_demand = sum(demand_predictions.values())
43
  allocation = {school: (demand / total_demand) * total_bandwidth for school, demand in demand_predictions.items()}
44
  return allocation
45
 
46
  def sdn_load_balancer(network_graph, demand_predictions):
47
- # Simulating a simple SDN-based routing decision
48
  shortest_paths = {}
49
  for school in demand_predictions.keys():
50
  shortest_paths[school] = nx.shortest_path(network_graph, source='Central_Node', target=school)
51
  return shortest_paths
52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
  # Create a simple network topology
54
  graph = nx.Graph()
55
 
@@ -61,17 +100,24 @@ graph.add_edges_from([
61
 
62
  # Train model and make predictions
63
  forecast = train_prophet(df)
64
- demand_predictions = {f"School_{i}": np.random.randint(20, 100) for i in range(1, 6)}
65
- bandwidth_allocation = allocate_bandwidth(demand_predictions)
66
- network_routes = sdn_load_balancer(graph, demand_predictions)
 
67
 
68
  # Streamlit UI
69
  st.title("Smart Network Resource Allocation with SDN Load Balancing")
 
70
  fig = px.line(df, x="Timestamp", y="Bandwidth_Usage", color="School", title="Bandwidth Usage Over Time")
71
  st.plotly_chart(fig)
72
 
73
  st.write("Predicted Bandwidth Allocations:")
74
- st.json(bandwidth_allocation)
 
75
 
76
  st.write("SDN-based Load Balancing Routes:")
77
- st.json(network_routes)
 
 
 
 
 
5
  from datetime import datetime, timedelta
6
  from prophet import Prophet
7
  import networkx as nx
8
+ from ryu.base import app_manager
9
+ from ryu.controller import ofp_event
10
+ from ryu.controller.handler import MAIN_DISPATCHER, set_ev_cls
11
+ from ryu.ofproto import ofproto_v1_3
12
+ from ryu.lib.packet import packet, ethernet
13
 
14
  # Generate synthetic data
15
  def generate_data():
16
+ schools = [f"School_{i}" for i in range(1, 11)] # 10 Schools
17
+ time_range = [datetime.now() - timedelta(hours=i) for i in range(24)] # Past 24 hours
18
 
19
  data = []
20
  for school in schools:
 
29
  # Load or generate data
30
  df = generate_data()
31
 
32
+ def detect_anomalies(df):
33
+ df['Z_Score'] = (df['Bandwidth_Usage'] - df['Bandwidth_Usage'].mean()) / df['Bandwidth_Usage'].std()
34
+ anomalies = df[df['Z_Score'].abs() > 2] # Mark as anomaly if Z-score > 2
35
+ return anomalies
36
+
37
  def train_prophet(df):
38
+ df["Timestamp"] = pd.to_datetime(df["Timestamp"]) # Convert to datetime format
39
  df_numeric = df[["Timestamp", "Bandwidth_Usage"]] # Select only numeric columns
40
+ df_prophet = df_numeric.groupby("Timestamp").mean().reset_index() # Average bandwidth per timestamp
41
+ df_prophet.columns = ["ds", "y"] # Prophet model requires columns: ds (date) and y (value)
42
 
43
  model = Prophet()
44
+ model.fit(df_prophet) # Train Prophet on past data
45
 
46
  future = model.make_future_dataframe(periods=5, freq="H") # Predict next 5 hours
47
  forecast = model.predict(future)
 
49
  return forecast
50
 
51
  def allocate_bandwidth(demand_predictions, total_bandwidth=500):
52
+ total_demand = sum(demand_predictions.values()) # Calculate total demand
53
  allocation = {school: (demand / total_demand) * total_bandwidth for school, demand in demand_predictions.items()}
54
  return allocation
55
 
56
  def sdn_load_balancer(network_graph, demand_predictions):
 
57
  shortest_paths = {}
58
  for school in demand_predictions.keys():
59
  shortest_paths[school] = nx.shortest_path(network_graph, source='Central_Node', target=school)
60
  return shortest_paths
61
 
62
+ # SDN Controller Class
63
+ class SimpleSwitch13(app_manager.RyuApp):
64
+ OFP_VERSIONS = [ofproto_v1_3.OFP_VERSION]
65
+
66
+ def __init__(self, *args, **kwargs):
67
+ super(SimpleSwitch13, self).__init__(*args, **kwargs)
68
+ self.mac_to_port = {}
69
+
70
+ @set_ev_cls(ofp_event.EventOFPPacketIn, MAIN_DISPATCHER)
71
+ def packet_in_handler(self, ev):
72
+ msg = ev.msg
73
+ datapath = msg.datapath
74
+ ofproto = datapath.ofproto
75
+ parser = datapath.ofproto_parser
76
+ in_port = msg.match['in_port']
77
+
78
+ pkt = packet.Packet(msg.data)
79
+ eth = pkt.get_protocol(ethernet.ethernet)
80
+ dst = eth.dst
81
+ src = eth.src
82
+
83
+ if dst in self.mac_to_port:
84
+ out_port = self.mac_to_port[dst]
85
+ else:
86
+ out_port = ofproto.OFPP_FLOOD
87
+
88
+ actions = [parser.OFPActionOutput(out_port)]
89
+ out = parser.OFPPacketOut(datapath=datapath, buffer_id=msg.buffer_id, in_port=in_port, actions=actions, data=msg.data)
90
+ datapath.send_msg(out)
91
+
92
  # Create a simple network topology
93
  graph = nx.Graph()
94
 
 
100
 
101
  # Train model and make predictions
102
  forecast = train_prophet(df)
103
+ demand_predictions = {f"School_{i}": np.random.randint(20, 100) for i in range(1, 6)} # Random demand per school
104
+ bandwidth_allocation = allocate_bandwidth(demand_predictions) # Allocate bandwidth
105
+ network_routes = sdn_load_balancer(graph, demand_predictions) # Compute SDN-based routes
106
+ anomalies = detect_anomalies(df) # Detect anomalies
107
 
108
  # Streamlit UI
109
  st.title("Smart Network Resource Allocation with SDN Load Balancing")
110
+
111
  fig = px.line(df, x="Timestamp", y="Bandwidth_Usage", color="School", title="Bandwidth Usage Over Time")
112
  st.plotly_chart(fig)
113
 
114
  st.write("Predicted Bandwidth Allocations:")
115
+ for school, bandwidth in bandwidth_allocation.items():
116
+ st.write(f"{school}: {bandwidth:.2f} Mbps")
117
 
118
  st.write("SDN-based Load Balancing Routes:")
119
+ for school, path in network_routes.items():
120
+ st.write(f"{school}: {' -> '.join(path)}")
121
+
122
+ st.write("Detected Anomalies:")
123
+ st.dataframe(anomalies)