#!/usr/bin/env python3 """How comfortable and ordinary does a converted plan look? Beyond sizes (proportions.py) this looks at the shape of the outline and at the way the rooms connect (the doors and openings the chain's topology step gives the plan). `assess(plan, topology)` returns (hard problems, score between 0 and 1). A plan with hard problems is not used; the score ranks the others. Hard: a compact outline (rooms fill at least 80% of their bounding box and 88% of their convex hull, no void inside); the entrance is in the living or the dining room; the kitchen opens onto the dining or the living room; no door from the kitchen into a bedroom; every bathroom door opens onto the living room or the hallway; every bedroom door opens onto the living room, the hallway or the dining room; a balcony is reachable; at most one hallway and it serves at least two doors; the living room and every bedroom have a window. Soft (weights in WEIGHTS): compact outline, bedrooms off the living room or hallway and not the dining room, kitchen next to the dining room, living room open onto the balcony, living room and bedrooms not long and thin, a window in the dining room, a bathroom next to the master, living + dining about a quarter to a third of the area. comfort.py --src --library lib.json --tier 120 --out ranked.json [--workers 16] """ import argparse import copy import json from multiprocessing import Pool from shapely.geometry import box from shapely.ops import unary_union WEIGHTS = dict(compact=0.22, bedroom_doors=0.14, kitchen_dining=0.10, balcony_open=0.08, living_shape=0.10, bedroom_shape=0.10, dining_window=0.06, bath_by_master=0.10, public_share=0.10) BED = ('master', 'guest') def is_bedroom(rid): return rid in BED or rid.startswith('bedroom_') def geometry(plan): boxes = {r['room_id']: box(*r['bounds_m']) for r in plan['rooms']} union = unary_union(list(boxes.values())) area = sum(b.area for b in boxes.values()) x0, y0, x1, y1 = union.bounds parts = list(getattr(union, 'geoms', [union])) return dict(boxes=boxes, area=area, fill=area / ((x1 - x0) * (y1 - y0)), hull=union.area / union.convex_hull.area, holes=sum(len(p.interiors) for p in parts), parts=len(parts)) def aspect(bounds): w, h = bounds[2] - bounds[0], bounds[3] - bounds[1] return max(w, h) / min(w, h) def ramp(value, bad, good): """0 at `bad`, 1 at `good`, linear in between (works in both directions).""" return max(0.0, min(1.0, (value - bad) / (good - bad))) def assess(plan, topo): out, soft = [], {} g = geometry(plan) bounds = {r['room_id']: r['bounds_m'] for r in plan['rooms']} area = {rid: b.area for rid, b in g['boxes'].items()} if g['fill'] < 0.80: out.append('outline_not_compact_%.2f' % g['fill']) if g['hull'] < 0.88: out.append('outline_has_notches_%.2f' % g['hull']) if g['holes'] or g['parts'] > 1: out.append('void_inside_the_outline') doors = [d for d in topo['doors'] if len(d['room_ids']) == 2] entry = [d['room_ids'][0] for d in topo['doors'] if len(d['room_ids']) == 1] door_of = {} for d in doors: a, b = d['room_ids'] door_of.setdefault(a, set()).add(b) door_of.setdefault(b, set()).add(a) opened = {} for a in topo['topology_adjacencies']: if a.get('open_connection') and a.get('connection_kind') != 'solid_wall_no_door': x, y = a['room_ids'] opened.setdefault(x, set()).add(y) opened.setdefault(y, set()).add(x) linked = {rid: door_of.get(rid, set()) | opened.get(rid, set()) for rid in bounds} if not entry or entry[0] not in ('living', 'dining'): out.append('entrance_not_in_a_public_room') if not ({'living', 'dining'} & opened.get('kitchen', set())): out.append('kitchen_not_open_to_living_or_dining') bedrooms = [rid for rid in bounds if is_bedroom(rid)] for rid in bedrooms: if 'kitchen' in door_of.get(rid, set()): out.append('door_from_kitchen_to_%s' % rid) if not door_of.get(rid, set()) <= {'living', 'hallway', 'dining'}: out.append('%s_door_not_to_living_hallway_or_dining' % rid) if 'bath' in bounds and not door_of.get('bath', set()) <= {'living', 'hallway'}: out.append('bath_door_not_to_living_or_hallway') if 'balcony' in bounds and not linked['balcony']: out.append('balcony_not_reachable') halls = [rid for rid in bounds if rid.startswith('hallway')] if len(halls) > 1: out.append('more_than_one_hallway') for rid in halls: if len(door_of.get(rid, set()) - {'living'}) < 2: out.append('hallway_serves_fewer_than_two_rooms') windowed = {w['room_id'] for w in topo['windows']} for rid in ['living'] + bedrooms: if rid not in windowed: out.append('%s_without_window' % rid) if out: return out, 0.0 soft['compact'] = ramp(g['fill'], 0.80, 0.95) * 0.5 + ramp(g['hull'], 0.88, 0.98) * 0.5 via = [door_of[rid] for rid in bedrooms] soft['bedroom_doors'] = sum(1.0 if 'dining' not in v else 0.4 for v in via) / len(via) soft['kitchen_dining'] = 1.0 if 'dining' in linked['kitchen'] else 0.3 soft['balcony_open'] = 1.0 if 'balcony' not in bounds else (1.0 if 'balcony' in opened.get('living', set()) or any('balcony' in opened.get(b, set()) for b in bedrooms) else 0.4) soft['living_shape'] = ramp(aspect(bounds['living']), 2.3, 1.4) soft['bedroom_shape'] = sum(ramp(aspect(bounds[b]), 1.9, 1.3) for b in bedrooms) / len(bedrooms) soft['dining_window'] = 1.0 if 'dining' in windowed else 0.3 near = [a for a in topo['topology_adjacencies'] if set(a['room_ids']) == {'bath', 'master'}] soft['bath_by_master'] = 1.0 if near or 'hallway' in linked.get('bath', set()) else 0.5 share = (area['living'] + area['dining']) / g['area'] soft['public_share'] = 1.0 if 0.25 <= share <= 0.33 else ramp(abs(share - 0.29), 0.14, 0.04) return [], sum(WEIGHTS[k] * v for k, v in soft.items()) _NATIVE = None def _init(src): global _NATIVE import screen_library as sl sl.init_worker(src) _NATIVE = sl.NATIVE def _one(plan): topo = _NATIVE.add_plan_topology(copy.deepcopy(plan), include_windows=True) problems, score = assess(plan, topo) return plan['plan_id'], problems, score def main(): ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument('--src', required=True) ap.add_argument('--library', required=True) ap.add_argument('--out', required=True) ap.add_argument('--workers', type=int, default=16) args = ap.parse_args() plans = json.load(open(args.library))['plans'] with Pool(args.workers, initializer=_init, initargs=(args.src,)) as pool: rows = pool.map(_one, plans, chunksize=32) ranked = sorted(((pid, score) for pid, problems, score in rows if not problems), key=lambda r: -r[1]) reasons = {} for _, problems, _ in rows: for item in problems: key = item.rsplit('_', 1)[0] if item.rsplit('_', 1)[-1].replace('.', '').isdigit() else item reasons[key] = reasons.get(key, 0) + 1 json.dump(dict(library=args.library, passed=len(ranked), total=len(rows), ranked=ranked, reasons=dict(sorted(reasons.items(), key=lambda kv: -kv[1]))), open(args.out, 'w')) print('%d of %d plans pass the hard checks' % (len(ranked), len(rows))) for key, count in sorted(reasons.items(), key=lambda kv: -kv[1])[:12]: print(' %6d %s' % (count, key)) if __name__ == '__main__': main()