Datasets:
Download code/robohome/src/engine/spatial_priors.py from RoboParty/RoboHome: direct link, hf CLI and curl.
- Browser
- Download file 17.2 kB
-
https://huggingface.co/datasets/RoboParty/RoboHome/resolve/main/code/robohome/src/engine/spatial_priors.py
- Command line
-
hf download hf://datasets/RoboParty/RoboHome/code/robohome/src/engine/spatial_priors.py
-
curl -L -o spatial_priors.py https://huggingface.co/datasets/RoboParty/RoboHome/resolve/main/code/robohome/src/engine/spatial_priors.py
17.2 kB
| """Additive spatial prior receipts; no scene edits, file access, or dependencies.""" | |
| from __future__ import annotations | |
| from collections import Counter | |
| import json | |
| import math | |
| from typing import Optional | |
| def _identifier(value): | |
| return isinstance(value, str) and bool(value.strip()) | |
| def _sha256(value): | |
| return (isinstance(value, str) and len(value) == 64 | |
| and all(character in "0123456789abcdefABCDEF" for character in value)) | |
| def _rectangle(value): | |
| if not isinstance(value, list) or len(value) != 4: | |
| return False | |
| try: | |
| return (all(type(number) in (int, float) and math.isfinite(number) | |
| for number in value) | |
| and value[0] < value[2] and value[1] < value[3]) | |
| except OverflowError: | |
| return False | |
| def _overlaps(left, right): | |
| return (max(left[0], right[0]) < min(left[2], right[2]) | |
| and max(left[1], right[1]) < min(left[3], right[3])) | |
| def _duplicates(records, key): | |
| counts = Counter(record[key] for record in records | |
| if isinstance(record, dict) and _identifier(record.get(key))) | |
| return {value for value, count in counts.items() if count > 1} | |
| def _preferences(value): | |
| if not isinstance(value, (dict, list)) or not value: | |
| return False | |
| try: | |
| json.dumps(value, allow_nan=False) | |
| except (TypeError, ValueError, OverflowError, RecursionError): | |
| return False | |
| return True | |
| def evaluate_priors(manifest: dict, priors: Optional[dict]) -> dict: | |
| """Evaluate declared rectangular reservations and retrieve soft motif IDs. | |
| Python >=3.9, stdlib only. Inputs are borrowed read-only; output contains | |
| fresh containers. No geometry is inferred, transformed, moved, or deleted. | |
| Manifest contract (other fields are ignored): | |
| entities: list[dict] with unique, nonblank string entity_id. Optional | |
| asset_sha256 is a 64-digit hexadecimal asset identity; absent/None means | |
| unavailable. A present invalid hash cannot establish source identity. | |
| Optional supported_by_entity_id, support_entity_id, parent_entity_id are | |
| aliases for the child's support; non-null values must agree and resolve | |
| to a different manifest entity. These fields follow the separate latest | |
| source snapshot's task bindings and MetricEntityLayout. No imports from | |
| that snapshot or dependence on its entrypoints are required. | |
| Priors is None or a dict with these optional list fields ONLY: | |
| surfaces: [{entity_id, bounds_xy_m, source_sha256}]. Each record explicitly | |
| DECLARES a measured usable rectangle, in that support's local XY frame, | |
| metres. Exactly one per support. AABB/OBB extents, polygons, mesh bounds, | |
| world coordinates, and manifest footprint fields are never substitutes. | |
| This function trusts the declaration; it does not measure or authenticate | |
| a mesh or certify an arbitrary polygon's interior from its AABB. | |
| reservations: [{support_entity_id, bounds_xy_m, purpose}]. Purpose is a | |
| nonblank string; bounds must fit a declared surface. Positive-area | |
| intersections on the same support conflict; edge/corner contact is OK. | |
| footprints: [{entity_id, support_entity_id, bounds_xy_m, | |
| source_sha256 (optional)}]. Each explicitly declares the | |
| actual occupied rectangular footprint of an existing child, already in | |
| its support's local frame. One per child. A manifest support reference | |
| must agree when present. Missing footprints for known children of a | |
| reserved support yield insufficient_evidence; size/yaw/pose are never | |
| used to fill them in. Source hash is checked when supplied. Absence of | |
| a footprint hash is accepted as caller-declared occupancy evidence. | |
| motifs: [{motif_id, entity_ids, source_sha256, relative_preferences}]. IDs | |
| are nonblank strings; entity_ids is a nonempty unique list resolving to | |
| manifest entities. Preferences is a nonempty JSON-serializable dict/list | |
| with finite numbers. The single source hash must match EVERY referenced | |
| non-null manifest asset_sha256, when available. Thus a multi-asset motif | |
| with differing known hashes is rejected; this v1 contract does not hash | |
| a collection or accept a per-entity hash map. Retrieval checks identity | |
| and metadata only. Preferences, including coordinate-like fields, are | |
| never applied or returned as authoritative coordinates. | |
| All bounds are lists [xmin,ymin,xmax,ymax], finite int/float (no bool), with | |
| strictly positive width/height. Source hashes are required for surfaces and | |
| motifs, case-insensitive 64-digit hex; no file reads verify those assertions. | |
| Unknown top-level priors keys or malformed/stale/ambiguous evidence yield | |
| insufficient_evidence. Invalid reservation records, OOB reservations, and | |
| reservation/reservation or reservation/footprint overlap yield | |
| geometry_rejected, taking precedence over insufficient_evidence. Missing or | |
| empty requests yield not_requested; otherwise geometry_feasible means only | |
| these declared checks passed (motif-only requests are metadata checks). | |
| Returns schema='frontier.spatial-priors.v1', status (above), | |
| scope='rectangular-measured-surface', diagnostics=[{code,entity_ids,message}], | |
| accepted_motif_ids (input order), reservations (structurally valid request | |
| records in input order, INCLUDING conflicting/unverified ones, not approvals), | |
| physical_qualified=False, whole_task_acceptance=False, and | |
| global_validation_required=True. Bad motifs are omitted independently; | |
| accepted IDs remain soft candidates even if another check rejects geometry. | |
| Duplicate surface/footprint/motif IDs invalidate ALL corresponding records. | |
| Full global geometry, required inventory, frozen pose, and physical validation | |
| remain the caller's responsibility; neither inputs nor their poses change. | |
| """ | |
| result = dict(schema="frontier.spatial-priors.v1", status="not_requested", | |
| scope="rectangular-measured-surface", diagnostics=[], | |
| accepted_motif_ids=[], reservations=[], physical_qualified=False, | |
| whole_task_acceptance=False, global_validation_required=True) | |
| rejected = False | |
| insufficient = False | |
| def diagnostic(code, entity_ids, message, geometry=False, info=False): | |
| nonlocal rejected, insufficient | |
| result["diagnostics"].append(dict( | |
| code=code, entity_ids=[value for value in entity_ids if _identifier(value)], | |
| message=message)) | |
| if geometry: | |
| rejected = True | |
| elif not info: | |
| insufficient = True | |
| if priors is None: | |
| return result | |
| if not isinstance(priors, dict): | |
| diagnostic("invalid_priors", [], "Priors must be a dictionary or None.") | |
| result["status"] = "insufficient_evidence" | |
| return result | |
| fields = ("surfaces", "reservations", "footprints", "motifs") | |
| if any(key not in fields for key in priors): | |
| diagnostic("unknown_priors_field", [], "Unsupported top-level priors field.") | |
| records = {} | |
| for key in fields: | |
| value = priors.get(key, []) | |
| if not isinstance(value, list): | |
| diagnostic("invalid_" + key, [], key + " must be a list.") | |
| value = [] | |
| records[key] = value | |
| requested = bool(records["reservations"] or records["motifs"]) | |
| if not requested and not any(records.values()): | |
| result["status"] = "insufficient_evidence" if insufficient else "not_requested" | |
| return result | |
| entities = {} | |
| raw_entities = manifest.get("entities") if isinstance(manifest, dict) else None | |
| if not isinstance(raw_entities, list): | |
| diagnostic("invalid_manifest", [], "Manifest must supply an entities list.") | |
| raw_entities = [] | |
| duplicate_entities = _duplicates(raw_entities, "entity_id") | |
| for identifier in sorted(duplicate_entities): | |
| diagnostic("duplicate_entity", [identifier], "Manifest entity ID is ambiguous.") | |
| for entity in raw_entities: | |
| if not isinstance(entity, dict) or not _identifier(entity.get("entity_id")): | |
| diagnostic("invalid_entity", [], "Manifest entities require nonblank entity IDs.") | |
| elif entity["entity_id"] not in duplicate_entities: | |
| entities[entity["entity_id"]] = entity | |
| def source_matches(record, identifiers, kind): | |
| source = record.get("source_sha256") | |
| if not _sha256(source): | |
| diagnostic("invalid_" + kind, identifiers, "Require a source SHA-256 identity.") | |
| return False | |
| valid = True | |
| for identifier in identifiers: | |
| known = entities[identifier].get("asset_sha256") | |
| if known is None: | |
| continue | |
| if not _sha256(known): | |
| diagnostic("invalid_asset_hash", [identifier], | |
| "Manifest asset_sha256 is neither unavailable nor a SHA-256.") | |
| valid = False | |
| elif known.lower() != source.lower(): | |
| diagnostic("stale_" + kind, [identifier], | |
| "Prior source identity differs from the manifest asset hash.") | |
| valid = False | |
| return valid | |
| parents = {} | |
| invalid_parents = set() | |
| for identifier, entity in entities.items(): | |
| references = [entity[key] for key in | |
| ("supported_by_entity_id", "support_entity_id", "parent_entity_id") | |
| if entity.get(key) is not None] | |
| if (any(not _identifier(value) for value in references) | |
| or len(set(value for value in references if _identifier(value))) > 1 | |
| or any(value == identifier or value not in entities | |
| for value in references if _identifier(value))): | |
| diagnostic("invalid_support_relation", [identifier], | |
| "Support aliases must agree and resolve to another manifest entity.") | |
| invalid_parents.add(identifier) | |
| elif references: | |
| parents[identifier] = references[0] | |
| surfaces = {} | |
| duplicate_surfaces = _duplicates(records["surfaces"], "entity_id") | |
| for identifier in sorted(duplicate_surfaces): | |
| diagnostic("duplicate_surface", [identifier], "Require one measured rectangle per support.") | |
| for surface in records["surfaces"]: | |
| if not isinstance(surface, dict): | |
| diagnostic("invalid_surface", [], "Surface must be a record.") | |
| continue | |
| identifier = surface.get("entity_id") | |
| if not _identifier(identifier) or not _rectangle(surface.get("bounds_xy_m")): | |
| diagnostic("invalid_surface", [identifier], "Surface requires an ID and usable rectangle.") | |
| elif identifier in duplicate_surfaces: | |
| continue | |
| elif identifier not in entities: | |
| diagnostic("unknown_surface_entity", [identifier], "Surface entity is absent or ambiguous.") | |
| elif source_matches(surface, [identifier], "surface"): | |
| surfaces[identifier] = surface["bounds_xy_m"] | |
| for reservation in records["reservations"]: | |
| if (not isinstance(reservation, dict) | |
| or not _identifier(reservation.get("support_entity_id")) | |
| or not _identifier(reservation.get("purpose")) | |
| or not _rectangle(reservation.get("bounds_xy_m"))): | |
| identifier = reservation.get("support_entity_id") if isinstance(reservation, dict) else None | |
| diagnostic("invalid_reservation", [identifier], | |
| "Reservation requires support ID, purpose, and positive finite rectangle.", | |
| geometry=True) | |
| continue | |
| identifier = reservation["support_entity_id"] | |
| bounds = reservation["bounds_xy_m"] | |
| result["reservations"].append(dict(support_entity_id=identifier, | |
| bounds_xy_m=list(bounds), | |
| purpose=reservation["purpose"])) | |
| surface = surfaces.get(identifier) | |
| if surface is None: | |
| diagnostic("missing_surface", [identifier], | |
| "Reservation requires an unambiguous measured, current source rectangle.") | |
| elif not (surface[0] <= bounds[0] and surface[1] <= bounds[1] | |
| and bounds[2] <= surface[2] and bounds[3] <= surface[3]): | |
| diagnostic("reservation_out_of_bounds", [identifier], | |
| "Reservation extends outside the declared usable rectangle.", geometry=True) | |
| reservations = result["reservations"] | |
| for index, left in enumerate(reservations): | |
| for right in reservations[index + 1:]: | |
| if (left["support_entity_id"] == right["support_entity_id"] | |
| and _overlaps(left["bounds_xy_m"], right["bounds_xy_m"])): | |
| diagnostic("reservation_overlap", [left["support_entity_id"]], | |
| "Reservations overlap with positive area on one support.", geometry=True) | |
| footprints = {} | |
| duplicate_footprints = _duplicates(records["footprints"], "entity_id") | |
| for identifier in sorted(duplicate_footprints): | |
| diagnostic("duplicate_footprint", [identifier], "Occupied child footprint is ambiguous.") | |
| for footprint in records["footprints"]: | |
| if not isinstance(footprint, dict): | |
| diagnostic("invalid_footprint", [], "Footprint must be a record.") | |
| continue | |
| identifier = footprint.get("entity_id") | |
| support = footprint.get("support_entity_id") | |
| if (not _identifier(identifier) or not _identifier(support) | |
| or not _rectangle(footprint.get("bounds_xy_m"))): | |
| diagnostic("invalid_footprint", [identifier], | |
| "Footprint requires child/support IDs and a positive finite rectangle.") | |
| elif identifier in duplicate_footprints or identifier in invalid_parents: | |
| continue | |
| elif identifier not in entities or support not in entities: | |
| diagnostic("unknown_footprint_entity", [support, identifier], | |
| "Footprint child and support must resolve to manifest entities.") | |
| elif identifier == support or (identifier in parents and parents[identifier] != support): | |
| diagnostic("footprint_support_mismatch", [support, identifier], | |
| "Footprint support disagrees with the manifest child relation.") | |
| elif ("source_sha256" not in footprint | |
| or source_matches(footprint, [identifier], "footprint")): | |
| footprints[identifier] = footprint | |
| reserved_supports = {item["support_entity_id"] for item in reservations} | |
| for identifier, support in parents.items(): | |
| if support in reserved_supports and identifier not in footprints: | |
| diagnostic("missing_child_footprint", [support, identifier], | |
| "Known supported child has no usable explicit occupied rectangle.") | |
| for footprint in footprints.values(): | |
| for reservation in reservations: | |
| if (footprint["support_entity_id"] == reservation["support_entity_id"] | |
| and _overlaps(footprint["bounds_xy_m"], reservation["bounds_xy_m"])): | |
| diagnostic("reservation_footprint_overlap", | |
| [footprint["support_entity_id"], footprint["entity_id"]], | |
| "Reservation intersects an explicit existing child footprint.", geometry=True) | |
| duplicate_motifs = _duplicates(records["motifs"], "motif_id") | |
| for identifier in sorted(duplicate_motifs): | |
| diagnostic("duplicate_motif", [], "Motif ID is ambiguous: " + identifier) | |
| for motif in records["motifs"]: | |
| if not isinstance(motif, dict): | |
| diagnostic("invalid_motif", [], "Motif must be a record.") | |
| continue | |
| identifier = motif.get("motif_id") | |
| identifiers = motif.get("entity_ids") | |
| if (not _identifier(identifier) or not isinstance(identifiers, list) | |
| or not identifiers or any(not _identifier(value) for value in identifiers) | |
| or len(set(identifiers)) != len(identifiers) | |
| or not _preferences(motif.get("relative_preferences"))): | |
| diagnostic("invalid_motif", [], "Motif requires an ID, unique entities, and finite metadata.") | |
| elif identifier in duplicate_motifs: | |
| continue | |
| elif any(value not in entities for value in identifiers): | |
| diagnostic("unknown_motif_entity", identifiers, | |
| "Every motif entity must resolve to the manifest inventory.") | |
| elif source_matches(motif, identifiers, "motif"): | |
| result["accepted_motif_ids"].append(identifier) | |
| diagnostic("motif_soft_preference", identifiers, | |
| "Retrieved metadata only; full global validation is still required.", info=True) | |
| result["status"] = ("geometry_rejected" if rejected else | |
| "insufficient_evidence" if insufficient else | |
| "geometry_feasible" if requested else "not_requested") | |
| return result | |