# AI Vastu Floor Plan Generator — Model Architecture --- ## Table of Contents 1. [System Overview](#1-system-overview) 2. [Full Data Flow](#2-full-data-flow) 3. [Synthetic Data — Templates](#3-synthetic-data--templates) 4. [AI Model — Graph VAE](#4-ai-model--graph-vae) 5. [AI Model — Geometry Predictor](#5-ai-model--geometry-predictor) 6. [Post-Processing Pipeline](#6-post-processing-pipeline) 7. [Optimisation Model](#7-optimisation-model) 8. [Interactive Editor](#8-interactive-editor) 9. [User Management / Session Layer](#9-user-management--session-layer) 10. [Summary Table](#10-summary-table) --- ## 1. System Overview The system is a **Graph Neural Network + Rule-based Optimisation** pipeline that generates Vastu-compliant residential floor plans. It takes a user's plot dimensions and room preferences as input, generates multiple candidate floor plans using trained AI models, scores them against Vastu and architectural objectives, and lets the user fine-tune the best plan via an interactive drag-and-drop editor. **Three-stage pipeline:** ``` Stage 1 — GENERATE Synthetic templates + Graph VAE + Geometry Predictor Stage 2 — OPTIMISE Multi-objective scoring function ranks N candidate plans Stage 3 — EDIT User fine-tunes the optimised plan in an interactive canvas ``` --- ## 2. Full Data Flow ``` ┌─────────────────────────────────────────────────────┐ │ USER (Streamlit UI) │ │ Plot size · Road side · BHK type · Room checklist │ │ Vastu rules · Objective weights │ └──────────────────────────┬──────────────────────────┘ │ ▼ ┌─────────────────────────────────────────────────────┐ │ SYNTHETIC DATA GENERATOR │ │ pdf_templates.py / pdf_templates_2bhk.py │ │ pdf_templates_3bhk.py │ │ │ │ 3 layout variants × plot size × road side │ │ → N candidate raw floor plans │ └──────────────────────────┬──────────────────────────┘ │ room_names[], plot_w, plot_h ▼ ┌─────────────────────────────────────────────────────┐ │ AI GENERATION STAGE │ │ │ │ ┌──────────────────┐ ┌────────────────────────┐ │ │ │ GRAPH VAE │ │ GEOMETRY PREDICTOR │ │ │ │ graph_vae.pth │ │ geometry_predictor.pth│ │ │ │ │ │ │ │ │ │ z ~ N(0,1) │ │ GCN(4 layers) │ │ │ │ → room types │───▶│ → (cx, cy, w, h) │ │ │ │ → adjacency │ │ per room │ │ │ └──────────────────┘ └────────────────────────┘ │ └──────────────────────────┬──────────────────────────┘ │ raw boxes [{name,x,y,w,h}] ▼ ┌─────────────────────────────────────────────────────┐ │ POST-PROCESSING PIPELINE │ │ ml_pipeline.py │ │ │ │ 1. Force-directed repair (push/pull rooms) │ │ 2. Squarify treemap (100% space fill) │ │ 3. Hard constraint passes (staircase, pooja, │ │ bad adjacency, foyer-kitchen, corridor) │ │ 4. Gap fill + overlap resolve │ └──────────────────────────┬──────────────────────────┘ │ clean FloorPlan objects ▼ ┌─────────────────────────────────────────────────────┐ │ OPTIMISATION MODEL │ │ generator.py │ │ │ │ 6 objectives scored per plan: │ │ VS · AQ · CS · SU · AC · LC │ │ Weighted fitness → plans ranked │ │ Top N plans returned │ └──────────────────────────┬──────────────────────────┘ │ ranked plan pairs ▼ ┌─────────────────────────────────────────────────────┐ │ INTERACTIVE EDITOR │ │ floorplan_editor (Canvas JS) │ │ │ │ User drags / resizes / deletes rooms │ │ Constraints enforced in real-time │ │ Apply → re-score → update metrics │ └─────────────────────────────────────────────────────┘ ``` --- ## 3. Synthetic Data — Templates **Files:** `core/pdf_templates.py`, `core/pdf_templates_2bhk.py`, `core/pdf_templates_3bhk.py` Since no labelled building dataset is available, templates serve as the **synthetic data source**. They are parameterized architectural layout generators derived from standard room guide tables. ### What they produce Each template generates a **perimeter-ring layout** — rooms are placed on four wall strips (South road strip, West strip, North strip, East strip) around a central corridor. Room sizes are sampled from guide-table ranges with ±18% flexibility to produce diversity. ### 3 Structural Variants (3BHK example) | Variant | Corridor | Living position | Kitchen position | |---|---|---|---| | 0 — Living next to Foyer | Vertical (N–S) | South strip (road side) | East column | | 1 — Horizontal Corridor | Horizontal (E–W) | South strip | East column | | 2 — Public North | Vertical (N–S) | North strip | East column (SE) | All 3 variants satisfy the same Vastu zone rules — kitchen SE, master bed SW, pooja NE — but differ in the circulation spine position, which produces structurally different plans. ### Vastu Quadrant Mapping ``` NW ┌─────────┬─────────┐ NE │Bathroom │ Pooja │ │Utility │ Living │ │Bed 2/3 │ Balcony │ ├─────────┼─────────┤ │ Master │ Kitchen │ │ Bed │ Dining │ │Staircase│ Utility │ SW └─────────┴─────────┘ SE ``` Each plan passes through the same AI + optimisation pipeline after generation, so the output quality is consistent regardless of which template variant was used. --- ## 4. AI Model — Graph VAE **File:** `core/ml_models.py` → class `GraphVAE` **Weights:** `models/graph_vae.pth` ### Purpose Learns the **latent distribution of valid room connectivity graphs** from synthetic floor plan data. At inference, samples from this distribution to generate novel room topology (which rooms exist and which are adjacent). ### Architecture ``` Input X : N × C (N = room count, C = number of room classes, one-hot) A : N × N (adjacency matrix) ENCODER GCNLayer 1 : (C → 128) H = ReLU( D^-0.5 · Â · D^-0.5 · XW ) GCNLayer 2 : (128 → 256) GCNLayer 3 : (256 → 128) Linear μ : (128 → 16) mean of latent distribution Linear σ : (128 → 16) log-variance of latent distribution REPARAMETERISATION z = μ + exp(0.5 × logVar) × ε, ε ~ N(0, I) DECODER node_logits = Linear(16 → 128 → 256 → C) room type per node edge_logits = z @ z.T edge existence per pair OUTPUT node_probs : N × C (softmax → room type probabilities) edge_probs : N × N (sigmoid → adjacency probabilities) Training Loss L = BCE(node_logits, true_nodes) + BCE(edge_logits, true_edges) + KL( N(μ,σ²) || N(0,1) ) ``` ### Inference Procedure ``` 1. Sample z ~ N(0, I) with shape (target_rooms × 3, 16) 2. Decode → node probabilities for each of 3× oversampled nodes 3. Force 4 critical rooms (living, kitchen, master bed, common bath) 4. Greedily fill remaining slots, respecting per-class caps 5. Re-sample z for the exact N chosen rooms 6. Decode edges → threshold at 0.55 → adjacency matrix 7. Overlay hard-coded critical edges (staircase–foyer, foyer–living, etc.) Output: room_names[], adj_matrix[N×N] ``` --- ## 5. AI Model — Geometry Predictor **File:** `core/ml_models.py` → class `GeometryPredictor` **Weights:** `models/geometry_predictor.pth` ### Purpose Given the room topology from the Graph VAE, predicts the **initial bounding box** (position + size) for each room. Outputs are in normalised [0,1] space, scaled to the actual plot at inference. ### Architecture ``` Input X : N × C (same one-hot room features as VAE) A : N × N (adjacency matrix from VAE output) 4 GCN LAYERS GCNLayer 1 : (C → 128) GCNLayer 2 : (128 → 256) GCNLayer 3 : (256 → 256) GCNLayer 4 : (256 → 128) MLP HEAD (per node) Linear(128 → 128) → ReLU Linear(128 → 64) → ReLU Linear(64 → 4) → Sigmoid Output per room: (cx, cy, w, h) all in [0, 1] Training Loss: MSE on normalised (cx, cy, w, h) Training data: synthetic (room_graph, bounding_box) pairs from templates ``` ### Inference Scaling ``` raw_w = max(min_width[room], predicted_w × plot_w × 0.7) raw_h = max(min_height[room], predicted_h × plot_h × 0.6) raw_x = cx × plot_w - raw_w / 2 (clamped to plot boundary) raw_y = cy × plot_h - raw_h / 2 ``` --- ## 6. Post-Processing Pipeline **File:** `core/ml_pipeline.py` The Geometry Predictor produces a valid topology but rooms overlap and may violate Vastu zones. The pipeline repairs this deterministically in 4 phases. ### Phase 1 — Force-Directed Repair (600 iterations) ``` Every iteration: For each overlapping pair (i, j): Compute overlap on x and y axis Push apart along the smaller overlap axis Clamp both rooms inside plot boundary Every 5 iterations: For each adjacent pair in the graph: If centres are too far apart → nudge both toward each other (step 0.3 ft) Every 30 iterations (if still overlapping): Shrink all rooms by 5% (preserving minimums) to break deadlocks ``` ### Phase 2 — Squarify Treemap (100% Fill) ``` 1. Compute target area per room proportional to AI predictions 2. Group rooms into 4 Vastu quadrants (SW, SE, NW, NE) 3. Split inner buildable rectangle 50/50 → 4 quadrant sub-rectangles 4. If a quadrant is empty → merge its area into the largest neighbour 5. Rescale each quadrant's rooms to exactly fill their rectangle 6. Run squarified treemap algorithm per quadrant → always-square-ish rooms, no gaps, no overlaps ``` ### Phase 3 — Hard Constraint Passes (in order) | Pass | Function | What it enforces | |---|---|---| | 1 | `_pin_staircase_to_corner` | Staircase on a plot edge (SW preferred) | | 2 | `_pin_entry_rooms_to_road` | Staircase + foyer on road-facing edge | | 3 | `_separate_bad_adjacencies` | kitchen≠foyer, pooja≠bathroom/utility, kitchen≠bathroom | | 4 | `_force_break_foyer_kitchen_wall` | Last-resort foyer trim if swap couldn't separate | | 5 | `_cap_utility_area` | Utility never larger than 85% of kitchen area | | 6 | `_enforce_room_shape_limits` | Aspect ratio ≤ 1.618 (golden ratio); max area from guide | | 7 | `_clamp_compact_rooms` | Service rooms (bath, utility, foyer) within guide ranges | | 8 | `_enforce_staircase_size` | Staircase long axis 14–18 ft | | 9 | `_enforce_pooja_square` | Pooja snapped to nearest valid square: 4×4…8×8 ft | | 10 | `detect_corridors` | Flood-fill empty interior → mark as `internal_corridor` | | 11 | `_trim_corridor_to_rooms` | Corridor ends only where rooms touch its sides | | 12 | `_fill_gaps` | Expand rooms to eliminate voids (priority: living > dining > bedrooms > service) | ### Phase 4 — Final Overlap Resolve ``` Up to 80 passes: For each remaining overlapping pair: Compute overlap on x and y axis Find the smallest-area cut (box, axis, amount) that removes the overlap Apply the cut (retreat one edge), keep room ≥ 2 ft in that direction Stop when zero overlaps remain ``` --- ## 7. Optimisation Model **File:** `core/generator.py` → `_score_one()`, `rank_plans()` Not a neural network. A **weighted multi-objective scoring function** that evaluates each candidate plan and ranks them by overall fitness. ### Six Objective Scores #### VS — Vastu Score ``` For each room with a Vastu rule: Determine the room's compass zone from its centre position Match zone against rule's good_zones list 3-tier weights: HIGH = 1.0 / MED = 0.5 / LOW = 0.2 Award best matching tier per room VS = Σ(best_tier_credit) / Σ(top_tier_weight) Example rules: Kitchen HIGH → SE MED → S, E Master Bed HIGH → SW MED → S, W Pooja Room HIGH → NE MED → N, E Living Room HIGH → NE MED → N, E Bathroom HIGH → NW MED → N, W ``` #### AQ — Adjacency Quality ``` 4-tier adjacency matrix between every room pair: HIGH → must share a wall weight = +1.0 MED → should be close weight = +0.5 LOW → indirect connection OK weight = +0.2 ZERO → should be separate penalty = -0.5 if sharing a wall FORBIDDEN → must never share a wall penalty = -1.0 if sharing a wall Corridor hub credit: Any two rooms both touching the corridor → treated as 80% adjacent (one doorway away) AQ = max(0, Σ(got × weight) / Σ(total weight) − 0.08 × penalties) ``` #### CS — Cost Score ``` Estimate ₹ construction cost: Base cost = total_area × rate_per_sqft (Standard / Premium / Luxury) Wall cost = total_wall_length × ₹ per metre Plumbing = distance between wet rooms × ₹ per metre run ratio = cost_per_sqft / base_rate CS = 1.0 if ratio ≤ 1.05 CS = 0.0 if ratio ≥ 1.40 CS = interpolated otherwise ``` #### SU — Space Usage ``` SU = total_room_area / plot_area (capped at 1.0) ``` #### AC — Area Compliance ``` For each room: Compute deviation from guide-table target area Penalise proportionally to deviation AC = average(1 − |actual_area − target_area| / target_area) ``` #### LC — Layout Compactness ``` Bounding box of all rooms → compute: isoperimetric_quotient = 4π × bbox_area / perimeter² fill_ratio = total_room_area / bbox_area LC = 0.4 × isoperimetric_quotient + 0.6 × fill_ratio ``` ### Weighted Fitness Function ``` F = w_vs × VS + w_aq × AQ + w_cs × CS + w_su × SU + w_ac × AC + w_lc × LC Default weights (user-adjustable via sidebar): VS = 0.30 Vastu compliance AQ = 0.25 Adjacency quality CS = 0.15 Cost efficiency SU = 0.15 Space usage AC = 0.10 Area compliance LC = 0.05 Layout compactness Sum = 1.00 N plans are scored → sorted by F descending → top plans shown ``` --- ## 8. Interactive Editor **Files:** `floorplan_editor/__init__.py`, `floorplan_editor/frontend/index.html` A custom Streamlit component built on an **HTML5 Canvas** that lets the user fine-tune the AI-optimised plan with enforced architectural constraints. ### Communication Protocol (Streamlit ↔ Canvas) ``` Streamlit → Canvas (streamlit:render) rooms[] : [{name, x, y, w, h}] in feet plot_w : float (ft) plot_h : float (ft) road_side : "S" | "N" | "E" | "W" Canvas → Streamlit (streamlit:setComponentValue) updated rooms[] : [{name, x, y, w, h}] Triggered only on explicit "Apply Changes" click ``` ### Room Interaction Modes | Mode | Rooms | What user can do | |---|---|---| | `free` | Master Bed, Pooja, Kitchen, Attached Bath, Study, Corridor, Utility | Drag to move + drag corner handles to resize | | `size_only` | Balcony | Drag inner-edge handles to resize — road edge stays fixed | | `position_only` | Staircase | Drag body to move — size locked at 12′ × 10′ | | `frozen` | Foyer, Living, Dining, Bedrooms, Common Bath, Lift | No interaction — locked by optimizer | ### Real-Time Constraints (enforced on mouseup) ``` Master Bedroom size rule: master.w × master.h must be > any(bed_01, bed_02, bed_03).area + 1 sq ft Violation → interaction REVERTED instantly, info bar shows reason Staircase size: w and h are clamped to 12 ft × 10 ft during every drag move Setback boundary: All rooms clamped to inner buildable area during drag (road side: 6.56 ft / other sides: 3.28 ft) Snap grid: 0.5 ft ``` ### Validation on Apply ``` Checks run before sending to Streamlit: Zone checks : Master Bed in SW half, Pooja in NE half, Kitchen in SE half Staircase size : auto-corrected to 12×10 if drifted Adjacency : Master Bed ↔ Attached Bath must share wall Living ↔ Staircase must share wall Kitchen ↔ Dining must share wall Pooja adjacent to Living OR Dining Balcony : must remain on road-facing side Overlaps : warning (applies anyway, fitness penalises) Warnings shown in amber. No hard block — user sees the score impact. ``` ### Re-scoring After Edit ``` Streamlit receives updated rooms[] → creates new FloorPlan object → runs _score_one() with same Vastu rules + weights as sidebar → updates top_plans[idx] in session state → st.rerun() → UI refreshes with new scores ``` --- ## 9. User Management / Session Layer There is no multi-user authentication system. This is a single-tenant Streamlit application. User state is managed entirely through `st.session_state` within one browser session. ### Session State Keys | Key | Type | Purpose | |---|---|---| | `app_layout_version` | str | Version tag — if mismatched, clears all plan state to force regeneration | | `last_top_plans` | list | Ranked plan pairs `{raw, optimised, peak}` — persists across reruns | | `last_road_side` | str | Road side used when plans were generated | | `last_plan_type` | str | `"1BHK"` / `"2BHK"` / `"3BHK"` | | `last_edit_{idx}` | list | Last rooms sent from editor for plan tab `idx` — used to prevent rerun loops | ### Lifecycle ``` 1. User opens app → session_state empty → show landing screen 2. User clicks Generate → run pipeline → store plans in session_state 3. User switches tabs → plans loaded from session_state (no re-generation) 4. User edits in canvas → editor sends rooms → Python rescores → stores back 5. User changes plan type → session_state cleared → must regenerate 6. Browser refresh → session_state lost → must regenerate ``` --- ## 10. Summary Table | Component | Technology | File(s) | Purpose | |---|---|---|---| | Streamlit UI | Python / Streamlit | `app.py` | User interface, sidebar config, plan display | | Synthetic Data | Parametric templates (3 variants per BHK) | `core/pdf_templates*.py` | Diverse starting plans — replaces real building dataset | | Graph VAE | 3-layer GCN encoder + linear decoder (latent=16) | `core/ml_models.py`, `models/graph_vae.pth` | Room topology generation | | Geometry Predictor | 4-layer GCN + MLP head (→ cx,cy,w,h) | `core/ml_models.py`, `models/geometry_predictor.pth` | Initial room geometry from topology | | Post-Processing | Force-directed + squarify + 12 constraint passes | `core/ml_pipeline.py` | Repair overlaps, enforce Vastu zones, fill gaps | | Optimisation | Weighted 6-objective scoring function | `core/generator.py` | Rank and select best plans | | Interactive Editor | HTML5 Canvas custom Streamlit component | `floorplan_editor/` | Human fine-tuning with enforced constraints | | Session Layer | `st.session_state` | `app.py` | In-session plan persistence (no database) | --- *Document reflects codebase state as of June 2026.*