File size: 43,206 Bytes
870b85a
3f15e9f
870b85a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
#!/usr/bin/env python3
"""Convert Graph2Plan / RPLAN records into RoboHome floor plans with rectangular rooms, without the old "exactly six rooms" and
"boxes must not overlap" screening.

The chain models every room as an axis-aligned rectangle. A source room is a rectilinear polygon (`rBoundary`), so each room becomes one of
the maximal rectangles inside its polygon. The rest of a polygon is left empty and counted in `retained_area_fraction`.

Cutting every room down to one rectangle breaks the contacts between rooms (a bedroom that opened onto the hall of an L-shaped living room no
longer touches the living-room rectangle). The conversion therefore works in three steps, always against the rules the chain's topology step
applies (what may carry a door, how long a shared wall has to be, which rooms hold several portals):
1. `_pick_rectangles` hill-climbs over each room's maximal rectangles and over the living/dining options (the living room takes the arm of
   its polygon the other rooms open onto; its left-over becomes the dining room, or the dining room is cut from it);
2. `repair_contacts` grows rectangles into free floor inside the source outline, smallest growth first, until every room reaches the living
   room. Rectangles only grow, so no contact is lost and none overlap;
3. `add_hallway` turns the free hall leg of the living polygon into a `hallway` room when that connects rooms nothing else can reach.
The bigger of the two public rooms is then named the living room. Whatever still cannot reach the living room is refused with the reason named.

  convert_rplan.py --mat data.mat --out library.json [--limit N] [--seed S] [--min-retained 0.8] [--workers 8]

Room mapping (RPLAN label -> room id / type): 0 living / living_room, 1 master / master_bedroom, 7 second room -> guest / guest_bedroom,
further bedrooms (5 child, 8 guest) and studies (6, only after the real bedrooms) -> bedroom_3.. / guest_bedroom (the id and type the
three-bedroom template in task_scene_setup.py uses), 2 kitchen / kitchen, 3 bath / bathroom, 9 balcony / balcony, 4 dining -> dining /
dining_room. 10 entrance, 11 storage and unknown labels are not represented (their floor stays free). A flat without a second bedroom, or
whose rooms cannot be connected to the living room, is refused with the reason named.
"""
import argparse
import json
import math
import random
import sys
from pathlib import Path

import numpy as np
from shapely import contains_xy
from shapely.geometry import Polygon, box
from shapely.ops import unary_union
from shapely.validation import make_valid

LABEL_NAMES = {0: 'living', 1: 'master', 2: 'kitchen', 3: 'bath', 4: 'dining', 5: 'child', 6: 'study', 7: 'second', 8: 'guest',
               9: 'balcony', 10: 'entrance', 11: 'storage'}
BEDROOM_LABELS = (1, 7, 5, 8, 6)        # preference order for who becomes master / guest / further bedrooms; a study (6) is a bedroom of last resort
TARGET_AREA_M2 = 90.0                   # same uniform scaling as the 25-plan library: target area, longest side at most 14.8 m
MAX_EXTENT_M = 14.8
MIN_SIDE_M = {'balcony': 1.2, 'bath': 1.65, 'hallway': 1.0}    # every other room: 2.0 m (the 24 plans of rplan_production_25 are all above)
DEFAULT_MIN_SIDE_M = 2.0
# Shortest side (metres) a room may have, by profile. The 24 plans of rplan_production_25 have: living >= 3.2, master 2.7, guest 2.8, dining 2.2,
# kitchen 2.1, bath 1.65, balcony 1.05. 'balanced' stays a little under that where the first runs of the chain showed a room is still
# furnishable; 'wide' keeps every room that has any chance, and a third bedroom or a living room under 2.5 m often fails in the chain
# (a bed or a sofa has no pose). The numbers travel with the library (`options.min_side`).
PROFILES = {
    'balanced': {'living': 2.8, 'bedroom': 2.5, 'dining': 2.0, 'kitchen': 1.8, 'bath': 1.5, 'balcony': 1.0, 'default': 1.8},
    'wide': {'living': 1.8, 'bedroom': 1.8, 'dining': 1.8, 'kitchen': 1.6, 'bath': 1.5, 'balcony': 1.0, 'default': 1.8},
}


def min_side_for(limits, room_id):
    """Shortest side allowed for a room: its own entry, else the group entry ('bedroom' for master, guest and bedroom_N), else 'default'."""
    if room_id in limits:
        return limits[room_id]
    if (room_id in ('master', 'guest') or room_id.startswith('bedroom_')) and 'bedroom' in limits:
        return limits['bedroom']
    if room_id.startswith('hallway') and 'hallway' in limits:
        return limits['hallway']
    return limits.get('default', DEFAULT_MIN_SIDE_M)
DINING_MIN_FRACTION = 0.22              # an L-shaped living room gives a dining room when the left-over holds this share of its area
SPLIT_FRACTION = 0.34                   # otherwise the dining room is cut from the living room like in the 25-plan library
# Order of the rooms in a plan. A hallway has to come first: the generator gives a room that has no door yet one door to a public room it
# touches, going through the rooms in this order, and a bedroom that took the hallway as its door before the hallway got its own would leave
# the hallway without a way to the living room.
ROOM_ORDER = ['hallway', 'hallway_2', 'kitchen', 'dining', 'bath', 'master', 'living', 'guest', 'study', 'balcony']
DOOR_CLEAR_M = 1.05                     # a shared wall must be a door wide (the chain cuts a 1.0 m portal) plus a little margin
BALCONY_CLEAR_M = 1.95                  # balcony openings keep 0.45 m beside the 1.0 m portal on both sides
MAX_GROWTH = 2.5                        # a rectangle may grow to at most this multiple of its starting area while contacts are repaired
MAX_ASPECT = 5.0                        # longest side over shortest side of a rectangle (the living room is exempt)
# door pairs the chain's topology step refuses (FORBIDDEN_DOOR_TYPE_PAIRS in rhg_task_contract_generate_v16_1p_procedural_pure.py)
FORBIDDEN_TYPE_PAIRS = {frozenset(p) for p in (('kitchen', 'bathroom'), ('master_bedroom', 'guest_bedroom'), ('bathroom', 'master_bedroom'),
                                               ('bathroom', 'guest_bedroom'))}
BALCONY_OPEN_WITH = ('master_bedroom', 'guest_bedroom', 'living_room')
PUBLIC_TYPES = ('living_room', 'dining_room')
CONNECTOR_TYPES = PUBLIC_TYPES + ('hallway',)     # rooms the other rooms may take their door to
MAX_HALLWAYS = 2
HALLWAY_MIN_AREA_M2 = 1.5
HALLWAY_MIN_SIDE_M = 1.0
MAX_CANDIDATES = 8                      # maximal rectangles of a room polygon that the search may pick from (largest first)


def polygon_of(vertices):
    poly = Polygon([(float(x), float(y)) for x, y in vertices])
    if not poly.is_valid:
        poly = make_valid(poly)
        if poly.geom_type != 'Polygon':
            poly = max((g for g in getattr(poly, 'geoms', []) if g.geom_type == 'Polygon'), key=lambda g: g.area, default=Polygon())
    return poly


def maximal_rectangles(poly, limit=6):
    """Maximal axis-aligned rectangles inside a rectilinear polygon of integer corners (no rectangle inside it can be made bigger), largest
    first. The sides of such a rectangle lie on lines through polygon vertices, so the search runs on the grid those lines cut."""
    parts = [g for g in getattr(poly, 'geoms', [poly]) if g.geom_type == 'Polygon' and not g.is_empty]
    if not parts:
        return []
    xs = sorted({int(round(c[0])) for g in parts for c in g.exterior.coords})
    ys = sorted({int(round(c[1])) for g in parts for c in g.exterior.coords})
    if len(xs) < 2 or len(ys) < 2:
        return []
    gx, gy = np.meshgrid((np.array(xs[:-1]) + np.array(xs[1:])) / 2.0, (np.array(ys[:-1]) + np.array(ys[1:])) / 2.0)
    inside = contains_xy(poly, gx, gy)                  # inside[row, column]: grid cell between consecutive y / x lines
    rows, cols = inside.shape
    found = set()
    for top in range(rows):
        alive = np.ones(cols, dtype=bool)
        for bottom in range(top, rows):
            alive &= inside[bottom]
            if not alive.any():
                break
            left = 0
            while left < cols:
                if not alive[left]:
                    left += 1
                    continue
                right = left
                while right + 1 < cols and alive[right + 1]:
                    right += 1
                if (top == 0 or not inside[top - 1, left:right + 1].all()) and (bottom == rows - 1 or not inside[bottom + 1, left:right + 1].all()):
                    found.add((xs[left], ys[top], xs[right + 1], ys[bottom + 1]))
                left = right + 1
    return sorted(found, key=lambda r: (-(r[2] - r[0]) * (r[3] - r[1]), r))[:limit]


def largest_rectangle(poly):
    """Largest axis-aligned rectangle inside a rectilinear polygon, or None."""
    found = maximal_rectangles(poly, 1)
    return found[0] if found else None


def rooms_from_record(labels, polygons):
    """[(label, polygon)] with the polygons made valid; unknown or empty ones are skipped."""
    out = []
    for label, vertices in zip(labels, polygons):
        poly = polygon_of(vertices)
        if not poly.is_empty and poly.area > 0:
            out.append((int(label), poly))
    return out


def assign_ids(rooms):
    """Give every represented room an id and type. Returns ([(id, type, polygon, label)], notes)."""
    notes, out = [], []
    by_label = {}
    for label, poly in rooms:
        by_label.setdefault(label, []).append(poly)
    for polys in by_label.values():
        polys.sort(key=lambda p: -p.area)
    singles = {0: ('living', 'living_room'), 2: ('kitchen', 'kitchen'), 3: ('bath', 'bathroom'), 9: ('balcony', 'balcony'), 4: ('dining', 'dining_room')}
    for label, (rid, rtype) in singles.items():
        for i, poly in enumerate(by_label.get(label, [])):
            if i == 0:
                out.append((rid, rtype, poly, label))
            else:
                notes.append('extra_%s_dropped' % LABEL_NAMES[label])
    bedrooms = [(label, poly) for label in BEDROOM_LABELS for poly in by_label.get(label, [])]
    if bedrooms:
        # master is the label-1 room when there is one, otherwise the biggest bedroom; the next biggest is the guest bedroom
        master_index = next((i for i, (l, _) in enumerate(bedrooms) if l == 1), None)
        if master_index is None:
            master_index = max(range(len(bedrooms)), key=lambda i: bedrooms[i][1].area)
        master = bedrooms[master_index]
        rest = sorted((lp for i, lp in enumerate(bedrooms) if i != master_index), key=lambda lp: (lp[0] == 6, -lp[1].area))
        out.append(('master', 'master_bedroom', master[1], master[0]))
        # further bedrooms follow the three-bedroom template in task_scene_setup.py: id bedroom_N, type guest_bedroom
        for index, (label, poly) in enumerate(rest):
            out.append(('guest' if index == 0 else 'bedroom_%d' % (index + 2), 'guest_bedroom', poly, label))
        if any(label == 6 for label, _ in bedrooms):
            notes.append('study_used_as_bedroom')
    for label in (10, 11):
        if by_label.get(label):
            notes.append('%s_not_represented' % LABEL_NAMES[label])
    unknown = sorted(set(by_label) - set(LABEL_NAMES))
    if unknown:
        notes.append('unknown_labels_not_represented_%s' % '_'.join(str(u) for u in unknown))
    return out, notes


def contact_overlap(a, b):
    """Length of the wall two touching rectangles share (0 when they do not touch along an edge)."""
    along_y = min(a[3], b[3]) - max(a[1], b[1]) if (a[2] == b[0] or b[2] == a[0]) else 0
    along_x = min(a[2], b[2]) - max(a[0], b[0]) if (a[3] == b[1] or b[3] == a[1]) else 0
    return max(0, along_y, along_x)


def edge_need(type_a, type_b, door_px, balcony_px, strict=True):
    """Shared wall (pixels) a pair of room types needs to be connected the way the chain connects them, or None when the chain would not.
    Public rooms and the kitchen open onto each other; a bedroom or bathroom gets its one main door to a public room (or hallway) it touches; a balcony
    opens onto a bedroom or the living room (the portal keeps clearance beside it) or gets a door to the dining room. Contacts between two
    private or service rooms are not counted when `strict`: a room without a public neighbour is given a door to such a room only as a last
    resort, and that door does not lead anywhere unless the other room is connected on its own. Without `strict` such contacts count."""
    pair = {type_a, type_b}
    if frozenset(pair) in FORBIDDEN_TYPE_PAIRS:
        return None
    if 'balcony' in pair:
        other = type_b if type_a == 'balcony' else type_a
        if other in BALCONY_OPEN_WITH:
            return balcony_px
        return door_px if other == 'dining_room' else None
    return door_px if (pair & set(CONNECTOR_TYPES) or not strict) else None


def leads_on(type_a, type_b, strict=True):
    """True when a room of type_a that has been reached passes the connection on to a room of type_b. The living room, the dining room and a
    hallway are hubs: every other room takes its door to one of them (a hallway gets its own door to a public room). The kitchen is open to the living and
    the dining room, so it joins those two but nothing else. A bedroom or bathroom has one door, so it is a dead end; only a balcony opens
    onto a bedroom. Without `strict` every contact leads on."""
    if not strict or type_a in CONNECTOR_TYPES:
        return True
    return type_b in PUBLIC_TYPES if type_a == 'kitchen' else type_b == 'balcony'


def reachable_rooms(geo, types, door_px, balcony_px, start='living', strict=True):
    """Rooms the living room reaches through contacts that are long enough and that the chain turns into a connection (see edge_need)."""
    seen, stack = {start}, [start]
    while stack:
        a = stack.pop()
        for b in geo:
            if b in seen or not leads_on(types[a], types[b], strict):
                continue
            need = edge_need(types[a], types[b], door_px, balcony_px, strict)
            if need is not None and contact_overlap(geo[a], geo[b]) >= need:
                seen.add(b)
                stack.append(b)
    return seen


def footprint_cells(polygons):
    """Boolean raster [y, x] of the cells (unit squares of the source pixel grid) that lie inside any source room polygon."""
    width = int(math.ceil(max(p.bounds[2] for p in polygons)))
    height = int(math.ceil(max(p.bounds[3] for p in polygons)))
    foot = np.zeros((height, width), dtype=bool)
    for poly in polygons:
        x0, y0 = int(math.floor(poly.bounds[0])), int(math.floor(poly.bounds[1]))
        x1, y1 = int(math.ceil(poly.bounds[2])), int(math.ceil(poly.bounds[3]))
        xs, ys = np.meshgrid(np.arange(x0, x1) + 0.5, np.arange(y0, y1) + 0.5)
        foot[y0:y1, x0:x1] |= contains_xy(poly, xs, ys)
    return foot


def _run(rect, side, free, limit):
    """How many cells in a row the rectangle can grow towards `side` over free floor."""
    x0, y0, x1, y1 = rect
    height, width = free.shape
    k = 0
    while k < limit:
        if side == 'E':
            ok = x1 + k < width and free[y0:y1, x1 + k].all()
        elif side == 'W':
            ok = x0 - k - 1 >= 0 and free[y0:y1, x0 - k - 1].all()
        elif side == 'S':
            ok = y1 + k < height and free[y1 + k, x0:x1].all()
        else:
            ok = y0 - k - 1 >= 0 and free[y0 - k - 1, x0:x1].all()
        if not ok:
            break
        k += 1
    return k


def _grown(rect, side, k):
    x0, y0, x1, y1 = rect
    return {'E': [x0, y0, x1 + k, y1], 'W': [x0 - k, y0, x1, y1], 'S': [x0, y0, x1, y1 + k], 'N': [x0, y0 - k, x1, y1]}[side]


def _best_move(geo, types, free, reached, start_area, door_px, balcony_px, max_growth, strict=True):
    """Cheapest growth (added area, room, side, cells, other room) that joins a stranded room to the living room's group, or None."""
    best = None
    for mover in sorted(geo):
        old_area = (geo[mover][2] - geo[mover][0]) * (geo[mover][3] - geo[mover][1])
        for side in 'EWSN':
            for k in range(1, _run(geo[mover], side, free, max(free.shape)) + 1):
                grown = _grown(geo[mover], side, k)
                new_area = (grown[2] - grown[0]) * (grown[3] - grown[1])
                if new_area > max_growth * start_area[mover] or (best is not None and new_area - old_area >= best[0]):
                    break
                for other in sorted(geo):
                    if other == mover or (other in reached) == (mover in reached):
                        continue            # only a contact between the living room's group and a stranded room helps
                    inside, outside = (mover, other) if mover in reached else (other, mover)
                    if not leads_on(types[inside], types[outside], strict):
                        continue            # ... and only when the room on the connected side can pass the connection on
                    need = edge_need(types[mover], types[other], door_px, balcony_px, strict)
                    if need is not None and contact_overlap(grown, geo[other]) >= need:
                        best = (new_area - old_area, mover, side, k, other)
                        break
                else:
                    continue
                break                       # growing further in this direction would only cost more
    return best


def repair_contacts(geo, types, foot, door_px, balcony_px, max_growth=MAX_GROWTH, start_area=None, strict=True):
    """Grow rectangles over free floor until every room reaches the living room, or no growth helps.

    geo: {room id: [x0, y0, x1, y1]} in source pixels (integers), changed in place; types: {room id: chain room type};
    foot: footprint raster from footprint_cells; start_area: the area each room may grow from (default: the current one); strict: see edge_need.
    Returns (moves, ids of the rooms that stay unreachable)."""
    free = foot.copy()
    for x0, y0, x1, y1 in geo.values():
        free[y0:y1, x0:x1] = False
    start_area = start_area or {rid: (r[2] - r[0]) * (r[3] - r[1]) for rid, r in geo.items()}
    moves = []
    for _ in range(4 * len(geo)):
        reached = reachable_rooms(geo, types, door_px, balcony_px, strict=strict)
        if len(reached) == len(geo):
            break
        best = _best_move(geo, types, free, reached, start_area, door_px, balcony_px, max_growth, strict)
        if best is None:
            break
        _, mover, side, k, other = best
        geo[mover] = _grown(geo[mover], side, k)
        free[geo[mover][1]:geo[mover][3], geo[mover][0]:geo[mover][2]] = False
        moves.append('%s_grows_%s_%d_px_to_reach_%s' % (mover, side, k, other))
    return moves, sorted(set(geo) - reachable_rooms(geo, types, door_px, balcony_px, strict=strict))


def add_hallway(geo, types, living_poly, door_px, balcony_px, hall_min_px, hall_min_area_px, strict=True):
    """Give the part of the living polygon that no room uses (the hall leg of an L- or T-shaped living room) to a `hallway` rectangle when
    that connects rooms that otherwise cannot reach the living room. Returns the new room id, or None when no hallway helps.
    The biggest free rectangle that connects the most stranded rooms wins; it has to be reached itself."""
    if sum(1 for t in types.values() if t == 'hallway') >= MAX_HALLWAYS:
        return None
    free = living_poly.difference(unary_union([box(*r) for r in geo.values()]))
    if free.is_empty:
        return None
    before = len(geo) - len(reachable_rooms(geo, types, door_px, balcony_px, strict=strict))
    new_id = 'hallway' if 'hallway' not in geo else 'hallway_2'
    best = None
    for rect in maximal_rectangles(free, MAX_CANDIDATES):
        width, height = rect[2] - rect[0], rect[3] - rect[1]
        if min(width, height) < hall_min_px or width * height < hall_min_area_px:
            continue
        trial, trial_types = dict(geo, **{new_id: list(rect)}), dict(types, **{new_id: 'hallway'})
        after = len(trial) - len(reachable_rooms(trial, trial_types, door_px, balcony_px, strict=strict))
        if after < before and (best is None or (after, -width * height) < best[0]):
            best = ((after, -width * height), list(rect))
    if best is None:
        return None
    geo[new_id], types[new_id] = best[1], 'hallway'
    return new_id


def _estimate_scale(geo, scale_target, max_extent):
    """Metres per pixel that bring the rectangles to the target area, without the longest side passing max_extent."""
    area_px = sum((r[2] - r[0]) * (r[3] - r[1]) for r in geo.values())
    extent = max(max(r[2] for r in geo.values()) - min(r[0] for r in geo.values()), max(r[3] for r in geo.values()) - min(r[1] for r in geo.values()))
    return min(math.sqrt(scale_target / area_px), max_extent / extent)


def _split_options(living, s0, side_limit):
    """Every way to cut a dining room (SPLIT_FRACTION of the width or height) off one side of the living rectangle that leaves both rooms wide
    enough: [(side, dining, rest)]."""
    a, b, c, d = living
    options = []
    for side in ('left', 'right', 'bottom', 'top'):
        if side in ('left', 'right'):
            cut = int(round((c - a) * SPLIT_FRACTION))
            dining, rest = ([a, b, a + cut, d], [a + cut, b, c, d]) if side == 'left' else ([c - cut, b, c, d], [a, b, c - cut, d])
        else:
            cut = int(round((d - b) * SPLIT_FRACTION))
            dining, rest = ([a, b, c, b + cut], [a, b + cut, c, d]) if side == 'bottom' else ([a, d - cut, c, d], [a, b, c, d - cut])
        if all(min(r[2] - r[0], r[3] - r[1]) * s0 >= side_limit(name) - 1e-9 for name, r in (('dining', dining), ('living', rest))):
            options.append((side, dining, rest))
    return options


def _living_options(living_poly, candidates, native_dining, force_split, s0, side_limit):
    """What the living room and its dining room can look like: [(living rectangle, dining rectangle or None, dining source, split side)].
    Each of the largest maximal rectangles of the living polygon can be the living room; the dining room is the biggest rectangle in the
    left-over (when it holds DINING_MIN_FRACTION of the polygon) or a part cut off the living rectangle."""
    options = []
    for rect in candidates:
        rect = [int(v) for v in rect]
        if native_dining:
            options.append((rect, None, 'native', None))
            continue
        if not force_split:
            leftover = living_poly.difference(box(*rect))
            piece = largest_rectangle(leftover) if not leftover.is_empty else None
            if piece is not None and (piece[2] - piece[0]) * (piece[3] - piece[1]) >= DINING_MIN_FRACTION * living_poly.area:
                options.append((rect, [int(round(v)) for v in piece], 'living_leftover_rectangle', None))
        options.extend((rest, dining, 'split_living', side) for side, dining, rest in _split_options(rect, s0, side_limit))
    return options


def _pick_rectangles(candidates, types, living_options, s0, side_limit, door_px, balcony_px, strict=True):
    """Choose each room's rectangle among its maximal rectangles, and the living/dining option, by hill-climbing on (rooms that cannot reach
    the living room or are too small, then least floor lost). A room whose largest rectangle lost its contacts can take another one, and the
    living room can take the arm of its polygon that the other rooms open onto. Returns (rects, chosen living option)."""
    movable = [rid for rid in candidates if rid != 'living' and len(candidates[rid]) > 1]
    pick, living_pick = {rid: 0 for rid in movable}, 0

    def build(pick, living_pick):
        rects = {rid: list(options[pick.get(rid, 0)]) for rid, options in candidates.items() if rid != 'living'}
        living, dining, _, _ = living_options[living_pick]
        rects['living'] = list(living)
        if dining is not None:
            rects['dining'] = list(dining)
        return rects

    def score(rects):
        reached = reachable_rooms(rects, types, door_px, balcony_px, strict=strict)
        small = sum(1 for rid, r in rects.items() if min(r[2] - r[0], r[3] - r[1]) * s0 < side_limit(rid) - 1e-9)
        # a stranded room may still be reached by growing later; a room that is too small cannot be fixed, so it weighs more
        return len(rects) - len(reached) + 3 * small, -sum((r[2] - r[0]) * (r[3] - r[1]) for r in rects.values())

    best = score(build(pick, living_pick))
    for _ in range(3 * (len(movable) + 1)):
        move = None
        trials = [(None, k, score(build(pick, k))) for k in range(len(living_options)) if k != living_pick]
        trials += [(rid, k, score(build(dict(pick, **{rid: k}), living_pick))) for rid in movable for k in range(len(candidates[rid])) if k != pick[rid]]
        for rid, k, result in trials:
            if result < best and (move is None or result < move[2]):
                move = (rid, k, result)
        if move is None:
            break
        rid, k, best = move
        if rid is None:
            living_pick = k
        else:
            pick[rid] = k
    return build(pick, living_pick), living_options[living_pick]


def convert(record, scale_target=TARGET_AREA_M2, max_extent=MAX_EXTENT_M, min_retained=0.0, force_split=False, min_side=None, extra_bedroom_area=0.0,
            repair=True, max_aspect=MAX_ASPECT, max_growth=MAX_GROWTH, require_guest=True, strict_access=False, drop_balcony=True, candidates_per_room=MAX_CANDIDATES, hallways=True, debug=None, fixed_scale=None, scale_range=None):
    """record: dict(name, rType, rBoundary[list of Nx2]). Returns (plan, None) or (None, reason).
    min_side: {room id: metres} overriding MIN_SIDE_M / DEFAULT_MIN_SIDE_M; extra_bedroom_area: square metres added to the target area for every
    bedroom-like room beyond two; repair: grow rectangles until every room reaches the living room (see repair_contacts);
    fixed_scale: metres per source pixel, the same for every plan (instead of scaling each plan to `scale_target`): a bigger flat in the data
    then stays a bigger flat with its own proportions; scale_range: (low, high) metres per pixel, the scale that gives `scale_target` clamped to that
    range, so a plan is never stretched more than the range allows (no max_extent clamp in this mode);
    require_guest: refuse a flat without a second bedroom; strict_access: refuse a flat in which a bedroom, bathroom or kitchen only reaches the
    living room through another private or service room; drop_balcony: leave out a balcony that cannot be opened onto a bedroom or the living
    room instead of refusing the flat; debug: a dict that is filled with the rectangles of a flat refused for rooms that cannot reach the living
    room."""
    if record.get('corrupt'):
        return None, 'corrupt_record_nan_vertices'
    def scale_of(geo):
        if fixed_scale:
            return fixed_scale
        if scale_range:
            area_px = sum((r[2] - r[0]) * (r[3] - r[1]) for r in geo.values())
            return min(max(math.sqrt(scale_target / area_px), scale_range[0]), scale_range[1])
        return _estimate_scale(geo, scale_target, max_extent)

    labels = list(record['rType'])
    sides = dict(MIN_SIDE_M, **(min_side or {}))
    extra_bedrooms = max(0, sum(1 for k in labels if k in BEDROOM_LABELS) - 2)
    base_target = scale_target
    scale_target = scale_target + extra_bedroom_area * extra_bedrooms
    rooms = rooms_from_record(labels, record['rBoundary'])
    if not rooms:
        return None, 'no_valid_room_polygon'
    named, notes = assign_ids(rooms)
    ids = {rid for rid, *_ in named}
    for need, reason in (('living', 'no_living_room'), ('master', 'no_bedroom'), ('kitchen', 'no_kitchen'), ('bath', 'no_bathroom'),
                         ('guest', 'no_second_bedroom' if require_guest else None)):
        if reason and need not in ids:
            return None, reason
    candidates, types, source_area = {}, {'dining': 'dining_room'}, 0.0
    for rid, rtype, poly, label in named:
        found = [[int(v) for v in r] for r in maximal_rectangles(poly, candidates_per_room)]
        if not found:
            return None, 'no_rectangle_in_%s' % rid
        candidates[rid], types[rid] = found, rtype
        source_area += poly.area

    def side_limit(rid):
        return min_side_for(sides, rid)

    # the living room is one of its polygon's maximal rectangles; an L-shaped one hands its left-over to a dining room, otherwise the dining
    # room is cut from the living rectangle
    s0 = scale_of({rid: c[0] for rid, c in candidates.items()})
    living_poly = next(p for rid, _, p, _ in named if rid == 'living')
    options = _living_options(living_poly, candidates['living'], 'dining' in candidates, force_split, s0, side_limit)
    if not options:
        return None, 'living_room_too_small_to_split'
    foot = footprint_cells([poly for _, poly in rooms]) if repair else None

    def lay_out(strict):
        """Pick each room's rectangle, then grow rectangles until every room reaches the living room: (rects, option, moves, stranded)."""
        if not repair:
            rects = {rid: list(c[0]) for rid, c in candidates.items() if rid != 'living'}
            rects['living'] = list(options[0][0])
            if options[0][1] is not None:
                rects['dining'] = list(options[0][1])
            return rects, options[0], [], []
        rects, option = _pick_rectangles(candidates, types, options, s0, side_limit, int(math.ceil(DOOR_CLEAR_M / s0)),
                                         int(math.ceil(BALCONY_CLEAR_M / s0)), strict)
        types.update({rid: t for rid, t in types.items() if rid in rects})
        start_area = {rid: (r[2] - r[0]) * (r[3] - r[1]) for rid, r in rects.items()}
        moves = []
        for _ in range(MAX_HALLWAYS + 1):
            for _ in range(3):      # growing rooms lowers the metres per pixel, so wall lengths are checked again at the new scale
                s = scale_of(rects)
                door_px, balcony_px = int(math.ceil(DOOR_CLEAR_M / s)), int(math.ceil(BALCONY_CLEAR_M / s))
                more, stranded = repair_contacts(rects, {rid: types[rid] for rid in rects}, foot, door_px, balcony_px, max_growth, start_area, strict)
                moves += more
                if stranded or not more:
                    break
            if not stranded or not hallways:
                break
            # rooms are still stranded: the hall leg of the living polygon may become a hallway that reaches them
            hall = add_hallway(rects, types, living_poly, door_px, balcony_px, int(math.ceil(HALLWAY_MIN_SIDE_M / s)),
                               int(math.ceil(HALLWAY_MIN_AREA_M2 / (s * s))), strict)
            if hall is None:
                break
            start_area[hall] = (rects[hall][2] - rects[hall][0]) * (rects[hall][3] - rects[hall][1])
            moves.append('%s_added_from_the_living_polygon' % hall)
        return rects, option, moves, stranded

    # a bedroom, bathroom or kitchen should touch a public room; a flat that only works when one of them is reached through another private
    # or service room (a contact the chain also accepts, through a last-resort door) is kept but marked `indirect`
    # a balcony that cannot be opened onto a bedroom or the living room is optional in the chain, so it is left out (its floor stays free)
    acceptable = ([], ['balcony']) if drop_balcony else ([],)
    rects, option, moves, stranded = lay_out(True)
    access = 'direct'
    if stranded not in acceptable and repair and not strict_access:
        loose = lay_out(False)
        if loose[3] in acceptable:
            (rects, option, moves, stranded), access = loose, 'indirect'
    if stranded == ['balcony'] and drop_balcony:
        del rects['balcony']
        stranded = []
        notes.append('balcony_dropped_not_reachable')
    types = {rid: t for rid, t in types.items() if rid in rects}
    if stranded:
        if debug is not None:       # lets a caller draw what went wrong
            debug.update(rects={k: list(v) for k, v in rects.items()}, types=dict(types), stranded=stranded, moves=moves,
                         polygons={rid: [list(c) for c in poly.exterior.coords] for rid, _, poly, _ in named})
        return None, 'cannot_reach_living_%s' % types[stranded[0]]
    _, _, dining_source, dining_side = option
    kept_area = sum((r[2] - r[0]) * (r[3] - r[1]) for r in rects.values())
    retained = min(1.0, kept_area / source_area) if source_area else 0.0
    if retained < min_retained:
        return None, 'retained_area_%.2f_below_%.2f' % (retained, min_retained)
    scale = scale_of(rects)       # one uniform scale for the whole plan
    # The bigger of the two public rooms is the living room (sofa group, robot start); the dining room gets the smaller rectangle. They open onto
    # each other, so swapping them keeps the plan connected unless a balcony or hallway depended on which one it touches (checked below).
    area = lambda r: (r[2] - r[0]) * (r[3] - r[1])
    swapped = False
    if 'dining' in rects and dining_source != 'native' and area(rects['dining']) > area(rects['living']):
        trial = dict(rects, living=rects['dining'], dining=rects['living'])
        reached = reachable_rooms(trial, types, int(math.ceil(DOOR_CLEAR_M / scale)), int(math.ceil(BALCONY_CLEAR_M / scale)), strict=(access == 'direct'))
        def shape_ok(rid):      # wide enough, and the dining room (the living room is exempt) not a strip longer than max_aspect times its width
            short, long_ = sorted((trial[rid][2] - trial[rid][0], trial[rid][3] - trial[rid][1]))
            return short * scale >= side_limit(rid) - 1e-9 and (rid == 'living' or long_ <= max_aspect * short)
        if len(reached) == len(trial) and shape_ok('living') and shape_ok('dining'):
            rects, swapped = trial, True
    ox, oy = min(r[0] for r in rects.values()), min(r[1] for r in rects.values())
    # Coordinates are rounded to a centimetre. With millimetres the middle of a shared wall can fall on half a millimetre and the one-metre portal
    # declared around it comes out 1.001 m wide, which the shell builder refuses ("Ordinary openings require a one-metre declared interval").
    plan_rooms = [{'room_id': rid, 'room_type': types[rid], 'bounds_m': [round((r[0] - ox) * scale, 2), round((r[1] - oy) * scale, 2),
                                                                          round((r[2] - ox) * scale, 2), round((r[3] - oy) * scale, 2)]}
                  for rid, r in rects.items()]
    for room in plan_rooms:
        x0, y0, x1, y1 = room['bounds_m']
        short, long_ = min(x1 - x0, y1 - y0), max(x1 - x0, y1 - y0)
        if short < side_limit(room['room_id']) - 1e-9:
            if room['room_id'] == 'dining' and dining_source == 'living_leftover_rectangle' and not force_split:
                # the left-over is too narrow: cut the dining room out of the living room instead
                return convert(record, base_target, max_extent, min_retained, True, min_side, extra_bedroom_area, repair, max_aspect, max_growth, require_guest,
                               strict_access, drop_balcony, candidates_per_room, hallways, debug, fixed_scale, scale_range)
            return None, 'room_too_small_%s' % room['room_id']
        if long_ > max_aspect * short and room['room_id'] != 'living' and not room['room_id'].startswith('hallway'):
            return None, 'room_too_elongated_%s' % room['room_id']
    plan_rooms.sort(key=lambda r: ROOM_ORDER.index(r['room_id']) if r['room_id'] in ROOM_ORDER else 99)
    name = str(record['name'])
    plan = {
        'plan_id': 'rplan_graph2plan_%s' % name, 'rplan_source_file': 'data.mat', 'rplan_source_id': name,
        'rplan_labels_present': [int(x) for x in labels],
        'rplan_conversion': {
            'method': 'polygon_largest_rectangle_contact_repair_v2' if repair else 'polygon_largest_rectangle_v1', 'scale_m_per_px': scale,
            'origin_px': [ox, oy], 'target_area_m2_before_clamp': round(scale_target, 1), 'retained_area_fraction': round(retained, 3),
            'dining_source': dining_source, 'dining_side': dining_side, 'living_dining_swapped': swapped, 'access': access,
            'contact_repairs': moves, 'notes': sorted(set(notes)),
        },
        'rooms': plan_rooms,
        'open_room_type_pairs': [['kitchen', 'dining_room'], ['dining_room', 'living_room']],
        'wall_thickness_m': 0.2, 'wall_height_m': 3.0,
    }
    return plan, None


def load_records(mat_path, limit=None, seed=0):
    import scipy.io as sio
    data = sio.loadmat(str(mat_path), squeeze_me=False, struct_as_record=False)['data']
    n = data.shape[0]
    indices = list(range(n))
    if limit:
        random.Random(seed).shuffle(indices)
        indices = sorted(indices[:limit])
    for i in indices:
        e = data[i, 0][0, 0]
        boundary = [np.asarray(x, dtype=float).reshape(-1, 2) for x in e.rBoundary.ravel()]
        corrupt = not all(np.isfinite(b).all() for b in boundary)      # a few records carry NaN vertices
        yield dict(name=str(e.name[0]), rType=[int(x) for x in e.rType.ravel()], corrupt=corrupt,
                   rBoundary=[] if corrupt else [b.astype(int).tolist() for b in boundary])


def _convert_one(args):
    record, options = args
    try:
        return record['name'], convert(record, **options)
    except Exception as exc:       # keep going; the reason is counted
        return record['name'], (None, 'exception_%s' % type(exc).__name__)


def main(argv=None):
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument('--mat', required=True, type=Path)
    ap.add_argument('--out', required=True, type=Path)
    ap.add_argument('--limit', type=int, help='convert a random subset of this size')
    ap.add_argument('--seed', type=int, default=0)
    ap.add_argument('--min-retained', type=float, default=0.8, help='drop plans whose rectangles keep less than this share of the source room area')
    ap.add_argument('--workers', type=int, default=1)
    ap.add_argument('--target-area', type=float, default=TARGET_AREA_M2, help='area in square metres the rectangles are scaled to (default %(default)s)')
    ap.add_argument('--max-extent', type=float, default=MAX_EXTENT_M, help='longest side of the whole plan in metres (default %(default)s); the scale is clamped to it, so a large target area needs a larger value')
    ap.add_argument('--scale-m-per-px', type=float, help='one scale in metres per source pixel for every plan (overrides --target-area and --max-extent): plans keep their own size, so a large flat is large and has large-flat proportions')
    ap.add_argument('--scale-range', type=float, nargs=2, metavar=('LOW', 'HIGH'), help='scale each plan towards --target-area, but keep the scale (metres per source pixel) between LOW and HIGH, so no plan is stretched much beyond its natural size (overrides --max-extent)')
    ap.add_argument('--extra-bedroom-area', type=float, default=0.0, help='square metres added to the target area for every bedroom beyond two')
    ap.add_argument('--profile', choices=sorted(PROFILES), default='balanced',
                    help='shortest sides allowed (metres): ' + '; '.join('%s: %s' % (n, ' '.join('%s %.1f' % kv for kv in p.items())) for n, p in sorted(PROFILES.items())))
    for key in ('living', 'bedroom', 'dining', 'kitchen', 'bath', 'balcony'):
        ap.add_argument('--min-' + key, type=float, help='shortest side of the %s (overrides the profile; bedroom = master, guest and bedroom_N)' % key)
    ap.add_argument('--min-side', type=float, help='shortest side of every other room (overrides the profile)')
    ap.add_argument('--max-aspect', type=float, default=MAX_ASPECT, help='longest over shortest side allowed for a room other than the living room')
    ap.add_argument('--max-growth', type=float, default=MAX_GROWTH, help='a room may grow to this multiple of its first rectangle while contacts are repaired')
    ap.add_argument('--no-repair', action='store_true', help='keep the plain largest rectangles (rooms may lose their contact with the living room)')
    ap.add_argument('--strict-access', action='store_true', help='refuse flats whose bedroom, bathroom or kitchen only reaches the living room through another private room')
    ap.add_argument('--candidates', type=int, default=MAX_CANDIDATES, help='maximal rectangles of a room polygon the search may pick from')
    ap.add_argument('--no-hallways', action='store_true', help='do not turn the hall leg of a living room into a hallway room (the chain\'s JPG path knows the type, its generator does not)')
    ap.add_argument('--keep-balcony', action='store_true', help='refuse a flat whose balcony cannot be opened onto a bedroom or the living room (default: leave the balcony out)')
    ap.add_argument('--allow-single-bedroom', action='store_true', help='also convert flats with one bedroom (the generator expects master and guest)')
    args = ap.parse_args(argv)
    records = list(load_records(args.mat, args.limit, args.seed))
    min_side = dict(PROFILES[args.profile])
    min_side.update({key: getattr(args, 'min_' + key) for key in ('living', 'bedroom', 'dining', 'kitchen', 'bath', 'balcony') if getattr(args, 'min_' + key) is not None})
    if args.min_side is not None:
        min_side['default'] = args.min_side
    options = dict(scale_target=args.target_area, max_extent=args.max_extent, min_retained=args.min_retained, extra_bedroom_area=args.extra_bedroom_area, min_side=min_side,
                   repair=not args.no_repair, max_aspect=args.max_aspect, max_growth=args.max_growth, require_guest=not args.allow_single_bedroom,
                   strict_access=args.strict_access, drop_balcony=not args.keep_balcony, candidates_per_room=args.candidates, hallways=not args.no_hallways,
                   fixed_scale=args.scale_m_per_px, scale_range=tuple(args.scale_range) if args.scale_range else None)
    jobs = [(r, options) for r in records]
    if args.workers > 1:
        from multiprocessing import Pool
        with Pool(args.workers) as pool:
            results = pool.map(_convert_one, jobs, chunksize=64)
    else:
        results = [_convert_one(j) for j in jobs]
    plans, reasons = [], {}
    for _, (plan, reason) in results:
        if plan:
            plans.append(plan)
        else:
            key = reason.split('_below_')[0] if reason.startswith('retained_area') else reason
            reasons[key] = reasons.get(key, 0) + 1
    out = {'schema': 'robohousegen.rplan_seed_file.polygon_rectangles_v1', 'source': 'Graph2Plan RPLAN release, room polygons reduced to rectangles',
           'plan_count': len(plans), 'source_record_count': len(records), 'options': options,
           'rejected_by_reason': dict(sorted(reasons.items(), key=lambda kv: -kv[1])), 'plans': plans}
    args.out.write_text(json.dumps(out, ensure_ascii=False))
    print('%d of %d source records converted' % (len(plans), len(records)))
    for reason, count in out['rejected_by_reason'].items():
        print('  %6d  %s' % (count, reason))
    return 0


if __name__ == '__main__':
    sys.exit(main())