Datasets:
File size: 14,859 Bytes
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 | #!/usr/bin/env python3
"""Run the checks the native shell adapter performs before Blender on every plan of a converted library, and keep the plans that pass.
Same code path as build_native_shell_case.py: validate_plan, add_plan_topology(include_windows=True), the scene envelope contract, the
metric layout contract and validate_connectivity. On top:
- a contact that is a little too short for a portal (0.75 to 1.0 m: the chain refuses it as a portal-contract violation), or a portal that
leaves less than 2 cm of wall beside it (the shell builder fails on it), is repaired by moving one wall of one of the two rooms by up to
0.5 m, as long as the chain then accepts the plan (--no-fix turns this off);
- a plan whose floor outline is pinched to a point by two rooms that only meet at a corner is refused (`floor_pinch`): the shell builder
cannot close the floor slab;
- a kitchen or bedroom without an exterior window is refused. The generator of the live tree only places windows for the ids master, guest,
living, kitchen, balcony, dining and bath; with that generator further bedrooms (bedroom_3 ...) are recorded in
`further_bedrooms_without_window`, not refused. A generator with patch_extra_bedroom_windows.py places their windows, so there a further
bedroom without one is refused too;
- the generator's topology score is recorded; its hard reject refuses the plan only with --topology-gate, because the shell adapter's own
selector, scene_input.select_rplan, does not apply it.
screen_library.py --src <repo root> --library in.json --out out.json [--workers 8] [--limit N] [--min-score S] [--allow-missing-windows]
[--topology-gate] [--no-fix]
"""
import argparse
import copy
import importlib
import json
import os
import sys
import tempfile
from collections import Counter
from pathlib import Path
NATIVE = None
ADAPTER = None
STEPS_M = (0.05, 0.10, 0.15, 0.20, 0.30, 0.40, 0.50) # how far a wall may be moved to repair a short contact
OVERLAP_TOLERANCE_M = 0.02
MIN_WALL_STUB_M = 0.02 # a portal has to leave at least this much wall beside it (treated like a too short contact: a wall is moved)
DEFAULT_LIMITS_M = {'kitchen': 1.6, 'bath': 1.5, 'balcony': 1.0, 'hallway': 1.0, 'default': 1.8} # shortest side a repair may leave (a library's own options win)
def init_worker(src):
global NATIVE, ADAPTER
src = Path(src)
helpers = src / 'engine/source/scripts/internal/scene_generation'
tmp = tempfile.mkdtemp(prefix='rplan_screen_')
os.environ.update(RHG_BASE_SCRIPT=str(helpers / 'base/rhg_fullhome_test_generate_v2.py'), RHG_OUT_ROOT=tmp, RHG_CANDIDATE_CACHE_DIR=tmp,
RHG_WALL_HEIGHT_M='3.0', RHG_DOOR_WIDTH_M='1.0', RHG_DOOR_HEIGHT_M='2.4', RHG_TEST_SCENE_COUNT='1')
sys.path[:0] = [str(src), str(helpers), str(src / 'engine/source'), str(src / 'engine/supervisor_site')]
NATIVE = importlib.import_module('rhg_task_contract_generate_v16_1p_procedural_pure')
ADAPTER = importlib.import_module('build_native_shell_case')
def pinched_floor(plan, eps=0.004):
"""True when two rooms meet at a corner with the other two quadrants around that point empty (a diagonal contact, which pinches the floor
outline or a void inside it to a point). The shell builder cannot make a closed floor slab from that ("Floor slab mesh is not a closed
manifold"): all four such plans of a 400-plan sample failed, none of the 391 plans without one did."""
boxes = [r['bounds_m'] for r in plan['rooms']]
def filled(x, y):
return any(b[0] < x < b[2] and b[1] < y < b[3] for b in boxes)
corners = {(b[i], b[j]) for b in boxes for i in (0, 2) for j in (1, 3)}
for x, y in corners:
ne, nw, sw, se = filled(x + eps, y + eps), filled(x - eps, y + eps), filled(x - eps, y - eps), filled(x + eps, y - eps)
if (ne and sw and not nw and not se) or (nw and se and not ne and not sw):
return True
return False
def wall_stub(adjacency):
"""The shorter piece of wall left beside the portal of a shared wall, or None when the adjacency has no ordinary portal. The shell builder
cannot cut an opening that fills the whole wall (a plan with a stub of 0.000 m failed)."""
interval = adjacency.get('open_interval_m') or adjacency.get('door_interval_m')
if not interval or adjacency.get('balcony_side_clearance_m'):
return None
lo, hi = adjacency['overlap_interval_m']
return min(interval[0] - lo, hi - interval[1])
def evaluate(plan):
"""The chain's checks before Blender on one plan: dict(reason, violations, disconnected, score, connectivity, final). `reason` is None
when every check passes; the chain stops at the first problem, so only the data gathered up to that point is filled in."""
out = dict(reason=None, violations=[], disconnected=[], score=None, connectivity=None, final=None)
try:
ADAPTER.validate_plan(plan)
except ValueError as exc:
out['reason'] = 'validate_plan: ' + str(exc)[:60]
return out
if pinched_floor(plan):
out['reason'] = 'floor_pinch'
return out
try:
topo = NATIVE.add_plan_topology(copy.deepcopy(plan), include_windows=True)
out['violations'] = [a for a in topo.get('topology_adjacencies', [])
if a.get('portal_contract_violation_v16_21p') or (wall_stub(a) is not None and wall_stub(a) < MIN_WALL_STUB_M)]
if out['violations']:
out['reason'] = 'portal_contract_violation'
return out
out['score'] = NATIVE.score_rplan_topology_v16_12(topo)
out['final'] = final = NATIVE.apply_scene_envelope_contract_v16_21p(topo)
out['connectivity'] = ADAPTER.validate_connectivity(final, NATIVE.build_metric_layout_contract_v14(final))
except ValueError as exc:
text = str(exc)
if text.startswith('Disconnected'):
out['reason'], out['disconnected'] = 'disconnected', text.split(': ', 1)[1].split(',')
else:
out['reason'] = 'portal_without_width' if 'no usable width' in text else 'value_error: ' + text[:50]
except Exception as exc:
out['reason'] = 'exception_' + type(exc).__name__
return out
def cost(result):
"""What is still wrong with a plan (smaller is better)."""
if result['reason'] is None:
return 0
if result['reason'] == 'portal_contract_violation':
return len(result['violations'])
return 10 * len(result['disconnected']) if result['reason'] == 'disconnected' else 1000
def min_side_for(limits, room_id):
"""Shortest side allowed for a room (the same lookup as convert_rplan.min_side_for): its own entry, else the group entry ('bedroom' for
master, guest and bedroom_N; 'hallway'), 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['default']
def valid_bounds(plan, room_id, bounds, limits):
"""True when a room with these bounds is still wide enough and overlaps no other room."""
x0, y0, x1, y1 = bounds
if min(x1 - x0, y1 - y0) < min_side_for(limits, room_id) - 1e-9:
return False
for other in plan['rooms']:
if other['room_id'] != room_id:
a, b, c, d = other['bounds_m']
if min(x1, c) - max(x0, a) > OVERLAP_TOLERANCE_M and min(y1, d) - max(y0, b) > OVERLAP_TOLERANCE_M:
return False
return True
def fix_up(plan, result, limits, rounds=4):
"""Repair portal-contract violations (a shared wall slightly shorter than a one metre portal) by moving one end of that wall, that is
an edge of one of the two rooms along the wall, by up to 0.5 m. Each round takes the move after which the chain complains least.
Returns (plan, result, descriptions of the moves)."""
moves = []
for _ in range(rounds):
if result['reason'] != 'portal_contract_violation':
break
rooms = {r['room_id']: r for r in plan['rooms']}
tried, best = set(), None
for rec in result['violations']:
for rid in rec['room_ids']:
for edge in ((1, 3) if rec['wall_orientation'] == 'V' else (0, 2)):
for step in STEPS_M:
for sign in (-1, 1):
bounds = list(rooms[rid]['bounds_m'])
bounds[edge] = round(bounds[edge] + sign * step, 3)
if (rid, edge, sign * step) in tried or not valid_bounds(plan, rid, bounds, limits):
continue
tried.add((rid, edge, sign * step))
trial = copy.deepcopy(plan)
next(r for r in trial['rooms'] if r['room_id'] == rid)['bounds_m'] = bounds
outcome = evaluate(trial)
key = (cost(outcome), step)
if best is None or key < best[0]:
best = (key, trial, outcome, '%s.%s %+.2f m' % (rid, ('x0', 'y0', 'x1', 'y1')[edge], sign * step))
if best is None or best[0][0] >= cost(result):
break
_, plan, result, label = best
moves.append(label)
return plan, result, moves
def screen_one(job):
plan, options = job
pid = plan['plan_id']
result = evaluate(plan)
moves = []
if result['reason'] == 'portal_contract_violation' and options['fix']:
plan, result, moves = fix_up(plan, result, options['limits'])
if result['reason']:
return pid, None, result['reason']
final, score = result['final'], result['score']
windowed = {w['room_id'] for w in final.get('windows', [])}
# a generator that knows further bedrooms (patch_extra_bedroom_windows.py) places their windows, so a bedroom_N without one has no exterior wall
must_have = {'kitchen', 'master', 'guest'} | ({r['room_id'] for r in final['rooms'] if r['room_id'].startswith('bedroom_')}
if hasattr(NATIVE, 'bedroom_window_ids_v1') else set())
missing = sorted(r['room_id'] for r in final['rooms'] if r['room_id'] not in windowed and r['room_id'] in must_have)
unlit = sorted(r['room_id'] for r in final['rooms'] if r['room_id'] not in windowed and r['room_id'].startswith('bedroom_') and r['room_id'] not in missing)
if missing and not options['allow_missing_windows']:
return pid, None, 'no_exterior_window_' + ('kitchen' if 'kitchen' in missing else 'bedroom')
if score.get('hard_reject') and options['topology_gate']:
return pid, None, 'topology_hard_reject: ' + ','.join(sorted(set(score.get('issue_kinds', []))))[:60]
if options['min_score'] is not None and float(score.get('score', 0)) < options['min_score']:
return pid, None, 'topology_score_below_minimum'
out = copy.deepcopy(plan)
out['rplan_screening'] = {
'topology_score': score.get('score'), 'topology_hard_reject': bool(score.get('hard_reject')),
'issue_kinds': sorted(set(score.get('issue_kinds', []))), 'missing_window_rooms': missing, 'further_bedrooms_without_window': unlit,
'narrow_portal_ids': result['connectivity'].get('narrow_portal_ids', []), 'wall_moves': moves, 'room_count': len(plan['rooms']),
'bedroom_count': sum(1 for r in plan['rooms'] if 'bedroom' in r['room_type']),
'room_area_m2': {r['room_id']: round((r['bounds_m'][2] - r['bounds_m'][0]) * (r['bounds_m'][3] - r['bounds_m'][1]), 2) for r in plan['rooms']},
'room_min_side_m': {r['room_id']: round(min(r['bounds_m'][2] - r['bounds_m'][0], r['bounds_m'][3] - r['bounds_m'][1]), 2) for r in plan['rooms']},
}
out['rplan_screening']['total_area_m2'] = round(sum(out['rplan_screening']['room_area_m2'].values()), 1)
return pid, out, None
def main(argv=None):
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument('--src', required=True, type=Path, help='repository root (the code tree whose generator is used)')
ap.add_argument('--library', required=True, type=Path)
ap.add_argument('--out', required=True, type=Path)
ap.add_argument('--workers', type=int, default=1)
ap.add_argument('--limit', type=int)
ap.add_argument('--min-score', type=float)
ap.add_argument('--allow-missing-windows', action='store_true')
ap.add_argument('--topology-gate', action='store_true',
help='also refuse the plans the generator\'s own selector (select_rplan_plans_v16_12) hard-rejects; the shell adapter does not apply it')
ap.add_argument('--no-fix', action='store_true', help='do not repair short contacts, refuse the plan')
args = ap.parse_args(argv)
library = json.loads(args.library.read_text())
plans = library['plans'][:args.limit] if args.limit else library['plans']
options = dict(min_score=args.min_score, allow_missing_windows=args.allow_missing_windows, topology_gate=args.topology_gate, fix=not args.no_fix,
limits=dict(DEFAULT_LIMITS_M, **(library.get('options', {}).get('min_side') or {})))
jobs = [(p, options) for p in plans]
if args.workers > 1:
from multiprocessing import Pool
with Pool(args.workers, initializer=init_worker, initargs=(str(args.src),)) as pool:
results = pool.map(screen_one, jobs, chunksize=16)
else:
init_worker(str(args.src))
results = [screen_one(j) for j in jobs]
kept = [plan for _, plan, _ in results if plan]
reasons = Counter(reason for _, plan, reason in results if not plan)
out = {k: v for k, v in library.items() if k not in ('plans', 'plan_count', 'rejected_by_reason')}
out.update(schema='robohousegen.rplan_seed_file.screened_v1', plan_count=len(kept), screened_count=len(plans),
screening_options=options, rejected_by_reason=dict(reasons.most_common()), plans=kept)
args.out.write_text(json.dumps(out, ensure_ascii=False))
print('%d of %d plans pass' % (len(kept), len(plans)))
for reason, count in reasons.most_common():
print(' %6d %s' % (count, reason))
repaired = sum(1 for p in kept if p['rplan_screening']['wall_moves'])
print('%d of the kept plans needed a wall moved to lengthen or remove a short contact' % repaired)
scores = sorted(float(p['rplan_screening']['topology_score'] or 0) for p in kept)
if scores:
print('topology score of the kept plans: min %.2f median %.2f max %.2f' % (scores[0], scores[len(scores) // 2], scores[-1]))
return 0
if __name__ == '__main__':
sys.exit(main())
|