File size: 21,417 Bytes
c05974a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
# 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.*