-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathoptimizer.py
More file actions
239 lines (205 loc) · 10.1 KB
/
optimizer.py
File metadata and controls
239 lines (205 loc) · 10.1 KB
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
"""
BreezePath AI — AI Cooling Optimizer
Evaluates multiple cooling strategies and recommends the best actions.
Includes optional budget-constrained optimization.
"""
import copy
from model import compute_heat
from simulation import simulate_wind
from metrics import compute_metrics
# ═══════════════════════════════════════════════════════════════════
# COST TABLE (₹ in lakhs)
# ═══════════════════════════════════════════════════════════════════
COSTS = {
"add_tree": 0.5, # ₹0.5 lakh per tree cell
"add_water": 1.5, # ₹1.5 lakh per water cell
"reduce_height": 2.0, # ₹2 lakh per floor reduction
}
def _evaluate_grid(grid):
"""Run heat + wind simulation and return metrics."""
g = compute_heat(grid)
w = simulate_wind(g)
m = compute_metrics(g, w)
return g, w, m
def _try_action(grid, action_type, row, col, extra=None):
"""Apply a single action to a copy of the grid and return (new_grid, cost)."""
g = copy.deepcopy(grid)
cost = 0.0
if action_type == "add_tree":
g[row][col] = {"type": "vegetation", "height": 1, "heat": 0.0, "wind_block": 0.0}
cost = COSTS["add_tree"]
elif action_type == "add_water":
g[row][col] = {"type": "water", "height": 0, "heat": 0.0, "wind_block": 0.0}
cost = COSTS["add_water"]
elif action_type == "reduce_height":
if g[row][col]["type"] == "building" and g[row][col]["height"] > 1:
reduction = min(2, g[row][col]["height"] - 1)
g[row][col]["height"] -= reduction
cost = COSTS["reduce_height"] * reduction
return g, cost
# ═══════════════════════════════════════════════════════════════════
# CORE OPTIMIZER
# ═══════════════════════════════════════════════════════════════════
def optimize_cooling(grid, budget=None, max_suggestions=5):
"""
Evaluate candidate cooling actions and return the best ones.
For each candidate cell, tries adding vegetation, water, or reducing height.
Ranks by temperature reduction per unit cost (or absolute if no budget).
Returns list of suggestion dicts sorted by effectiveness:
[{
"action": str,
"icon": str,
"row": int, "col": int,
"description": str,
"temp_reduction": float,
"cost": float,
"benefit_ratio": float,
}]
"""
rows, cols = len(grid), len(grid[0])
_, _, base_mets = _evaluate_grid(grid)
base_temp = base_mets["avg_temp"]
candidates = []
# Identify hot cells and their neighbors for tree/water placement
hot_cells = []
for r in range(rows):
for c in range(cols):
if grid[r][c]["heat"] > 33:
hot_cells.append((r, c, grid[r][c]["heat"]))
hot_cells.sort(key=lambda x: -x[2])
# Find empty/building neighbors of hot cells as candidates
tested = set()
for hr, hc, _ in hot_cells[:20]: # top 20 hottest
for dr in range(-1, 2):
for dc in range(-1, 2):
nr, nc = hr + dr, hc + dc
if 0 <= nr < rows and 0 <= nc < cols and (nr, nc) not in tested:
tested.add((nr, nc))
cell = grid[nr][nc]
# Try adding tree on empty/building cells
if cell["type"] in ("empty", "building"):
g, cost = _try_action(grid, "add_tree", nr, nc)
_, _, m = _evaluate_grid(g)
dt = base_temp - m["avg_temp"]
if dt > 0.01:
ratio = dt / max(cost, 0.01)
candidates.append({
"action": "add_tree",
"icon": "🌳",
"row": nr, "col": nc,
"description": f"Plant trees at ({nr}, {nc})",
"detail": f"Reduces avg temp by {dt:.2f}°C",
"temp_reduction": round(dt, 3),
"cost": cost,
"benefit_ratio": round(ratio, 3),
})
# Try adding water on empty cells
if cell["type"] == "empty":
g, cost = _try_action(grid, "add_water", nr, nc)
_, _, m = _evaluate_grid(g)
dt = base_temp - m["avg_temp"]
if dt > 0.01:
ratio = dt / max(cost, 0.01)
candidates.append({
"action": "add_water",
"icon": "💧",
"row": nr, "col": nc,
"description": f"Add water feature at ({nr}, {nc})",
"detail": f"Reduces avg temp by {dt:.2f}°C",
"temp_reduction": round(dt, 3),
"cost": cost,
"benefit_ratio": round(ratio, 3),
})
# Try reducing building height
if cell["type"] == "building" and cell["height"] >= 3:
g, cost = _try_action(grid, "reduce_height", nr, nc)
_, _, m = _evaluate_grid(g)
dt = base_temp - m["avg_temp"]
if dt > 0.005:
ratio = dt / max(cost, 0.01)
candidates.append({
"action": "reduce_height",
"icon": "📐",
"row": nr, "col": nc,
"description": f"Reduce building height at ({nr}, {nc})",
"detail": f"Reduces avg temp by {dt:.2f}°C, improves wind",
"temp_reduction": round(dt, 3),
"cost": cost,
"benefit_ratio": round(ratio, 3),
})
if len(candidates) > 40: # cap for perf
break
if len(candidates) > 40:
break
if len(candidates) > 40:
break
# Sort by benefit ratio (best bang for buck)
candidates.sort(key=lambda x: -x["benefit_ratio"])
# Budget filtering
if budget is not None and budget > 0:
selected = []
remaining = budget
for c in candidates:
if c["cost"] <= remaining:
selected.append(c)
remaining -= c["cost"]
if len(selected) >= max_suggestions:
break
return selected, budget - remaining # return (suggestions, total_spent)
return candidates[:max_suggestions], sum(c["cost"] for c in candidates[:max_suggestions])
def compute_optimization_impact(grid, suggestions):
"""Apply all suggestions and compute the combined impact."""
g = copy.deepcopy(grid)
for s in suggestions:
if s["action"] == "add_tree":
g[s["row"]][s["col"]] = {"type": "vegetation", "height": 1, "heat": 0.0, "wind_block": 0.0}
elif s["action"] == "add_water":
g[s["row"]][s["col"]] = {"type": "water", "height": 0, "heat": 0.0, "wind_block": 0.0}
elif s["action"] == "reduce_height":
if g[s["row"]][s["col"]]["type"] == "building":
g[s["row"]][s["col"]]["height"] = max(1, g[s["row"]][s["col"]]["height"] - 2)
_, _, base_mets = _evaluate_grid(grid)
opt_grid, opt_wind, opt_mets = _evaluate_grid(g)
return {
"optimized_grid": opt_grid,
"optimized_wind": opt_wind,
"optimized_metrics": opt_mets,
"base_metrics": base_mets,
"delta_temp": round(base_mets["avg_temp"] - opt_mets["avg_temp"], 2),
"delta_wind": round(opt_mets["wind_efficiency"] - base_mets["wind_efficiency"], 2),
"delta_cooling": round(opt_mets["cooling_score"] - base_mets["cooling_score"], 1),
}
def generate_optimizer_story(suggestions, impact, budget_used=None):
"""Generate human-readable optimization narrative."""
stories = []
total_reduction = impact["delta_temp"]
n = len(suggestions)
if total_reduction > 0:
cost_str = f" for ₹{budget_used:.1f} lakh" if budget_used else ""
stories.append(
f"🧠 **AI Optimal Strategy:** By implementing **{n} targeted changes**{cost_str}, "
f"city temperature can be reduced by **{total_reduction:.2f}°C**."
)
else:
stories.append("ℹ️ Current city is already well-optimized for cooling.")
if impact["delta_wind"] > 0:
stories.append(f"🌬️ Wind efficiency improves by **{impact['delta_wind']:.1f}%**.")
if impact["delta_cooling"] > 0:
stories.append(f"❄️ Cooling score increases by **{impact['delta_cooling']:.1f}** points.")
# Energy savings narrative
if total_reduction > 0.3:
savings = min(25, total_reduction * 5)
stories.append(f"⚡ Projected energy savings: **~{savings:.0f}%** reduction in cooling costs.")
tree_count = sum(1 for s in suggestions if s["action"] == "add_tree")
water_count = sum(1 for s in suggestions if s["action"] == "add_water")
height_count = sum(1 for s in suggestions if s["action"] == "reduce_height")
parts = []
if tree_count:
parts.append(f"{tree_count} tree plantings")
if water_count:
parts.append(f"{water_count} water features")
if height_count:
parts.append(f"{height_count} height reductions")
if parts:
stories.append(f"📋 Actions: {', '.join(parts)}.")
return stories