Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2,022 changes: 2,013 additions & 9 deletions backend/app/data/buildingPlacementEdges.json

Large diffs are not rendered by default.

419 changes: 412 additions & 7 deletions backend/app/data/catalogue_dwelling_programmes.json

Large diffs are not rendered by default.

10 changes: 9 additions & 1 deletion backend/app/services/building_placement_edges.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,9 +100,17 @@ def building_contact_geometry(zone, geometry):
left = -native_width / 2 if row["left"] == "abut" else -max(width, native_width) / 2
right = native_width / 2 if row["right"] == "abut" else max(width, native_width) / 2
front, rear = -native_depth / 2, max(depth, native_depth) / 2
outline = row.get("outlineM")
if outline and (
p.get("building_geometry_basis") != "placement_plot"
or width + 0.01 < native_width
or depth + 0.01 < native_depth
or (abs(width - depth) > 0.01 and (width - depth) * (native_width - native_depth) < 0)
):
return geometry
return Polygon(
[
(center[0] + (x * c - y * s) / east, center[1] + (x * s + y * c) / 111320)
for x, y in ((left, front), (right, front), (right, rear), (left, rear))
for x, y in outline or ((left, front), (right, front), (right, rear), (left, rear))
]
)
16 changes: 10 additions & 6 deletions backend/app/services/model_contract.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,12 +89,12 @@ def uses_placement_plot(properties: dict[str, Any]) -> bool:


@lru_cache(maxsize=1)
def _dwelling_programmes() -> tuple[dict, ...]:
def _quantity_records() -> tuple[dict, ...]:
return tuple(json.loads((DATA / "catalogue_dwelling_programmes.json").read_text(encoding="utf-8"))["records"])


def catalogue_housing_programme(properties: dict[str, Any]) -> dict | None:
"""Return only a reviewed programme for the unchanged native revision."""
def catalogue_building_quantities(properties: dict[str, Any]) -> dict | None:
"""Return reviewed quantities for the matching catalogue revision and storeys."""
facts = native_model_facts(properties)
if not facts:
return None
Expand All @@ -103,13 +103,17 @@ def catalogue_housing_programme(properties: dict[str, Any]) -> dict | None:
programme = next(
(
row
for row in _dwelling_programmes()
for row in _quantity_records()
if row["variant_id"] == facts["variant_id"] and row["revision"] == facts["revision"]
),
None,
)
if not programme:
return None
# Some saved allocation shapes use a catalogue variant as a design
# reference. Description quantities describe a single placed model.
if programme.get("requires_placement_plot") and properties.get("building_geometry_basis") != "placement_plot":
return None
# A model capable of student edits is still its reviewed native home when
# saved with this exact revision and native storeys. Future/edited house
# assemblies receive no programme merely from a shared parent archetype.
Expand All @@ -122,5 +126,5 @@ def catalogue_housing_programme(properties: dict[str, Any]) -> dict | None:


def catalogue_dwellings(properties: dict[str, Any]) -> int | None:
programme = catalogue_housing_programme(properties)
return programme["dwellings"] if programme else None
programme = catalogue_building_quantities(properties)
return programme.get("dwellings") if programme else None
43 changes: 34 additions & 9 deletions backend/app/services/student_report.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@

from app.services.plan_metrics import DerivedMetric
from app.services.saved_site_assessment import matching_assessment
from app.services.model_contract import uses_placement_plot, catalogue_dwellings, catalogue_housing_programme
from app.services.model_contract import catalogue_building_quantities, catalogue_dwellings, uses_placement_plot
from app.services.lego_assembly import DETACHED_ARCHETYPE_IDS, catalog_parent_archetype_id
from app.services.residual_landscape import community_3d_source_hash
from app.services.policy_intelligence.retrieval import (
Expand Down Expand Up @@ -689,6 +689,22 @@ def union_area(records: list[dict]) -> float | None:
str(bid) for z in plot_zones for bid in ([z["building_id"]] if z["building_id"] else []) + z["building_ids"]
}
plot_shapes = [measured[z["id"]] for z in plot_zones if z["id"] in measured]
catalogue_floor_areas = {}
for zone in plot_zones:
props = zone["properties"]
if (
zone["zone_type"] != "building"
or zone["id"] not in measured
or props.get("building_geometry_basis") != "placement_plot"
or props.get("native_home_plot") is True
or props.get("building_footprint_scale", 1) != 1
):
continue
linked_keys = set(([zone["building_id"]] if zone["building_id"] else []) + zone["building_ids"])
quantities = catalogue_building_quantities(props) or {}
floor_area = positive(quantities.get("gross_floor_area_m2"))
if len(linked_keys) <= 1 and floor_area is not None:
catalogue_floor_areas.setdefault(next(iter(linked_keys), zone["id"]), floor_area)
metric(
"building_placement_plot_m2",
"Building placement plots",
Expand All @@ -713,9 +729,14 @@ def union_area(records: list[dict]) -> float | None:
or building["id"] in plot_ids
or building["id"] in plot_building_ids
):
# A detached recipe is anchored to its whole plot, including
# yards. That parent polygon is never a building floor plate.
missing_floors.append(building)
# A catalogue estimate comes from the model record. A saved
# placement plot supplies neither a footprint nor a floor plate.
floor_area = catalogue_floor_areas.get(building["id"])
if floor_area is None:
missing_floors.append(building)
else:
gfa += floor_area
measured_floor_plates += 1
continue
geom = _shape(building)
if geom is None:
Expand All @@ -730,21 +751,21 @@ def union_area(records: list[dict]) -> float | None:
gfa += area * floors
measured_floor_plates += 1
unresolved_development = any(not z["building_id"] and not z["building_ids"] for z in development_areas)
has_unknown_buildings = bool(missing_floors or unresolved_development)
has_unknown_buildings = bool(missing_floors or unresolved_development or plot_ids or plot_building_ids)
metric(
"building_footprint_m2",
"Known building footprints (incomplete)" if has_unknown_buildings else "Known building footprints",
unary_union(areas).area if areas else None if has_unknown_buildings else 0,
"m²",
"Union of drawn building footprints and linked footprint records; excludes development allocations and authored-model placement plots whose individual floor plates are unmeasured.",
"Union of drawn building footprints and linked footprint records. Catalogue placement plots do not supply building footprints.",
)
complete = not missing_floors and all(z["building_id"] or z["building_ids"] for z in development_areas)
metric(
"gfa_m2",
"Floor-area estimate" if complete else "Known floor area (incomplete)",
gfa if measured_floor_plates or complete else None,
"m²",
"Estimate from drawn footprints × recorded storeys, assuming equal floor plates. Excludes unknown floors, unresolved allocations and authored-model placement plots. Model bounding rectangles are not measured floor plates.",
"Estimate from reviewed catalogue quantities and drawn footprints × recorded storeys, assuming equal drawn floor plates. Excludes unmeasured plots, unknown floors and unresolved allocations.",
0.7,
)
if missing_floors or not complete:
Expand Down Expand Up @@ -792,7 +813,7 @@ def recorded_count(value):
number = 0.0 if value == 0 and not isinstance(value, bool) else positive(value)
return int(number) if number is not None and number.is_integer() else None

programme_zones = {zone["id"]: catalogue_housing_programme(zone["properties"]) for zone in quantity_zones}
programme_zones = {zone["id"]: catalogue_building_quantities(zone["properties"]) for zone in quantity_zones}
for zone in quantity_zones:
programme = programme_zones[zone["id"]]
if programme and programme.get("source_title"):
Expand Down Expand Up @@ -991,7 +1012,11 @@ def recorded_count(value):
"Sum of current server-certified detached recipe dwelling counts, deduplicated by linked building. Repeated podium/floor/roof modules represent one dwelling per segment, not additional units.",
0.95,
)
programme_resolved_zone_ids = {zone_id for zone_id, programme in programme_zones.items() if programme}
programme_resolved_zone_ids = {
zone_id
for zone_id, programme in programme_zones.items()
if programme and programme.get("dwellings") is not None
}
unresolved_zone_ids = detached_zone_ids - compiled_detached_zone_ids - programme_resolved_zone_ids
pending = len(unresolved_zone_ids)
pending_zones = [zone for zone in zones if zone["id"] in unresolved_zone_ids]
Expand Down
7 changes: 7 additions & 0 deletions backend/tests/test_building_placement_edges.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,13 @@ def test_packaged_manifest_matches_browser_policy():
assert json.loads(MANIFEST.read_text()) == json.loads(frontend.read_text())


def test_crescent_outline_requires_the_authored_plot_axes():
crescent = zone(
"london_crescent_terrace_bath_stone", width=130, depth=150, building_geometry_basis="placement_plot"
)
assert building_contact_geometry(crescent, crescent.geometry) is crescent.geometry


@pytest.mark.parametrize("angle", [0, 37, 90, 180])
def test_padded_plots_may_overlap_but_native_buildings_may_not(angle):
width = building_edge_contracts()["validation_cast_iron_italianate"]["nativeWidthM"]
Expand Down
27 changes: 27 additions & 0 deletions backend/tests/test_building_save_overlap.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,33 @@ async def test_save_allows_reviewed_side_by_side_buildings_with_overlapping_plot
)


@pytest.mark.asyncio
@pytest.mark.parametrize("overlap", [False, True])
async def test_save_fits_the_bath_crescent_to_its_curved_outline(overlap):
from tests.test_building_placement_edges import zone

neighbour = zone(y=12 if overlap else -12, width=4, depth=4)
neighbour.name = "Neighbour"
neighbour.properties = {}
crescent = zone(
width=126.4,
depth=48.5,
pick_place_asset="london_crescent_terrace_bath_stone",
development_selected_variant_id="london-crescent-terrace-bath-stone",
pick_place_model_revision="crescent-terrace-bath-stone-clay-v006",
building_geometry_basis="placement_plot",
)
db = SimpleNamespace(execute=AsyncMock(return_value=result(rows=[neighbour])))
save = site_zones._assert_new_catalogue_building_clear(
db, uuid.uuid4(), "building", crescent.geometry, crescent.properties
)
if overlap:
with pytest.raises(HTTPException, match="Neighbour"):
await save
else:
await save


@pytest.mark.asyncio
@pytest.mark.parametrize(
"properties",
Expand Down
27 changes: 27 additions & 0 deletions backend/tests/test_student_report.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,33 @@ def test_exact_catalogue_dwelling_programmes_are_counted_without_plot_floor_area
assert values(analyze_snapshot(plan))["catalogue_dwellings"] is None


def test_native_office_estimate_counts_its_floor_area_once_after_compilation():
compiled = SimpleNamespace(
id=uuid.uuid4(),
name="Courtyard office",
footprint=rectangle(),
height_meters=7.4,
floor_count=2,
specifications={},
)
office = zone(
"building",
building_geometry_basis="placement_plot",
pick_place_asset="clay_brick_timber_two_storey_office",
development_selected_variant_id="brick_timber_two_storey_office",
pick_place_model_revision="brick-timber-courtyard-office-clay-v004",
floor_count=2,
)
office.building_id = compiled.id
plan = snapshot([office], [compiled])
result = values(analyze_snapshot(plan))
assert result["gfa_m2"] == 224
assert result["gfa_ft2"] == pytest.approx(2411.12, abs=0.01)
assert result["building_footprint_m2"] is None
plan["zones"][0]["properties"]["pick_place_model_revision"] = "old-revision"
assert values(analyze_snapshot(plan))["gfa_m2"] is None


def test_proposed_study_area_is_separate_clipped_and_deduplicated():
boundary = zone("site_boundary")
collection = {
Expand Down
35 changes: 35 additions & 0 deletions frontend/scripts/check-model-contract.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,38 @@ const content = JSON.stringify({schema:'cityprompt.native-model-contract@1',reco
if(process.argv.includes('--write')) writeFileSync(target,content);
else if(readFileSync(target,'utf8').replace(/\r\n/g,'\n') !== content) throw new Error('Backend model contract is stale; run node scripts/check-model-contract.mjs --write');
console.log('Backend model contract matches authored catalogue: '+fileURLToPath(target));

const quantities = read('../src/data/catalogueBuildingQuantities.json');
const quantityIdentities = new Set();
const areaMethods = new Set(['storey_sections', 'typical_plate', 'source_programme']);
const authoredQuantities = [];
for (const { estimated_gross_floor_area_m2, estimated_dwellings_range, area_method, ...authored } of quantities.records) {
const { variant_id, revision, gross_floor_area_m2, dwellings } = authored;
const identity = `${variant_id}@${revision}`;
if (quantityIdentities.has(identity) || !records.some(record => record.variant_id === variant_id && record.revision === revision)) {
throw new Error(`Invalid or duplicate catalogue quantity identity: ${identity}`);
}
const hasAuthoredQuantity = gross_floor_area_m2 != null || dwellings != null;
const hasEstimatedArea = estimated_gross_floor_area_m2 !== undefined;
const hasEstimatedDwellings = estimated_dwellings_range !== undefined;
const validDwellingRange = Array.isArray(estimated_dwellings_range) && estimated_dwellings_range.length === 2
&& estimated_dwellings_range.every(value => Number.isInteger(value) && value >= 0)
&& estimated_dwellings_range[0] <= estimated_dwellings_range[1];
if ((!hasAuthoredQuantity && !hasEstimatedArea && !hasEstimatedDwellings)
|| (gross_floor_area_m2 != null && (!Number.isFinite(gross_floor_area_m2) || gross_floor_area_m2 <= 0))
|| (dwellings != null && (!Number.isInteger(dwellings) || dwellings < 0))
|| (hasEstimatedArea && (!Number.isFinite(estimated_gross_floor_area_m2) || estimated_gross_floor_area_m2 < 0))
|| (hasEstimatedDwellings && !validDwellingRange)
|| (area_method !== undefined && !areaMethods.has(area_method))) {
throw new Error(`Invalid catalogue quantity: ${identity}`);
}
quantityIdentities.add(identity);
// The backend reports use authored programmes. Planning estimates belong to the picker.
if (hasAuthoredQuantity) authoredQuantities.push(authored);
}
const quantityTarget = new URL('../../backend/app/data/catalogue_dwelling_programmes.json', import.meta.url);
const quantityContent = JSON.stringify({ ...quantities, records: authoredQuantities }, null, 2) + '\n';
if (process.argv.includes('--write')) writeFileSync(quantityTarget, quantityContent);
else if (readFileSync(quantityTarget, 'utf8').replace(/\r\n/g, '\n') !== quantityContent) {
throw new Error('Backend catalogue quantities are stale; run node scripts/check-model-contract.mjs --write');
}
Loading