import numpy as np import random import math import os from core.constants import (ROOM_MIN_AREA, ROOM_MAX_AREA, REQUIRED_ADJACENCIES, VASTU_RULES, COST_PER_SQFT, PLUMBING_COST_PER_METER, WALL_COST_PER_METER, CLIMATE_ZONES, ADJACENCY_MATRIX, ADJ_WEIGHTS, ADJ_HIGH, ADJ_MED, ADJ_LOW, ADJ_ZERO, ADJ_FORBIDDEN, get_adjacency_class) class Room: def __init__(self, name, x, y, w, h): self.name = name self.x = x # left edge (ft) self.y = y # bottom edge (ft) self.w = w # width (ft) self.h = h # height (ft) self.area = w * h @property def cx(self): return self.x + self.w / 2 @property def cy(self): return self.y + self.h / 2 @property def right(self): return self.x + self.w @property def top(self): return self.y + self.h def zone(self, plot_w, plot_h): """Return compass zone of room centre relative to plot.""" cx_n = self.cx / plot_w # 0-1 cy_n = self.cy / plot_h # 0-1 (0=south, 1=north) if cx_n < 0.33: h = "W" elif cx_n > 0.66: h = "E" else: h = "C" if cy_n > 0.66: v = "N" elif cy_n < 0.33: v = "S" else: v = "M" zone_map = { ("W","N"): "NW", ("C","N"): "N", ("E","N"): "NE", ("W","M"): "W", ("C","M"): "Centre", ("E","M"): "E", ("W","S"): "SW", ("C","S"): "S", ("E","S"): "SE", } return zone_map.get((h, v), "Centre") def shares_wall(self, other, tol=0.5, min_overlap=2.0): """Two rooms share a wall iff their edges meet AND they have a real overlap along that wall (≥ `min_overlap` ft). Tiny corner kisses (< 2 ft) don't count — they're geometric artefacts, not doors. """ touching_v = (abs(self.right - other.x) < tol or abs(other.right - self.x) < tol) if touching_v: ov = min(self.top, other.top) - max(self.y, other.y) if ov >= min_overlap: return True touching_h = (abs(self.top - other.y) < tol or abs(other.top - self.y) < tol) if touching_h: ov = min(self.right, other.right) - max(self.x, other.x) if ov >= min_overlap: return True return False def distance_to(self, other): return math.sqrt((self.cx - other.cx)**2 + (self.cy - other.cy)**2) def overlaps(self, other, tol=0.5): return (self.x + tol < other.right and other.x + tol < self.right and self.y + tol < other.top and other.y + tol < self.top) class FloorPlan: def __init__(self, rooms, plot_w, plot_h): self.rooms = rooms # list of Room objects self.plot_w = plot_w self.plot_h = plot_h self.scores = {} def get_room(self, name): for r in self.rooms: if r.name == name: return r return None def generate_floorplan(room_names, plot_w, plot_h, seed=None): """ Rule-guided rectangle packing floor plan generator. Places rooms using priority order and adjacency hints. Returns a FloorPlan object. """ if seed is not None: random.seed(seed) np.random.seed(seed) # Sort by size priority: living first, then bedrooms, kitchen, others priority_order = [ "living_room", "dining_room", "kitchen", "master_bedroom", "bedroom_01", "bedroom_02", "bedroom_03", "foyer", "attached_bathroom", "attached_bathroom_02", "common_bathroom", "pooja_room", "balcony", "utility_area", "study", "powder_room", "internal_corridor" ] sorted_rooms = sorted(room_names, key=lambda r: priority_order.index(r) if r in priority_order else 99) placed = [] MARGIN = 1.0 # ft wall thickness # Compute target area per room (scaled to fit plot) plot_area = plot_w * plot_h usable_area = plot_area * 0.85 # 85% usable total_min = sum(ROOM_MIN_AREA.get(r, 80) for r in sorted_rooms) scale = min(usable_area / total_min, 1.6) def target_dims(room_name): min_a = ROOM_MIN_AREA.get(room_name, 80) * scale # Add randomness for variety area = min_a * random.uniform(1.0, 1.3) # Prefer aspect ratios between 1:1 and 1:2 aspect = random.uniform(1.0, 1.8) w = math.sqrt(area * aspect) h = area / w w = max(w, 8.0) # min 8ft h = max(h, 8.0) w = min(w, plot_w - 2 * MARGIN) h = min(h, plot_h - 2 * MARGIN) return round(w, 1), round(h, 1) def find_position(room_name, w, h): """Try to place room adjacent to a preferred neighbour, else grid pack.""" preferred_neighbours = [a[1] if a[0]==room_name else (a[0] if a[1]==room_name else None) for a in REQUIRED_ADJACENCIES] preferred_neighbours = [n for n in preferred_neighbours if n] # Try placing next to placed preferred neighbours candidates = [] for pn in preferred_neighbours: pr = next((r for r in placed if r.name == pn), None) if pr: # Try right of pr for dx, dy in [(pr.w+MARGIN, 0), (0, pr.h+MARGIN), (-w-MARGIN, 0), (0, -h-MARGIN)]: nx = pr.x + dx ny = pr.y + dy nx = max(MARGIN, min(nx, plot_w - w - MARGIN)) ny = max(MARGIN, min(ny, plot_h - h - MARGIN)) trial = Room(room_name, nx, ny, w, h) if all(not trial.overlaps(p) for p in placed): candidates.append((nx, ny, 0)) # 0 = preferred if candidates: candidates.sort(key=lambda c: c[2]) return candidates[0][0], candidates[0][1] # Fallback: grid scan step = 2.0 best = None best_score = float('inf') for gx in np.arange(MARGIN, plot_w - w - MARGIN + 0.1, step): for gy in np.arange(MARGIN, plot_h - h - MARGIN + 0.1, step): trial = Room(room_name, gx, gy, w, h) if all(not trial.overlaps(p) for p in placed): # Score by distance to plot centre (pack centrally) cx_dist = abs(gx + w/2 - plot_w/2) cy_dist = abs(gy + h/2 - plot_h/2) score = cx_dist + cy_dist + random.uniform(0, 3) if score < best_score: best_score = score best = (gx, gy) if best: return best # Last resort: random return (random.uniform(MARGIN, max(MARGIN, plot_w-w-MARGIN)), random.uniform(MARGIN, max(MARGIN, plot_h-h-MARGIN))) for room_name in sorted_rooms: w, h = target_dims(room_name) x, y = find_position(room_name, w, h) placed.append(Room(room_name, round(x, 1), round(y, 1), round(w, 1), round(h, 1))) return FloorPlan(placed, plot_w, plot_h) # ── Scoring Functions ────────────────────────────────────────────────────────── def score_adjacency_quality(fp): """AQ — 0 to 1. Uses the 4-tier ADJACENCY_MATRIX from constants: HIGH/MED/LOW reward sharing a wall (or being corridor-connected); ZERO/FORBIDDEN penalise wall-sharing. The internal corridor counts as a hub: any two rooms that both touch the corridor are treated as functionally adjacent at 80% credit, since circulation between them is one short doorway away. """ room_map = {r.name: r for r in fp.rooms} names = list(room_map.keys()) corridor = next((r for r in fp.rooms if r.name == "internal_corridor"), None) on_corridor = set() if corridor is not None: for r in fp.rooms: if r.name != "internal_corridor" and r.shares_wall(corridor): on_corridor.add(r.name) pos_total = 0.0 pos_got = 0.0 penalty = 0.0 for i, n1 in enumerate(names): for n2 in names[i+1:]: if "internal_corridor" in (n1, n2): continue # corridor handled implicitly via hub credit cls = get_adjacency_class(n1, n2) w = ADJ_WEIGHTS.get(cls, 0.0) ra, rb = room_map[n1], room_map[n2] shares = ra.shares_wall(rb) if w > 0: pos_total += w if shares: pos_got += w elif n1 in on_corridor and n2 in on_corridor: pos_got += w * 0.80 # corridor-hub credit else: d = ra.distance_to(rb) pos_got += w * max(0.0, 1.0 - d / (fp.plot_w * 0.6)) elif w < 0 and shares: penalty += -w base = (pos_got / pos_total) if pos_total > 0 else 0.0 score = max(0.0, base - 0.08 * penalty) return round(min(score, 1.0), 3) def score_vastu(fp, selected_rules=None): """VS — 0 to 1. 3-tier rules (HIGH 1.0 / MED 0.5 / LOW 0.2). A room often has multiple rules across tiers (e.g. Kitchen HIGH=SE, MED=S/E). We award the BEST matching tier per room: the denominator counts the room's highest tier weight, the numerator the credit for the actually-occupied zone. """ room_map = {r.name: r for r in fp.rooms} # Group rules by room_name rules_by_room = {} for rule_name, room_name, good_zones, weight in VASTU_RULES: if selected_rules and rule_name not in selected_rules: continue if room_name not in room_map: continue rules_by_room.setdefault(room_name, []).append( (rule_name, good_zones, weight)) total_w = 0.0 satisfied_w = 0.0 details = [] for room_name, rules in rules_by_room.items(): zone = room_map[room_name].zone(fp.plot_w, fp.plot_h) # Denominator: room's top-tier weight (HIGH > MED > LOW) top_weight = max(w for _, _, w in rules) total_w += top_weight # Numerator: best tier whose zone the room actually sits in best_credit = 0.0 best_rule = None best_status = "miss" for rname, zones, w in rules: if zone in zones: if w > best_credit: best_credit = w best_rule = rname best_status = "match" satisfied_w += best_credit if best_rule is None: best_rule = rules[0][0] details.append((best_rule, room_name, zone, best_status)) score = round(satisfied_w / total_w, 3) if total_w > 0 else 0.0 return score, details def score_spatial_efficiency(fp): """SE — 0 to 1.""" total_room_area = sum(r.area for r in fp.rooms) plot_area = fp.plot_w * fp.plot_h area_util = min(total_room_area / plot_area, 1.0) # Graph connectivity — all rooms reachable via shared walls? connected = 0 for r in fp.rooms: for other in fp.rooms: if r != other and r.shares_wall(other): connected += 1 break connectivity = connected / len(fp.rooms) if fp.rooms else 0 se = 0.5 * area_util + 0.5 * connectivity return round(se, 3) def score_layout_compactness(fp): """LC — 0 to 1.""" if not fp.rooms: return 0.0 total_area = sum(r.area for r in fp.rooms) # Perimeter of bounding box of all rooms min_x = min(r.x for r in fp.rooms) max_x = max(r.right for r in fp.rooms) min_y = min(r.y for r in fp.rooms) max_y = max(r.top for r in fp.rooms) bbox_area = (max_x - min_x) * (max_y - min_y) bbox_perim = 2 * ((max_x - min_x) + (max_y - min_y)) compactness = (4 * math.pi * bbox_area) / (bbox_perim ** 2) if bbox_perim > 0 else 0 fill = total_area / bbox_area if bbox_area > 0 else 0 lc = 0.4 * compactness + 0.6 * fill return round(min(lc, 1.0), 3) def score_cost(fp, finishing: str = "Standard") -> float: """CS — 0 to 1. Lower estimated rupee cost per sqft → higher score. Plans that waste walls or have far-apart wet zones are penalised. """ total_area = sum(r.area for r in fp.rooms) or 1.0 total = estimate_cost(fp, finishing=finishing) cost_per_sqft = total / total_area base_rate = COST_PER_SQFT.get(finishing, 2400) # Anything ≤1.05× the base rate is "ideal" (score 1.0). Beyond 1.40× → 0. ratio = cost_per_sqft / base_rate if ratio <= 1.05: return 1.0 if ratio >= 1.40: return 0.0 return round(1.0 - (ratio - 1.05) / 0.35, 3) def estimate_cost(fp, finishing="Standard"): """Returns estimated construction cost in ₹.""" total_area_sqft = sum(r.area for r in fp.rooms) base_cost = total_area_sqft * COST_PER_SQFT[finishing] # Wall length cost total_wall = 0 for r in fp.rooms: total_wall += 2 * (r.w + r.h) # Subtract shared walls (save ~30% for shared) shared = 0 for i, r1 in enumerate(fp.rooms): for r2 in fp.rooms[i+1:]: if r1.shares_wall(r2): shared += min(r1.w, r2.w, r1.h, r2.h) wall_cost = (total_wall - shared * 0.6) * WALL_COST_PER_METER * 0.3048 # ft to m # Plumbing cost — distance between wet areas wet_rooms = [r for r in fp.rooms if any(w in r.name for w in ["bathroom","kitchen","utility"])] plumbing_cost = 0 if len(wet_rooms) > 1: for i in range(len(wet_rooms)-1): d = wet_rooms[i].distance_to(wet_rooms[i+1]) * 0.3048 # ft to m plumbing_cost += d * PLUMBING_COST_PER_METER total = base_cost + wall_cost + plumbing_cost return round(total) def score_area_compliance(fp, room_names): """AC — 0 to 1.""" scores = [] for r in fp.rooms: min_a = ROOM_MIN_AREA.get(r.name, 80) max_a = ROOM_MAX_AREA.get(r.name, 200) if r.area < min_a: dev = (min_a - r.area) / min_a elif r.area > max_a: dev = (r.area - max_a) / max_a else: dev = 0 scores.append(max(0, 1 - dev)) return round(sum(scores) / len(scores), 3) if scores else 0.0 def climate_suggestions(fp, climate_zone): """Returns list of climate suggestion strings.""" zone_data = CLIMATE_ZONES.get(climate_zone, {}) suggestions = [] wwr = zone_data.get("wwr", 0.20) buf = zone_data.get("buffer", "W") suggestions.append(f"Target Window-to-Wall Ratio: {int(wwr*100)}% " f"({'smaller windows reduce heat gain' if wwr < 0.25 else 'larger windows improve daylight'})") suggestions.append(f"Place utility/store rooms on {buf}-facing walls as thermal buffer zones") suggestions.append("Ensure cross-ventilation: living room and kitchen should have openings on opposite walls") suggestions.append("Orient long axis of building East-West to minimise afternoon sun exposure") if "Hot" in climate_zone: suggestions.append("Use high thermal mass materials (brick/concrete) for South and West walls") suggestions.append("Consider roof overhang depth of 0.6–0.9m on South-facing windows") elif "Cold" in climate_zone: suggestions.append("Maximise South-facing glazing for passive solar heat gain") suggestions.append("Use double-glazed windows on North-facing rooms") return suggestions def _ml_boxes_to_floorplan(boxes, plot_w, plot_h): """Convert a list of ML pipeline boxes into a FloorPlan with Room objects.""" rooms = [] for b in boxes: rooms.append(Room(b["name"], round(float(b["x"]), 2), round(float(b["y"]), 2), round(float(b["w"]), 2), round(float(b["h"]), 2))) return FloorPlan(rooms, plot_w, plot_h) def _complete_and_shape_boxes(boxes, requested_rooms, plot_w, plot_h, max_ratio=1.495, road_side="S", variant_index=0): """Keep every requested room and avoid long strip rooms. The slightly-below-1.5 cap survives the two-decimal rounding done by Room/FloorPlan conversion. """ allowed_names = set(requested_rooms or []) | {"internal_corridor"} out = [dict(b) for b in boxes if b.get("name") in allowed_names] present = {b.get("name") for b in out} cursor = 0 for room_name in requested_rooms or []: if room_name in present: continue area = max(float(ROOM_MIN_AREA.get(room_name, 60)), 25.0) w = max(area ** 0.5, 5.0) h = max(area / w, 5.0) x = 3.28 + (cursor % 3) * max(w, 6.0) y = 6.56 + (cursor // 3) * max(h, 6.0) out.append({ "name": room_name, "x": min(x, max(plot_w - w - 3.28, 0.0)), "y": min(y, max(plot_h - h - 3.28, 0.0)), "w": w, "h": h, }) present.add(room_name) cursor += 1 shaped = [] for b in out: fixed = dict(b) w = max(float(fixed.get("w", 1.0)), 0.1) h = max(float(fixed.get("h", 1.0)), 0.1) if fixed.get("name") in set(requested_rooms or []): min_area = max(float(ROOM_MIN_AREA.get(fixed["name"], 25.0)), 25.0) if w * h < min_area * 0.85 or min(w, h) < 3.0: cx = float(fixed.get("x", 0.0)) + w / 2.0 cy = float(fixed.get("y", 0.0)) + h / 2.0 short = max((min_area / max_ratio) ** 0.5, 3.0) long = short * max_ratio if w >= h: w, h = long, short else: w, h = short, long fixed["x"] = min(max(cx - w / 2.0, 0.0), max(plot_w - w, 0.0)) fixed["y"] = min(max(cy - h / 2.0, 0.0), max(plot_h - h, 0.0)) fixed["w"] = w fixed["h"] = h if fixed.get("name") != "internal_corridor": if w > h * max_ratio: new_w = h * max_ratio fixed["x"] = float(fixed.get("x", 0.0)) + (w - new_w) / 2.0 fixed["w"] = new_w elif h > w * max_ratio: new_h = w * max_ratio fixed["y"] = float(fixed.get("y", 0.0)) + (h - new_h) / 2.0 fixed["h"] = new_h shaped.append(fixed) return _enforce_backend_hard_rules(shaped, requested_rooms, plot_w, plot_h, max_ratio=max_ratio, road_side=road_side, variant_index=variant_index) def _box_touches(a, b, tol=0.65, min_overlap=1.5): touching_v = abs((a["x"] + a["w"]) - b["x"]) <= tol or \ abs((b["x"] + b["w"]) - a["x"]) <= tol if touching_v: overlap = min(a["y"] + a["h"], b["y"] + b["h"]) - max(a["y"], b["y"]) if overlap >= min_overlap: return True touching_h = abs((a["y"] + a["h"]) - b["y"]) <= tol or \ abs((b["y"] + b["h"]) - a["y"]) <= tol if touching_h: overlap = min(a["x"] + a["w"], b["x"] + b["w"]) - max(a["x"], b["x"]) if overlap >= min_overlap: return True return False def _boxes_overlap(a, b, tol=0.05): return (a["x"] + tol < b["x"] + b["w"] and b["x"] + tol < a["x"] + a["w"] and a["y"] + tol < b["y"] + b["h"] and b["y"] + tol < a["y"] + a["h"]) def _touches_outer_wall(b, plot_w, plot_h, tol=0.75): return (b["x"] <= tol or b["y"] <= tol or b["x"] + b["w"] >= plot_w - tol or b["y"] + b["h"] >= plot_h - tol) def _clamp_box_inside(b, plot_w, plot_h): b["w"] = max(float(b["w"]), 1.0) b["h"] = max(float(b["h"]), 1.0) b["x"] = min(max(float(b.get("x", 0.0)), 0.0), max(plot_w - b["w"], 0.0)) b["y"] = min(max(float(b.get("y", 0.0)), 0.0), max(plot_h - b["h"], 0.0)) def _inner_bounds(plot_w, plot_h, road_side="S"): road, other = 6.56, 3.28 left = road if road_side == "W" else other right = road if road_side == "E" else other bottom = road if road_side == "S" else other top = road if road_side == "N" else other return left, bottom, plot_w - right, plot_h - top def _swap_rectangles(boxes, name_a, name_b): a = next((b for b in boxes if b["name"] == name_a), None) b = next((b for b in boxes if b["name"] == name_b), None) if not a or not b: return False a["x"], b["x"] = b["x"], a["x"] a["y"], b["y"] = b["y"], a["y"] a["w"], b["w"] = b["w"], a["w"] a["h"], b["h"] = b["h"], a["h"] return True def _resolve_backend_overlaps(boxes, plot_w, plot_h, max_passes=80): for _ in range(max_passes): changed = False for i in range(len(boxes)): for j in range(i + 1, len(boxes)): a, b = boxes[i], boxes[j] if not _boxes_overlap(a, b): continue changed = True ox = min(a["x"] + a["w"], b["x"] + b["w"]) - max(a["x"], b["x"]) oy = min(a["y"] + a["h"], b["y"] + b["h"]) - max(a["y"], b["y"]) if ox <= oy: shift = ox / 2.0 + 0.15 if a["x"] + a["w"] / 2 <= b["x"] + b["w"] / 2: a["x"] -= shift b["x"] += shift else: a["x"] += shift b["x"] -= shift else: shift = oy / 2.0 + 0.15 if a["y"] + a["h"] / 2 <= b["y"] + b["h"] / 2: a["y"] -= shift b["y"] += shift else: a["y"] += shift b["y"] -= shift _clamp_box_inside(a, plot_w, plot_h) _clamp_box_inside(b, plot_w, plot_h) if not changed: return boxes return _non_overlapping_row_repack(boxes, plot_w, plot_h) def _hard_rules_ok(boxes, plot_w, plot_h, road_side="S"): ix0, iy0, ix1, iy1 = _inner_bounds(plot_w, plot_h, road_side) room = {b["name"]: b for b in boxes} for b in boxes: if (b["x"] < ix0 - 0.05 or b["y"] < iy0 - 0.05 or b["x"] + b["w"] > ix1 + 0.05 or b["y"] + b["h"] > iy1 + 0.05): return False for i, a in enumerate(boxes): for b in boxes[i + 1:]: if _boxes_overlap(a, b): return False pooja = room.get("pooja_room") if pooja is not None: if pooja["y"] + pooja["h"] < iy1 - 0.75 or pooja["x"] + pooja["w"] / 2 < (ix0 + ix1) * 0.5: return False stair = room.get("external_staircase") if stair is not None and (abs(stair["w"] - 12.0) > 0.05 or abs(stair["h"] - 10.0) > 0.05): return False living = room.get("living_room") if stair is not None and living is not None and not _box_touches(stair, living): return False master = room.get("master_bedroom") if master is not None: master_area = master["w"] * master["h"] for name in ("bedroom_01", "bedroom_02", "bedroom_03"): other = room.get(name) if other is not None and master_area < other["w"] * other["h"] - 1.0: return False attached = room.get("attached_bathroom") if attached is not None: if not (attached["x"] <= ix0 + 0.75 or attached["y"] <= iy0 + 0.75 or attached["x"] + attached["w"] >= ix1 - 0.75 or attached["y"] + attached["h"] >= iy1 - 0.75): return False if master is not None and not _box_touches(attached, master): return False common = room.get("common_bathroom") if common is not None and not ( common["x"] <= ix0 + 0.75 or common["y"] <= iy0 + 0.75 or common["x"] + common["w"] >= ix1 - 0.75 or common["y"] + common["h"] >= iy1 - 0.75): return False pooja = room.get("pooja_room") if pooja is not None: for wet_name in ("common_bathroom", "attached_bathroom", "utility_area"): wet = room.get(wet_name) if wet is not None and _box_touches(pooja, wet, tol=0.75, min_overlap=1.5): return False for wet_name in ("common_bathroom", "attached_bathroom"): wet = room.get(wet_name) if wet is not None: if wet["w"] * wet["h"] > ROOM_MAX_AREA.get(wet_name, 77) + 8.0: return False if max(wet["w"] / max(wet["h"], 0.1), wet["h"] / max(wet["w"], 0.1)) > 1.8: return False return True def _constraint_layout(boxes, requested_rooms, plot_w, plot_h, max_ratio=1.495, road_side="S", variant_index=0): ix0, iy0, ix1, iy1 = _inner_bounds(plot_w, plot_h, road_side) iw, ih = ix1 - ix0, iy1 - iy0 requested = [r for r in dict.fromkeys(requested_rooms or [b["name"] for b in boxes]) if r != "foyer"] placed = [] variant = int(variant_index or 0) cycle = variant // 5 public_family = (variant + 3 * cycle) % 4 def add(name, x, y, w, h): if name not in requested or any(b["name"] == name for b in placed): return None b = {"name": name, "x": round(ix0 + x, 3), "y": round(iy0 + y, 3), "w": round(max(w, 1.0), 3), "h": round(max(h, 1.0), 3)} placed.append(b) return b def add_corridor(x, y, w, h): b = {"name": "internal_corridor", "x": round(ix0 + x, 3), "y": round(iy0 + y, 3), "w": round(max(w, 1.0), 3), "h": round(max(h, 1.0), 3)} placed.append(b) return b # Real visual families: 5 public/service arrangements x 4 private-zone # arrangements. This deliberately changes room positions/adjacencies, not # just dimensions. service_family = variant % 3 private_family = (variant // 3) % 7 road_h = 10.0 right_w = 7.4 left_w = iw - right_w top_h = 16.0 if private_family in (0, 2) else 18.0 mid_h = ih - road_h - top_h bath_w = 6.0 pooja_h = 7.0 utility_h = 8.0 kitchen_h = 10.0 add("external_staircase", 0, 0, 12.0, road_h) add("living_room", 12.0, 0, left_w - 12.0, road_h) add("balcony", left_w, 0, right_w, road_h) # Middle band: living/master/dining/service move by family. if service_family == 0: attach_w = 6.0 add("attached_bathroom", 0, road_h, attach_w, 8.0) add_corridor(attach_w, road_h, max(left_w - attach_w, 1.0), 8.0) add("master_bedroom", 0, road_h + 8.0, left_w, mid_h - 8.0) add("kitchen", left_w, road_h, right_w, kitchen_h) add("utility_area", left_w, road_h + kitchen_h, right_w, utility_h) dining_h = max(ih - road_h - kitchen_h - utility_h - pooja_h, 6.0) add("dining_room", left_w, road_h + kitchen_h + utility_h, right_w, dining_h) elif service_family == 1: upper_h = 8.0 add("attached_bathroom", 0, road_h, 6.0, upper_h) add_corridor(6.0, road_h, left_w - 6.0, upper_h) add("master_bedroom", 0, road_h + upper_h, left_w, mid_h - upper_h) add("kitchen", left_w, road_h, right_w, kitchen_h) add("utility_area", left_w, road_h + kitchen_h, right_w, utility_h) dining_h = max(ih - road_h - kitchen_h - utility_h - pooja_h, 6.0) add("dining_room", left_w, road_h + kitchen_h + utility_h, right_w, dining_h) else: # Balcony stays on the road but shifts next to the staircase; living is # a middle room touching the staircase from above. placed[:] = [b for b in placed if b["name"] not in ("living_room", "dining_room", "balcony")] add("balcony", 12.0, 0, max(left_w - 12.0, 1.0), road_h) add("attached_bathroom", 0, road_h, 6.0, 8.0) add("living_room", 6.0, road_h, 10.0, 8.0) add_corridor(16.0, road_h, max(left_w - 16.0, 1.0), 8.0) add("master_bedroom", 0, road_h + 8.0, left_w, mid_h - 8.0) add("kitchen", left_w, road_h, right_w, kitchen_h) add("utility_area", left_w, road_h + kitchen_h, right_w, utility_h) dining_h = max(ih - road_h - kitchen_h - utility_h - pooja_h, 6.0) add("dining_room", left_w, road_h + kitchen_h + utility_h, right_w, dining_h) add("pooja_room", left_w, ih - pooja_h, right_w, pooja_h) # Private/top band. Bedrooms touch exterior walls but are arranged in four # visibly different topologies. top_y = ih - top_h bedroom_order = [name for name in ("bedroom_01", "bedroom_02", "bedroom_03", "study", "lift") if name in requested] wash_w, wash_h = 6.0, 7.5 if private_family in (0, 3, 6): add("common_bathroom", 0, top_y + top_h - wash_h, wash_w, wash_h) if bedroom_order: add(bedroom_order[0], 0, top_y, wash_w, top_h - wash_h) bedroom_order = bedroom_order[1:] bed_x, bed_y, bed_w, bed_h = wash_w, top_y, left_w - wash_w, top_h cols = max(len(bedroom_order), 1) for i, name in enumerate(bedroom_order if private_family != 6 else list(reversed(bedroom_order))): add(name, bed_x + i * bed_w / cols, bed_y, bed_w / cols, bed_h) elif private_family in (1, 4): add("common_bathroom", 0, top_y + top_h - wash_h, wash_w, wash_h) if bedroom_order: add(bedroom_order[0], 0, top_y, wash_w, top_h - wash_h) bedroom_order = bedroom_order[1:] bed_x, bed_y, bed_w, bed_h = wash_w, top_y, left_w - wash_w, top_h rows = max(len(bedroom_order), 1) for i, name in enumerate(bedroom_order if private_family == 1 else list(reversed(bedroom_order))): add(name, bed_x, bed_y + i * bed_h / rows, bed_w, bed_h / rows) elif private_family in (2, 5): add("common_bathroom", 0, top_y + top_h - wash_h, wash_w, wash_h) if bedroom_order: add(bedroom_order[0], 0, top_y, wash_w, top_h - wash_h) bedroom_order = bedroom_order[1:] bed_x, bed_y, bed_w, bed_h = wash_w, top_y, left_w - wash_w, top_h if len(bedroom_order) == 2: add(bedroom_order[0], bed_x, bed_y, bed_w / 2.0, bed_h) add(bedroom_order[1], bed_x + bed_w / 2.0, bed_y, bed_w / 2.0, bed_h) elif len(bedroom_order) > 2: add(bedroom_order[0], bed_x, bed_y + bed_h * 0.5, bed_w / 2.0, bed_h * 0.5) add(bedroom_order[1], bed_x + bed_w / 2.0, bed_y + bed_h * 0.5, bed_w / 2.0, bed_h * 0.5) rest = bedroom_order[2:] cols = max(len(rest), 1) for i, name in enumerate(rest): add(name, bed_x + i * bed_w / cols, bed_y, bed_w / cols, bed_h * 0.5) else: for name in bedroom_order: add(name, bed_x, bed_y, bed_w, bed_h) # Safety: if any requested room was not placed, put it in a compact middle # slot away from walls. This rarely triggers but prevents silent omissions. for name in requested: if not any(b["name"] == name for b in placed): add(name, 13.0, road_h + 1.0, 6.0, 6.0) return placed right_w = min(max(iw * 0.21 + [-0.7, 0.0, 0.6, 1.0, -0.3][variant % 5] + 0.32 * cycle, 6.3), 9.6) left_w = iw - right_w bottom_h = 10.0 middle_h = min(max((ih - bottom_h) * 0.42 + [0.0, 0.7, -0.4, 1.0, -0.8][variant % 5] + 0.32 * cycle, 16.0), 19.0) private_h = ih - bottom_h - middle_h balcony_front_w = min(max(right_w, 6.0), 8.4) if "balcony" in requested else 0.0 living_w = max(iw - 12.0 - balcony_front_w, 8.0) add("external_staircase", 0, 0, 12.0, 10.0) attach_w = min(max(left_w * (0.20 + 0.012 * (variant % 3)), 6.0), 6.8) master_w = min(max(left_w * (0.58 + 0.015 * ((variant + 1) % 3)), 15.0), 16.4) mid_corr_w = 0.0 dining_w = left_w - attach_w - master_w - mid_corr_w if dining_w < 5.0: master_w = max(master_w - (5.0 - dining_w), 12.0) dining_w = left_w - attach_w - master_w - mid_corr_w if public_family < 4: add("living_room", 12.0, 0, living_w, bottom_h) add("balcony", 12.0 + living_w, 0, balcony_front_w, bottom_h) add("attached_bathroom", 0, bottom_h, attach_w, middle_h) add("master_bedroom", attach_w, bottom_h, master_w, middle_h) if mid_corr_w > 0: add_corridor(attach_w + master_w, bottom_h + 1.0, mid_corr_w, max(middle_h - 2.0, 1.0)) add("dining_room", attach_w + master_w + mid_corr_w, bottom_h, dining_w, middle_h) service_family = (variant // 2) % 4 service_h = ih - bottom_h kitchen_h = min(max(service_h * (0.21 + 0.01 * (variant % 3)), 9.0), 12.0) corridor_h = 0.0 pooja_h = min(max(right_w, 5.0), 8.0) rx = left_w if service_family in (0, 1): utility_h = max(service_h - kitchen_h - pooja_h - corridor_h, 7.0) ry = bottom_h if service_family == 0: add("kitchen", rx, ry, right_w, kitchen_h) ry += kitchen_h add("utility_area", rx, ry, right_w, utility_h) else: add("utility_area", rx, ry, right_w, utility_h) ry += utility_h add("kitchen", rx, ry, right_w, kitchen_h) add("pooja_room", rx, ih - pooja_h, right_w, pooja_h) elif service_family == 2 and dining_w >= 14.0 and variant in (2, 10): # Kitchen comes into the middle, utility stays on the service wall. service_mid_w = min(max(dining_w * 0.55, 6.0), max(dining_w - 3.0, 6.0)) # Replace dining area locally with kitchen + dining split. placed[:] = [b for b in placed if b["name"] != "dining_room"] dining_x = attach_w + master_w + mid_corr_w add("kitchen", dining_x, bottom_h, service_mid_w, middle_h) add("dining_room", dining_x + service_mid_w, bottom_h, dining_w - service_mid_w, middle_h) add("utility_area", rx, bottom_h, right_w, service_h - pooja_h) add("pooja_room", rx, ih - pooja_h, right_w, pooja_h) elif False: # Utility moves to the middle beside dining; kitchen remains on service wall. util_mid_w = min(max(dining_w * 0.45, 5.5), max(dining_w - 3.0, 5.5)) placed[:] = [b for b in placed if b["name"] != "dining_room"] dining_x = attach_w + master_w + mid_corr_w add("utility_area", dining_x, bottom_h, util_mid_w, middle_h) add("dining_room", dining_x + util_mid_w, bottom_h, dining_w - util_mid_w, middle_h) add("kitchen", rx, bottom_h, right_w, kitchen_h) add("pooja_room", rx, ih - pooja_h, right_w, pooja_h) else: add("kitchen", rx, bottom_h, right_w, kitchen_h) add("utility_area", rx, bottom_h + kitchen_h, right_w, service_h - kitchen_h - pooja_h) add("pooja_room", rx, ih - pooja_h, right_w, pooja_h) top_y = bottom_h + middle_h top_h = ih - top_y bedroom_order = ("bedroom_01", "bedroom_02", "bedroom_03", "study", "lift") if variant % 2: bedroom_order = tuple(reversed(bedroom_order)) bedroom_names = [name for name in bedroom_order if name in requested] wet_family = (variant // 4) % 2 if variant in (12, 15): wet_family = 1 - wet_family if len(bedroom_names) <= 2: wet_family = 0 if wet_family == 0 or not bedroom_names: bath_w = min(max(left_w * 0.22, 6.0), 7.0) bedroom_area_w = left_w - bath_w common_h = top_h add("common_bathroom", 0, top_y + top_h - common_h, bath_w, common_h) bed_x, bed_y, bed_w, bed_h = bath_w, top_y, bedroom_area_w, top_h else: bath_w = min(max(left_w * 0.24, 7.0), 8.0) common_h = min(max(top_h * 0.36, 8.0), 10.0) add("common_bathroom", 0, top_y + top_h - common_h, bath_w, common_h) add(bedroom_names[0], 0, top_y, bath_w, top_h - common_h) bedroom_names = bedroom_names[1:] bed_x, bed_y, bed_w, bed_h = bath_w, top_y, left_w - bath_w, top_h family = public_family % 4 if bedroom_names and family in (1, 3): row_h = bed_h / len(bedroom_names) ordered = bedroom_names if family == 1 else list(reversed(bedroom_names)) for i, name in enumerate(ordered): add(name, bed_x, bed_y + i * row_h, bed_w, row_h) elif bedroom_names and family == 2 and len(bedroom_names) >= 2: top_band = bed_h * 0.52 lower_band = bed_h - top_band add(bedroom_names[0], bed_x, bed_y + lower_band, bed_w / 2.0, top_band) add(bedroom_names[1], bed_x + bed_w / 2.0, bed_y + lower_band, bed_w / 2.0, top_band) rest = bedroom_names[2:] if rest: col_w = bed_w / len(rest) for i, name in enumerate(rest): add(name, bed_x + i * col_w, bed_y, col_w, lower_band) else: add_corridor(bed_x + 1.0, bed_y + 1.0, max(bed_w - 2.0, 1.0), max(lower_band - 2.0, 1.0)) elif bedroom_names: row_h = bed_h / len(bedroom_names) for i, name in enumerate(bedroom_names): add(name, bed_x, bed_y + i * row_h, bed_w, row_h) else: add_corridor(bed_x + 1.0, bed_y + 1.0, max(bed_w - 2.0, 1.0), max(bed_h - 2.0, 1.0)) x = bath_w y = top_y + max(1.0, top_h * 0.35) for name in requested: if any(b["name"] == name for b in placed): continue add(name, x, y, min(8.0, bed_w), min(7.0, bed_h * 0.4)) x += 8.0 for b in placed: if b["name"] == "external_staircase": b["w"], b["h"] = 12.0, 10.0 return placed def _boxes_from_gpt_column_spec(spec, plot_w, plot_h): boxes = [] total_w = sum(max(float(col.get("width", 0.0)), 1e-6) for col in spec) or 1.0 x = 0.0 for col_index, col in enumerate(spec): col_w = plot_w * max(float(col.get("width", 0.0)), 1e-6) / total_w if col_index == len(spec) - 1: col_w = plot_w - x rooms = col.get("rooms", []) if isinstance(col, dict) else [] total_h = sum(max(float(room.get("height", 0.0)), 1e-6) for room in rooms) or 1.0 y = 0.0 for room_index, room in enumerate(rooms): name = room.get("name") if isinstance(room, dict) else None if not name: continue h = plot_h * max(float(room.get("height", 0.0)), 1e-6) / total_h if room_index == len(rooms) - 1: h = plot_h - y boxes.append({"name": name, "x": x, "y": y, "w": col_w, "h": h}) y += h x += col_w return boxes def _generate_gpt_backend_boxes(required_rooms, optional_rooms, plot_w, plot_h, road_side, n): try: from core import gpt_layout except Exception: return [] if not gpt_layout.gpt_available(): return [] specs = gpt_layout.propose_column_layouts( required_rooms or [], optional_rooms or [], plot_w, plot_h, road_side, n_variants=min(max(n, 1), 6), timeout=45.0) if not specs: return [] return [_boxes_from_gpt_column_spec(spec, plot_w, plot_h) for spec in specs[:n]] def _non_overlapping_row_repack(boxes, plot_w, plot_h, max_ratio=1.495): if not boxes: return boxes rows = max(1, int(math.ceil(math.sqrt(len(boxes) * plot_h / max(plot_w, 1.0))))) cols = max(1, int(math.ceil(len(boxes) / rows))) cell_w = plot_w / cols cell_h = plot_h / rows order = sorted(boxes, key=lambda b: ( 0 if b["name"] == "pooja_room" else 1 if b["name"] in ("common_bathroom", "attached_bathroom", "attached_bathroom_02") else 2 if b["name"] == "master_bedroom" else 3 if b["name"] == "external_staircase" else 4, b["name"], )) for idx, b in enumerate(order): row = idx // cols col = idx % cols w = min(cell_w * 0.92, cell_h * 0.92 * max_ratio) h = min(cell_h * 0.92, w * max_ratio) if b["name"] == "external_staircase": w, h = min(12.0, cell_w * 0.92), min(10.0, cell_h * 0.92) b["x"] = col * cell_w + (cell_w - w) / 2.0 b["y"] = row * cell_h + (cell_h - h) / 2.0 b["w"] = max(w, 1.0) b["h"] = max(h, 1.0) return boxes def _enforce_backend_hard_rules(boxes, requested_rooms, plot_w, plot_h, max_ratio=1.495, road_side="S", variant_index=0): boxes = [dict(b) for b in boxes] room = {b["name"]: b for b in boxes} stair = room.get("external_staircase") if stair is not None: stair["w"], stair["h"] = 12.0, 10.0 stair["x"], stair["y"] = 0.0, 0.0 _clamp_box_inside(stair, plot_w, plot_h) pooja = room.get("pooja_room") if pooja is not None: pooja["w"] = min(max(pooja["w"], 3.0), 8.0) pooja["h"] = min(max(pooja["h"], 3.0), 8.0) if pooja["w"] > pooja["h"] * max_ratio: pooja["w"] = pooja["h"] * max_ratio if pooja["h"] > pooja["w"] * max_ratio: pooja["h"] = pooja["w"] * max_ratio pooja["x"] = plot_w - pooja["w"] pooja["y"] = plot_h - pooja["h"] master = room.get("master_bedroom") if master is not None: other_beds = [room[name] for name in ("bedroom_01", "bedroom_02", "bedroom_03") if name in room] largest_other = max((b["w"] * b["h"] for b in other_beds), default=0.0) if largest_other and master["w"] * master["h"] <= largest_other + 1.0: target_area = min(max(largest_other + 20.0, ROOM_MIN_AREA.get("master_bedroom", 150)), min(plot_w * plot_h * 0.22, ROOM_MAX_AREA.get("master_bedroom", 384))) short = (target_area / max_ratio) ** 0.5 master["w"], master["h"] = short * max_ratio, short _clamp_box_inside(master, plot_w, plot_h) attached = room.get("attached_bathroom") if attached is not None and master is not None: attached["w"] = min(max(attached["w"], 5.0), 7.0) attached["h"] = min(max(attached["h"], 5.0), 8.0) attached["x"] = min(master["x"] + master["w"], max(plot_w - attached["w"], 0.0)) attached["y"] = master["y"] if attached["x"] <= master["x"] + master["w"] - 0.2: attached["x"] = max(master["x"] - attached["w"], 0.0) _clamp_box_inside(attached, plot_w, plot_h) living = room.get("living_room") if living is not None and stair is not None and not _box_touches(living, stair): living["x"] = stair["x"] + stair["w"] living["y"] = stair["y"] living["h"] = max(living["h"], min(10.0, plot_h - living["y"])) _clamp_box_inside(living, plot_w, plot_h) for wet_name in ("common_bathroom", "attached_bathroom", "attached_bathroom_02"): wet = room.get(wet_name) if wet is None or _touches_outer_wall(wet, plot_w, plot_h): continue distances = { "W": wet["x"], "E": plot_w - (wet["x"] + wet["w"]), "S": wet["y"], "N": plot_h - (wet["y"] + wet["h"]), } side = min(distances, key=distances.get) if side == "W": wet["x"] = 0.0 elif side == "E": wet["x"] = plot_w - wet["w"] elif side == "S": wet["y"] = 0.0 else: wet["y"] = plot_h - wet["h"] _clamp_box_inside(wet, plot_w, plot_h) for b in boxes: if b["name"] != "internal_corridor": if b["w"] > b["h"] * max_ratio: b["w"] = b["h"] * max_ratio elif b["h"] > b["w"] * max_ratio: b["h"] = b["w"] * max_ratio _clamp_box_inside(b, plot_w, plot_h) boxes = _resolve_backend_overlaps(boxes, plot_w, plot_h) # Re-check critical adjacencies after overlap repair. If repair displaced # them, use rectangle swaps with the nearest suitable rooms. room = {b["name"]: b for b in boxes} if "living_room" in room and "external_staircase" in room and \ not _box_touches(room["living_room"], room["external_staircase"]): living = room["living_room"] stair = room["external_staircase"] living["x"] = min(stair["x"] + stair["w"], max(plot_w - living["w"], 0.0)) living["y"] = stair["y"] _clamp_box_inside(living, plot_w, plot_h) if "attached_bathroom" in room and "master_bedroom" in room and \ not _box_touches(room["attached_bathroom"], room["master_bedroom"]): attached = room["attached_bathroom"] master = room["master_bedroom"] attached["x"] = min(master["x"] + master["w"], max(plot_w - attached["w"], 0.0)) attached["y"] = master["y"] _clamp_box_inside(attached, plot_w, plot_h) boxes = _resolve_backend_overlaps(boxes, plot_w, plot_h) if not _hard_rules_ok(boxes, plot_w, plot_h, road_side=road_side): boxes = _constraint_layout(boxes, requested_rooms, plot_w, plot_h, max_ratio=max_ratio, road_side=road_side, variant_index=variant_index) return boxes def generate_population(room_names, plot_w, plot_h, n=20, required_rooms=None, optional_rooms=None, road_side="S"): """Generate n candidate plans. Returns a list of (raw_fp, optimised_fp) tuples so the UI can compare the AI's untouched output against the Vastu-optimised + space-tiled version. Falls back to the rule-based packer if the trained weights aren't present. """ plans = [] requested_rooms = list(dict.fromkeys(list(required_rooms or room_names) + list(optional_rooms or []))) requested_rooms = [room for room in requested_rooms if room != "foyer"] backend_required = [room for room in (required_rooms or room_names) if room != "foyer"] backend_optional = [room for room in (optional_rooms or []) if room != "foyer"] # Start with deterministic visual families. These indices are selected by # room-position signatures, so a mere 10x9 -> 9x8 resize does not count as # a different plan. family_variants = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 17, 18, 22, 23, 26] for variant_index in family_variants[:max(n, 1)]: boxes = _constraint_layout( [], requested_rooms, plot_w, plot_h, road_side=road_side, variant_index=variant_index) fp = _ml_boxes_to_floorplan(boxes, plot_w, plot_h) fp.template_name = f"family_variant_{variant_index}" plans.append((fp, fp)) if os.getenv("USE_MODEL_BACKENDS", "false").lower() not in ("1", "true", "yes"): return plans[:n] try: gpt_box_sets = _generate_gpt_backend_boxes( backend_required, backend_optional, plot_w, plot_h, road_side, min(n, 4), ) for idx, boxes in enumerate(gpt_box_sets): shaped = _complete_and_shape_boxes( boxes, requested_rooms, plot_w, plot_h, road_side=road_side, variant_index=idx) plans.append((_ml_boxes_to_floorplan(shaped, plot_w, plot_h), _ml_boxes_to_floorplan(shaped, plot_w, plot_h))) except Exception as e: print(f"[generator] GPT backend unavailable, continuing: {e}") # Optional external backend hook. It is disabled unless HouseGAN++ is # explicitly installed/configured, so the Streamlit app remains runnable. try: from core import external_houseganpp if os.getenv("USE_HOUSEGANPP", "false").lower() in ("1", "true", "yes") and \ external_houseganpp.is_ready(): external_plans = external_houseganpp.generate_population( room_names=[room for room in room_names if room != "foyer"], plot_w=plot_w, plot_h=plot_h, n=min(n, 3), required_rooms=backend_required, optional_rooms=backend_optional, road_side=road_side, ) if external_plans: offset = len(plans) for idx, p in enumerate(external_plans): raw = _complete_and_shape_boxes( p["raw_boxes"], requested_rooms, plot_w, plot_h, road_side=road_side, variant_index=offset + idx) opt = _complete_and_shape_boxes( p["boxes"], requested_rooms, plot_w, plot_h, road_side=road_side, variant_index=offset + idx) plans.append((_ml_boxes_to_floorplan(raw, plot_w, plot_h), _ml_boxes_to_floorplan(opt, plot_w, plot_h))) except Exception as e: print(f"[generator] HouseGAN++ backend unavailable, continuing: {e}") # Try the trained-model pipeline try: from core import ml_pipeline if ml_pipeline.is_ready(): ml_plans = ml_pipeline.generate_population( plot_w=plot_w, plot_h=plot_h, n=n, required_rooms=backend_required, optional_rooms=backend_optional, road_side=road_side) offset = len(plans) for idx, p in enumerate(ml_plans): raw = _complete_and_shape_boxes( p["raw_boxes"], requested_rooms, plot_w, plot_h, road_side=road_side, variant_index=offset + idx) opt = _complete_and_shape_boxes( p["boxes"], requested_rooms, plot_w, plot_h, road_side=road_side, variant_index=offset + idx) plans.append((_ml_boxes_to_floorplan(raw, plot_w, plot_h), _ml_boxes_to_floorplan(opt, plot_w, plot_h))) return plans[:max(n, len(plans))] except Exception as e: print(f"[generator] ML pipeline unavailable, falling back to rules: {e}") for i in range(max(0, n - len(plans))): fp = generate_floorplan(room_names, plot_w, plot_h, seed=i * 7 + 42) plans.append((fp, fp)) # no optimisation in fallback return plans def score_space_usage(fp, road_side: str = "S") -> float: """SU — fraction of the buildable (inner-setback) area actually covered by rooms. Overlapping area is counted once (a 1ft x 1ft pixel grid is used so overlaps don't inflate the score).""" sb_road, sb_other = 6.56, 3.28 # 2m / 1m left = sb_road if road_side == "W" else sb_other right = sb_road if road_side == "E" else sb_other bottom = sb_road if road_side == "S" else sb_other top = sb_road if road_side == "N" else sb_other inner_w = max(fp.plot_w - left - right, 1e-6) inner_h = max(fp.plot_h - bottom - top, 1e-6) inner_area = inner_w * inner_h # rasterise the inner buildable rectangle at 0.5 ft resolution import numpy as np res = 0.5 gx = max(1, int(round(inner_w / res))) gy = max(1, int(round(inner_h / res))) grid = np.zeros((gx, gy), dtype=bool) for r in fp.rooms: x0 = max(0, int(math.floor((r.x - left) / res))) y0 = max(0, int(math.floor((r.y - bottom) / res))) x1 = min(gx, int(math.ceil((r.x + r.w - left) / res))) y1 = min(gy, int(math.ceil((r.y + r.h - bottom) / res))) if x1 > x0 and y1 > y0: grid[x0:x1, y0:y1] = True used_cells = int(grid.sum()) used_area = used_cells * res * res return round(min(used_area / inner_area, 1.0), 3) def check_hard_constraints(fp): """Validator that returns a dict {rule: True/False} for every hard constraint in the professor's spec. Failed rules drag down Fitness.""" rooms = {r.name: r for r in fp.rooms} pw, ph = fp.plot_w, fp.plot_h results = {} # Setback tolerance — a room "touches" the setback rectangle if it # comes within 1 ft of it. (Setbacks are 6.56 ft road / 3.28 ft other.) SB_TOL = 1.0 SB_OTHER = 3.28 SB_ROAD = 6.56 def touches_west(r): return r.x <= SB_OTHER + SB_TOL def touches_east(r): return r.right >= pw - SB_OTHER - SB_TOL def touches_south(r): return r.y <= SB_ROAD + SB_TOL # treat S as road by default def touches_north(r): return r.top >= ph - SB_OTHER - SB_TOL # 1. Staircase in a corner zone (touches the road edge AND a side edge) s = rooms.get("external_staircase") if s is not None: in_corner = ( (touches_west(s) or touches_east(s)) and (touches_south(s) or touches_north(s)) ) results["staircase_in_corner"] = in_corner else: results["staircase_in_corner"] = True # 2. Pooja in NE / N / E zone (use Room.zone) p = rooms.get("pooja_room") if p is not None: results["pooja_in_NE_N_E"] = p.zone(pw, ph) in ("NE", "N", "E") else: results["pooja_in_NE_N_E"] = True # 3. HC1: Pooja must NOT share a wall with any wet room or utility area if p is not None: pooja_wet_ok = True for wet_name in ("common_bathroom", "attached_bathroom", "attached_bathroom_02", "utility_area"): wet = rooms.get(wet_name) if wet and p.shares_wall(wet, tol=0.5, min_overlap=2.0): pooja_wet_ok = False break results["pooja_not_touching_wet"] = pooja_wet_ok else: results["pooja_not_touching_wet"] = True # 4. Min sizes ok = True for r in fp.rooms: if r.area < ROOM_MIN_AREA.get(r.name, 25) - 2: ok = False break results["min_sizes_met"] = ok # 5. All inside setback rectangle sb_road, sb_other = 6.56, 3.28 # we don't know road_side here; use the loose check (any room outside plot) results["inside_plot"] = all( r.x >= -0.1 and r.y >= -0.1 and r.right <= pw + 0.1 and r.top <= ph + 0.1 for r in fp.rooms ) # 6. Balcony near road edge — at least one balcony touches the setback bals = [r for r in fp.rooms if r.name == "balcony"] if bals: touches_any_edge = any( touches_west(b) or touches_east(b) or touches_south(b) or touches_north(b) for b in bals ) results["balcony_on_edge"] = touches_any_edge else: results["balcony_on_edge"] = True # 7. Master >= every other bedroom m = rooms.get("master_bedroom") if m is not None: other_areas = [rooms[k].area for k in ("bedroom_01", "bedroom_02", "bedroom_03") if k in rooms] results["master_largest_bedroom"] = all(m.area >= oa - 1 for oa in other_areas) else: results["master_largest_bedroom"] = True # 8. No overlaps between rooms overlaps = 0 rs = fp.rooms for i in range(len(rs)): for j in range(i + 1, len(rs)): a, b = rs[i], rs[j] if (a.x + 0.1 < b.right and b.x + 0.1 < a.right and a.y + 0.1 < b.top and b.y + 0.1 < a.top): overlaps += 1 results["no_overlaps"] = overlaps == 0 # 9. Every room touches the setback rectangle (external wall rule), with # the client's per-room EXCEPTIONS: # * internal_corridor — always exempt (interior circulation) # * pooja — exempt if surrounded only by living/balcony/kitchen/ # dining/study # * living — exempt if one side touches a balcony # * kitchen— exempt if one side touches the utility # * dining — exempt if surrounded by living/kitchen/balcony/staircase/ # study/pooja # * washrooms — exempt if surrounded by balcony/utility/staircase def _on_setback(r): return (touches_west(r) or touches_east(r) or touches_south(r) or touches_north(r)) def _touches(a_name, b_name): a, b = rooms.get(a_name), rooms.get(b_name) return bool(a and b and a.shares_wall(b, tol=0.5, min_overlap=1.5)) def _neighbours(r): out = set() for o in fp.rooms: if o is r: continue if r.shares_wall(o, tol=0.5, min_overlap=1.5): out.add(o.name) return out _EXEMPT = { "pooja_room": {"living_room", "balcony", "kitchen", "dining_room", "study"}, "living_room": {"balcony"}, "kitchen": {"utility_area"}, "dining_room": {"living_room", "kitchen", "balcony", "external_staircase", "study", "pooja_room"}, "common_bathroom": {"balcony", "utility_area", "external_staircase"}, "attached_bathroom": {"balcony", "utility_area", "external_staircase"}, "attached_bathroom_02": {"balcony", "utility_area", "external_staircase"}, } rule = True for r in fp.rooms: if r.name == "internal_corridor": continue if _on_setback(r): continue exempt_set = _EXEMPT.get(r.name) if exempt_set is not None: nb = _neighbours(r) if r.name in ("living_room", "kitchen"): # exempt if AT LEAST ONE side touches the listed room if nb & exempt_set: continue else: # exempt if SURROUNDED ONLY by the listed rooms (and corridor) if nb and nb <= (exempt_set | {"internal_corridor"}): continue rule = False break results["all_rooms_on_boundary"] = rule # ── MANDATORY adjacencies (fail the layout if violated) ──────────────── # staircase ↔ living, master_bedroom ↔ attached_bath if "external_staircase" in rooms and "living_room" in rooms: results["staircase_touches_living"] = _touches( "external_staircase", "living_room") else: results["staircase_touches_living"] = True if "master_bedroom" in rooms and "attached_bathroom" in rooms: results["master_touches_attached_bath"] = _touches( "master_bedroom", "attached_bathroom") else: results["master_touches_attached_bath"] = True # utility / common bath / attached bath MUST touch the setback rectangle wet_setback_ok = True for wet in ("utility_area", "common_bathroom", "attached_bathroom", "attached_bathroom_02"): w = rooms.get(wet) if w is not None and not _on_setback(w): # attached/common bath keep their surrounded-by exception ex = _EXEMPT.get(wet) nb = _neighbours(w) if ex else set() if not (ex and nb and nb <= (ex | {"internal_corridor"})): wet_setback_ok = False break results["wet_rooms_on_setback"] = wet_setback_ok # HC2: Kitchen must not share a wall with any bathroom kitchen = rooms.get("kitchen") if kitchen is not None: kitchen_bath_ok = True for wet_name in ("common_bathroom", "attached_bathroom", "attached_bathroom_02"): wet = rooms.get(wet_name) if wet and kitchen.shares_wall(wet, tol=0.5, min_overlap=2.0): kitchen_bath_ok = False break results["kitchen_not_touching_bathroom"] = kitchen_bath_ok else: results["kitchen_not_touching_bathroom"] = True # HC3: Staircase must share a wall with foyer (entry connectivity) stair = rooms.get("external_staircase") foyer_r = rooms.get("foyer") if stair is not None and foyer_r is not None: results["staircase_touches_foyer"] = stair.shares_wall( foyer_r, tol=0.5, min_overlap=2.0) else: results["staircase_touches_foyer"] = True # HC4: Pooja must not be extremely elongated (aspect ratio ≤ 2.5) if p is not None: long_side = max(p.w, p.h) short_side = max(min(p.w, p.h), 0.1) results["pooja_near_square"] = (long_side / short_side) <= 2.5 else: results["pooja_near_square"] = True # HC5: Corridor must connect to at least one bedroom AND one public room corridor = rooms.get("internal_corridor") if corridor is not None: bedroom_keys = {"master_bedroom", "bedroom_01", "bedroom_02", "bedroom_03"} public_keys = {"living_room", "foyer", "dining_room"} touches_bed = any( rooms[k].shares_wall(corridor, tol=0.5, min_overlap=2.0) for k in bedroom_keys if k in rooms ) touches_pub = any( rooms[k].shares_wall(corridor, tol=0.5, min_overlap=2.0) for k in public_keys if k in rooms ) results["corridor_connects_zones"] = touches_bed and touches_pub else: results["corridor_connects_zones"] = True # HC6: Coverage ≥ 0.88 (total room area / inner buildable area) sb_road, sb_other = 6.56, 3.28 inner_w = max(pw - 2.0 * sb_other, 1.0) inner_h = max(ph - sb_road - sb_other, 1.0) inner_area = inner_w * inner_h total_room_area = sum(r.area for r in fp.rooms) results["coverage_adequate"] = (total_room_area / inner_area) >= 0.95 return results def _score_one(fp, selected_vastu_rules, weights): w_aq, w_vs, w_su, w_ac, w_cs, w_lc = weights aq = score_adjacency_quality(fp) se = score_spatial_efficiency(fp) lc = score_layout_compactness(fp) vs, vastu_details = score_vastu(fp, selected_vastu_rules) ac = score_area_compliance(fp, [r.name for r in fp.rooms]) su = score_space_usage(fp) cs = score_cost(fp) hard = check_hard_constraints(fp) _CRITICAL = {"pooja_not_touching_wet", "kitchen_not_touching_bathroom", "no_overlaps", "staircase_touches_living", "master_touches_attached_bath", "wet_rooms_on_setback"} n_critical = sum(1 for k, v in hard.items() if not v and k in _CRITICAL) n_normal = sum(1 for k, v in hard.items() if not v and k not in _CRITICAL) penalty = 0.15 * n_critical + 0.07 * n_normal fitness = (w_vs * vs + w_aq * aq + w_cs * cs + w_su * su + w_ac * ac + w_lc * lc) fitness = max(0.0, fitness - penalty) fp.scores = { "AQ": aq, "SE": se, "LC": lc, "VS": vs, "AC": ac, "SU": su, "CS": cs, "Fitness": round(fitness, 4), "vastu_details": vastu_details, "hard_constraints": hard, "hard_failed": n_critical + n_normal, } return fp def _make_peak_optimised(opt_fp, selected_vastu_rules, weights, road_side="S", trials=None, plan_index=0): """Create a stronger third-stage plan by searching multiple layout variants/seeds for the same selected room set and returning the highest scoring candidate. This is the deterministic stand-in for a future GPT API layout proposal. """ try: from core import ml_pipeline room_names = [r.name for r in opt_fp.rooms if r.name != "internal_corridor"] best_fp = opt_fp best_score = opt_fp.scores.get("Fitness", -1) # Selection is Vastu-weighted: Vastu compliance is the user's top # priority, so it gets extra pull on top of its 30% slice of Fitness. def _sel(fp): return (-fp.scores.get("hard_failed", 0), 0.4 * fp.scores.get("Fitness", 0) + 0.6 * fp.scores.get("VS", 0), fp.scores.get("AQ", 0)) # Best candidate found *within the pinned variant*, independent of the # input optimised plan. This is what keeps the six displayed plans # structurally distinct: if we compared against ``opt_fp`` (whose score # may exceed a particular variant's), low-scoring variants would be # discarded and every plan would collapse back to the single global best. variant_best_fp = None variant_best_key = None def consider(boxes): nonlocal best_fp, best_score, variant_best_fp, variant_best_key if not boxes: return # Same minimal geometry-first post-chain that generate_one_plan uses. boxes = ml_pipeline._optimise_designed_layout( boxes, opt_fp.plot_w, opt_fp.plot_h, road_side) candidate = _ml_boxes_to_floorplan(boxes, opt_fp.plot_w, opt_fp.plot_h) _score_one(candidate, selected_vastu_rules, weights) cand_key = _sel(candidate) if cand_key > _sel(best_fp): best_fp = candidate best_score = candidate.scores.get("Fitness", 0) if variant_best_key is None or cand_key > variant_best_key: variant_best_fp = candidate variant_best_key = cand_key if trials is None: trials = int(os.getenv("PEAK_TRIALS", "18")) # Optional GPT candidate. Off by default on deployment unless # USE_GPT_PEAK=true, because API calls can make Render restart during # long generations. if os.getenv("USE_GPT_PEAK", "false").lower() in ("1", "true", "yes"): try: from core.gpt_layout import propose_layout, get_style_hint setbacks = ml_pipeline.get_setbacks(road_side) style_hint = get_style_hint(plan_index) gpt_boxes = propose_layout( room_names, opt_fp.plot_w, opt_fp.plot_h, road_side, setbacks, timeout=float(os.getenv("GPT_TIMEOUT", "20")), style_hint=style_hint) consider(gpt_boxes) except Exception as exc: print(f"[peak:gpt] unavailable, using deterministic candidates: {exc}") # Pin each generated plan to its OWN structural variant so the six # displayed plans are visibly different instead of all collapsing to the # single global best. perimeter_ring_layout derives its variant from # ``option_score % 6`` (which includes the seed), so we only feed seeds # whose variant matches this plan's index and keep the best candidate # *within that variant*. geom_offset = int(sum((r.x * 13 + r.y * 17 + r.w * 19 + r.h * 23) for r in opt_fp.rooms)) % 997 want_variant = plan_index % 6 base = int(ml_pipeline.variant_offset( room_names, opt_fp.plot_w, opt_fp.plot_h, road_side)) examined = 0 # The variant rendered by perimeter_ring_layout is # ``(base + passed_seed) % 6``. We sweep ``passed_seed`` over the geom # offset window but only keep seeds whose variant matches this plan's # index, so plan ``i`` always renders variant ``i % 6``. seed = geom_offset seed_limit = geom_offset + trials * 6 + 60 while examined < trials and seed < seed_limit: if (base + seed) % 6 == want_variant: boxes = ml_pipeline.perimeter_ring_layout( room_names, opt_fp.plot_w, opt_fp.plot_h, road_side=road_side, seed=seed) consider(boxes) examined += 1 seed += 1 # Prefer the best layout found *within this plan's pinned variant* so the # six displayed plans stay visibly different. The variant candidates are # always valid (gapless, Vastu-reassigned) template layouts, so it is # safe to return one even if its score trails the input plan. if variant_best_fp is not None: return variant_best_fp if best_fp is opt_fp: # Safety net: variant search produced nothing at all; fall back to # the original diverse-seed sweep so we still emit a plan. for step in range(trials): consider(ml_pipeline.perimeter_ring_layout( room_names, opt_fp.plot_w, opt_fp.plot_h, road_side=road_side, seed=101 + geom_offset + step * 7)) return best_fp except Exception as exc: print(f"[peak] failed, using normal optimised plan: {exc}") return opt_fp def rank_plans(plans, selected_vastu_rules, w_vs=0.30, w_aq=0.25, w_cs=0.15, w_su=0.15, w_ac=0.10, w_lc=0.05, road_side="S", regenerate_peak=True): """Score and rank plans. Accepts either a list of FloorPlan (legacy) or a list of (raw, optimised) tuples. Returns a list of dicts: {"raw": raw_fp, "optimised": opt_fp, "fitness_gain": float} sorted by the OPTIMISED plan's fitness, descending. Objectives (in priority order per the guide's spec): VS (Vastu) + AQ (Adjacency) + CS (Cost) + SU (Space) + AC (Area Deviation) + LC (Layout Compactness) ``regenerate_peak`` — when True (default) the displayed "peak" plan is re-laid-out from scratch by ``_make_peak_optimised`` (the ml_pipeline best-of-N search). When False the supplied OPTIMISED plan is shown AS-IS as the peak (used for the PDF-template source, so the displayed plan keeps the reference-PDF look instead of being regenerated). """ weights = (w_aq, w_vs, w_su, w_ac, w_cs, w_lc) pairs = [] for idx, item in enumerate(plans): if isinstance(item, tuple): raw_fp, opt_fp = item else: raw_fp = opt_fp = item _score_one(raw_fp, selected_vastu_rules, weights) _score_one(opt_fp, selected_vastu_rules, weights) if regenerate_peak: peak_fp = _make_peak_optimised( opt_fp, selected_vastu_rules, weights, road_side=road_side, plan_index=idx) else: peak_fp = opt_fp # show the PDF plan as-is pairs.append({ "raw": raw_fp, "optimised": opt_fp, "peak": peak_fp, "fitness_gain": round( opt_fp.scores["Fitness"] - raw_fp.scores["Fitness"], 4), "peak_gain": round( peak_fp.scores["Fitness"] - raw_fp.scores["Fitness"], 4), }) pairs.sort(key=lambda p: p["peak"].scores["Fitness"], reverse=True) def structural_signature(fp): key_rooms = ["living_room", "master_bedroom", "dining_room", "kitchen", "utility_area", "common_bathroom", "attached_bathroom", "attached_bathroom_02", "bedroom_01", "bedroom_02", "bedroom_03", "pooja_room"] sig = [] for name in key_rooms: r = fp.get_room(name) if r is None: continue # Position cells only; dimensions are intentionally ignored. sig.append((name, int((r.cx / max(fp.plot_w, 1e-6)) * 16), int((r.cy / max(fp.plot_h, 1e-6)) * 16))) edges = [] for i, a in enumerate(fp.rooms): if a.name == "internal_corridor": continue for b in fp.rooms[i + 1:]: if b.name == "internal_corridor": continue if a.shares_wall(b, tol=0.75, min_overlap=1.5): edges.append(tuple(sorted((a.name, b.name)))) return (tuple(sig), tuple(sorted(set(edges)))) diversified = [] seen = set() for pair in pairs: sig = structural_signature(pair["peak"]) if sig in seen: continue seen.add(sig) diversified.append(pair) if len(diversified) < len(pairs): used = {id(p) for p in diversified} diversified.extend(p for p in pairs if id(p) not in used) return diversified