File size: 8,902 Bytes
fa645f6
 
 
2d287d6
659f36f
dcbc929
c11cfeb
 
f861cc8
71ca5ad
 
fa645f6
dbc589b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fa645f6
f861cc8
 
 
 
 
 
 
c11cfeb
fa645f6
 
 
 
 
 
 
 
c11cfeb
 
 
 
 
 
 
 
 
f861cc8
c11cfeb
 
 
71ca5ad
 
 
 
 
 
f861cc8
71ca5ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f861cc8
71ca5ad
 
 
f861cc8
71ca5ad
 
 
 
 
 
 
 
 
 
 
 
 
f861cc8
71ca5ad
 
 
 
 
 
 
 
 
 
 
 
 
f861cc8
c11cfeb
f861cc8
fa645f6
c11cfeb
dbc589b
 
 
 
f861cc8
 
 
 
71ca5ad
 
 
 
 
f861cc8
 
71ca5ad
f861cc8
 
 
dcbc929
fa645f6
71ca5ad
 
 
 
c11cfeb
fa645f6
c11cfeb
dbc589b
fa645f6
71ca5ad
 
 
 
 
 
c11cfeb
 
 
2d287d6
f861cc8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dcbc929
c11cfeb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dbc589b
 
 
fa645f6
4fbf8e2
 
 
 
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
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)