"""Hybrid apartment floor-plan layout engine. Two sources feed one geometry engine and one scorer: * a deterministic BACKBONE of architect-correct column blueprints, which guarantees a floor of good plans on any plot with no external service, and * an optional LLM proposer, which adds creative structural variety on top when an API key is configured. Both emit the same abstract spec — a left-to-right list of columns, each a bottom-to-top list of rooms — which this module renders as an EXACT tiling (gapless and overlap-free by construction) and then repairs with tiling-safe passes (reorder rooms inside a column, resize inside a column, swap labels) to enforce the hard rules: * external staircase is EXACTLY 12x10, on the road edge, beside the living * pooja is a small niche (<= ~28 sqft) and never touches a washroom/utility * master bedroom is the biggest bedroom; each attached bath touches its own * every requested room exists Nothing is ever rejected — imperfect ("creative") plans are simply ranked after the clean ones, so the best 5-6 lead the 20. This follows the architecture of recent research (HouseTune 2024, "Generative Floor Plan Design with LLMs via RLVR" 2026): a model proposes a structured JSON layout; deterministic code guarantees the geometry. """ from __future__ import annotations import copy import itertools import json import os import random import re import time from typing import Dict, List, Optional, Tuple from .constants import ROOM_MIN_AREA, ROOM_SIZE_RANGES from .generator import FloorPlan, Room try: from dotenv import load_dotenv except Exception: # pragma: no cover load_dotenv = None MODEL = os.getenv("LAYOUT_MODEL", "gpt-5.2") SETBACK_ROAD, SETBACK_OTHER = 6.56, 3.28 # 2 m / 1 m STAIR_LONG, STAIR_SHORT = 12.0, 10.0 # fixed staircase block POOJA_MAX_AREA = 28.0 # NOTE: "attached_bathroom_02" does NOT end with "bathroom", so never test for # a washroom with .endswith() — always use this tuple. BATHROOMS = ("common_bathroom", "attached_bathroom", "attached_bathroom_02") WET = BATHROOMS + ("utility_area",) BEDROOMS = ("master_bedroom", "bedroom_01", "bedroom_02", "bedroom_03") _SPEC_CACHE: dict = {} # Human-readable reason the layout model was last unavailable (surfaced in the # app so a broken key / timeout / missing package is never a silent fallback). LAST_ERROR: Optional[str] = None # Set once the container is shown to have no outbound route to the proposer # endpoint. Without this, EVERY generation re-pays the full network timeout — # which is what made the hosted app sit on a spinner for minutes at a time # before falling back to the backbone. The backbone alone fills a population, # so after the first proven failure the model path is skipped outright. _NET_DEAD = False # Client-facing wording. Nothing printed from this module names the provider, # the endpoint or the model id: the Space's Logs tab is visible to anyone with # the URL, and the product is presented as an AI layout engine throughout. _ENGINE = "AI layout engine" # The proposer's credentials. LAYOUT_API_KEY is the name to use; the legacy # variable is still read so existing deployments keep working. _KEY_VARS = ("LAYOUT_API_KEY", "OPENAI_API_KEY") def _api_key_source() -> Tuple[Optional[str], Optional[str]]: """(key, name_of_the_env_var_it_came_from). The value is never logged.""" if load_dotenv is not None: load_dotenv() for var in _KEY_VARS: key = os.getenv(var) if key and key.strip(): return key.strip(), var return None, None def _api_key() -> Optional[str]: return _api_key_source()[0] def available() -> bool: """True when the optional LLM proposer is configured. The backbone always works, so a False here only means less structural variety.""" return bool(_api_key()) # ── Layout proposer (optional LLM) ──────────────────────────────────────────── _SYSTEM = """You are a senior Indian residential architect designing APARTMENT FLATS (builder-floor style). Design floor plans as vertical COLUMNS on a buildable rectangle. Feet units. The ROAD is at the BOTTOM (south); x grows EAST; each column's FIRST room touches the road, its LAST room touches the rear (north). A layout = left(WEST)->right(EAST) list of columns. Each column has a width in feet and a bottom->top list of rooms with depths in feet. Column widths must sum to the buildable width; each column's depths must sum to the buildable height (the engine normalises small errors — the flat is FULLY tiled, walls shared, NO empty space, like a real apartment). DESIGN RULES (a practical Indian flat): - external_staircase: EXACTLY 12 ft x 10 ft (give its column width 10 or 12 ft) and it must TOUCH AN OUTER WALL: front (road end) or rear (top) of any column, or anywhere along the leftmost/rightmost column. NEVER landlocked in the interior. There is NO foyer — this stair block IS the entry, so the LIVING ROOM must share a wall with it DIRECTLY. VARY the stair wall across layouts: front-left, front-right, rear-left, rear-right, middle of a side column — do NOT put it in the same place in every layout. The stair column must ALSO contain other rooms stacked with it — NEVER a column holding only the staircase. - living_room: LARGE (>= 12 ft x 12 ft), at the front (south half), the hub. - kitchen: SOUTH-EAST / EAST (east column, front half), 8-10 ft wide. Kitchen must NOT touch a bathroom. - utility_area: COMPULSORY in every layout, attached to the kitchen. - dining_room: COMPULSORY in every layout, between kitchen and living. - study: OPTIONAL filler — include it ONLY where a column has spare depth (e.g. where a foyer would have been); 7-10 ft each side. - master_bedroom: the BIGGEST bedroom (~12x14+), SOUTH-WEST / WEST. - other bedrooms: rear (north), each smaller than the master, min 10 ft side. - attached_bathroom beside the master; attached_bathroom_02 beside the biggest secondary bedroom when requested; common_bathroom reachable from the middle; bathrooms 5-7 ft wide. NEVER give a bathroom or utility the FULL width of a column wider than 8 ft — put two services side by side, pair a bath with its bedroom, or use the narrow service column. NEVER place pooja_room next to any bathroom or utility. - pooja_room: TINY niche (4x5 to 5x5). When a pooja is requested, EVERY layout MUST include one NARROW SERVICE COLUMN (4.5-6.5 ft wide) and the pooja goes at its north end — NEVER as a full-width strip across a 10-13 ft column. Below the pooja put a study/corridor/balcony as a buffer, then the bathrooms/utility further down that column. In MOST layouts the pooja sits NORTH-EAST / north / east; a FEW creative layouts may put it elsewhere. In EVERY layout it must NEVER touch a bathroom or utility. - balcony: at the ROAD FRONT — make it the FIRST room of a column (4-6 ft deep) with the living/dining right behind it, like a real street-facing balcony. Only an occasional variation layout may use the rear instead. - internal_corridor (optional): a thin 3-4 ft connector bounded by rooms. - Room proportions must be realistic: no habitable room narrower than 7 ft, aspect ratio under ~2.2. - SIZE HIERARCHY (hard rules): living_room is the BIGGEST public room (bigger than dining and kitchen); EVERY bedroom is bigger than EVERY bathroom; master_bedroom is the biggest bedroom; pooja is the smallest room. A bedroom smaller than a washroom is an instant failure. - WINDOWS: every bedroom and bathroom must touch an OUTER wall (front, rear, left or right edge). The interior belongs to living/dining/kitchen and circulation — never bury a bedroom or washroom in the centre. OUTPUT ONLY JSON (no markdown): {"layouts":[{"columns":[{"width":,"rooms":[{"name":"","depth":}, ...]},...]},...]} Produce the requested number of layouts. Every layout must be STRUCTURALLY unique: a different stair wall, a different column count, bedrooms on different sides, mirrored arrangements, different stacking order of the rooms. Two layouts that differ only in room SIZES are NOT unique — that is a failure. COLUMN MATH: an average room needs 7-8 ft of depth, so a column of height H holds about H/7 rooms — BALANCE the room count across columns (12 rooms in two 30 ft columns = 6 + 6, NEVER 9 + 3; a 3 ft deep bedroom is an instant failure). If the buildable width is UNDER 26 ft use 2 columns (each 10-13 ft), or 2 wide columns PLUS one narrow 4.5-6 ft service column — a great tight-plot pattern is: pooja at the very top (north) of the service column, a study right below it as a buffer, then the bathrooms/utility. Otherwise use 2-4 columns, and any column holding a living/kitchen/bedroom/ dining must be at least 8 ft wide (only a pure service column may be 4-6 ft). On a small plot use COMPACT depths (habitable 6.5-8 ft, service 3.5-4.5 ft) for EVERY room instead of starving a few rooms. At least HALF the layouts must follow every rule above strictly; the rest may be more experimental/creative (still fully tiled, still realistic room sizes). Include EVERY requested room exactly once per layout (except study, which is optional filler — only where space allows); add nothing else (internal_corridor allowed, foyer NOT allowed).""" def _chat_json(client, model, user, temperature=0.9, timeout=None): kw = dict(model=model, response_format={"type": "json_object"}, messages=[{"role": "system", "content": _SYSTEM}, {"role": "user", "content": user}]) try: r = client.chat.completions.create(temperature=temperature, **kw) except Exception as exc: if "temperature" in str(exc).lower(): r = client.chat.completions.create(**kw) else: raise return json.loads(r.choices[0].message.content or "{}") def _room_guide(names) -> str: out = [] for n in names: (wlo, whi), (dlo, dhi) = ROOM_SIZE_RANGES.get(n, ((6, 12), (8, 14))) out.append(f"{n}: {wlo}-{whi} ft wide x {dlo}-{dhi} ft deep") return "\n".join(out) def _probe_network(host: str = "api.openai.com") -> Tuple[str, bool]: """Called only after every attempt failed. Pins the fault on DNS, TLS or the service itself, so the logs say what is actually wrong instead of the SDK's bare "Connection error.". Cheap, and never runs on the happy path. Returns (human explanation, egress_is_dead). When egress is dead the caller stops trying for the rest of the process. The endpoint host is never named in the returned text — these lines reach the hosted Logs tab. """ import socket import ssl proxies = sorted(k for k in os.environ if "proxy" in k.lower()) try: socket.gethostbyname(host) except Exception as exc: return (f"DNS lookup of the {_ENGINE} endpoint failed " f"({type(exc).__name__}) -- the container has no outbound " f"internet. proxy vars: {proxies or 'none'}", True) try: ctx = ssl.create_default_context() with socket.create_connection((host, 443), timeout=8) as sock: with ctx.wrap_socket(sock, server_hostname=host) as tls: ver = tls.version() except Exception as exc: return (f"the {_ENGINE} endpoint resolves but TLS failed " f"({type(exc).__name__}) -- egress blocked, missing CA " f"certificates, or a proxy. proxy vars: {proxies or 'none'}", True) return (f"network is fine (TLS {ver}); the failure is at the service level " f"(credentials, quota, or model access). " f"proxy vars: {proxies or 'none'}", False) _REDACT = re.compile( r"(api\.openai\.com|openai|OpenAI|gpt[-_.]?[\w.]*|sk-[A-Za-z0-9_-]+)", re.IGNORECASE) def _scrub(text: str) -> str: """SDK exception text names the vendor, the endpoint and sometimes the key. All three reach the hosted Logs tab, which anyone with the Space URL can open, so they are replaced before anything is printed. The fault type and the chain survive — only the identifiers go.""" return _REDACT.sub("[engine]", str(text)) def _explain(exc: BaseException) -> str: """The SDK collapses every network fault into the useless string "Connection error.". Walk the __cause__/__context__ chain so the log names the real fault: DNS failure, TLS/certificate error, refused, proxy, quota.""" parts = [f"{type(exc).__name__}: {_scrub(exc)}"] seen = {id(exc)} cur = exc.__cause__ or exc.__context__ while cur is not None and id(cur) not in seen and len(parts) < 5: parts.append(f"caused by {type(cur).__name__}: {_scrub(cur)}") seen.add(id(cur)) cur = cur.__cause__ or cur.__context__ return " <- ".join(parts) def _propose(required, optional, build_w, build_h, n) -> Optional[list]: """One proposer call -> layout specs. FAILURES ARE LOUD (printed to the console AND kept in LAST_ERROR for the UI) so a silent fall-back can never hide a broken key/quota/timeout. Returning None just means the backbone carries the whole population.""" global LAST_ERROR, _NET_DEAD if _NET_DEAD: # Proven unreachable earlier in this process. Re-trying would cost the # full timeout again for a result already known, so go straight to the # backbone instead of parking the user on a spinner. LAST_ERROR = (f"{_ENGINE} unreachable from this host (established " f"earlier); backbone blueprints are carrying the " f"population") return None key, key_var = _api_key_source() if not key: LAST_ERROR = (f"{_ENGINE} credentials not configured " "(set LAYOUT_API_KEY in .env or the Space secrets)") print(f"[layout_engine] {LAST_ERROR}") return None # Log neither the key nor which variable supplied it — only that one was # found and its shape, so a truncated secret is still diagnosable. print(f"[layout_engine] credentials found (len={len(key)})") try: from openai import OpenAI # SDK, isolated here except Exception as exc: LAST_ERROR = f"{_ENGINE} client unavailable: {type(exc).__name__}" print(f"[layout_engine] {LAST_ERROR}") return None rooms_all = list(dict.fromkeys(list(required) + list(optional))) user = json.dumps({ "buildable_rectangle_ft": {"width": round(build_w, 1), "height": round(build_h, 1)}, "rooms_required": rooms_all, "room_size_guide": _room_guide(rooms_all), "n_layouts": n, }) model = MODEL # A layout call takes 30-60 s, so the per-call floor stays at 90 s. The # BUDGET is the new part: two attempts at a 180 s timeout could block for # six minutes before the backbone took over, which on the hosted app looked # like the page had died. The whole function now works to one wall-clock # deadline and simply skips the retry when the budget is gone. timeout = max(float(os.getenv("LAYOUT_TIMEOUT", "120")), 90.0) budget = max(float(os.getenv("LAYOUT_BUDGET", "150")), timeout) started = time.monotonic() allowed = set(rooms_all) | {"internal_corridor"} specs = [] for attempt in (1, 2): # retry transient errors AND unusable answers left = budget - (time.monotonic() - started) if attempt == 2 and left < 20: print(f"[layout_engine] retry skipped, {left:.0f}s of the " f"{budget:.0f}s budget left") break try: client = OpenAI(api_key=key, timeout=min(timeout, max(left, 15))) data = _chat_json(client, model, user) except Exception as exc: LAST_ERROR = (f"{_ENGINE} call failed " f"(try {attempt}): {_explain(exc)}") print(f"[layout_engine] {LAST_ERROR}") if attempt == 2: # both tries died: say WHY, once diag, dead = _probe_network() LAST_ERROR += f" | diagnosis: {diag}" print(f"[layout_engine] diagnosis: {diag}") if dead: _NET_DEAD = True print("[layout_engine] no outbound route — the " f"{_ENGINE} will be skipped for the rest of this " "session; backbone blueprints carry the population") continue specs = _parse_specs(data, allowed) if "pooja_room" in allowed and specs: # the pooja needs a narrow (<=7 ft) column for a sane niche — # prefer the layouts that actually built one narrow = [s for s in specs if min(c[0] for c in s) <= 7.0] if len(narrow) >= max(3, n // 4): specs = narrow if len(specs) >= max(3, n // 4): break LAST_ERROR = (f"{_ENGINE} returned only {len(specs)} usable layouts " f"(try {attempt})") print(f"[layout_engine] {LAST_ERROR}") if not specs: return None # LAST_ERROR already explains why LAST_ERROR = None # success — clear it return specs def _parse_specs(data, allowed): """JSON answer -> [[col_width, [[room, depth], ...]], ...] specs (lenient: bad columns/rooms are skipped, a layout needs >= 2 usable columns).""" raw = data.get("layouts") if isinstance(data, dict) else None if not isinstance(raw, list): raw = [data] if isinstance(data, dict) and "columns" in data else [] specs = [] for lay in raw: cols = lay.get("columns") if isinstance(lay, dict) else None if not isinstance(cols, list) or not (2 <= len(cols) <= 5): continue spec = [] for col in cols: try: cw = float(col.get("width", 0)) except Exception: cw = 0.0 rooms = [] for rm in (col.get("rooms") or []): nm = rm.get("name") if isinstance(rm, dict) else None if nm not in allowed: continue try: d = max(float(rm.get("depth", 0)), 1.0) except Exception: d = 6.0 rooms.append([nm, d]) if cw > 0 and rooms: spec.append([cw, rooms]) if len(spec) >= 2: specs.append(spec) return specs # ── Deterministic rendering (tiling-safe by construction) ───────────────────── def _insert_missing(spec, needed): """Every requested room must exist: drop stray duplicates, then insert any missing room into the column with the most spare depth (guide-mid depth).""" seen = set() for cw, rooms in spec: keep = [] for nm, d in rooms: if nm != "internal_corridor" and nm in seen: continue # duplicate — drop seen.add(nm) keep.append([nm, d]) rooms[:] = keep for nm in needed: if nm in seen: continue (_, _), (dlo, dhi) = ROOM_SIZE_RANGES.get(nm, ((6, 10), (6, 10))) depth = (dlo + dhi) / 2.0 # widest non-staircase column (its rooms compress the least) cands = [c for c in spec if not any(r[0] == "external_staircase" for r in c[1])] or spec col = max(cands, key=lambda c: c[0]) col[1].append([nm, depth]) seen.add(nm) # a column emptied by de-duping would break the tiling — give it a filler for cw, rooms in spec: if not rooms: rooms.append(["balcony", 8.0]) return spec def _fix_staircase(spec, build_w): """Stair column width -> 10 or 12 exactly (delta shared by other columns). The stair keeps the position the proposer chose (front, rear, or a side column) — it is only snapped to the nearer END of its column when it would be landlocked in the interior (not touching any outer wall).""" ci = next((i for i, (_, rooms) in enumerate(spec) if any(nm == "external_staircase" for nm, _ in rooms)), None) if ci is None: return spec if len(spec[ci][1]) == 1: # a stair-only column would stretch the stair to the full building # depth — never allow it if len(spec) > 2: # merge the stair into the nearest column (at its road end) and # drop the empty column (_spec_to_boxes renormalises widths) stair = spec[ci][1][0] spec.pop(ci) ci = min(ci, len(spec) - 1) spec[ci][1].insert(0, stair) else: # only 2 columns: pull the deepest habitable room over instead other = spec[1 - ci][1] donor = max((r for r in other if r[0] in HABITABLE), key=lambda r: r[1], default=None) if donor is None and len(other) > 1: donor = max(other, key=lambda r: r[1]) # any room at all if donor is not None and len(other) > 1: other.remove(donor) spec[ci][1].append(donor) cw, rooms = spec[ci] target_w = STAIR_SHORT if abs(cw - STAIR_SHORT) <= abs(cw - STAIR_LONG) \ else STAIR_LONG target_d = STAIR_LONG if target_w == STAIR_SHORT else STAIR_SHORT delta = cw - target_w others = [c for i, c in enumerate(spec) if i != ci] tot = sum(c[0] for c in others) or 1.0 for c in others: c[0] = max(4.0, c[0] + delta * (c[0] / tot)) spec[ci][0] = target_w si = next(i for i, r in enumerate(rooms) if r[0] == "external_staircase") edge_col = ci in (0, len(spec) - 1) # touches a side wall if not edge_col and si not in (0, len(rooms) - 1): stair = rooms.pop(si) # landlocked: snap to if si <= len(rooms) / 2: # the nearer end rooms.insert(0, stair) si = 0 else: rooms.append(stair) si = len(rooms) - 1 rooms[si][1] = target_d return spec HABITABLE = ("living_room", "kitchen", "dining_room", "study") + BEDROOMS def _floor_depth(nm): if nm == "pooja_room": return 2.5 return 6.5 if nm in HABITABLE else 3.5 def _merge_excess_columns(spec, ih): """A 50 ft tall column needs ~5 rooms to fill sanely, so a 14-room plan supports at most ~3 columns — merge the thinnest columns when a spec has too many, otherwise every column starves and stretches its rooms.""" min_rooms = max(2, int(round(ih / 9.5))) total = sum(len(c[1]) for c in spec) max_cols = max(2, int(round(total / float(min_rooms)))) def keep(c): # never merge away the stair (fixed 10/12 ft) or the pooja's narrow # service column (merging would re-stretch the niche) return any(nm in ("external_staircase", "pooja_room") for nm, _ in c[1]) while len(spec) > max_cols: cands = [i for i, c in enumerate(spec) if not keep(c)] if len(cands) < 1: break i = min(cands, key=lambda i: spec[i][0]) # thinnest mergeable nbrs = [j for j in (i - 1, i + 1) if 0 <= j < len(spec) and not keep(spec[j]) and spec[j][0] + spec[i][0] <= 15.0] # never a 16 ft column if not nbrs: break j = min(nbrs, key=lambda j: spec[j][0]) spec[j][0] += spec[i][0] spec[j][1].extend(spec[i][1]) spec.pop(i) return spec def _rebalance_columns(spec, ih): """Balance the columns by MINIMUM depth load so one column never renders pancake rooms while another has slack (a 3BHK on a 30x40 plot used to stack 9 rooms in one column and 4 in the other). Only the staircase is immovable. Pure spec move — the tiling stays exact.""" def load(col): return sum(d if nm == "external_staircase" else _floor_depth(nm) for nm, d in col[1]) for _ in range(16): worst = max(spec, key=load) if load(worst) <= ih + 0.1: break movable = [r for r in worst[1] if r[0] != "external_staircase"] if len(movable) <= 1: break moved = False for room in sorted(movable, key=lambda r: _floor_depth(r[0])): target = min((c for c in spec if c is not worst), key=load, default=None) if target is not None and \ load(target) + _floor_depth(room[0]) < load(worst): worst[1].remove(room) target[1].append(room) moved = True break if not moved: break # Phase B: no STARVING columns. A column with too few rooms for the # building height stretches whatever it holds into mega strips (a lone # washroom becomes 10x34 = 344 sqft on a 40x60 plot). Every column needs # roughly height/13 rooms so the depth ceilings have absorbers to work # with; the deepest movable room migrates from the fullest column. min_rooms = max(2, int(round(ih / 9.5))) for _ in range(16): starving = min(spec, key=lambda c: len(c[1])) if len(starving[1]) >= min_rooms: break # donor: any column at least TWO rooms fuller — equalise even when # no column reaches min_rooms (e.g. 12 rooms over 4 columns) donor = max((c for c in spec if c is not starving and len(c[1]) >= len(starving[1]) + 2), key=lambda c: len(c[1]), default=None) if donor is None: break movable = [r for r in donor[1] if r[0] not in ("external_staircase", "pooja_room")] if not movable: break room = max(movable, key=lambda r: _floor_depth(r[0])) donor[1].remove(room) starving[1].append(room) return spec def _normalize_widths(spec, iw): s = iw / (sum(c[0] for c in spec) or 1.0) for c in spec: c[0] *= s return spec def _strip_corridors(spec): """Drop proposer-supplied internal_corridors. In a fully-tiled flat the corridor easily balloons into a depth sink (a 337 sqft 'passage'); we add at most ONE thin buffer later, only where a pooja/service genuinely needs separating. Empty columns are removed.""" for c in spec: c[1] = [r for r in c[1] if r[0] != "internal_corridor"] spec[:] = [c for c in spec if c[1]] return spec def _col_area(c): return sum(_ideal_area(nm) for nm, _ in c[1]) _THIN_SVC = ("common_bathroom", "attached_bathroom", "attached_bathroom_02", "utility_area") # An ATTACHED bath must keep the wall it shares with its own bedroom, so it is # never dragged into the service cluster. Only the shared bath and the utility # are groupable. _GROUPABLE_SVC = ("common_bathroom", "utility_area") def _group_services(spec): """Within each column, pull the groupable services (shared bath + utility) next to each other so the box-level pairing can fuse two full-width strips into a side-by-side pair (a 11x3.8 bath + 11x3.5 utility -> two ~5.5x7 rooms). Pure reorder — the column still tiles exactly.""" for cw, rooms in spec: svc = [r for r in rooms if r[0] in _GROUPABLE_SVC] if len(svc) < 2: continue # anchor the group just after the first service's original slot first = min(rooms.index(r) for r in svc) others = [r for r in rooms if r not in svc] rooms[:] = others[:first] + svc + others[first:] return spec def _set_column_count(spec, iw, ih): """Reduce to a column count the WIDTH can support (~11 ft per column) so no habitable room is squeezed into a 5 ft strip. Adjacent non-stair columns with the smallest combined area merge first; the stair column is left intact so it keeps its wall slot.""" K = max(2, min(4, int(round(iw / 11.0)))) def has_stair(c): return any(nm == "external_staircase" for nm, _ in c[1]) while len(spec) > K: best = None for i in range(len(spec) - 1): a, b = spec[i], spec[i + 1] if has_stair(a) or has_stair(b): continue ca = _col_area(a) + _col_area(b) if best is None or ca < best[0]: best = (ca, i) if best is None: break i = best[1] spec[i][1].extend(spec[i + 1][1]) spec.pop(i + 1) return spec def _col_load(c): """Effective room-slot load of a column. Each room fills ~one horizontal band; the staircase eats ~2 bands (120 sqft ~= 12 ft of the ~50 ft height), so it counts double. This is what governs per-room DEPTH — a column of 4 slots gives each room ~1/4 of the height (square-ish), whereas a 2-room column forces two 25 ft deep strips.""" load = 0.0 for nm, _ in c[1]: if nm == "external_staircase": load += 2.0 elif nm in ("pooja_room", "internal_corridor"): load += 0.5 # niche/buffer, half band else: load += 1.0 return load # An attached bath belongs to exactly one bedroom and must never be separated # from it — they move between columns together, as one unit. ATTACHED_OF = {"master_bedroom": "attached_bathroom", "bedroom_01": "attached_bathroom_02"} _ATTACHED_BATHS = tuple(ATTACHED_OF.values()) def _balance_columns(spec, ih): """Even out the ROOM-SLOT load across columns so every column ends up with ~4 bands (each room ~1/4 of the height = square-ish). Balancing by COUNT (not area) is what stops one big room stretching to 25 ft deep in a thin column. Hard invariant: NO column is left with a load below ~3 while another sits above ~4 — that pairing is exactly what produces a strip. The stair/pooja stay pinned, an attached bath travels with its bedroom; one room moves at a time, preserving adjacency as much as possible.""" PIN = ("external_staircase", "pooja_room") + _ATTACHED_BATHS if len(spec) < 2: return spec # target load per column so every room gets ~1/target of the height target = max(3.0, sum(_col_load(c) for c in spec) / len(spec)) for _ in range(60): hi = max(spec, key=_col_load) lo = min(spec, key=_col_load) # stop only when the spread is small AND the emptiest column is not # starved (load >= target-1 means its rooms won't stretch) if hi is lo or (_col_load(hi) - _col_load(lo) <= 1.0 and _col_load(lo) >= target - 1.0): break movable = [r for r in hi[1] if r[0] not in PIN] if len(hi[1]) <= 1 or not movable: break # move the SMALLEST room off the fullest column into the emptiest one # (keeps big rooms where they are; fills the thin column with a # service/medium so its big room no longer has to fill alone) room = min(movable, key=lambda r: _ideal_area(r[0])) _move_room(hi, lo, room) return spec def _move_room(src, dst, room): """Move a room between columns, dragging its attached bath along so the bedroom/bath pair is never split across columns.""" src[1].remove(room) dst[1].append(room) bath_nm = ATTACHED_OF.get(room[0]) if bath_nm: bath = next((r for r in src[1] if r[0] == bath_nm), None) if bath is not None: src[1].remove(bath) dst[1].append(bath) # lands right after its bedroom _MEDIUM = ("living_room", "kitchen", "dining_room", "study", "bedroom_01", "bedroom_02", "bedroom_03", "master_bedroom") def _fix_stair_column_mix(spec): """The staircase eats ~12 ft of its column's depth, so if the only other big room there is a single bedroom/living it stretches to fill the rest (a 10x30 living strip). Guarantee the stair column holds at least TWO medium rooms — they then share the depth at a sane 15-19 ft each. Pull a medium in from the column that has the most; push a shallow balcony out.""" def has_stair(c): return any(nm == "external_staircase" for nm, _ in c[1]) sc = next((c for c in spec if has_stair(c)), None) if sc is None or len(spec) < 2: return spec def n_medium(c): return sum(1 for nm, _ in c[1] if nm in _MEDIUM) for _ in range(3): if n_medium(sc) >= 2: break donor = max((c for c in spec if c is not sc and n_medium(c) >= 2), key=n_medium, default=None) if donor is None: break # move the smallest medium so the donor keeps its biggest rooms # (its attached bath, if any, comes along) room = min((r for r in donor[1] if r[0] in _MEDIUM), key=lambda r: _ideal_area(r[0])) _move_room(donor, sc, room) return spec def _fill_stair_column(spec, ih): """The staircase column has a FIXED width (10/12 ft) but the 120 sqft stair eats ~12 ft of its depth, so if it holds only 1-2 other rooms they stretch to fill the rest (a 10x34 master strip). Move rooms in/out until the column's total ideal area ~= width x height, so its rooms fill naturally at their proper size.""" def has_stair(c): return any(nm == "external_staircase" for nm, _ in c[1]) sc = next((c for c in spec if has_stair(c)), None) if sc is None or len(spec) < 2: return spec def area(c): return sum(_ideal_area(nm) for nm, _ in c[1]) # rooms that never move on their own: the stair, the pooja niche, and an # attached bath (it travels with its bedroom through _move_room) PINNED = ("external_staircase", "pooja_room") + _ATTACHED_BATHS target = sc[0] * ih for _ in range(6): gap = target - area(sc) others = [c for c in spec if c is not sc and len(c[1]) > 1] if gap > 60 and others: # under-filled: pull one donor = max(others, key=area) movable = [r for r in donor[1] if r[0] not in PINNED] if not movable: break # the room that best closes the gap without overshooting room = min(movable, key=lambda r: abs(gap - _ideal_area(r[0]))) _move_room(donor, sc, room) elif gap < -60 and len(sc[1]) > 2: # over-filled: push one movable = [r for r in sc[1] if r[0] not in PINNED] if not movable: break room = min(movable, key=lambda r: _ideal_area(r[0])) target_col = min((c for c in spec if c is not sc), key=area) _move_room(sc, target_col, room) else: break return spec def _assign_column_widths(spec, iw, ih): """Set each column's width from the IDEAL AREA of the rooms it holds: width = column_area / ih, so a column of big rooms (living+master) comes out wide and a pure service column comes out narrow — every room lands near square. The staircase column keeps its exact 10/12 ft; the rest are scaled to fill the remaining width with sane floors.""" def has_stair(c): return any(nm == "external_staircase" for nm, _ in c[1]) def col_area(c): return sum(_ideal_area(nm) for nm, _ in c[1] if nm != "external_staircase") stair_w = sum(c[0] for c in spec if has_stair(c)) or 0.0 others = [c for c in spec if not has_stair(c)] avail = max(iw - stair_w, 4.0) raw = {id(c): max(col_area(c) / ih, 1.0) for c in others} rsum = sum(raw.values()) or 1.0 for c in others: c[0] = avail * raw[id(c)] / rsum # floors from the finalised width bounds: a column must be at least as # wide as the largest MIN short-side of the rooms it holds (living 9, # master 10, bedrooms 8, kitchen 7...); a pure service column >= 4.5 ft. # Pull the deficit from the widest column that can spare it. def floor_for(c): mins = [MIN_SHORT_SIDE[nm] for nm, _ in c[1] if nm in MIN_SHORT_SIDE] if mins: return max(mins) if any(nm in HABITABLE for nm, _ in c[1]): return 7.5 return 4.5 for _ in range(4): deficit = [c for c in others if c[0] < floor_for(c) - 0.05] if not deficit: break c = min(deficit, key=lambda c: c[0]) need = floor_for(c) - c[0] donor = max((d for d in others if d is not c and d[0] - need >= floor_for(d)), key=lambda d: d[0], default=None) if donor is None: break donor[0] -= need c[0] += need return spec # Ideal FLOOR AREA per room (sqft). The depth a room receives in its column # is proportional to this — the spec decides topology (which rooms sit in # which column and their order) while these targets decide the SIZES. This is # what keeps a master ~= a bedroom instead of one becoming a 400 sqft strip. # Proportions straight from the client's finalised sheet (living = 152.2 as # the 1.0 reference: master 1.1x, parents' room 0.75x, kids' 0.667x, guest and # dining 0.5x, kitchen 0.4x, study 0.333x ...). The SAME table drives the # Room Size Accuracy metric (core/size_model.py), so the geometry builds what # the scoring expects. IDEAL_AREA = { "living_room": 152.2, "master_bedroom": 167.4, "bedroom_01": 114.2, "bedroom_02": 101.5, "bedroom_03": 76.1, "kitchen": 60.9, "dining_room": 76.1, "study": 50.7, "utility_area": 20.2, "common_bathroom": 19.0, "attached_bathroom": 25.4, "attached_bathroom_02": 25.4, "pooja_room": 15.2, "balcony": 40.0, "internal_corridor": 10.0, } # The finalised width-bounds (a room's SHORT side, ft) from the same sheet. # MIN drives the column-width floors, MAX caps a room's depth when its # column is wider than the bound. MIN_SHORT_SIDE = { "living_room": 9.0, "master_bedroom": 10.0, "bedroom_01": 8.0, "bedroom_02": 8.0, "bedroom_03": 8.0, "kitchen": 7.0, "dining_room": 5.0, } MAX_SHORT_SIDE = { "living_room": 12.0, "master_bedroom": 16.0, "bedroom_01": 12.0, "bedroom_02": 12.0, "bedroom_03": 12.0, "kitchen": 10.0, "dining_room": 8.0, "common_bathroom": 7.0, "attached_bathroom": 7.0, "attached_bathroom_02": 7.0, "utility_area": 6.0, "pooja_room": 5.0, } def _ideal_area(nm): return IDEAL_AREA.get(nm, 120.0) def _spec_to_boxes(spec, ix0, iy0, iw, ih): """Exact tiling: widths scaled to sum=iw; within each column the flexible rooms receive depth in proportion to their IDEAL AREA (not the spec's raw depths), so same-class rooms come out similar sizes and nothing balloons into a strip. Floors/ceilings then clamp any residual extreme.""" # the staircase column keeps its EXACT width (10 or 12); only the other # columns are scaled to absorb any width error. def has_stair(c): return any(nm == "external_staircase" for nm, _ in c[1]) stair_w = sum(c[0] for c in spec if has_stair(c)) other_w = sum(c[0] for c in spec if not has_stair(c)) or 1.0 oscale = max(iw - stair_w, 4.0) / other_w boxes = [] x = ix0 FIXED_DEPTH = ("external_staircase", "pooja_room") # never re-scaled for k, (cw, rooms) in enumerate(spec): w = cw if has_stair(spec[k]) else cw * oscale if k == len(spec) - 1: w = ix0 + iw - x fixed = sum(d for nm, d in rooms if nm in FIXED_DEPTH) avail = max(ih - fixed, 4.0) # depth proportional to ideal area (target_depth = ideal_area / width), # normalised so the flex rooms exactly fill the remaining column depth want = {m: _ideal_area(nm) / max(w, 1.0) for m, (nm, _) in enumerate(rooms) if nm not in FIXED_DEPTH} wsum = sum(want.values()) or 1.0 hs = [d if nm in FIXED_DEPTH else avail * want[m] / wsum for m, (nm, d) in enumerate(rooms)] # depth floors: enough depth that the room reaches its CODE MINIMUM # area at this column width (never below the old 6.5/3.5 comfort # floors, never an absurd demand in a very narrow column) def depth_floor(nm): base = 6.5 if nm in HABITABLE else 3.5 need = ROOM_MIN_AREA.get(nm, 25) / max(w, 1.0) return min(max(base, need), 14.0) for _ in range(3): for m, (nm, _) in enumerate(rooms): if nm in FIXED_DEPTH: continue floor = depth_floor(nm) if hs[m] >= floor: continue need = floor - hs[m] for q in sorted(range(len(rooms)), key=lambda q: -hs[q]): if q == m or rooms[q][0] in FIXED_DEPTH: continue qfloor = depth_floor(rooms[q][0]) give = min(need, hs[q] - qfloor) if give > 0: hs[q] -= give hs[m] += give need -= give if need <= 0.01: break # column overfull even at the minimum floors (tiny plot, many rooms): # share the shortfall in PROPORTION to each room's floor so the pain # is even — never one 3 ft pancake bedroom beside a 8 ft one flo = {m: depth_floor(rooms[m][0]) for m in range(len(rooms)) if rooms[m][0] not in FIXED_DEPTH} if flo: need_min = sum(flo.values()) avail = ih - sum(hs[m] for m in range(len(rooms)) if rooms[m][0] in FIXED_DEPTH) if need_min > avail + 0.05: k = max(avail, 4.0) / need_min for m, f in flo.items(): hs[m] = f * k # depth CEILINGS: a room must not become a long strip — cap depth at # ~2.2x the column width and hand the excess to under-cap neighbours # (balcony / corridor may stay long; stair & pooja are fixed). # ALSO: the client's width-bounds table caps a room's SHORT side (e.g. # dining <= 8 ft, bedroom <= 12 ft). In a column wider than that # bound, the depth becomes the short side — so cap the depth at the # bound to keep the room inside its finalised proportions. def cap_for(nm): if nm == "balcony": return min(2.2 * w, 8.0) # a balcony is shallow if nm == "internal_corridor": return min(2.2 * w, 6.0) # a passage is thin, never a sink cap = 2.2 * w if nm in HABITABLE else min(2.2 * w, 9.0) hi = MAX_SHORT_SIDE.get(nm) if hi is not None and w > hi: cap = min(cap, hi) return cap for _ in range(4): over = [m for m, (nm, _) in enumerate(rooms) if nm not in FIXED_DEPTH and hs[m] > cap_for(nm) + 0.05] for m in over: nm = rooms[m][0] excess = hs[m] - cap_for(nm) # hand excess to the room furthest BELOW its cap (spreads the # depth so nothing else balloons into a strip sink) for q in sorted(range(len(rooms)), key=lambda q: hs[q] - cap_for(rooms[q][0])): if q == m or rooms[q][0] in FIXED_DEPTH: continue take = min(excess, cap_for(rooms[q][0]) - hs[q]) if take > 0: hs[q] += take hs[m] -= take excess -= take if excess <= 0.01: break # exact column fill: spread any residual drift across the flex rooms # in proportion to their cap headroom, so nothing balloons into a # strip. If every room is already at its cap, the widest habitable # room takes the rest (a slightly big living beats a random strip). flex_idx = [m for m, (nm, _) in enumerate(rooms) if nm not in FIXED_DEPTH] for _ in range(4): drift = ih - sum(hs) if abs(drift) < 0.05 or not flex_idx: break head = {m: max(cap_for(rooms[m][0]) - hs[m], 0.0) for m in flex_idx} hsum = sum(head.values()) if drift > 0 and hsum > 0.05: for m in flex_idx: hs[m] += drift * head[m] / hsum else: # over cap (or no headroom): scale flex rooms to fit exactly cur = sum(hs[m] for m in flex_idx) or 1.0 tgt = ih - sum(hs[m] for m, (nm, _) in enumerate(rooms) if nm in FIXED_DEPTH) for m in flex_idx: hs[m] *= max(tgt, 1.0) / cur break y = iy0 for m, (nm, d) in enumerate(rooms): h = hs[m] if m == len(rooms) - 1: h = iy0 + ih - y boxes.append({"name": nm, "x": round(x, 2), "y": round(y, 2), "w": round(w, 2), "h": round(max(h, 1.0), 2)}) y += h x += w return boxes def _pair_thin_rooms(boxes, iw, ih, iy0): """Real plans put two small rooms SIDE BY SIDE, not as stacked full-width strips. Two thin same-class rooms stacked in one column are re-cut into a side-by-side pair sharing their combined depth: a 10x2.7 bathroom over a 10x2.7 utility becomes two ~5x5.4 rooms. The pair's combined footprint is unchanged, so the tiling stays exact. Services pair only with services (a kitchen must never end up beside a bathroom).""" SERVICE = ("common_bathroom", "attached_bathroom", "attached_bathroom_02", "utility_area", "balcony") HAB = ("kitchen", "dining_room", "study", "bedroom_01", "bedroom_02", "bedroom_03") # a service may also pair with a bedroom/study (an attached bath BESIDE # the bedroom is the classic plan) — but never with kitchen/dining BESIDE_OK = ("bedroom_01", "bedroom_02", "bedroom_03", "master_bedroom", "study") def group(nm): return "s" if nm in SERVICE else ("h" if nm in HAB else None) def compat(na, nb): ga, gb = group(na), group(nb) if ga == gb and ga is not None: return True if ga == "s" and nb in BESIDE_OK: return True if gb == "s" and na in BESIDE_OK: return True return False done = set() for a in boxes: ga = group(a["name"]) if ga is None or id(a) in done: continue lim = 4.8 if ga == "s" else 5.6 wmin = 8.0 if ga == "s" else 12.0 if a["h"] > lim or a["w"] < wmin: continue for b in boxes: if b is a or id(b) in done \ or not compat(a["name"], b["name"]) \ or b["h"] > (4.8 if group(b["name"]) == "s" else 5.6): continue if not (abs(a["x"] - b["x"]) < 0.3 and abs(a["w"] - b["w"]) < 0.3): continue # must share the column stacked = abs(a["y"] + a["h"] - b["y"]) < 0.3 \ or abs(b["y"] + b["h"] - a["y"]) < 0.3 pen0 = _violations(boxes, iw, ih, iy0) if stacked: # directly stacked: the cut is local — no repack needed, so # it works even in a column that already holds another pair col = [a, b] snap = {id(c): (c["x"], c["y"], c["w"], c["h"]) for c in col} else: # b must slide through the column to sit right after a — # only safe in a fully contiguous, stair-free column col = sorted([c for c in boxes if abs(c["x"] - a["x"]) < 0.3 and abs(c["w"] - a["w"]) < 0.3], key=lambda c: c["y"]) cy0 = min(c["y"] for c in col) span = max(c["y"] + c["h"] for c in col) - cy0 if abs(span - sum(c["h"] for c in col)) > 0.3: continue # column already holds a pair if any(c["name"] == "external_staircase" for c in col): continue # never slide rooms past the fixed stair snap = {id(c): (c["x"], c["y"], c["w"], c["h"]) for c in col} order = [c for c in col if c is not b] order.insert(order.index(a) + 1, b) y = cy0 for c in order: c["y"] = y y += c["h"] # side-by-side cut over the two cells' combined footprint, width # split by IDEAL AREA so two same-class services come out ~50/50 # (splitting by depth let a bath grab 68% and balloon to 84 sqft) y0p = min(a["y"], b["y"]) dd = a["h"] + b["h"] w, x0 = a["w"], a["x"] ia, ib = _ideal_area(a["name"]), _ideal_area(b["name"]) wa = max(3.5, min(w - 3.5, w * ia / (ia + ib))) a.update(x=x0, y=y0p, w=wa, h=dd) b.update(x=x0 + wa, y=y0p, w=w - wa, h=dd) # revert only on HARD damage (pooja-wet +10 / kitchen-bath +6); # a +-2.5 edge-score wobble must not undo de-stripping if _violations(boxes, iw, ih, iy0) > pen0 + 3.5: for c in col: c["x"], c["y"], c["w"], c["h"] = snap[id(c)] continue done.add(id(a)) done.add(id(b)) break return boxes def _split_wide_service(boxes): """LAST RESORT for a lone full-width service row in a wide column (a 14 x 4 bathroom with no thin partner to pair with): cut the cell into [service | passage] side by side. Only fires when the plan has no internal_corridor yet, so there is never more than one passage.""" if any(b["name"] == "internal_corridor" for b in boxes): return boxes new = [] for bx in boxes: if bx["name"] not in ("common_bathroom", "attached_bathroom", "attached_bathroom_02", "utility_area"): continue if bx["w"] < 9.5 or bx["h"] < 3.2 \ or bx["w"] <= 2.8 * bx["h"]: continue keep_w = min(7.0, max(5.0, 42.0 / bx["h"])) rest = bx["w"] - keep_w if rest < 3.0: continue new.append({"name": "internal_corridor", "x": bx["x"] + keep_w, "y": bx["y"], "w": rest, "h": bx["h"]}) bx["w"] = keep_w break # at most one passage boxes.extend(new) return boxes def _pair_pooja(boxes, iw, ih, iy0): """A pooja rendered as a full-width strip (12 x 2.5) is not a niche. Pair it side-by-side with a DRY flexible partner (study / internal_corridor) stacked in the same column: the pooja becomes ~4.5 ft wide with a sane aspect, the partner keeps the rest. Reverted when it worsens the plan.""" pj = next((b for b in boxes if b["name"] == "pooja_room"), None) if pj is None or max(pj["w"], pj["h"]) <= 2.6 * min(pj["w"], pj["h"]): return boxes if pj["w"] < 8.0 or pj["h"] > 4.0: return boxes for b in boxes: if b["name"] not in ("study", "internal_corridor") or b["h"] > 6.5: continue if not (abs(b["x"] - pj["x"]) < 0.3 and abs(b["w"] - pj["w"]) < 0.3): continue stacked = abs(pj["y"] + pj["h"] - b["y"]) < 0.3 \ or abs(b["y"] + b["h"] - pj["y"]) < 0.3 if not stacked: continue snap = {id(c): (c["x"], c["y"], c["w"], c["h"]) for c in (pj, b)} pen0 = _violations(boxes, iw, ih, iy0) y0p = min(pj["y"], b["y"]) dd = pj["h"] + b["h"] w, x0 = pj["w"], pj["x"] wa = max(4.0, min(w - 4.0, w * pj["h"] / dd)) pj.update(x=x0, y=y0p, w=wa, h=dd) b.update(x=x0 + wa, y=y0p, w=w - wa, h=dd) if _violations(boxes, iw, ih, iy0) > pen0 + 3.5: for c in (pj, b): c["x"], c["y"], c["w"], c["h"] = snap[id(c)] continue break return boxes def _shrink_to_area(boxes, bx, max_area): """Shrink an oversized box to ~max_area by trimming its depth (or width), handing the freed strip to a neighbour in the same column (or row) so the tiling stays exact. HABITABLE neighbours are preferred (bedrooms/living grow); the fixed staircase and the pooja never absorb.""" if bx["w"] * bx["h"] <= max_area + 1: return NO_ABSORB = ("external_staircase", "pooja_room") def deficit(c): # how far BELOW its ideal area a room is (a strip group counts its # combined area) — the neediest habitable room absorbs first, so a # squished bedroom grows and an already-large master never balloons area = sum(b["w"] * b["h"] for b in (c if isinstance(c, list) else [c])) nm = (c[0] if isinstance(c, list) else c)["name"] return _ideal_area(nm) - area def pick(cands): cands = [c for c in cands if c] if not cands: return None # prefer habitable, then the one furthest below its ideal size cands.sort(key=lambda c: ( 0 if (c[0] if isinstance(c, list) else c)["name"] in HABITABLE else 1, -deficit(c))) return cands[0] new_h = max(3.5, max_area / max(bx["w"], 1.0)) if bx["w"] / new_h > 3.0 and bx["w"] * bx["h"] <= max_area * 1.5: return # trimming depth would create a strip — a slightly # oversized room beats a 12x3 sliver freed = bx["h"] - new_h if freed > 0.1: def span_group(edge_y, from_above): """All absorb-ok boxes whose edge meets bx's edge and which together tile bx's full width (handles side-by-side pairs).""" if from_above: grp = [b for b in boxes if b is not bx and b["name"] not in NO_ABSORB and abs(b["y"] - edge_y) < 0.3 and b["x"] >= bx["x"] - 0.3 and b["x"] + b["w"] <= bx["x"] + bx["w"] + 0.3] else: grp = [b for b in boxes if b is not bx and b["name"] not in NO_ABSORB and abs(b["y"] + b["h"] - edge_y) < 0.3 and b["x"] >= bx["x"] - 0.3 and b["x"] + b["w"] <= bx["x"] + bx["w"] + 0.3] if grp and abs(sum(b["w"] for b in grp) - bx["w"]) < 0.5: return grp return None belows = span_group(bx["y"], from_above=False) aboves = span_group(bx["y"] + bx["h"], from_above=True) cands = [g for g in (belows, aboves) if g] if cands: # give the freed depth to the group with the NEEDIEST habitable # room (grows a squished bedroom, never the already-large master) grp = max(cands, key=lambda g: max( (deficit(b) for b in g if b["name"] in HABITABLE), default=-1e9)) if grp is belows: bx["y"] += freed bx["h"] = new_h for b in grp: b["h"] += freed else: bx["h"] = new_h for b in grp: b["y"] -= freed b["h"] += freed return new_w = max(3.5, max_area / max(bx["h"], 1.0)) if bx["h"] / new_w > 3.0 and bx["w"] * bx["h"] <= max_area * 1.6: return freed_w = bx["w"] - new_w if freed_w <= 0.1: return same_row = [b for b in boxes if b is not bx and b["name"] not in NO_ABSORB and abs(b["y"] - bx["y"]) < 0.3 and abs(b["h"] - bx["h"]) < 0.3] left = next((b for b in same_row if abs(b["x"] + b["w"] - bx["x"]) < 0.3), None) right = next((b for b in same_row if abs(bx["x"] + bx["w"] - b["x"]) < 0.3), None) tgt = pick([left, right]) if tgt is not None: if tgt is left: bx["x"] += freed_w bx["w"] = new_w left["w"] += freed_w else: bx["w"] = new_w right["x"] -= freed_w right["w"] += freed_w def _balance_service_pairs(boxes): """Two services sitting side by side (same row, shared depth) must split their width by ideal area, not lopsidedly — otherwise one bath grabs 68% and balloons to 84 sqft next to a sliver utility. Equalises the pair in place (their combined footprint is unchanged, so the tiling stays exact).""" SVC = ("common_bathroom", "attached_bathroom", "attached_bathroom_02", "utility_area") for a in boxes: if a["name"] not in SVC: continue for b in boxes: if b is a or b["name"] not in SVC: continue same_row = abs(a["y"] - b["y"]) < 0.3 and abs(a["h"] - b["h"]) < 0.3 if not same_row: continue # a is the LEFT member of the adjacent pair if abs(a["x"] + a["w"] - b["x"]) > 0.3: continue total = a["w"] + b["w"] ia, ib = _ideal_area(a["name"]), _ideal_area(b["name"]) wa = max(3.5, min(total - 3.5, total * ia / (ia + ib))) a["w"] = wa b["x"] = a["x"] + wa b["w"] = total - wa return boxes def _cap_services(boxes): """Washrooms/utility have realistic MAXIMA — an XL washroom beside a compact bedroom is what makes a plan look broken. The freed strip grows a habitable neighbour, so bedrooms can only get bigger here.""" CAPS = {"common_bathroom": 45.0, "attached_bathroom": 42.0, "attached_bathroom_02": 42.0, "utility_area": 38.0} for bx in boxes: cap = CAPS.get(bx["name"]) if cap is not None: _shrink_to_area(boxes, bx, cap) _balance_service_pairs(boxes) return boxes def _cap_public_hierarchy(boxes): """The living room is the biggest public room, ALWAYS: any kitchen or dining that out-sizes it is shrunk (freed strip grows a neighbour — often the living room itself). Runs after the label fixes so it works on the final living rectangle.""" living = max((b for b in boxes if b["name"] == "living_room"), key=lambda b: b["w"] * b["h"], default=None) if living is None: return boxes lv = living["w"] * living["h"] for nm in ("kitchen", "dining_room"): for bx in [b for b in boxes if b["name"] == nm]: if bx["w"] * bx["h"] > lv - 3: _shrink_to_area(boxes, bx, max(lv - 3, 40.0)) return boxes def _touching(a, b): """Strict contact test for the pooja-wet rule: ANY shared wall segment counts, even a sliver (the door-worthy _adjacent needs 1.5 ft).""" return _adjacent(a, b, tol=0.7, min_ov=0.3) def _adjacent(a, b, tol=0.6, min_ov=1.5): ax0, ay0, ax1, ay1 = a["x"], a["y"], a["x"] + a["w"], a["y"] + a["h"] bx0, by0, bx1, by1 = b["x"], b["y"], b["x"] + b["w"], b["y"] + b["h"] if abs(ax1 - bx0) < tol or abs(bx1 - ax0) < tol: if min(ay1, by1) - max(ay0, by0) >= min_ov: return True if abs(ay1 - by0) < tol or abs(by1 - ay0) < tol: if min(ax1, bx1) - max(ax0, bx0) >= min_ov: return True return False def _violations(boxes, iw, ih, iy0): """Soft score (lower = better) used to ORDER plans and pick permutations.""" idx = {} for b in boxes: idx.setdefault(b["name"], []).append(b) pen = 0.0 ex0, ex1 = SETBACK_OTHER, SETBACK_OTHER + iw def on_edge(b): return (b["x"] <= ex0 + 0.6 or b["x"] + b["w"] >= ex1 - 0.6 or b["y"] <= iy0 + 0.6 or b["y"] + b["h"] >= iy0 + ih - 0.6) pooja = idx.get("pooja_room", [None])[0] if pooja is not None: if any(_touching(pooja, w) for nm in WET for w in idx.get(nm, [])): pen += 10.0 cy = (pooja["y"] + pooja["h"] / 2 - iy0) / ih cx = (pooja["x"] + pooja["w"] / 2) / iw if cy < 0.6: pen += 2.0 # pooja should sit north if cx < 0.5: pen += 1.0 # ... and east # ISOLATED pooja (client complaint): it must open onto a public room, # a corridor or an outer wall — never be walled in by bedrooms only pub = ("living_room", "dining_room", "kitchen", "internal_corridor") if not on_edge(pooja) and not any( _adjacent(pooja, b) for nm in pub for b in idx.get(nm, [])): pen += 4.0 # a pooja is a NICHE — an oversized one reads as a spare bedroom if pooja["w"] * pooja["h"] > POOJA_MAX_AREA + 4.0: pen += 3.5 kit = idx.get("kitchen", [None])[0] if kit is not None: if any(_adjacent(kit, w) for nm in ("common_bathroom", "attached_bathroom", "attached_bathroom_02") for w in idx.get(nm, [])): pen += 6.0 if not on_edge(kit): pen += 2.5 # kitchen wants a wall stair = idx.get("external_staircase", [None])[0] living = max(idx.get("living_room", [None]) or [None], key=lambda b: b["w"] * b["h"] if b else 0) if stair is not None and living is not None: # no foyer any more — the stair block IS the entry, living must touch it if not _adjacent(stair, living): pen += 8.0 if stair is not None: # the stair may sit on ANY outer wall, but never landlocked inside x0, x1 = SETBACK_OTHER, SETBACK_OTHER + iw if not (stair["x"] <= x0 + 0.5 or stair["x"] + stair["w"] >= x1 - 0.5 or stair["y"] <= iy0 + 0.5 or stair["y"] + stair["h"] >= iy0 + ih - 0.5): pen += 10.0 if living is not None and (living["y"] + living["h"] / 2 - iy0) / ih > 0.55: pen += 2.0 # living should sit front balc = idx.get("balcony", [None])[0] if balc is not None and abs(balc["y"] - iy0) > 0.5: pen += 3.0 # balcony wants road front master = idx.get("master_bedroom", [None])[0] if master is not None and any( b["w"] * b["h"] > master["w"] * master["h"] + 1 for nm in ("bedroom_01", "bedroom_02", "bedroom_03") for b in idx.get(nm, [])): pen += 3.0 # an ATTACHED bath is only attached if it shares a wall with its bedroom: # attached_bathroom -> master, attached_bathroom_02 -> bedroom_01 for bed_nm, bath_nm in (("master_bedroom", "attached_bathroom"), ("bedroom_01", "attached_bathroom_02")): bed = idx.get(bed_nm, [None])[0] bath = idx.get(bath_nm, [None])[0] if bed is not None and bath is not None and not _adjacent(bed, bath): pen += 4.0 # SIZE HIERARCHY: a bedroom below the biggest washroom reads broken, and # the living room must stay the biggest public room bath_max = max((b["w"] * b["h"] for nm in ("common_bathroom", "attached_bathroom", "attached_bathroom_02") for b in idx.get(nm, [])), default=0.0) for nm in BEDROOMS: for b in idx.get(nm, []): if b["w"] * b["h"] < bath_max - 1: pen += 4.0 if bath_max > 60.0: pen += 4.0 # an XL washroom is never right if living is not None: for nm in ("dining_room", "kitchen"): for b in idx.get(nm, []): if b["w"] * b["h"] > living["w"] * living["h"] + 1: pen += 3.0 # pooja is a NICHE — a stretched full-width strip is not a pooja if pooja is not None and \ max(pooja["w"], pooja["h"]) > 2.6 * min(pooja["w"], pooja["h"]): pen += 2.5 # bedrooms need windows, washrooms belong on edges — landlocked = bad ex0, ex1 = SETBACK_OTHER, SETBACK_OTHER + iw for b in boxes: if b["name"] in BEDROOMS or b["name"] in BATHROOMS: on_edge = (b["x"] <= ex0 + 0.5 or b["x"] + b["w"] >= ex1 - 0.5 or b["y"] <= iy0 + 0.5 or b["y"] + b["h"] >= iy0 + ih - 0.5) if not on_edge: pen += 3.0 if b["name"] in BEDROOMS else 2.5 # These mirror the hard quality gates so a plan that would FAIL review # never out-ranks a clean (e.g. backbone) plan on the same plot. for b in boxes: if b["name"] in BEDROOMS + ("living_room", "kitchen", "dining_room"): if max(b["w"], b["h"]) > 2.5 * min(b["w"], b["h"]): pen += 4.0 # strip room (gate) if b["name"] in ("master_bedroom", "bedroom_01", "bedroom_02", "bedroom_03", "living_room"): if b["w"] * b["h"] < 78.0 or min(b["w"], b["h"]) < 7.0: pen += 4.0 # cramped room (gate) return pen def _improve_order(spec, ix0, iy0, iw, ih, rng): """Permute rooms WITHIN each column to lower the violation score. The staircase is free to move too — the landlocked penalty in _violations keeps it on an outer wall while letting it sit front, rear, or along a side column. Column permutation preserves the perfect tiling.""" for _sweep in range(2): # 2nd sweep: earlier columns adapt to later for ci in range(len(spec)): rooms = spec[ci][1] if not (2 <= len(rooms) <= 6): continue best, best_pen = None, None for perm in itertools.permutations(rooms): spec[ci][1] = list(perm) pen = _violations(_spec_to_boxes(spec, ix0, iy0, iw, ih), iw, ih, iy0) if best_pen is None or pen < best_pen - 1e-9: best_pen, best = pen, list(perm) spec[ci][1] = best return spec def _pooja_to_narrow_column(spec): """A pooja belongs in a narrow service column: if its column is wider than ~9 ft (a full-width pooja strip would exceed the niche size), MOVE it to the narrowest non-staircase column. Pure spec move — tiling stays exact.""" pci = pr = None for ci, (cw, rooms) in enumerate(spec): for r in rooms: if r[0] == "pooja_room": pci, pr = ci, r if pr is None or spec[pci][0] <= 8.0 or len(spec[pci][1]) < 2: return spec def _narrow(ci): """Squeeze a pure-service column to 6.5 ft (excess width shared by the other non-stair columns — column-level, tiling stays exact).""" cw, rooms = spec[ci] if cw <= 8.0 or any(nm in HABITABLE or nm == "external_staircase" for nm, _ in rooms): return False excess = cw - 6.5 others = [c for i, c in enumerate(spec) if i != ci and not any(nm == "external_staircase" for nm, _ in c[1])] tot = sum(c[0] for c in others) or 1.0 for c in others: c[0] += excess * (c[0] / tot) spec[ci][0] = 6.5 return True # best case: the pooja's OWN column is pure service — just narrow it if _narrow(pci): return spec # prefer a column with NO wet rooms and FEW habitable rooms; a narrower # column renders a squarer niche cands = [ci for ci, (cw, rooms) in enumerate(spec) if ci != pci and cw <= spec[pci][0]] if not cands: return spec tci = min(cands, key=lambda ci: ( any(nm in WET for nm, _ in spec[ci][1]), any(nm == "external_staircase" for nm, _ in spec[ci][1]), sum(1 for nm, _ in spec[ci][1] if nm in HABITABLE), spec[ci][0])) spec[pci][1].remove(pr) spec[tci][1].append(pr) # top of the column (north) _narrow(tci) return spec def _reorder_pooja_column(boxes): """LAST-RESORT pooja-wet fix: permute the vertical ORDER of the rooms in the pooja's own column (box-space; the column's footprint is unchanged, so the tiling stays exact) and keep the ordering with no pooja-wet contact, preferring the pooja high (north).""" pj = next((b for b in boxes if b["name"] == "pooja_room"), None) if pj is None: return boxes wet = [b for b in boxes if b["name"] in WET] if not any(_touching(pj, w) for w in wet): return boxes col = sorted([b for b in boxes if abs(b["x"] - pj["x"]) < 0.3 and abs(b["w"] - pj["w"]) < 0.3], key=lambda b: b["y"]) if not (2 <= len(col) <= 7): return boxes y0 = min(b["y"] for b in col) span = max(b["y"] + b["h"] for b in col) - y0 if abs(span - sum(b["h"] for b in col)) > 0.3: return boxes # column holds a side-by-side pair — repacking # full-width members would overlap it others_wet = [w for w in wet if w not in col] orig = [(b["y"]) for b in col] best, best_key = None, None stair_i = next((i for i, b in enumerate(col) if b["name"] == "external_staircase"), None) for perm in itertools.permutations(col): if stair_i is not None and perm[stair_i] is not col[stair_i]: continue # the stair keeps its wall position y = y0 pos = {} for b in perm: pos[id(b)] = y y += b["h"] # evaluate pooja-wet contact in this ordering def probe(b): return {"name": b["name"], "x": b["x"], "y": pos[id(b)], "w": b["w"], "h": b["h"]} pjp = probe(pj) touch = any(_touching(pjp, probe(w)) for w in col if w is not pj and w["name"] in WET) touch = touch or any(_touching(pjp, w) for w in others_wet) key = (1 if touch else 0, -pos[id(pj)]) # no contact, pooja north if best_key is None or key < best_key: best_key, best = key, {id(b): pos[id(b)] for b in perm} if best is not None and best_key[0] == 0: for b in col: b["y"] = best[id(b)] return boxes def _reorder_wet_columns(boxes, iw, ih, iy0): """When a wet room in a NEIGHBOURING column touches the pooja, permute that column's vertical order to slide the wet room out of the pooja's y-band (footprint unchanged — tiling stays exact). Reverted if the move makes the overall plan worse.""" pj = next((b for b in boxes if b["name"] == "pooja_room"), None) if pj is None: return boxes for wbox in [w for w in boxes if w["name"] in WET and _touching(pj, w)]: col = sorted([b for b in boxes if abs(b["x"] - wbox["x"]) < 0.3 and abs(b["w"] - wbox["w"]) < 0.3], key=lambda b: b["y"]) if not (2 <= len(col) <= 7) or pj in col: continue # same-column contact: _reorder_pooja_column's job y0 = min(b["y"] for b in col) span = max(b["y"] + b["h"] for b in col) - y0 if abs(span - sum(b["h"] for b in col)) > 0.3: continue # column holds a side-by-side pair — skip it stair_i = next((i for i, b in enumerate(col) if b["name"] == "external_staircase"), None) pen_before = _violations(boxes, iw, ih, iy0) orig_y = {id(b): b["y"] for b in col} applied = False for perm in itertools.permutations(col): if stair_i is not None and perm[stair_i] is not col[stair_i]: continue # the stair keeps its wall position y = y0 pos = {} for b in perm: pos[id(b)] = y y += b["h"] def probe(b): return {"name": b["name"], "x": b["x"], "y": pos[id(b)], "w": b["w"], "h": b["h"]} if any(_touching(pj, probe(b)) for b in col if b["name"] in WET): continue for b in col: b["y"] = pos[id(b)] if _violations(boxes, iw, ih, iy0) <= pen_before: applied = True break for b in col: # worse overall — roll back and keep b["y"] = orig_y[id(b)] # trying other orderings if not applied: for b in col: b["y"] = orig_y[id(b)] return boxes def _cap_pooja(spec): """Pooja is a tiny niche: cap its area; the freed depth goes to the largest room in the same column (tiling preserved by renormalisation).""" for cw, rooms in spec: for r in rooms: if r[0] == "pooja_room": # clamp BOTH ways: a spec sometimes proposes a 1 ft sliver r[1] = min(max(r[1], 2.8), max(POOJA_MAX_AREA / max(cw, 1.0), 2.8), 6.0) return spec def _niche_pooja(boxes, iw, ih, iy0): """Force the pooja into a compact NICHE shape (aspect <= ~1.7). A wide full-width strip (10 x 2.8 = 28 sqft — passes the AREA cap but reads as a stretched band) is narrowed to ~5.5 ft wide; the freed horizontal strip goes to a same-row DRY neighbour (never wet), else becomes the plan's single internal_corridor buffer. Never leaves a hole: if neither placement works the pooja is restored to its original strip. Tiling stays exact.""" pj = next((b for b in boxes if b["name"] == "pooja_room"), None) if pj is None: return boxes aspect = max(pj["w"], pj["h"]) / max(min(pj["w"], pj["h"]), 0.1) if aspect <= 1.7 and pj["w"] * pj["h"] <= POOJA_MAX_AREA + 1: return boxes # already a fine niche if pj["w"] <= pj["h"] * 1.5: return boxes # only WIDE strips here keep_w = min(6.0, max(4.5, POOJA_MAX_AREA / max(pj["h"], 1.0))) keep_w = min(keep_w, pj["w"] - 2.8) if keep_w < 4.0 or keep_w * pj["h"] < 14.5: return boxes # never trim the niche below its code minimum freed_w = pj["w"] - keep_w x0, y0, h = pj["x"], pj["y"], pj["h"] # a niche hugs a WALL: keep the pooja on its outer edge, push the freed # strip toward the interior ex0, ex1 = SETBACK_OTHER, SETBACK_OTHER + iw trim_right = abs(x0 - ex0) < 0.6 or abs((x0 + pj["w"]) - ex1) >= 0.6 strip_x = x0 + keep_w if trim_right else x0 pj_x = x0 if trim_right else x0 + freed_w # 1) a same-row DRY neighbour flush against the freed strip can absorb it for b in boxes: if b is pj or b["name"] in WET or b["name"] == "external_staircase": continue if abs(b["y"] - y0) > 0.4 or abs(b["h"] - h) > 0.4: continue if trim_right and abs(b["x"] - (x0 + pj["w"])) < 0.4: pj["x"], pj["w"] = pj_x, keep_w b["x"], b["w"] = strip_x, b["w"] + freed_w return boxes if not trim_right and abs((b["x"] + b["w"]) - x0) < 0.4: pj["x"], pj["w"] = pj_x, keep_w b["w"] += freed_w return boxes # 2) no dry neighbour: a buffer corridor fills the freed strip. A stretched # 13x2.5 "pooja" is a far worse defect than a second thin passage, so # allow up to two — the circulation metric keeps the total honest. if sum(1 for b in boxes if b["name"] == "internal_corridor") < 2: pj["x"], pj["w"] = pj_x, keep_w boxes.append({"name": "internal_corridor", "x": strip_x, "y": y0, "w": freed_w, "h": h}) return boxes # else: leave as-is def _cap_pooja_box(boxes): """Final pooja cap in BOX space (column widths may have changed after the spec-space cap). The freed strip goes to the vertically-adjacent room in the SAME column, so the tiling stays exact.""" pj = next((b for b in boxes if b["name"] == "pooja_room"), None) if pj is None or pj["w"] * pj["h"] <= POOJA_MAX_AREA + 1: return boxes new_h = max(2.5, POOJA_MAX_AREA / max(pj["w"], 1.0)) freed = pj["h"] - new_h if freed <= 0.1: return boxes same_col = [b for b in boxes if b is not pj and abs(b["x"] - pj["x"]) < 0.3 and abs(b["w"] - pj["w"]) < 0.3] below = next((b for b in same_col if abs(b["y"] + b["h"] - pj["y"]) < 0.3), None) above = next((b for b in same_col if abs(pj["y"] + pj["h"] - b["y"]) < 0.3), None) if below is not None: # pooja slides north; the room below grows pj["y"] += freed pj["h"] = new_h below["h"] += freed elif above is not None: pj["h"] = new_h above["y"] -= freed above["h"] += freed else: # pooja fills its whole column: shrink its WIDTH instead, the strip # goes to a horizontally-adjacent room with the same vertical span new_w = max(2.5, POOJA_MAX_AREA / max(pj["h"], 1.0)) freed_w = pj["w"] - new_w if freed_w <= 0.1: return boxes same_row = [b for b in boxes if b is not pj and b["name"] != "external_staircase" # 12x10 is FIXED and abs(b["y"] - pj["y"]) < 0.3 and abs(b["h"] - pj["h"]) < 0.3] left = next((b for b in same_row if abs(b["x"] + b["w"] - pj["x"]) < 0.3), None) right = next((b for b in same_row if abs(pj["x"] + pj["w"] - b["x"]) < 0.3), None) if left is not None: pj["x"] += freed_w pj["w"] = new_w left["w"] += freed_w elif right is not None: pj["w"] = new_w right["x"] -= freed_w right["w"] += freed_w return boxes def _fix_attached_baths(boxes): """An 'attached' bath that does not touch its bedroom is a broken plan. The box passes (pairing, service grouping, pooja reordering) can slide a bath away from its bedroom, so as a final repair we SWAP LABELS with a bathroom that does touch it. Geometry is untouched, all bathrooms are similar in size, so the tiling stays exact.""" def find(nm): return next((b for b in boxes if b["name"] == nm), None) for bed_nm, bath_nm in ATTACHED_OF.items(): bed, bath = find(bed_nm), find(bath_nm) if bed is None or bath is None or _adjacent(bed, bath): continue # a bathroom that already touches this bedroom; never steal the bath # that is correctly attached to the OTHER bedroom protected = set() for other_bed, other_bath in ATTACHED_OF.items(): if other_bed == bed_nm: continue ob, ot = find(other_bed), find(other_bath) if ob is not None and ot is not None and _adjacent(ob, ot): protected.add(other_bath) cands = [b for b in boxes if b["name"] in BATHROOMS and b is not bath and b["name"] not in protected and _adjacent(bed, b)] if cands: # prefer the shared bath — it has no bedroom of its own to satisfy tgt = min(cands, key=lambda b: 0 if b["name"] == "common_bathroom" else 1) bath["name"], tgt["name"] = tgt["name"], bath["name"] return boxes def _label_fixes(boxes): """Label-only repairs (geometry untouched): the living room opens off the staircase when possible; master = biggest bedroom (run AFTER the living swap, which can hand a big rectangle to another bedroom label); the pooja label moves off a wet wall if a clean swap target exists.""" # living = the biggest PUBLIC room — a living room smaller than the # kitchen/dining reads as a broken plan (run BEFORE the stair-adjacency # swap so that fix operates on the final living rectangle) pub = [b for b in boxes if b["name"] in ("living_room", "kitchen", "dining_room")] living = next((b for b in pub if b["name"] == "living_room"), None) if living is not None: big = max(pub, key=lambda b: b["w"] * b["h"]) if big is not living and \ big["w"] * big["h"] > living["w"] * living["h"] + 1: living["name"], big["name"] = big["name"], living["name"] # living beside stair (label swap; early-exit when already fine) stair = next((b for b in boxes if b["name"] == "external_staircase"), None) living = max((b for b in boxes if b["name"] == "living_room"), key=lambda b: b["w"] * b["h"], default=None) if stair is not None and living is not None \ and not _adjacent(stair, living): for tier in (("dining_room", "study", "bedroom_01", "bedroom_02", "bedroom_03"), ("kitchen",)): # kitchen: last resort cands = [b for b in boxes if b["name"] in tier and _adjacent(b, stair) and min(b["w"], b["h"]) >= 5.0] # tight plots: rooms # (the biggest candidate wins, so on roomy plots this still picks # a proper 7ft+ room) if cands: target = max(cands, key=lambda b: b["w"] * b["h"]) target["name"], living["name"] = "living_room", target["name"] break # master = biggest bedroom beds = [b for b in boxes if b["name"] in BEDROOMS] if beds: biggest = max(beds, key=lambda b: b["w"] * b["h"]) master = next((b for b in beds if b["name"] == "master_bedroom"), None) if master is None: biggest["name"] = "master_bedroom" elif biggest is not master and \ biggest["w"] * biggest["h"] > master["w"] * master["h"] + 1: master["name"], biggest["name"] = biggest["name"], master["name"] # pooja off a wet wall via label swap with a small dry room pooja = next((b for b in boxes if b["name"] == "pooja_room"), None) if pooja is not None: wet = [b for b in boxes if b["name"] in WET] if any(_touching(pooja, w) for w in wet): cands = [b for b in boxes if b["name"] in ("study", "balcony", "internal_corridor") and not any(_touching(b, w) for w in wet) and b["w"] * b["h"] <= 60.0 and max(b["w"], b["h"]) <= 12.0] # never a full column if cands: target = min(cands, key=lambda b: b["w"] * b["h"]) pooja["name"], target["name"] = target["name"], pooja["name"] # NUCLEAR fallback: pooja could not move — relocate the WET label # instead (swap it with a small dry room that does not touch the # pooja; geometry is untouched, so the tiling stays exact) pooja = next(b for b in boxes if b["name"] == "pooja_room") kitchen = next((b for b in boxes if b["name"] == "kitchen"), None) for w in [w for w in boxes if w["name"] in WET and _touching(pooja, w)]: for tier in ("internal_corridor", "study", "balcony", "dining_room"): cands = [b for b in boxes if b["name"] == tier and not _touching(pooja, b) and not (w["name"] in BATHROOMS and kitchen is not None and _adjacent(b, kitchen))] if cands: tgt = min(cands, key=lambda b: b["w"] * b["h"]) w["name"], tgt["name"] = tgt["name"], w["name"] break # STRETCHED pooja (a full-width sliver is not a niche): move the label # into a compact dry cell — the final re-cap then shrinks it to ~28 sqft # with a sane aspect because the new cell is narrow enough pooja = next((b for b in boxes if b["name"] == "pooja_room"), None) if pooja is not None and \ max(pooja["w"], pooja["h"]) > 2.6 * min(pooja["w"], pooja["h"]): wet = [b for b in boxes if b["name"] in WET] for tier in (("study", "internal_corridor"), ("balcony",)): cands = [b for b in boxes if b["name"] in tier and not any(_touching(b, w) for w in wet) and b["w"] <= 8.5 and b["w"] * b["h"] >= 16.0 and max(b["w"], b["h"]) <= 13.0] if cands: target = min(cands, key=lambda b: b["w"] * b["h"]) pooja["name"], target["name"] = target["name"], pooja["name"] break return boxes def _rotate(boxes, plot_w, plot_h, road_side): if road_side == "S": return boxes out = [] for b in boxes: x, y, w, h = b["x"], b["y"], b["w"], b["h"] if road_side == "N": nx, ny, nw, nh = plot_w - x - w, plot_h - y - h, w, h elif road_side == "E": nx, ny, nw, nh = plot_w - y - h, x, h, w else: # W nx, ny, nw, nh = y, plot_h - x - w, h, w out.append({"name": b["name"], "x": nx, "y": ny, "w": nw, "h": nh}) return out def _mirror_x(boxes, ix0, iw): """Mirror the whole tiling left<->right inside the buildable rectangle — adjacencies survive intact, so it is a free source of structural variety when there are fewer unique specs than requested plans.""" x1 = 2 * ix0 + iw return [{**b, "x": x1 - b["x"] - b["w"]} for b in boxes] def _jitter(boxes, ix0, iy0, ix1, iy1, amount, rng): """RAW 'AI generated' look: walls slide a little; overlaps allowed but nothing may leave the buildable rectangle.""" out = [] for b in boxes: d = dict(b) d["x"] += rng.uniform(-amount, amount) d["y"] += rng.uniform(-amount, amount) d["w"] = max(3.0, d["w"] + rng.uniform(-amount, amount)) d["h"] = max(3.0, d["h"] + rng.uniform(-amount, amount)) d["x"] = max(ix0, min(d["x"], ix1 - d["w"])) d["y"] = max(iy0, min(d["y"], iy1 - d["h"])) out.append(d) return out # ── Public API ──────────────────────────────────────────────────────────────── def _spec_from_columns(columns): """columns = list of columns, each a list of room-name strings (road->rear order, west->east column order). Convert to the engine's spec format with placeholder width/depth (both recomputed by the sizing engine).""" spec = [] for col in columns: rooms = [[nm, 8.0] for nm in col if nm] if rooms: spec.append([10.0, rooms]) return spec def _backbone_specs(bhk_tag, required, optional): """Deterministic, architect-correct column blueprints for a BHK. These are the guaranteed-good floor: the staircase sits at a road corner with the living beside it, bedrooms hug the outer (edge) columns, the public spine (living/dining/kitchen) fills the centre, wet rooms are grouped, and the pooja is a north-east niche. Every variant is then sized/polished by the shared engine, so they render well on any 30-45 ft plot. Rooms not selected are simply omitted.""" present = set(required) | set(optional) def keep(seq): return [r for r in seq if r in present] beds = keep(["master_bedroom", "bedroom_01", "bedroom_02", "bedroom_03"]) if not beds: beds = ["master_bedroom"] baths = keep(["attached_bathroom", "attached_bathroom_02", "common_bathroom"]) abath = "attached_bathroom" if "attached_bathroom" in present else \ (baths[0] if baths else None) cbath = "common_bathroom" if "common_bathroom" in present else \ (baths[-1] if baths else None) has_util = "utility_area" in present has_pooja = "pooja_room" in present has_balcony = "balcony" in present has_study = "study" in present # the SECOND attached bath belongs to the biggest secondary bedroom abath2 = "attached_bathroom_02" if "attached_bathroom_02" in present else None master = beds[0] others = beds[1:] # secondary bedrooms def unit(bed): """A bedroom travels with its own attached bath so the two always share a column, and therefore a wall. Only master and bedroom_01 have one.""" if bed == master and abath: return [bed, abath] if others and bed == others[0] and abath2: return [bed, abath2] return [bed] def split(seq): """Alternate a list into (front-half, back-half) for two edge columns.""" a, b = [], [] for i, x in enumerate(seq): (a if i % 2 == 0 else b).append(x) return a, b def flat(beds_): out = [] for b in beds_: out += unit(b) return out blueprints = [] # ---- Blueprint A: stair + master on the WEST edge, public spine centre, # secondary bedrooms + pooja on the EAST edge ---------------------- westA = ["external_staircase", master] + ([abath] if abath else []) \ + flat(others[:1]) centreA = keep(["living_room", "dining_room", "kitchen"]) \ + ([cbath] if cbath and cbath != abath else []) \ + (["utility_area"] if has_util else []) eastA = (["balcony"] if has_balcony else []) \ + flat(others[1:]) \ + (["study"] if has_study else []) \ + (["pooja_room"] if has_pooja else []) blueprints.append([westA, centreA, eastA]) # ---- Blueprint B: bedrooms on BOTH edges, stair + living + kitchen the # public spine, pooja tucked NE. Kitchen sits east (SE vastu). ----- ba, bb = split(others) westB = [master] + ([abath] if abath else []) + flat(ba) centreB = ["external_staircase"] + keep(["living_room", "dining_room"]) \ + ([cbath] if cbath and cbath != abath else []) eastB = (["balcony"] if has_balcony else []) \ + keep(["kitchen"]) + (["utility_area"] if has_util else []) \ + flat(bb) + (["study"] if has_study else []) \ + (["pooja_room"] if has_pooja else []) blueprints.append([westB, centreB, eastB]) # ---- Blueprint C: stair on the EAST edge, master WEST, a compact 3-col # arrangement with the pooja beside the kitchen in the NE ---------- westC = (["balcony"] if has_balcony else []) + [master] \ + ([abath] if abath else []) + flat(others[:1]) centreC = keep(["living_room", "dining_room", "kitchen"]) \ + (["utility_area"] if has_util else []) \ + ([cbath] if cbath and cbath != abath else []) eastC = ["external_staircase"] + flat(others[1:]) \ + (["study"] if has_study else []) \ + (["pooja_room"] if has_pooja else []) blueprints.append([westC, centreC, eastC]) # keep only non-empty columns, convert to specs, and add a mirrored twin # of each for left<->right variety (the engine mirrors geometrically too) specs = [] for bp in blueprints: cols = [c for c in bp if c] if len(cols) >= 2: specs.append((_spec_from_columns(cols), False)) specs.append((_spec_from_columns([list(reversed(c)) for c in reversed(cols)]), False)) # engineered PINNED families, designed against the finalised scoring: # V-plans chase vastu >= 80, A-plans chase adjacency >= 80. # entries become (spec, pinned, mirror_ok) out = [(s, p, True) for s, p in specs] for cols, mirror_ok in _engineered_columns(bhk_tag, present): cols = [[nm for nm in col if nm in present or nm == "external_staircase"] for col in cols] cols = [c for c in cols if c] if len(cols) >= 2: out.append((_spec_from_columns(cols), True, mirror_ok)) return out # ── Engineered PINNED blueprints (searched against the finalised scoring) ──── # Column lists are road-south frame, west->east, each bottom->top; found by a # hill-climb against the REAL metrics with the mandatory gates (room aspect # and room-size accuracy >= 80) enforced. V-plans maximise Vastu Compliance, # A-plans maximise Adjacency Satisfaction — the client accepts that each # comes at the other's expense. Rooms absent from a request are filtered out. _ENGINEERED: Dict[str, List[List[List[str]]]] = { "3bhk": [ # V: vastu plain 91.7 / weighted 57.5, aspect 88, size 84 [["balcony", "bedroom_01", "bedroom_02", "common_bathroom", "attached_bathroom", "utility_area"], ["external_staircase", "pooja_room", "master_bedroom"], ["dining_room", "living_room", "kitchen"]], [["balcony", "bedroom_01", "bedroom_02", "attached_bathroom", "common_bathroom", "utility_area"], ["external_staircase", "pooja_room", "master_bedroom"], ["dining_room", "living_room", "kitchen"]], [["balcony", "common_bathroom", "bedroom_02", "bedroom_01", "attached_bathroom", "utility_area"], ["external_staircase", "pooja_room", "master_bedroom"], ["dining_room", "living_room", "kitchen"]], [["balcony", "attached_bathroom", "bedroom_01", "bedroom_02", "common_bathroom", "utility_area"], ["external_staircase", "pooja_room", "master_bedroom"], ["dining_room", "living_room", "kitchen"]], # A: adjacency 88.3, aspect 90+, size 84+ [["bedroom_02", "external_staircase", "common_bathroom", "bedroom_01"], ["balcony", "living_room", "pooja_room", "master_bedroom"], ["dining_room", "kitchen", "utility_area", "attached_bathroom"]], [["bedroom_02", "external_staircase", "attached_bathroom", "bedroom_01"], ["balcony", "living_room", "pooja_room", "master_bedroom"], ["dining_room", "kitchen", "utility_area", "common_bathroom"]], [["bedroom_01", "external_staircase", "attached_bathroom", "bedroom_02"], ["balcony", "living_room", "pooja_room", "master_bedroom"], ["dining_room", "kitchen", "utility_area", "common_bathroom"]], [["bedroom_01", "external_staircase", "common_bathroom", "bedroom_02"], ["balcony", "living_room", "pooja_room", "master_bedroom"], ["dining_room", "kitchen", "utility_area", "attached_bathroom"]], ], "2bhk": [ # V: vastu plain 81.8 / weighted 64.5, aspect 88, size 80 [["balcony", "master_bedroom", "external_staircase", "attached_bathroom", "utility_area"], ["common_bathroom", "dining_room", "bedroom_01"], ["living_room", "kitchen", "pooja_room"]], [["balcony", "master_bedroom", "external_staircase", "common_bathroom", "utility_area"], ["attached_bathroom", "dining_room", "bedroom_01"], ["living_room", "kitchen", "pooja_room"]], [["balcony", "master_bedroom", "external_staircase", "attached_bathroom", "utility_area"], ["common_bathroom", "dining_room", "bedroom_01"], ["pooja_room", "living_room", "kitchen"]], [["balcony", "master_bedroom", "external_staircase", "utility_area", "attached_bathroom"], ["common_bathroom", "dining_room", "bedroom_01"], ["living_room", "kitchen", "pooja_room"]], # A: adjacency 84.2 (vastu plain 81.8 too), aspect 83+, size 85+ [["balcony", "master_bedroom", "attached_bathroom", "external_staircase"], ["bedroom_01", "living_room"], ["common_bathroom", "utility_area", "kitchen", "dining_room", "pooja_room"]], [["balcony", "master_bedroom", "common_bathroom", "external_staircase"], ["bedroom_01", "living_room"], ["attached_bathroom", "utility_area", "kitchen", "dining_room", "pooja_room"]], [["balcony", "master_bedroom", "attached_bathroom", "external_staircase"], ["bedroom_01", "living_room"], ["pooja_room", "common_bathroom", "utility_area", "kitchen", "dining_room"]], [["balcony", "master_bedroom", "attached_bathroom", "external_staircase"], ["bedroom_01", "living_room"], ["common_bathroom", "utility_area", "pooja_room", "kitchen", "dining_room"]], ], "4bhk": [ # V: vastu plain 86.7 / weighted 74.0, aspect 90, size 81+ [["master_bedroom", "bedroom_01", "utility_area", "bedroom_03", "attached_bathroom_02", "attached_bathroom"], ["common_bathroom", "bedroom_02", "dining_room", "living_room"], ["pooja_room", "balcony", "kitchen", "external_staircase", "study"]], [["master_bedroom", "bedroom_01", "utility_area", "attached_bathroom", "bedroom_03", "attached_bathroom_02"], ["common_bathroom", "bedroom_02", "dining_room", "living_room"], ["pooja_room", "balcony", "kitchen", "external_staircase", "study"]], [["master_bedroom", "bedroom_01", "utility_area", "attached_bathroom", "bedroom_03", "attached_bathroom_02"], ["common_bathroom", "bedroom_02", "dining_room", "living_room"], ["pooja_room", "balcony", "kitchen", "study", "external_staircase"]], [["master_bedroom", "bedroom_01", "utility_area", "attached_bathroom_02", "attached_bathroom", "bedroom_03"], ["common_bathroom", "bedroom_02", "dining_room", "living_room"], ["pooja_room", "balcony", "kitchen", "external_staircase", "study"]], # A: adjacency 78.3 (structural best under the gates), aspect 90+ [["balcony", "common_bathroom", "bedroom_02", "living_room", "utility_area"], ["kitchen", "dining_room", "external_staircase", "pooja_room"], ["attached_bathroom_02", "bedroom_03", "master_bedroom", "attached_bathroom", "bedroom_01", "study"]], [["balcony", "common_bathroom", "bedroom_02", "living_room", "utility_area"], ["kitchen", "pooja_room", "external_staircase", "dining_room"], ["attached_bathroom_02", "bedroom_03", "master_bedroom", "attached_bathroom", "bedroom_01", "study"]], [["balcony", "common_bathroom", "bedroom_02", "utility_area", "living_room"], ["kitchen", "dining_room", "external_staircase", "pooja_room"], ["attached_bathroom_02", "bedroom_03", "master_bedroom", "attached_bathroom", "bedroom_01", "study"]], [["balcony", "common_bathroom", "bedroom_02", "living_room", "utility_area"], ["kitchen", "dining_room", "pooja_room", "external_staircase"], ["attached_bathroom_02", "bedroom_03", "master_bedroom", "attached_bathroom", "bedroom_01", "study"]], ], } # a 1BHK is small enough that the classic blueprints already satisfy the # targets; reuse the 2bhk engineered set minus the absent rooms _ENGINEERED["1bhk"] = _ENGINEERED["2bhk"] # the first four entries of every set are the V-family (vastu-optimised, # NEVER mirrored — mirroring swaps east/west and destroys the zones); the # rest are the A-family (adjacency-optimised, mirror-safe since adjacency # is symmetric) _N_VASTU_VARIANTS = 4 def _engineered_columns(bhk_tag, present): """Yields (columns, mirror_ok) for the engineered pinned blueprints.""" out = [] for i, cols in enumerate(_ENGINEERED.get(bhk_tag, ())): out.append((copy.deepcopy(cols), i >= _N_VASTU_VARIANTS)) return out def _render_spec(spec, needed, ix0, iy0, iw, ih, rng, mirror=False, pinned=False): """Take one abstract column spec (proposer or backbone blueprint) all the way to a sized, tiled, polished box list. This is the SHARED geometry engine, so both sources are sized and cleaned identically. `pinned` marks an ENGINEERED blueprint whose room-to-column assignment and in-column order were designed against the finalised scoring — the passes that shuffle rooms around are skipped so the design survives; the sizing, tiling and repair passes still run in full.""" spec = copy.deepcopy(spec) if not pinned: # engineered blueprints may carry a deliberate connector corridor; # proposer corridors are depth sinks and get stripped spec = _strip_corridors(spec) spec = _insert_missing(spec, needed) spec = _fix_staircase(spec, iw) if not pinned: spec = _set_column_count(spec, iw, ih) spec = _balance_columns(spec, ih) spec = _fix_stair_column_mix(spec) # NOTE: _fill_stair_column (area-rebalance of the stair column) was tried # here for short plots, but it wrecks the proven tall-plot arrangements — # slot balancing + the depth floors handle both acceptably. spec = _cap_pooja(spec) spec = _assign_column_widths(spec, iw, ih) if not pinned: spec = _improve_order(spec, ix0, iy0, iw, ih, rng) spec = _group_services(spec) boxes = _spec_to_boxes(spec, ix0, iy0, iw, ih) boxes = _pair_thin_rooms(boxes, iw, ih, iy0) boxes = _split_wide_service(boxes) boxes = _pair_pooja(boxes, iw, ih, iy0) boxes = _cap_services(boxes) boxes = _cap_pooja_box(boxes) boxes = _reorder_pooja_column(boxes) boxes = _reorder_wet_columns(boxes, iw, ih, iy0) boxes = _label_fixes(boxes) # bath<->bath label swap only: every candidate is a wet cell, so the wet # footprint (and hence the pooja-wet rule) is unchanged by this repair boxes = _fix_attached_baths(boxes) boxes = _cap_public_hierarchy(boxes) boxes = _cap_pooja_box(boxes) # re-cap after any pooja label swap boxes = _niche_pooja(boxes, iw, ih, iy0) if mirror: boxes = _mirror_x(boxes, ix0, iw) return boxes def generate_population(bhk_tag: str, required, optional, plot_w: float, plot_h: float, road_side: str, n: int = 20, raw_jitter: float = 1.4, base_seed: int = 0) -> Optional[List[Tuple]]: """HYBRID generator. A deterministic architect-correct BACKBONE guarantees a floor of good plans on any plot; the model adds variety ON TOP when a key is present. Both go through the same geometry engine and the same scorer, so the best plans (from either source) rank first. Returns [(raw_fp, optimised_fp), ...] best-first, or None only if nothing renders.""" # Build in a road-south frame; rotate to the real road side at the end. layout_w = plot_h if road_side in ("E", "W") else plot_w layout_h = plot_w if road_side in ("E", "W") else plot_h ix0 = SETBACK_OTHER iy0 = SETBACK_ROAD iw = layout_w - 2 * SETBACK_OTHER ih = layout_h - SETBACK_ROAD - SETBACK_OTHER all_rooms = list(dict.fromkeys(list(required) + list(optional))) needed = [r for r in all_rooms if r != "study"] # ── Tier 1: deterministic backbone (always available) ────────────────── # entries are (source, spec, pinned, mirror_ok); pinned = engineered # against the finalised scoring, so the room-shuffling passes leave it # alone; mirror_ok = False for vastu plans (mirroring swaps east/west) pool = [("bb", s, pinned, mirror_ok) for s, pinned, mirror_ok in _backbone_specs(bhk_tag, required, optional)] # ── Tier 2: model variety (only when a key exists) ───────────────────── if available(): ck = (bhk_tag, round(plot_w, 1), round(plot_h, 1), road_side, tuple(sorted(all_rooms)), n) model_specs = _SPEC_CACHE.get(ck) if model_specs is None: model_specs = _propose(required, optional, iw, ih, n) if model_specs: _SPEC_CACHE[ck] = model_specs # cache success only if model_specs: print(f"[layout_engine] {bhk_tag}: model {len(model_specs)} + " f"backbone {len(pool)} layouts") pool += [("ai", s, False, True) for s in model_specs] else: print(f"[layout_engine] {bhk_tag}: model unavailable, " f"backbone {len(pool)} layouts") else: print(f"[layout_engine] {bhk_tag}: no API key, " f"backbone {len(pool)} layouts") if not pool: return None # ── render every spec, mirror-fill for uniqueness, score, rank ───────── plans = [] seen_sigs = set() def _sig(bs): return tuple(sorted((b["name"], round(b["x"]), round(b["y"])) for b in bs)) def _hard_ok(boxes): """Invariants that NO plan may ever violate, even a gate-filler: each attached bath shares a wall with its own bedroom, and there are no overlaps. A plan that fails these is dropped outright.""" idx = {} for b in boxes: idx.setdefault(b["name"], []).append(b) for bed_nm, bath_nm in ATTACHED_OF.items(): bed = idx.get(bed_nm, [None])[0] bath = idx.get(bath_nm, [None])[0] if bed is not None and bath is not None \ and not _adjacent(bed, bath): return False return True def _gate_aspect_ok(fp): """Generation's OWN aspect gate, intentionally decoupled from the displayed aspect metric. It keeps the historical "a room up to 1.8:1 is fine, tapering to zero at 3.0:1" curve so the SAME plans keep passing even though the shown aspect score was re-based to penalise from a perfect square. Do NOT swap this for metrics.aspect_ratio_score -- that would silently change which plans generate.""" from . import metrics as _m exempt = _m._ASPECT_EXEMPT vals = [] for r in fp.rooms: if r.name in exempt: continue lo, hi = min(r.w, r.h), max(r.w, r.h) if lo <= 0: continue asp = hi / lo vals.append(1.0 if asp <= 1.8 else max(0.0, min(1.0, (3.0 - asp) / 1.2))) return (sum(vals) / len(vals)) >= 0.795 if vals else True def _passes_gates(boxes): """The client's PREFERRED all-plan gates: room-size accuracy and aspect ratio both >= 80. Gate-passers fill the top slots; the rest are still shown (best-first) rather than falling to ugly templates.""" from . import metrics as _m fp = FloorPlan([Room(b["name"], b["x"], b["y"], b["w"], b["h"]) for b in boxes], layout_w, layout_h) if not _gate_aspect_ok(fp): return False return _m.room_size_accuracy(fp, "S")[0] >= 0.795 # Two buckets: plans that pass the mandatory gates (room-size + aspect # >= 80) and the rest. Passing plans always fill the top slots; if fewer # than n pass (a short / rotated frame where the geometry can't satisfy # every gate), we STILL fill up to n with the best remaining plans rather # than return short and let the caller fall back to the ugly templates. passing, failing = [], [] for j in range(3 * max(n, len(pool))): if len(passing) >= max(n, 1) and j >= len(pool): break source, base, pinned, mirror_ok = pool[j % len(pool)] rng = random.Random(base_seed + j * 977 + 13) # reuse alternates a mirror — never on a vastu-pinned blueprint # (mirroring swaps east and west, destroying its zones) mirror = (j // len(pool)) % 2 == 1 and mirror_ok boxes = _render_spec(base, needed, ix0, iy0, iw, ih, rng, mirror, pinned) if _sig(boxes) in seen_sigs and mirror_ok: boxes = _mirror_x(boxes, ix0, iw) if _sig(boxes) in seen_sigs: continue # a true duplicate — skip if not _hard_ok(boxes): continue # detached bath / overlap — drop seen_sigs.add(_sig(boxes)) pen = _violations(boxes, iw, ih, iy0) opt = _rotate(boxes, plot_w, plot_h, road_side) raw = _rotate( _jitter(boxes, ix0, iy0, ix0 + iw, iy0 + ih, raw_jitter, rng), plot_w, plot_h, road_side) entry = (pen, j, source, j % len(pool), raw, opt) (passing if _passes_gates(boxes) else failing).append(entry) passing.sort(key=lambda p: (p[0], p[1])) # engine score first failing.sort(key=lambda p: (p[0], p[1])) # tier flag travels with each entry: 0 = passes the gates, 1 = filler chosen = [(0, e) for e in passing] + [(1, e) for e in failing] chosen = chosen[:max(n, 1)] # passing lead, fill the rest pairs = [] for tier, (pen, _j, source, si, raw, opt) in chosen: name = f"{bhk_tag}_{source}_{si}" raw_fp = FloorPlan([Room(b["name"], round(b["x"], 2), round(b["y"], 2), round(b["w"], 2), round(b["h"], 2)) for b in raw], plot_w, plot_h) opt_fp = FloorPlan([Room(b["name"], round(b["x"], 2), round(b["y"], 2), round(b["w"], 2), round(b["h"], 2)) for b in opt], plot_w, plot_h) raw_fp.template_name = opt_fp.template_name = name pairs.append((tier, raw_fp, opt_fp)) # FINAL ordering: gate-passers ALWAYS rank above fillers; within each tier # the client's finalised fitness decides the order, so rank 1 is the best # gate-passing plan under the official scoring system. try: from . import metrics as _metrics scored = sorted( ((tier, -_metrics.evaluate(o, road_side).fitness, i) for i, (tier, _r, o) in enumerate(pairs)), key=lambda t: (t[0], t[1], t[2])) pairs = [(pairs[i][1], pairs[i][2]) for _t, _f, i in scored] except Exception as exc: # pragma: no cover print(f"[layout_engine] fitness ordering skipped: {exc}") pairs = [(r, o) for _t, r, o in pairs] return pairs