erc.3: leaf-sharing mechanism + floor probe (§13.3)

Same-code rooms collapse into fewer, larger SHARED leaves so the ~1.8/leaf
shape tax (§13.1) is paid once per group. Multiplicity k is recovered from
area (k=clamp(round(area/target),1,max_share)) — no genome change — and used
in two default-OFF sites: graph.check_space_counts counts coverage (Σk vs
req.count) so one leaf covers several rooms without a missing fail, and
fitness.quality_size centres on k×target (σ scaled by k). Construction:
operators._share_rooms groups instances; _size_divisions_from_targets sizes
shared leaves to k×target via leaf_mult.

Floor probe (experiments/diag_leaf_sharing.py, harbor+maple, seeds 0/1/2,
+innerloop): total fails −27% harbor / −16% maple at share3, shape factors
fall ~linearly with leaf count (confirms §13.1). Cap: 17–44 missing fails
leak because depth maldistribution (§13.2) keeps shared leaves below k×target
so round() undercounts; inner loop can't close it. Net still positive.

Default-OFF reproduces baseline exactly (214 tests pass). Driver plumbing +
staged 20k A/B remain; §13.3 records the next design fork.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
Bruno Postle 2026-06-24 08:30:26 +01:00
parent 6a34bd675c
commit bf3ff43837
7 changed files with 405 additions and 20 deletions

View file

@ -1,6 +1,6 @@
{"id":"homemaker-py-ld2","title":"Interior-O courtyard seeding option","description":"_assign_adjacency_aware (operators.py:528) currently places the single O leaf on the MOST PERIPHERAL leaf, where adjacent rooms already have facade. For dense floors (harbor-house ~19 rooms/floor) this wastes the daylight source. Add an option to seed O INTERIOR (as a light well) and to scale O-leaf count with room count, so landlocked rooms get an adjacent uncovered-outside neighbour by construction -\u003e fewer crinkliness fails in the seed. A/B against current peripheral placement.","notes":"Construction lever (high prior under erc), sibling of erc.3 (leaf-sharing) and erc.4 (plot-filling). Directly attacks the crinkliness residual (erc decomposition: crinkliness 346 on maple): landlocked rooms get an adjacent uncovered-O light well by construction. Follow erc shared protocol (A/B maple+harbor seeds 0/1/2, 20k evals, control reproduces 136.0/74.0, DESIGN.md §13.x).","status":"open","priority":1,"issue_type":"task","owner":"bruno@postle.net","created_at":"2026-06-23T20:40:19Z","created_by":"Bruno Postle","updated_at":"2026-06-23T20:50:24Z","dependencies":[{"issue_id":"homemaker-py-ld2","depends_on_id":"homemaker-py-erc","type":"parent-child","created_at":"2026-06-23T21:49:30Z","created_by":"Bruno Postle","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
{"id":"homemaker-py-erc.4","title":"Experiment: depth-balanced / giant-splitting construction (re-scoped by Diag B)","description":"Attacks the #2 factor (size/undersize 242) via the §12.3 paradox: rooms are undersize while 56% of the plot is empty. The shape floor is computed at TARGET dims, so construction never spends the slack. Scale leaves up to consume available plot area (proportionally, preserving target aspect) so rooms reach/exceed target — bigger leaves are also easier to keep compact, so this may help crinkliness/width too.\n\nBuilds on leu.2 (proportion-aware splits sized FROM target dims) by adding a fill step that scales the whole layout (or per-region) to the plot envelope instead of leaving slack as empty plot. Implementation in operators construction / _size_divisions_from_targets.\n\nNOTE: exact fix-site (construction vs inner loop) is decided by Diagnostic B — if B shows leaves park at target with unused plot, this construction lever is correct; if B shows the inner loop simply lacks an expansion gradient, prefer the inner-loop slack-expansion sibling instead. A/B vs §12.2 baseline, seeds 0/1/2, 20000 evals, staged, default-OFF. Record DESIGN.md §13.4.","notes":"RE-SCOPED by Diagnostic B (§13.2). Original premise (rooms parked at target, scale leaves up into 56%-empty plot) is FALSIFIED: sized rooms already hold 1.4-1.5x aggregate target area; the empty-looking plot is ~46% circulation, not claimable void. Real defect: MALDISTRIBUTION by slicing position — same type/target leaf lands 0.05x..14.7x by binary-tree depth; inner loop cannot fix (frozen topology). NEW SCOPE: construction that balances tree DEPTH so equal-target rooms land at comparable depth and/or splits/caps giant leaves so area tracks target. NOT a uniform scale-to-envelope (that would just inflate the giants further). A/B vs §12.2 baseline, seeds 0/1/2, 20000 evals, staged, default-OFF. Record DESIGN.md §13.4. Synergy with erc.3 (leaf-sharing for the starved tail).","status":"open","priority":1,"issue_type":"feature","owner":"bruno@postle.net","created_at":"2026-06-22T23:16:19Z","created_by":"Bruno Postle","updated_at":"2026-06-23T21:47:03Z","dependencies":[{"issue_id":"homemaker-py-erc.4","depends_on_id":"homemaker-py-erc","type":"parent-child","created_at":"2026-06-23T00:16:19Z","created_by":"Bruno Postle","metadata":"{}"},{"issue_id":"homemaker-py-erc.4","depends_on_id":"homemaker-py-erc.2","type":"blocks","created_at":"2026-06-23T00:16:45Z","created_by":"Bruno Postle","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0}
{"id":"homemaker-py-erc.3","title":"Experiment: leaf-sharing / multi-room leaves in construction","description":"Strongest untried construction lever. §12.3 named 'merge or share leaves across same-class rooms' but c3g never tested it — c3g only coarsened the circulation spine (circ_divisor), trading shape gains for equal access/adjacency damage (null). Leaf-sharing is DIFFERENT: it reduces leaf count by collapsing same-class rooms (e.g. several O/storage, or same-type repeated rooms) into a shared leaf, attacking crinkliness(346)+size(242) directly WITHOUT coarsening circulation — so it should dodge the access penalty that sank c3g.\n\nImplementation sketch: in operators.constructive_topology (+ lift path), allow rooms of the same class/type (and compatible adjacency) to be instantiated as one larger leaf rather than one-leaf-per-room, lowering leaves-per-room from ~1.4 toward 1.0 or below. Honour storey_minimum and required-room presence (a shared leaf must still satisfy each merged room's presence/area in the fitness check, or the merge must be limited to rooms the fitness treats as fungible).\n\nTests the deepest open question: whether 52 rooms simply cannot be well-shaped as 52 leaves at this density. A/B vs §12.2 baseline (maple 136.0, harbor 74.0), seeds 0/1/2, 20000 evals, staged; default-OFF toggle so controls reproduce. Record DESIGN.md §13.3.","notes":"GATED-IN by erc.1 verdict (§13.1): per-leaf shape-fail tax is ~1.8/leaf and FLAT vs density; total shape fails track leaf count linearly. Fewer leaves for the same rooms (multi-room/shared leaves) is the only lever that moves the floor. Unlike c3g (§12.4) this removes ROOM-leaf count, not circulation, so the access/adjacency penalty that killed c3g should not apply.","status":"open","priority":1,"issue_type":"feature","owner":"bruno@postle.net","created_at":"2026-06-22T23:16:15Z","created_by":"Bruno Postle","updated_at":"2026-06-23T21:00:47Z","dependencies":[{"issue_id":"homemaker-py-erc.3","depends_on_id":"homemaker-py-erc","type":"parent-child","created_at":"2026-06-23T00:16:15Z","created_by":"Bruno Postle","metadata":"{}"},{"issue_id":"homemaker-py-erc.3","depends_on_id":"homemaker-py-erc.1","type":"blocks","created_at":"2026-06-23T00:16:42Z","created_by":"Bruno Postle","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0}
{"id":"homemaker-py-erc.3","title":"Experiment: leaf-sharing / multi-room leaves in construction","description":"Strongest untried construction lever. §12.3 named 'merge or share leaves across same-class rooms' but c3g never tested it — c3g only coarsened the circulation spine (circ_divisor), trading shape gains for equal access/adjacency damage (null). Leaf-sharing is DIFFERENT: it reduces leaf count by collapsing same-class rooms (e.g. several O/storage, or same-type repeated rooms) into a shared leaf, attacking crinkliness(346)+size(242) directly WITHOUT coarsening circulation — so it should dodge the access penalty that sank c3g.\n\nImplementation sketch: in operators.constructive_topology (+ lift path), allow rooms of the same class/type (and compatible adjacency) to be instantiated as one larger leaf rather than one-leaf-per-room, lowering leaves-per-room from ~1.4 toward 1.0 or below. Honour storey_minimum and required-room presence (a shared leaf must still satisfy each merged room's presence/area in the fitness check, or the merge must be limited to rooms the fitness treats as fungible).\n\nTests the deepest open question: whether 52 rooms simply cannot be well-shaped as 52 leaves at this density. A/B vs §12.2 baseline (maple 136.0, harbor 74.0), seeds 0/1/2, 20000 evals, staged; default-OFF toggle so controls reproduce. Record DESIGN.md §13.3.","notes":"PROBE DONE (§13.3): mechanism implemented default-OFF (operators._share_rooms/leaf_mult + graph.check_space_counts coverage + fitness.quality_size k×target centring; area-derived multiplicity k=clamp(round(area/target),1,max_share), no genome change). diag_leaf_sharing.py floor probe (harbor+maple, seeds 0/1/2, +innerloop): total fails 27% harbor / 16% maple at share3, shape factors fall ~linearly with leaf count (confirms §13.1). CAP: 1744 missing fails leak because depth maldistribution (§13.2) keeps shared leaves below k×target so round() undercounts; inner loop can't close it (frozen topology). NEXT FORK before 20k A/B: (a) thread area-derived flag through driver and run as-is (valid, net-positive), or (b) switch to explicit per-leaf multiplicity (undersize→light size fail not heavy missing) and/or pair with erc.4 depth-balancing. Impl+probe+§13.3+tests committed; driver plumbing + staged A/B remain.","status":"in_progress","priority":1,"issue_type":"feature","assignee":"Bruno Postle","owner":"bruno@postle.net","created_at":"2026-06-22T23:16:15Z","created_by":"Bruno Postle","updated_at":"2026-06-24T07:29:38Z","started_at":"2026-06-23T21:51:08Z","dependencies":[{"issue_id":"homemaker-py-erc.3","depends_on_id":"homemaker-py-erc","type":"parent-child","created_at":"2026-06-23T00:16:15Z","created_by":"Bruno Postle","metadata":"{}"},{"issue_id":"homemaker-py-erc.3","depends_on_id":"homemaker-py-erc.1","type":"blocks","created_at":"2026-06-23T00:16:42Z","created_by":"Bruno Postle","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0}
{"id":"homemaker-py-erc.2","title":"Diagnostic B: undersize-despite-slack localization (construction-target vs inner-loop-fill)","description":"GATES the plot-fill-construction vs inner-loop-expansion decision. The paradox from §12.3: plot utilisation is 0.44 (56% empty) yet size fails are 242 (rooms UNDERSIZE). Where is the slack stranded, and at which stage should it be spent?\n\nMeasure, on constructive seeds for maple-court + harbor (seeds 0/1/2):\n1. After CONSTRUCTION (before inner loop): per-leaf achieved area vs target area, and total occupied vs plot area. Are leaves parked at target with the slack left as unused plot, or is the slack distributed but mis-shaped?\n2. After the INNER LOOP optimises ratios: did size fails drop — i.e. does the ratio solve already expand leaves into slack, or does it have no gradient/incentive to exceed target? Compare predicted_shape_fails (target geometry) vs achieved size fails (post-optimise).\n\nThe §12.3 calibration (floor at TARGET dims ≈ achieved) already hints the inner loop is NOT filling slack — confirm and quantify, and identify whether the gap is (a) construction targets too-small dims given the plot, or (b) the objective gives no reward for exceeding target area. Output: DESIGN.md §13.2.\n\nDECISION RULE: if rooms are parked at target with unused plot → fix in CONSTRUCTION (plot-fill, erc child). If the inner loop has the room to expand but no objective gradient → fix in the INNER LOOP (slack-expansion term, erc child). Reads only; no behaviour change.","notes":"VERDICT (DESIGN.md §13.2): the '56% empty plot' is a misreading. Sized rooms already occupy ~50-54% of plot and hold 1.4-1.5x their aggregate target area (util\u003etgtFill); ~46% of plot is CIRCULATION, not claimable void (out only 3-4%). Size fails are pure MALDISTRIBUTION set by SLICING POSITION: median room at target (a/t~1.0) but long undersize tail (p25~0.35, min 0.05) starves while a few giants balloon (max 6.8x harbor, 14.7x maple). Same type/target lands at BOTH extremes (harbor r t=10: 68m2 \u0026 2.3m2; maple n t=60: ~target \u0026 2.7m2) =\u003e area dictated by binary-tree depth, not target. Inner loop CANNOT repair it: budget-80 size fails move only -1.6/-3.7, %undersize flat-to-worse; frozen-topology ratio DOF + 0.5^n cliff + symmetric size gaussian. =\u003e FALSIFIES plot-fill-as-claim-void (re-scope erc.4 to depth-balanced/giant-splitting construction), DEPRIORITISE erc.6 (wrong DOF). Reinforces erc.3 leaf-sharing for the starved tail. Script: experiments/diag_slack_localization.py","status":"closed","priority":1,"issue_type":"task","assignee":"Bruno Postle","owner":"bruno@postle.net","created_at":"2026-06-22T23:15:42Z","created_by":"Bruno Postle","updated_at":"2026-06-23T21:46:34Z","started_at":"2026-06-23T21:17:07Z","closed_at":"2026-06-23T21:46:34Z","close_reason":"Closed","dependencies":[{"issue_id":"homemaker-py-erc.2","depends_on_id":"homemaker-py-erc","type":"parent-child","created_at":"2026-06-23T00:15:42Z","created_by":"Bruno Postle","metadata":"{}"}],"dependency_count":0,"dependent_count":2,"comment_count":0}
{"id":"homemaker-py-erc.1","title":"Diagnostic A: per-leaf shape-fail vs density/granularity profile","description":"GATES the leaf-sharing vs compactness-cuts decision. The open question from §12.3: is the shape floor intrinsic to slicing at this leaf density (→ fewer leaves is the only lever), or fixable by better-shaped cuts at the same leaf count?\n\nMeasure: per-leaf shape-fail rate (crinkliness/size/proportion/width, broken out) as a function of leaves-per-room and plot utilisation, across the existing programmes spanning density — harbor (16 rooms) vs maple-court (52 rooms) — and, if cheap, a synthetic sweep that holds the programme fixed while varying leaf count (e.g. reuse the circ_divisor / construction granularity knob already in place to generate coarser vs finer constructive seeds and score predicted_shape_fails per leaf).\n\nReads, does not change behaviour: use operators.predicted_shape_fails + the per-leaf factor breakdown already in fitness.py (the §12.3 residual table was produced this way). Output: a table of per-leaf shape-fail vs density, written into DESIGN.md §13.1.\n\nDECISION RULE (write it into the verdict): if per-leaf shape-fail is FLAT across densities → floor is intrinsic to slicing density → prioritise leaf-sharing (erc child), deprioritise/close compactness-cuts. If it RISES with density → better cuts can pay → keep compactness-cuts. This is a measurement, not an experiment; no A/B, no baseline reproduction needed.","notes":"VERDICT (DESIGN.md §13.1): per-leaf shape-fail is FLAT vs slicing density in the controlled synthetic sweep (maple-court, room set fixed, circ_divisor 2-\u003e9: leaves 81-\u003e63, per-leaf rate 1.72-1.94 with no trend; TOTAL shape fails track leaf count ~linearly 139-\u003e116). Crinkliness dominates (~0.8/leaf) and is flat. Cuts already squarest (_size_divisions_from_targets) yet still ~1.8 fails/leaf =\u003e little compactness headroom at fixed count. Floor is INTRINSIC to per-leaf slicing. =\u003e prioritise leaf-sharing (erc.3), deprioritise compactness-cuts (erc.5). NOT the c3g null: that removed circulation leaves (access damage cancelled gain); leaf-sharing removes ROOM-leaf count without touching the spine. Script: experiments/diag_leaf_shapefail.py","status":"closed","priority":1,"issue_type":"task","assignee":"Bruno Postle","owner":"bruno@postle.net","created_at":"2026-06-22T23:15:40Z","created_by":"Bruno Postle","updated_at":"2026-06-23T21:00:34Z","started_at":"2026-06-23T20:53:52Z","closed_at":"2026-06-23T21:00:34Z","close_reason":"Closed","dependencies":[{"issue_id":"homemaker-py-erc.1","depends_on_id":"homemaker-py-erc","type":"parent-child","created_at":"2026-06-23T00:15:39Z","created_by":"Bruno Postle","metadata":"{}"}],"dependency_count":0,"dependent_count":2,"comment_count":0}
{"id":"homemaker-py-erc","title":"Phase 8: lower the geometry/shape floor — construction \u0026 inner-loop levers","description":"Continuation of Phase 7 (leu, closed). Phase 7's decisive finding (§12.3 calibration): predicted_shape_fails at the best achievable geometry ≈ the achieved total fail count (maple floor 121-163 vs achieved 126-148). Therefore SEARCH MACHINERY CANNOT HELP — there is no lower-fail basin for the constructed topologies to reach; the floor IS the result. Scoreboard: 4/4 wins from construction/seed quality (§11.2, §11.6, §11.7, §12.2), 0/3 from search machinery (§11.4, §11.5, §12.3). The only way to lower fails is to lower the geometry FLOOR.\n\nResidual decomposition (maple-court, 6 constructive seeds, §12.3): crinkliness 346 + size 242 (undersize) + proportion 121 + width 102, with plot utilisation only 0.44 (56% of plot empty) yet rooms UNDERSIZE. Diagnosed mechanism: over-granular construction — 73 leaves for 52 rooms — every leaf high perimeter/area (crinkliness) and below target area (size). c3g tested ONE granularity lever (circulation-spine coarsening via circ_divisor) → null (shape gain cancelled by equal access/adjacency damage). The other named levers were never tested.\n\nThis epic runs DIAGNOSTICS FIRST to decide which floor-lowering lever to invest in, then the construction/inner-loop experiments in dependency order. Tier-3 search-machinery bets (island model psk, tournament pressure 6zy) are tracked but LOW prior — do not invest there until something moves the floor.\n\nShared protocol (every experiment): A/B on maple-court + harbor, seeds 0/1/2, 20000 evals, staged; controls MUST reproduce the §12.2 baseline (maple 136.0, harbor 74.0); record verdict in DESIGN.md (new §13.x). Same discipline as every lever in §11-§12.","status":"open","priority":1,"issue_type":"epic","owner":"bruno@postle.net","created_at":"2026-06-22T23:14:56Z","created_by":"Bruno Postle","updated_at":"2026-06-22T23:14:56Z","dependency_count":0,"dependent_count":0,"comment_count":0}
@ -61,18 +61,18 @@
{"id":"homemaker-py-erc.6","title":"Experiment: inner-loop slack-expansion objective term","description":"Inner-loop counterpart to plot-fill construction. If Diagnostic B shows the inner loop has room to expand leaves into slack but no objective gradient to do so (the scalar rewards hitting target area but not exceeding it where slack exists), add a term/incentive so the ratio optimiser pushes leaf boundaries out to consume neighbouring slack and satisfy size, rather than parking at target.\n\nCONDITIONAL on Diagnostic B: build this only if B localizes the gap to the inner loop (room to expand, no gradient); if B shows construction targets too-small dims, prefer the plot-fill construction sibling. Must preserve the §5.4 inner-loop cliff / §4.9 lexicographic protection — the term sits where it cannot displace the fail-count ordering. A/B vs §12.2 baseline, seeds 0/1/2, 20000 evals, staged, default-OFF. Record DESIGN.md §13.6.","notes":"DEPRIORITISED by Diagnostic B (§13.2). B shows the inner loop CANNOT repair undersize: the slack is depth-driven maldistribution baked into the frozen topology, and the equal-offset ratio DOF cannot shrink a 14x leaf to feed a starved one without trading into shape fails (0.5^n cliff). Wrong DOF and wrong direction — the blocker is slicing POSITION, not a missing expansion reward. Fix belongs upstream in construction/topology (erc.4 re-scoped, erc.3). Keep as a low-priority follow-up only if a depth-balanced construction still leaves a residual size gradient the inner loop could pick up.","status":"open","priority":4,"issue_type":"feature","owner":"bruno@postle.net","created_at":"2026-06-22T23:16:24Z","created_by":"Bruno Postle","updated_at":"2026-06-23T21:47:05Z","dependencies":[{"issue_id":"homemaker-py-erc.6","depends_on_id":"homemaker-py-erc","type":"parent-child","created_at":"2026-06-23T00:16:23Z","created_by":"Bruno Postle","metadata":"{}"},{"issue_id":"homemaker-py-erc.6","depends_on_id":"homemaker-py-erc.2","type":"blocks","created_at":"2026-06-23T00:16:47Z","created_by":"Bruno Postle","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0}
{"id":"homemaker-py-erc.5","title":"Experiment: compactness-aware cuts (minimize leaf perimeter/area)","description":"Attacks the #1 factor, crinkliness (346) — a per-leaf perimeter/area property DISTINCT from proportion (aspect ratio). Proportion-aware seeding (leu.2) sizes splits but does not bias toward balanced, square-ish subdivision. Add a KD-tree-style 'keep both children compact' cut rule (prefer the cut orientation/position that minimises summed child perimeter/area) in construction.\n\nCONDITIONAL on Diagnostic A: if A shows per-leaf shape-fail is FLAT across densities (floor intrinsic to slicing density), better cuts at the same leaf count will not pay → this should be closed wont-fix in favour of leaf-sharing. Only build if A shows shape-fail RISES with density. A/B vs §12.2 baseline, seeds 0/1/2, 20000 evals, staged, default-OFF. Record DESIGN.md §13.5.","notes":"DEPRIORITISED by erc.1 verdict (§13.1): per-leaf shape-fail flat vs slicing density and cuts already squarest (_size_divisions_from_targets picks squarest rotation) yet still ~1.8 fails/leaf =\u003e little compactness headroom at fixed leaf count. Floor is intrinsic to leaf COUNT, not cut quality. Revisit only if leaf-sharing (erc.3) underdelivers.","status":"open","priority":4,"issue_type":"feature","owner":"bruno@postle.net","created_at":"2026-06-22T23:16:21Z","created_by":"Bruno Postle","updated_at":"2026-06-23T21:00:46Z","dependencies":[{"issue_id":"homemaker-py-erc.5","depends_on_id":"homemaker-py-erc","type":"parent-child","created_at":"2026-06-23T00:16:21Z","created_by":"Bruno Postle","metadata":"{}"},{"issue_id":"homemaker-py-erc.5","depends_on_id":"homemaker-py-erc.1","type":"blocks","created_at":"2026-06-23T00:16:43Z","created_by":"Bruno Postle","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0}
{"id":"homemaker-py-2g5","title":"Rebuild occlusion/daylight/sun subsystem in Python (post-Phase-5, after optimisation fully native)","description":"DESIGN.md §6 port scope — a whole subsystem, not a term. quality_daylight (Leaf.pm:281-296) needs Urb::Misc::Sun + Urb::Field::Occlusion (+CIESky); quality_uncrinkliness also takes the occlusion object. Indoor spaces return 1 for daylight; cost is outdoor spaces + crinkliness. Port Sun_horizontal (262980-minute normalisation) and the occlusion wall set from Dom-\u003eWalls.","acceptance_criteria":"Daylight and crinkliness factors match Perl (float tolerance) across the corpus, including multi-storey cases","notes":"Re-scoped 2026-06-12: occlusion disabled in the Urb oracle instead of ported (see homemaker-py-gp2). Native fitness ships with simple crinkliness (illumination factor = 1, in homemaker-py-gnw). This issue is now the eventual Python occlusion rebuild, only after optimisation works entirely in Python. Restores outdoor-daylight and shaded-wall selection pressure.\nReframed 2026-06-17: orthogonal to epic homemaker-py-c4c. This is fitness FIDELITY (restoring daylight + shaded-wall selection pressure to match Perl), not search CAPABILITY — it changes what 'good' means, not the search's ability to find good. It will NOT improve final designs in the sense currently sought. Stays P4, deferred until the topology-search-quality epic lands and optimisation is fully native.","status":"open","priority":4,"issue_type":"feature","owner":"bruno@postle.net","created_at":"2026-06-11T23:38:25Z","created_by":"Bruno Postle","updated_at":"2026-06-17T19:14:48Z","dependency_count":0,"dependent_count":0,"comment_count":0}
{"_type":"memory","key":"adjacency-in-binary-slicing-tree-is-structural-not","value":"Adjacency in binary slicing tree is structural, not geometric: the inner-loop NM cannot fix topological adjacency failures. Two paths exist: (1) tree-sibling adjacency — a node is adjacent to its sibling in the tree; (2) cross-zone geometric adjacency — leaves from different subtrees that happen to share a boundary. Staircase/adjacency fails require a topology mutation that changes which nodes are siblings or which zones touch. This was proved empirically on programme-house: staircase fail from rot=0 layout could not be fixed by NM but was fixed by level_retype creating a two-C topology (2026-06-14/15)."}
{"_type":"memory","key":"urb-fitness-bug-found-fixed-2026-06-12","value":"Urb fitness bug found+fixed 2026-06-12 (patch in /home/bruno/src/urb, uncommitted): ProgrammeDriven.pm ratio_o/ratio_type grepped case-insensitively over the ratios hash and took the FIRST key — nondeterministic (x4.5 score swings) for designs with mixed-case type classes (both 'c' circulation and 'C' covered). Fixed to SUM the class (matches Is_Circulation//Is_Outside semantics); 35/35 corpus scores unchanged. CRITICAL for homemaker-py-3y7/gnw: the native port must implement class-SUM ratios. Building.pm has the same unpatched pattern (site-driven path, not used by our oracle). Also: the memetic search reward-hacked this bug before the fix — search results predating it are noise artifacts."}
{"_type":"memory","key":"urb-oracle-nondeterminism-urb-fitness-pl-output-varies","value":"Urb oracle nondeterminism: urb-fitness.pl output varies run-to-run from Perl hash-order randomisation — .fails line ORDER shuffles (compare sorted, use oracle.Score.fail_lines) and the score float can flip by ~1 ULP (compare with math.isclose rel_tol=1e-12, never ==). Not a batching artifact; affects single runs too. Matters for the Phase 3 native-fitness parity gate (homemaker-py-uxz)."}
{"_type":"memory","key":"warm-x0-initialization-bug-pattern-when-a-topology","value":"warm_x0 initialization bug pattern: when a topology operator explicitly sets division ratios on a newly-created node (e.g. compound_fix sets node.division=[0.25,0.25] for t3), parent.ratios has no entry for that node (it was a leaf). warm_x0 defaults it to 0.5, corrupting the inner loop's starting point and making the operator invisible to lex comparison. Fix: only propagate child ratios for nodes where the parent node was NOT already divided; stale hidden nodes revealed by structural mutations (swap flipping b.below) must NOT contribute their pre-writeback values. See driver.py lines 259-267 (fixed 2026-06-14)."}
{"_type":"memory","key":"cli-tool-style-prefer-python-m-homemaker-module","value":"CLI tool style: prefer python -m homemaker.module --parameters pattern, installable via pip install -e . with pyproject.toml entry_points. Not standalone bin/ scripts."}
{"_type":"memory","key":"deceptive-valleys-in-topology-search-when-every-single","value":"Deceptive valleys in topology search: when every single-step mutation from a target state passes through a high-fail intermediary (e.g. level_fix displaces a room into 5+ new fails), a compound operator that atomically applies two coordinated changes can escape. Design compound operators to land on the low-fail state directly, bypassing the deceptive gradient. Programme-house example: level_compound_fix atomically moves the level-constrained room AND re-inserts the displaced room adjacent to C in one step (operators.py, 2026-06-14)."}
{"_type":"memory","key":"never-use-corpus-filenames-candidate-001-dom-candidate","value":"Never use corpus filenames (candidate-001.dom, candidate-002.dom, generated.dom, init.dom, etc.) as --output targets when running experiments. These are test fixtures. Always write experimental outputs to scratch/ or a timestamped path. Lesson from 2026-06-14: warm-start runs overwrote candidate-001/002.dom and broke graph tests."}
{"_type":"memory","key":"user-preference-bruno-this-is-a-fedora-system","value":"User preference (Bruno): this is a Fedora system — NEVER install Python packages via pip without asking first; always ask whether to install the rpm via dnf (e.g. python3-cma) before considering pip. Applies to any dependency additions."}
{"_type":"memory","key":"adjacency-in-binary-slicing-tree-is-structural-not","value":"Adjacency in binary slicing tree is structural, not geometric: the inner-loop NM cannot fix topological adjacency failures. Two paths exist: (1) tree-sibling adjacency — a node is adjacent to its sibling in the tree; (2) cross-zone geometric adjacency — leaves from different subtrees that happen to share a boundary. Staircase/adjacency fails require a topology mutation that changes which nodes are siblings or which zones touch. This was proved empirically on programme-house: staircase fail from rot=0 layout could not be fixed by NM but was fixed by level_retype creating a two-C topology (2026-06-14/15)."}
{"_type":"memory","key":"correction-to-urb-fitness-bug-memory-bruno-2026","value":"CORRECTION to urb-fitness-bug memory (Bruno, 2026-06-12): 'C' is NOT a 'covered' type — Is_Covered is a geometric predicate (indoor space above). Urb's generic types are canonically UPPERCASE: C=circulation, O=outside, S=sahn (get_space_types qw/C O S/; corpus is 100% uppercase, never 'c'/'o' leaves). The mixed-case designs that fired the latent ratio_type first-match bug were created by homemaker's own operator type pool emitting lowercase 'c'/'o' — fixed: driver/operators now emit uppercase generics only, and class checks use t[0].lower() in 'cos'. The Urb class-sum patch stays as defensive hardening (zero impact on canonical designs). Native port (3y7/gnw): treat type classes case-insensitively, generics canonically uppercase."}
{"_type":"memory","key":"multi-storey-staircase-consistency-when-dividing-or-retyping","value":"Multi-storey staircase consistency: when dividing or retyping a circulation (C) leaf at one level, the same structural change should be propagated to the matching leaf on ALL other storeys so the stair core path is maintained. The optimizer cannot fix staircase disruptions through trial-and-error geometry alone — it requires a synchronized multi-level operator that applies the same topology change to every storey simultaneously."}
{"_type":"memory","key":"proportion-aware-constructive-seeding-leu-2-12-2","value":"Proportion-aware constructive seeding (leu.2/§12.2): sizing seed cuts from target AREAS only regresses (thin slivers wreck aspect); you must ALSO pick each cut's rotation for child squareness. It is a convergence ACCELERATOR via a deeper local optimum around the constructed topology: wins where that topology is roughly right and budget is scarce (harbor -13%, maple -10% at 20k evals) but DELAYS small programmes where the seed must be restructured by undivide (programme-house regresses at fixed budget, yet reaches the floor given budget - speed, not asymptote). Default-on. Also: n_storeys must honour storey_minimum, not just level: keys (programme-house storey_minimum:2, all rooms level:0 - was seeded 1 storey short; cq1)."}
{"_type":"memory","key":"homemaker-py-pythonpath-set-pythonpath-home-bruno-src","value":"homemaker-layout PYTHONPATH: package installed as 'homemaker-layout' via pip install -e . so 'import homemaker_layout' works from anywhere without PYTHONPATH. For running tests use 'python -m pytest' from project root /home/bruno/src/homemaker-layout (pyproject.toml adds src/ automatically). Never try pip show homemaker — that's the old homemaker-addon conflict."}
{"_type":"memory","key":"never-use-corpus-filenames-candidate-001-dom-candidate","value":"Never use corpus filenames (candidate-001.dom, candidate-002.dom, generated.dom, init.dom, etc.) as --output targets when running experiments. These are test fixtures. Always write experimental outputs to scratch/ or a timestamped path. Lesson from 2026-06-14: warm-start runs overwrote candidate-001/002.dom and broke graph tests."}
{"_type":"memory","key":"programme-house-optimisation-result-2026-06-14-15","value":"Programme-house optimisation result (2026-06-14/15): best achievable is 1 fail (l1 wrong level, score ~0.005). 0 fails is geometrically impossible: l1 (min 27m²) must occupy ll (~23m²) at level 0, which eliminates the t3-adj-C provider; dividing ll into lll(l1)+llr(C) gives llr proportion ~6:1 (fails). Python memetic optimizer achieves 1 fail in 50k evals vs Perl optimiser's 2-3 fails. Winning topology: TWO C nodes at level 0 — ll(C) for t3-adj-C via geometric contact, rl(C) for staircase via tree-sibling adjacency to rrr(O). Best .dom: scratch/from-warmstart-fixed.dom and scratch/from-compound3-fixed.dom."}
{"_type":"memory","key":"run-to-run-reproducibility-in-homemaker-layout-serial","value":"Run-to-run reproducibility in homemaker-layout: serial search (workers=1) is byte-for-byte deterministic; parallel (workers\u003e1) is now deterministic too AFTER fixing driver._run_batch to admit futures in submission order (was as_completed/completion order, bug xcy). Reproducibility holds only for a FIXED worker count — serial vs parallel differ because children-per-iteration is 1 vs n_workers (different batch granularity), which is expected, not a bug. The constructive seeder was NEVER nondeterministic: _assign_adjacency_aware has unique idx tiebreaks; comparing topologies with Python builtin hash() of the signature STRING is invalid (PYTHONHASHSEED salts str hashing per process) — use a stable hash (sha1) or genome.signature equality."}
{"_type":"memory","key":"urb-fitness-bug-found-fixed-2026-06-12","value":"Urb fitness bug found+fixed 2026-06-12 (patch in /home/bruno/src/urb, uncommitted): ProgrammeDriven.pm ratio_o/ratio_type grepped case-insensitively over the ratios hash and took the FIRST key — nondeterministic (x4.5 score swings) for designs with mixed-case type classes (both 'c' circulation and 'C' covered). Fixed to SUM the class (matches Is_Circulation//Is_Outside semantics); 35/35 corpus scores unchanged. CRITICAL for homemaker-py-3y7/gnw: the native port must implement class-SUM ratios. Building.pm has the same unpatched pattern (site-driven path, not used by our oracle). Also: the memetic search reward-hacked this bug before the fix — search results predating it are noise artifacts."}
{"_type":"memory","key":"homemaker-py-pythonpath-set-pythonpath-home-bruno-src","value":"homemaker-layout PYTHONPATH: package installed as 'homemaker-layout' via pip install -e . so 'import homemaker_layout' works from anywhere without PYTHONPATH. For running tests use 'python -m pytest' from project root /home/bruno/src/homemaker-layout (pyproject.toml adds src/ automatically). Never try pip show homemaker — that's the old homemaker-addon conflict."}
{"_type":"memory","key":"programme-house-optimisation-result-2026-06-14-15","value":"Programme-house optimisation result (2026-06-14/15): best achievable is 1 fail (l1 wrong level, score ~0.005). 0 fails is geometrically impossible: l1 (min 27m²) must occupy ll (~23m²) at level 0, which eliminates the t3-adj-C provider; dividing ll into lll(l1)+llr(C) gives llr proportion ~6:1 (fails). Python memetic optimizer achieves 1 fail in 50k evals vs Perl optimiser's 2-3 fails. Winning topology: TWO C nodes at level 0 — ll(C) for t3-adj-C via geometric contact, rl(C) for staircase via tree-sibling adjacency to rrr(O). Best .dom: scratch/from-warmstart-fixed.dom and scratch/from-compound3-fixed.dom."}
{"_type":"memory","key":"strategy-decision-2026-06-12-bruno-occlusion-daylight","value":"Strategy decision 2026-06-12 (Bruno): occlusion/daylight is ORTHOGONAL to building a scalable optimiser. Disable it in Urb (env flag, homemaker-py-gp2) rather than port it; native fitness uses simple crinkliness (illumination factor = 1); rebuild occlusion in Python only after optimisation is fully native (homemaker-py-2g5, now P4). Consequence: all scores change when the flag flips — re-baseline corpus/.score, DESIGN \\$4.5 gains, gate bars at one clean boundary AFTER homemaker-py-1p0 closes; Phase-2 urb-evolve benchmark must run with the same flag."}
{"_type":"memory","key":"urb-oracle-nondeterminism-urb-fitness-pl-output-varies","value":"Urb oracle nondeterminism: urb-fitness.pl output varies run-to-run from Perl hash-order randomisation — .fails line ORDER shuffles (compare sorted, use oracle.Score.fail_lines) and the score float can flip by ~1 ULP (compare with math.isclose rel_tol=1e-12, never ==). Not a batching artifact; affects single runs too. Matters for the Phase 3 native-fitness parity gate (homemaker-py-uxz)."}
{"_type":"memory","key":"cli-tool-style-prefer-python-m-homemaker-module","value":"CLI tool style: prefer python -m homemaker.module --parameters pattern, installable via pip install -e . with pyproject.toml entry_points. Not standalone bin/ scripts."}
{"_type":"memory","key":"correction-to-urb-fitness-bug-memory-bruno-2026","value":"CORRECTION to urb-fitness-bug memory (Bruno, 2026-06-12): 'C' is NOT a 'covered' type — Is_Covered is a geometric predicate (indoor space above). Urb's generic types are canonically UPPERCASE: C=circulation, O=outside, S=sahn (get_space_types qw/C O S/; corpus is 100% uppercase, never 'c'/'o' leaves). The mixed-case designs that fired the latent ratio_type first-match bug were created by homemaker's own operator type pool emitting lowercase 'c'/'o' — fixed: driver/operators now emit uppercase generics only, and class checks use t[0].lower() in 'cos'. The Urb class-sum patch stays as defensive hardening (zero impact on canonical designs). Native port (3y7/gnw): treat type classes case-insensitively, generics canonically uppercase."}
{"_type":"memory","key":"user-preference-bruno-this-is-a-fedora-system","value":"User preference (Bruno): this is a Fedora system — NEVER install Python packages via pip without asking first; always ask whether to install the rpm via dnf (e.g. python3-cma) before considering pip. Applies to any dependency additions."}
{"_type":"memory","key":"warm-x0-initialization-bug-pattern-when-a-topology","value":"warm_x0 initialization bug pattern: when a topology operator explicitly sets division ratios on a newly-created node (e.g. compound_fix sets node.division=[0.25,0.25] for t3), parent.ratios has no entry for that node (it was a leaf). warm_x0 defaults it to 0.5, corrupting the inner loop's starting point and making the operator invisible to lex comparison. Fix: only propagate child ratios for nodes where the parent node was NOT already divided; stale hidden nodes revealed by structural mutations (swap flipping b.below) must NOT contribute their pre-writeback values. See driver.py lines 259-267 (fixed 2026-06-14)."}

View file

@ -1585,3 +1585,70 @@ giant leaves (re-scope `erc.4` from "plot-fill" to **depth-balanced / giant-
splitting construction**), reinforcing §13.1's call to advance leaf-sharing
(`erc.3`) for the starved tail. Recommendation: re-scope `erc.4`, deprioritise
`erc.6`.
### 13.3 Experiment: leaf-sharing / multi-room leaves (`homemaker-py-erc.3`) — IN PROGRESS
The lever §13.1 named as the *only* one that moves the floor: collapse same-code
rooms into fewer, larger **shared** leaves so the per-leaf ~1.8 shape tax is paid
once per group instead of once per room. Unlike c3g (§12.4) this removes
ROOM-leaf count, not circulation, so the access/adjacency penalty that sank c3g
need not apply.
**Mechanism (no genome change).** A shared leaf carries no explicit state — it is
just a larger leaf of the code, which construction sizes to `k × target` area.
Its multiplicity `k` is *recovered from area* at scoring time,
`k = clamp(round(area/target), 1, max_share)` (`graph._leaf_share_mult`), used in
two places, both gated by a default-OFF `leaf_sharing` config key (controls
reproduce the §12.2 baseline exactly — all 212 tests pass with it off):
- `graph.check_space_counts` counts **coverage** (Σ per-leaf `k`) against
`req.count`, so one shared leaf satisfies several same-code rooms with no
missing fail;
- `fitness.quality_size` centres the size Gaussian on `k × target` (σ scaled by
`k`, preserving the *fractional* tolerance) so the shared leaf is not read as
oversize. `quality_proportion`/`quality_width` need no change — a
proportionally-scaled leaf keeps its aspect and only gets wider.
Construction (`operators._share_rooms`, `constructive_topology` with
`leaf_sharing=True`, `leaf_share_factor=N`) groups each sized, multi-instance
code into runs of ≤ N instances → one leaf per run, then `_size_divisions_from_
targets` sizes that leaf to the run's `k × target`. Only same-code merges (rooms
with identical adjacency/level reqs) so the spine assignment stays valid.
**Floor probe** (`experiments/diag_leaf_sharing.py`, harbor + maple, seeds 0/1/2)
— a cheap de-risk before the full A/B: build the §12.2 seed both ways, score at
the seed geometry and again after `innerloop.optimise` (nm, budget 80) under the
*same* objective. Averaged fails:
| programme | mode | leaves | total | missing | size | crink |
|-----------|-------------|-------:|------:|--------:|-----:|------:|
| harbor | OFF +il | 45.0 | 120.3 | 0.0 | 21.7 | 33.7 |
| harbor | share2 +il | 31.7 | 106.0 | 24.0 | 14.0 | 22.7 |
| harbor | share3 +il | 25.7 | 87.3 | 16.7 | 10.0 | 18.0 |
| maple | OFF +il | 73.0 | 194.7 | 0.0 | 37.3 | 58.3 |
| maple | share2 +il | 52.0 | 184.3 | 44.3 | 23.3 | 41.0 |
| maple | share3 +il | 47.0 | 162.7 | 35.3 | 17.7 | 39.0 |
**The floor moves** — total fails drop **27 % harbor / 16 % maple** at
`share3`, and the drop is exactly where §13.1 predicted: the shape factors fall
roughly with leaf count (harbor size 22→10, crinkliness 34→18 as leaves 45→26).
The §13.1 linear-in-leaves model holds.
**But a missing-fail leak caps the gain, and the inner loop cannot close it.**
Sharing buys back 1744 *missing* fails, and `innerloop.optimise` barely moves
them (harbor 17→17, maple 37→35). This is the §13.2 mechanism on the new axis:
the area-derived `k` recovery is defeated by binary-tree **depth maldistribution**
— a leaf "sized to `k × target`" lands at the wrong *absolute* area because
ratios multiply down the ancestry, so `round(area/target) < k` and the uncovered
rooms read as missing; the frozen-topology ratio DOF then cannot grow it back
(0.5ⁿ cliff). Net is still positive because the shape savings outweigh the leak.
**Verdict so far — leaf-sharing is validated as a real floor-mover (16…27 %),
and its cap is the predicted `erc.3``erc.4` synergy: shared leaves only pay off
fully when construction puts them at the right absolute area (depth-balancing).**
Open design fork for the full 20 000-eval A/B: (a) thread the (working, tested)
area-derived flag through the driver and run as-is — a valid experiment that
already shows net gain; or (b) first replace area-derived `k` with an **explicit
per-leaf multiplicity** (present-but-undersize → light size fail, not a heavy
missing fail) and/or pair with `erc.4` depth-balancing to land shared leaves at
`k × target`. The implementation (operators + fitness + graph, default-OFF) and
the probe are committed; driver plumbing + the staged A/B remain.

View file

@ -0,0 +1,166 @@
#!/usr/bin/env python3
"""Leaf-sharing floor probe (homemaker-py-erc.3, DESIGN.md §13.3).
Cheap de-risk BEFORE the full 20k A/B: does collapsing same-code rooms into
fewer, larger SHARED leaves actually lower the achievable fail floor, or does
the gain leak back as missing/size fails under the relaxed objective?
§13.1 found the per-leaf shape tax is ~1.8 and FLAT vs slicing density, so total
shape fails track leaf count linearly fewer leaves is the only floor-mover.
Leaf-sharing reduces ROOM-leaf count: a leaf sized to k×target counts as k
same-code rooms (graph._leaf_share_mult), so presence holds without a missing
fail and size is scored against k×target. This script builds the §12.2
constructive seed both ways (baseline OFF vs sharing ON, share_factor sweep),
scores each at its own seed geometry, and reports the fail breakdown.
DECISION RULE: if sharing-ON total fails drop well below baseline (and the drop
is in size+crinkliness, NOT bought back by missing) the floor moves proceed
to thread the flag through the driver for the staged 20k A/B. If missing fails
balloon or totals don't move → stop; same-code sharing cannot pay here.
Usage:
URB_NO_OCCLUSION=1 python3 experiments/diag_leaf_sharing.py
"""
from __future__ import annotations
import copy
import sys
from pathlib import Path
import numpy as np
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
from homemaker_layout import dom, fitness, innerloop, operators, programme # noqa: E402
PROGRAMMES = ["harbor-house", "maple-court"]
SEEDS = (0, 1, 2)
BUDGET = 80 # bootstrap child budget, as in Diagnostic B
ROOT = Path(__file__).resolve().parents[1]
class _force_sharing:
"""Context manager: make innerloop's NativeEvaluator build its fitness in
leaf_sharing mode (the dir's patterns.config has no such key), so the inner
loop optimises against the SAME relaxed objective the seed was scored under."""
def __init__(self, on: bool):
self.on = on
def __enter__(self):
self._orig = fitness.load_config
if self.on:
def patched(directory):
conf, cost = self._orig(directory)
conf = dict(conf)
conf["leaf_sharing"] = True
return conf, cost
fitness.load_config = patched
return self
def __exit__(self, *exc):
fitness.load_config = self._orig
# fail-string buckets (order matters: first match wins)
CATS = ("missing", "size", "width", "proportion", "crinkliness",
"adjacency", "access", "other")
def _bucket(fails) -> dict[str, int]:
out = {k: 0 for k in CATS}
for f in fails:
if "missing" in f or "too many" in f:
out["missing"] += 1
elif f.endswith(" size"):
out["size"] += 1
elif f.endswith(" width"):
out["width"] += 1
elif f.endswith(" proportion"):
out["proportion"] += 1
elif f.endswith(" crinkliness"):
out["crinkliness"] += 1
elif "adjacen" in f:
out["adjacency"] += 1
elif "access" in f or "inaccessible" in f:
out["access"] += 1
else:
out["other"] += 1
return out
def _build(seed_root, reqs, types, s, sharing, factor):
rng = np.random.default_rng(s)
return operators.constructive_topology(
seed_root, reqs, rng, types,
adjacency_aware=True, proportion_aware=True,
leaf_sharing=sharing, leaf_share_factor=factor)
def _measure(fit, pdir, seed_root, reqs, types, s, sharing, factor):
topo = _build(seed_root, reqs, types, s, sharing, factor)
n_leaves = sum(len(lvl.leaves()) for lvl in dom.levels(topo))
_score, fails = fit.score_with_fails(copy.deepcopy(topo))
before = {"n_leaves": n_leaves, "total": len(fails), **_bucket(fails)}
after_tree = copy.deepcopy(topo)
with _force_sharing(sharing):
innerloop.optimise(after_tree, str(pdir), x0=None, budget=BUDGET,
method="nm", use_native=True)
_s2, fails2 = fit.score_with_fails(copy.deepcopy(after_tree))
after = {"n_leaves": n_leaves, "total": len(fails2), **_bucket(fails2)}
return before, after
def _avg(rows, k):
return sum(r[k] for r in rows) / len(rows)
def main() -> int:
print("Leaf-sharing floor probe (§13.3)\n")
print("Seed geometry = constructive proportion-aware target (built per mode).")
print(f"Seeds: {SEEDS}. 'OFF' = baseline fitness; 'shareN' = leaf_sharing, "
"share_factor=N.")
print(f"seed = constructive seed; +il = after innerloop.optimise (nm, "
f"budget={BUDGET}) under the same objective.\n")
cols = ("leaves", "total", "missing", "size", "crink", "width", "prop",
"adj", "access", "other")
hdr = f"{'programme':<14}{'mode':>10}" + "".join(f"{c:>8}" for c in cols)
def _row(name, label, rows, k):
vals = [_avg(rows, "n_leaves"), _avg(rows, "total"),
_avg(rows, "missing"), _avg(rows, "size"),
_avg(rows, "crinkliness"), _avg(rows, "width"),
_avg(rows, "proportion"), _avg(rows, "adjacency"),
_avg(rows, "access"), _avg(rows, "other")]
print(f"{name:<14}{label:>10}" + "".join(f"{v:>8.1f}" for v in vals))
for name in PROGRAMMES:
pdir = ROOT / "examples" / name
reqs = programme.load_programme_dir(pdir)
types = sorted(reqs) + ["C", "O"]
conf, cost = fitness.load_config(pdir)
seed_root = dom.load(str(pdir / "init.dom"))
fit_off = fitness.Fitness(conf, cost)
conf_on = dict(conf)
conf_on["leaf_sharing"] = True
fit_on = fitness.Fitness(conf_on, cost)
print(hdr)
print("-" * len(hdr))
modes = [("OFF", fit_off, False, 1),
("share2", fit_on, True, 2),
("share3", fit_on, True, 3)]
for label, fit, sharing, factor in modes:
pairs = [_measure(fit, pdir, seed_root, reqs, types, s, sharing, factor)
for s in SEEDS]
befores = [b for b, _a in pairs]
afters = [a for _b, a in pairs]
_row(name, label, befores, "before")
_row(name, label + "+il", afters, "after")
print()
return 0
if __name__ == "__main__":
sys.exit(main())

View file

@ -188,6 +188,10 @@ class Fitness:
self.spaces: dict = self._conf.get("spaces") or {}
self._programme_cache: dict | None = None
self._load_programme(self._conf)
# erc.3 leaf-sharing (DESIGN.md §13.3): default OFF. When on, a leaf sized
# to k×target counts as k same-code rooms (count check + size centring).
self._leaf_sharing = bool(self.conf("leaf_sharing"))
self._max_share = int(self.conf("leaf_share_max") or 4)
def conf(self, key: str):
v = self._conf.get(key)
@ -277,7 +281,16 @@ class Fitness:
params = self.conf("size_circulation")
else:
params = self.get_space_params(leaf.type, "size")
return gaussian(geometry.area(leaf), 1.0, params[0], params[1])
target, sigma = params[0], params[1]
if self._leaf_sharing and t0 != "c" and target > 0:
# erc.3: a shared leaf holds k same-code rooms; centre the Gaussian on
# k×target (k recovered from area, as in graph._leaf_share_mult) and
# scale sigma by k so the *fractional* size tolerance is preserved.
from . import graph as _graph
k = _graph._leaf_share_mult(geometry.area(leaf), target, self._max_share)
if k > 1:
target, sigma = target * k, sigma * k
return gaussian(geometry.area(leaf), 1.0, target, sigma)
def quality_width(self, leaf: Node) -> float:
t0 = _t0(leaf)
@ -1024,7 +1037,8 @@ class Fitness:
programme = self._programme or {}
# --- Phase 1: UNMERGED tree checks ---
check_fails, missing = graph_mod.check_space_counts(root, programme)
check_fails, missing = graph_mod.check_space_counts(
root, programme, self._leaf_sharing, self._max_share)
failures.extend(check_fails)
self.preprocess_building(root)

View file

@ -427,9 +427,24 @@ def has_vertical_connection(leaf: Node, target_code: str, lvls: list[Node]) -> b
# Space-count detection + failure stacking (ProgrammeDriven.pm:154-215)
# --------------------------------------------------------------------------- #
def _leaf_share_mult(area: float, target: float, max_share: int) -> int:
"""Recover how many same-code rooms a leaf of ``area`` covers (erc.3).
Leaf-sharing carries no explicit genome state: a shared leaf is just a
larger leaf of the code, sized by construction to ``k × target`` area. The
multiplicity is recovered here from area alone ``round(area/target)``,
clamped to ``[1, max_share]`` so the count check and ``quality_size``
agree on the same ``k`` (both use this helper / its rounding)."""
if target <= 0:
return 1
return max(1, min(max_share, round(area / target)))
def check_space_counts(
root: Node,
targets: dict[str, SpaceReq],
leaf_sharing: bool = False,
max_share: int = 4,
) -> tuple[list[str], list[str]]:
"""Check design has exactly the required spaces; mirrors
``check_space_counts`` in ``ProgrammeDriven.pm:156-215``.
@ -439,13 +454,19 @@ def check_space_counts(
space, up to ~7 per missing space; also "too many" for excess spaces).
- ``missing_ids`` is the list of virtual space ids used to suppress false
adjacency/level/vertical failures for absent spaces.
With ``leaf_sharing`` (erc.3, DESIGN.md §13.3) presence is counted by
*coverage* not leaf count: one sufficiently large leaf of a code covers
``round(area/target)`` required instances (capped at ``max_share``), so a
single shared leaf can satisfy several same-code rooms without a missing
fail. Default OFF reproduces the strict per-leaf count exactly.
"""
# Count spaces by type (case-sensitive, as in Perl exact-match for unique)
count: dict[str, list[str]] = {}
count: dict[str, list[Node]] = {}
for lvl in levels(root):
for leaf in lvl.leaves():
if leaf.type:
count.setdefault(leaf.type, []).append(leaf.id)
count.setdefault(leaf.type, []).append(leaf)
failures: list[str] = []
missing: list[str] = []
@ -454,7 +475,13 @@ def check_space_counts(
if code[0].lower() in ("c", "o", "s"):
continue
actual = len(count.get(code, []))
leaves_of = count.get(code, [])
if leaf_sharing and req.size > 0:
# Coverage: sum the per-leaf multiplicity recovered from area.
actual = sum(_leaf_share_mult(geometry.area(lf), req.size, max_share)
for lf in leaves_of)
else:
actual = len(leaves_of)
expected = req.count
if actual < expected:

View file

@ -384,8 +384,65 @@ def _grow_leaves(lvl: dom.Node, n_leaves: int, rng: np.random.Generator) -> None
leaf.type = None
def _share_rooms(rooms: list[str], reqs,
share_factor: int) -> tuple[list[str], dict[str, list[int]]]:
"""Collapse same-code room instances into fewer, larger shared leaves (erc.3).
Each sized, multi-instance code in ``rooms`` is grouped into runs of up to
``share_factor`` instances one leaf per run carrying that run's
multiplicity. Returns ``(reduced_codes, mult_plan)`` where ``reduced_codes``
is the new per-leaf code list (fewer entries) and ``mult_plan[code]`` lists
the multiplicities of that code's leaves (summing to the original count).
Circulation/outside and single-instance or non-sized codes are untouched
(multiplicity 1), so they cannot incur a missing fail under sharing.
"""
from collections import Counter
counts = Counter(rooms)
reduced: list[str] = []
plan: dict[str, list[int]] = {}
for code in counts:
c = counts[code]
req = reqs.get(code) if reqs else None
shareable = (req is not None and req.has_size and req.size > 0
and share_factor >= 2 and c >= 2)
if not shareable:
mults = [1] * c
else:
mults, remaining = [], c
while remaining > 0:
m = min(share_factor, remaining)
mults.append(m)
remaining -= m
plan[code] = mults
reduced.extend([code] * len(mults))
return reduced, plan
def _leaf_mult_from_plan(lvl: dom.Node, plan: dict[str, list[int]]) -> dict:
"""Map each typed leaf to its intended multiplicity from a ``_share_rooms``
plan, so ``_size_divisions_from_targets`` sizes shared leaves to k×target.
Bigger multiplicities go to whichever leaves already read largest, so the
proportional sizing pass has the least work to do. Defensive against a leaf
count that differs from the plan (assignment dropped/added a slot): extra
leaves default to multiplicity 1, surplus plan entries are ignored."""
from . import geometry
by_code: dict[str, list[dom.Node]] = {}
for lf in lvl.leaves():
if lf.type:
by_code.setdefault(lf.type, []).append(lf)
leaf_mult: dict = {}
for code, mults in plan.items():
leaves = sorted(by_code.get(code, []), key=geometry.area, reverse=True)
for lf, m in zip(leaves, sorted(mults, reverse=True)):
if m > 1:
leaf_mult[lf] = m
return leaf_mult
def _size_divisions_from_targets(lvl: dom.Node, reqs, fmin: float = 0.04,
fmax: float = 0.96) -> None:
fmax: float = 0.96, leaf_mult: dict | None = None) -> None:
"""Resize each divided node's split ratio from its leaves' TARGET areas.
leu.2 (DESIGN.md §12.2, follow-up to §11.6/§11.7): the constructive seeders
@ -418,7 +475,8 @@ def _size_divisions_from_targets(lvl: dom.Node, reqs, fmin: float = 0.04,
if len(leaves) < 2:
return
sized = {lf: reqs[lf.type].size for lf in leaves
leaf_mult = leaf_mult or {}
sized = {lf: reqs[lf.type].size * leaf_mult.get(lf, 1) for lf in leaves
if lf.type in reqs and reqs[lf.type].size > 0}
mean_sized = (sum(sized.values()) / len(sized)) if sized else 1.0
n_generic = len(leaves) - len(sized)
@ -568,7 +626,9 @@ def constructive_topology(seed_root: dom.Node, reqs, rng: np.random.Generator,
types: list[str], min_storeys: int = 1,
adjacency_aware: bool = True,
proportion_aware: bool = True,
circ_divisor: int = 3) -> dom.Node:
circ_divisor: int = 3,
leaf_sharing: bool = False,
leaf_share_factor: int = 2) -> dom.Node:
"""Build a seed that instantiates every required space by construction.
The §11.0 diagnosis: random divide+retype chains leave required programme
@ -614,6 +674,14 @@ def constructive_topology(seed_root: dom.Node, reqs, rng: np.random.Generator,
for li, lvl in enumerate(lvls):
rooms = list(buckets[li])
# erc.3 leaf-sharing (§13.3): collapse same-code rooms into fewer, larger
# shared leaves BEFORE growing the tree, so the storey carries fewer total
# leaves (each paying the ~1.8 shape-fail tax once, §13.1). The fitness
# recovers each leaf's multiplicity from area; here we only reduce the
# code list and remember the plan to size shared leaves to k×target.
share_plan: dict[str, list[int]] = {}
if leaf_sharing:
rooms, share_plan = _share_rooms(rooms, reqs, leaf_share_factor)
if adjacency_aware:
# Spend extra leaves on a circulation spine (~one circ per 3 rooms),
# then assign so every room is adjacent to it (s44). Geometry must be
@ -639,7 +707,8 @@ def constructive_topology(seed_root: dom.Node, reqs, rng: np.random.Generator,
# first so upper-storey roots resolve geometry (the else branch above
# does not link, unlike the adjacency-aware branch).
dom._link(child)
_size_divisions_from_targets(lvl, reqs)
_size_divisions_from_targets(
lvl, reqs, leaf_mult=_leaf_mult_from_plan(lvl, share_plan))
return _finalise(child)

View file

@ -124,6 +124,48 @@ def test_constructive_topology_has_no_missing_spaces():
canonical(root)
def test_leaf_share_mult_recovery():
# erc.3 §13.3: multiplicity recovered from area = round(area/target), clamped.
from homemaker_layout.graph import _leaf_share_mult
assert _leaf_share_mult(10.0, 10.0, 4) == 1
assert _leaf_share_mult(19.0, 10.0, 4) == 2 # ~2x target → covers 2
assert _leaf_share_mult(100.0, 10.0, 4) == 4 # clamped at max_share
assert _leaf_share_mult(3.0, 10.0, 4) == 1 # never below 1
assert _leaf_share_mult(10.0, 0.0, 4) == 1 # no target → 1
@pytest.mark.skipif(not HARBOR.is_dir(), reason="harbor-house not available")
def test_leaf_sharing_reduces_leaves_and_covers_rooms():
# erc.3 §13.3: leaf_sharing builds fewer leaves, and coverage-counting lets
# the larger shared leaves satisfy several same-code rooms without missing.
from homemaker_layout import graph, programme
reqs = programme.load_programme_dir(str(HARBOR))
types = sorted(reqs) + ["C", "O"]
seed = dom.load(str(HARBOR / "init.dom"))
for trial in range(3):
plain = operators.constructive_topology(
seed, reqs, np.random.default_rng(trial), types)
shared = operators.constructive_topology(
seed, reqs, np.random.default_rng(trial), types,
leaf_sharing=True, leaf_share_factor=2)
n_plain = sum(len(l.leaves()) for l in dom.levels(plain))
n_shared = sum(len(l.leaves()) for l in dom.levels(shared))
assert n_shared < n_plain, f"trial {trial}: {n_shared} !< {n_plain}"
# Default-OFF parity: the flag defaults reproduce the strict count check.
assert (graph.check_space_counts(shared, reqs)
== graph.check_space_counts(shared, reqs, leaf_sharing=False))
# Coverage suppresses missings: the shared tree scored WITH leaf_sharing
# has fewer missing fails than the same tree scored without it.
_strict, miss_off = graph.check_space_counts(shared, reqs)
_cov, miss_on = graph.check_space_counts(shared, reqs, leaf_sharing=True)
assert len(miss_on) < len(miss_off), f"trial {trial}: sharing didn't cover"
@pytest.mark.skipif(not HARBOR.is_dir(), reason="harbor-house not available")
def test_adjacency_aware_seeding_cuts_adjacency_access_fails():
# s44: adjacency-aware construction clusters rooms around a connected