Talha1218's picture
Update app.py
71ca5ad verified
Raw History Blame Contribute Delete
8.9 kB
import streamlit as st
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import random
import os
import json
from matplotlib.colors import LinearSegmentedColormap
from deap import base, creator, tools, algorithms
from scipy.optimize import differential_evolution
from scipy.spatial.distance import cdist
# Custom CSS for styling
st.markdown("""
<style>
.title {
text-align: center;
color: #3498db;
}
.container {
text-align: center;
margin-bottom: 30px;
}
.stButton>button {
background-color: #3498db;
color: white;
font-size: 18px;
border-radius: 8px;
padding: 10px;
margin-top: 10px;
}
.stButton>button:hover {
background-color: #2980b9;
}
.stSlider>div>div>input {
background-color: #ecf0f1;
}
</style>
""", unsafe_allow_html=True)
# Router Models (with different ranges and powers)
router_models = {
'Basic Router': {'range': 20, 'power': 50},
'Advanced Router': {'range': 30, 'power': 75},
'High-End Router': {'range': 50, 'power': 100}
}
# Generate random layout for routers
def generate_layout(area_size, num_routers):
grid_size = int(np.sqrt(num_routers))
x = np.linspace(0, area_size, grid_size)
y = np.linspace(0, area_size, grid_size)
xx, yy = np.meshgrid(x, y)
points = np.vstack([xx.ravel(), yy.ravel()]).T
return points
# Function to create heatmap of signal strength
def create_heatmap(area_size, points, router_range):
heatmap = np.zeros((area_size, area_size))
for point in points:
x, y = point
for i in range(area_size):
for j in range(area_size):
distance = np.sqrt((x - i) ** 2 + (y - j) ** 2)
if distance < router_range:
heatmap[i, j] += max(0, router_range - distance)
heatmap = heatmap / np.max(heatmap)
return heatmap
# Simulated Annealing
def simulated_annealing(area_size, num_routers, router_range):
# Initialize random points
points = np.random.rand(num_routers, 2) * area_size
def energy(points):
heatmap = create_heatmap(area_size, points, router_range)
return -np.sum(heatmap) # Energy function (we want to maximize coverage)
def anneal(points):
current_temp = 100
min_temp = 1e-3
alpha = 0.99
while current_temp > min_temp:
new_points = points + np.random.normal(0, 5, points.shape)
new_points = np.clip(new_points, 0, area_size)
current_energy = energy(points)
new_energy = energy(new_points)
if new_energy > current_energy or np.random.rand() < np.exp((new_energy - current_energy) / current_temp):
points = new_points
current_temp *= alpha
return points
return anneal(points)
# Particle Swarm Optimization (PSO)
def particle_swarm_optimization(area_size, num_routers, router_range):
positions = np.random.rand(num_routers, 2) * area_size
velocities = np.random.rand(num_routers, 2) * 2 - 1
personal_best_positions = positions.copy()
personal_best_scores = np.array([np.inf] * num_routers)
global_best_position = positions[np.argmin(personal_best_scores)]
def objective_function(positions):
heatmap = create_heatmap(area_size, positions, router_range)
return -np.sum(heatmap) # Energy function (maximize coverage)
for i in range(100):
for j in range(num_routers):
score = objective_function(positions[j:j+1])
if score < personal_best_scores[j]:
personal_best_scores[j] = score
personal_best_positions[j] = positions[j]
global_best_position = personal_best_positions[np.argmin(personal_best_scores)]
for j in range(num_routers):
r1, r2 = np.random.rand(2)
velocities[j] = 0.5 * velocities[j] + r1 * (personal_best_positions[j] - positions[j]) + r2 * (global_best_position - positions[j])
positions[j] += velocities[j]
positions[j] = np.clip(positions[j], 0, area_size)
return positions
# Differential Evolution (DE)
def differential_evolution_optimization(area_size, num_routers, router_range):
def objective_function(x):
points = np.array(x).reshape((num_routers, 2))
heatmap = create_heatmap(area_size, points, router_range)
return -np.sum(heatmap) # Energy function (maximize coverage)
bounds = [(0, area_size), (0, area_size)] * num_routers # Define bounds for routers' positions
result = differential_evolution(objective_function, bounds, maxiter=1000, popsize=15, mutation=(0.5, 1), recombination=0.7)
points = np.array(result.x).reshape((num_routers, 2))
return points
# Streamlit UI
st.title("Network Coverage Optimization for 5G/WiFi", anchor="top")
# Sidebar Configuration Inputs
with st.sidebar:
st.header("Configuration")
area_size = st.slider("Select Area Size (m²)", 50, 500, 100, 10)
num_routers = st.slider("Select Number of Routers", 1, 20, 5, 1)
router_model = st.selectbox("Select Router Model", list(router_models.keys()))
router_range = router_models[router_model]['range']
router_power = router_models[router_model]['power']
optimize_method = st.radio("Optimization Method",
("Random Layout",
"Simulated Annealing",
"Particle Swarm Optimization",
"Differential Evolution"), key="method")
multi_floor = st.checkbox("Enable Multi-Floor Layout")
if multi_floor:
num_floors = st.slider("Select Number of Floors", 1, 5, 2)
floor_plan = st.file_uploader("Upload Floor Plan Image", type=["jpg", "jpeg", "png"])
# Default to 1 floor if multi-floor is not enabled
if not multi_floor:
num_floors = 1
# Generate Layout
if st.button("Generate Layout"):
# Generate layout based on method
if optimize_method == "Random Layout":
points = generate_layout(area_size, num_routers)
elif optimize_method == "Simulated Annealing":
points = simulated_annealing(area_size, num_routers, router_range)
elif optimize_method == "Particle Swarm Optimization":
points = particle_swarm_optimization(area_size, num_routers, router_range)
elif optimize_method == "Differential Evolution":
points = differential_evolution_optimization(area_size, num_routers, router_range)
# Create heatmap based on the layout
heatmap = create_heatmap(area_size, points, router_range)
# Plot Layout and Heatmap for each floor if multi-floor is enabled
for floor in range(1, num_floors + 1):
fig, ax = plt.subplots(figsize=(8, 6))
# Show Floor Plan Image if uploaded
if floor_plan is not None:
floor_plan_img = plt.imread(floor_plan)
ax.imshow(floor_plan_img, extent=[0, area_size, 0, area_size], aspect="auto", alpha=0.5)
# Plot routers and coverage
ax.scatter(points[:, 0], points[:, 1], color="blue", label="Router Location", s=100, edgecolor='black', alpha=0.7)
for i in range(len(points)):
circle = patches.Circle((points[i][0], points[i][1]), router_range, linewidth=1, edgecolor='green', facecolor='none', linestyle='--')
ax.add_patch(circle)
# Overlay heatmap
cmap = LinearSegmentedColormap.from_list("signal", ["red", "yellow", "green"])
ax.imshow(heatmap, extent=[0, area_size, 0, area_size], alpha=0.3, cmap=cmap)
ax.set_title(f"Network Coverage Layout - Floor {floor}", fontsize=18)
ax.set_xlabel("X Coordinates (m)", fontsize=14)
ax.set_ylabel("Y Coordinates (m)", fontsize=14)
ax.legend(loc="best")
plt.grid(True)
st.pyplot(fig)
# Show coverage percentage
total_area = area_size**2
coverage_area = np.pi * (router_range**2) * num_routers
coverage_percentage = (coverage_area / total_area) * 100
st.write(f"Total Area: {total_area} m²")
st.write(f"Total Coverage Area: {coverage_area:.2f} m²")
st.write(f"Coverage Percentage: {coverage_percentage:.2f}%")
# Save Layout as JSON (for download)
layout_data = {
"area_size": area_size,
"num_routers": num_routers,
"router_range": router_range,
"points": points.tolist()
}
json_filename = "optimized_layout.json"
with open(json_filename, 'w') as f:
json.dump(layout_data, f)
# Provide download button
with open(json_filename, 'r') as f:
st.download_button("Download Optimized Layout", f, file_name=json_filename)